UNPKG

@sega-so/sega-sdk

Version:

An SDK for building applications on top of SEGA.

2 lines 34.4 kB
var tt=Object.defineProperty,nt=Object.defineProperties;var rt=Object.getOwnPropertyDescriptors;var ce=Object.getOwnPropertySymbols;var Le=Object.prototype.hasOwnProperty,Fe=Object.prototype.propertyIsEnumerable;var De=(n,e,t)=>e in n?tt(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,F=(n,e)=>{for(var t in e||(e={}))Le.call(e,t)&&De(n,t,e[t]);if(ce)for(var t of ce(e))Fe.call(e,t)&&De(n,t,e[t]);return n},_=(n,e)=>nt(n,rt(e));var ue=(n,e)=>{var t={};for(var r in n)Le.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&ce)for(var r of ce(n))e.indexOf(r)<0&&Fe.call(n,r)&&(t[r]=n[r]);return t};var h=(n,e,t)=>new Promise((r,b)=>{var u=w=>{try{i(t.next(w))}catch(y){b(y)}},p=w=>{try{i(t.throw(w))}catch(y){b(y)}},i=w=>w.done?r(w.value):Promise.resolve(w.value).then(u,p);i((t=t.apply(n,e)).next())});import{get as Ee,set as it}from"lodash";var ye=class{constructor(e){this.logLevel=e.logLevel!==void 0?e.logLevel:0,this.name=e.name}set level(e){this.logLevel=e}get time(){return Date.now().toString()}get moduleName(){return this.name}isLogLevel(e){return e<=this.logLevel}error(...e){return this.isLogLevel(0)?(console.error(this.time,this.name,"sdk logger error",...e),this):this}logWithError(...e){let t=e.map(r=>typeof r=="object"?JSON.stringify(r):r).join(", ");throw new Error(t)}warning(...e){return this.isLogLevel(1)?(console.warn(this.time,this.name,"sdk logger warning",...e),this):this}info(...e){return this.isLogLevel(2)?(console.info(this.time,this.name,"sdk logger info",...e),this):this}debug(...e){return this.isLogLevel(3)?(console.debug(this.time,this.name,"sdk logger debug",...e),this):this}},Oe={},ot={};function E(n){let e=Ee(Oe,n);if(!e){let t=Ee(ot,n);e=new ye({name:n,logLevel:t}),it(Oe,n,e)}return e}import{PublicKey as J,sendAndConfirmTransaction as Ie,SystemProgram as Mt,Transaction as ie,TransactionMessage as oe,VersionedTransaction as se}from"@solana/web3.js";import Dt from"axios";import{PublicKey as Rt,AddressLookupTableAccount as Qe}from"@solana/web3.js";import{PublicKey as Nt}from"@solana/web3.js";import v from"bn.js";import Ir from"decimal.js";import dt from"big.js";import Xt from"bn.js";import st from"toformat";var at=st,Z=at;import me from"big.js";import ut from"bn.js";import lt from"decimal.js-light";import X from"bn.js";var Ve=9007199254740991;function W(n){let e=E("Sega_parseBigNumberish");if(n instanceof X)return n;if(typeof n=="string"){if(n.match(/^-?[0-9]+$/))return new X(n);e.logWithError(`invalid BigNumberish string: ${n}`)}return typeof n=="number"?(n%1&&e.logWithError(`BigNumberish number underflow: ${n}`),(n>=Ve||n<=-Ve)&&e.logWithError(`BigNumberish number overflow: ${n}`),new X(String(n))):typeof n=="bigint"?new X(n.toString()):(e.error(`invalid BigNumberish value: ${n}`),new X(0))}var le=E("module/fraction"),xe=Z(me),$=Z(lt),mt={0:$.ROUND_DOWN,1:$.ROUND_HALF_UP,2:$.ROUND_UP},pt={0:me.roundDown,1:me.roundHalfUp,2:me.roundUp},K=class n{constructor(e,t=new ut(1)){this.numerator=W(e),this.denominator=W(t)}get quotient(){return this.numerator.div(this.denominator)}invert(){return new n(this.denominator,this.numerator)}add(e){let t=e instanceof n?e:new n(W(e));return this.denominator.eq(t.denominator)?new n(this.numerator.add(t.numerator),this.denominator):new n(this.numerator.mul(t.denominator).add(t.numerator.mul(this.denominator)),this.denominator.mul(t.denominator))}sub(e){let t=e instanceof n?e:new n(W(e));return this.denominator.eq(t.denominator)?new n(this.numerator.sub(t.numerator),this.denominator):new n(this.numerator.mul(t.denominator).sub(t.numerator.mul(this.denominator)),this.denominator.mul(t.denominator))}mul(e){let t=e instanceof n?e:new n(W(e));return new n(this.numerator.mul(t.numerator),this.denominator.mul(t.denominator))}div(e){let t=e instanceof n?e:new n(W(e));return new n(this.numerator.mul(t.denominator),this.denominator.mul(t.numerator))}toSignificant(e,t={groupSeparator:""},r=1){Number.isInteger(e)||le.logWithError(`${e} is not an integer.`),e<=0&&le.logWithError(`${e} is not positive.`),$.set({precision:e+1,rounding:mt[r]});let b=new $(this.numerator.toString()).div(this.denominator.toString()).toSignificantDigits(e);return b.toFormat(b.decimalPlaces(),t)}toFixed(e,t={groupSeparator:""},r=1){return Number.isInteger(e)||le.logWithError(`${e} is not an integer.`),e<0&&le.logWithError(`${e} is negative.`),xe.DP=e,xe.RM=pt[r]||1,new xe(this.numerator.toString()).div(this.denominator.toString()).toFormat(e,t)}isZero(){return this.numerator.isZero()}};var an=E("Sega_amount"),cn=Z(dt);import{PublicKey as gt}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as We}from"@solana/spl-token";var Ke={chainId:101,address:gt.default.toBase58(),programId:We.toBase58(),decimals:9,symbol:"SOL",name:"solana",logoURI:"https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"sega",extensions:{coingeckoId:"solana"}},j={chainId:101,address:"So11111111111111111111111111111111111111112",programId:We.toBase58(),decimals:9,symbol:"WSOL",name:"Wrapped SOL",logoURI:"https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"sega",extensions:{coingeckoId:"solana"}};import{PublicKey as Se}from"@solana/web3.js";import{PublicKey as R,SystemProgram as ve,SYSVAR_RENT_PUBKEY as ht}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as bt}from"@solana/spl-token";function we({pubkey:n,isSigner:e=!1,isWritable:t=!0}){return{pubkey:n,isWritable:t,isSigner:e}}var hn=[we({pubkey:bt,isWritable:!1}),we({pubkey:ve.programId,isWritable:!1}),we({pubkey:ht,isWritable:!1})];function _e({publicKey:n,transformSol:e}){let t=qe(n.toString());if(t instanceof R)return e&&t.equals(Q)?Pe:t;if(e&&t.toString()===Q.toBase58())return Pe;if(typeof t=="string"){if(t===R.default.toBase58())return R.default;try{return new R(t)}catch(r){throw new Error("invalid public key")}}throw new Error("invalid public key")}function qe(n){try{return new R(n)}catch(e){return n}}var bn=new R("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),Tn=new R("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),yn=new R("SysvarRent111111111111111111111111111111111"),xn=new R("SysvarC1ock11111111111111111111111111111111"),Tt=new R("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),wn=new R("Sysvar1nstructions1111111111111111111111111"),Pn=ve.programId,Sn=new R("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),kn=new R("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),An=new R("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),Bn=new R("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),Cn=new R("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),In=new R("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),Nn=new R("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),Rn=new R("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),Mn=new R("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),Dn=new R("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),Ln=new R("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),Pe=new R("So11111111111111111111111111111111111111112"),Q=R.default;var pe=class pe{constructor({mint:e,decimals:t,symbol:r,name:b,skipMint:u=!1,isToken2022:p=!1}){if(e===Q.toBase58()||e instanceof Se&&Q.equals(e)){this.decimals=j.decimals,this.symbol=j.symbol,this.name=j.name,this.mint=new Se(j.address),this.isToken2022=!1;return}this.decimals=t,this.symbol=r||e.toString().substring(0,6),this.name=b||e.toString().substring(0,6),this.mint=u?Se.default:_e({publicKey:e}),this.isToken2022=p}equals(e){return this===e?!0:this.mint.equals(e.mint)}};pe.WSOL=new pe(_(F({},j),{mint:j.address}));var ee=pe;var de=class de{constructor({decimals:e,symbol:t="UNKNOWN",name:r="UNKNOWN"}){this.decimals=e,this.symbol=t,this.name=r}equals(e){return this===e}};de.SOL=new de(Ke);var ke=de;import yt from"bn.js";var Hn=new K(new yt(100));var $n=E("Sega_price");import{PublicKey as gr}from"@solana/web3.js";import br from"bn.js";var xt=new v(0),Wr=new v(1),Kr=new v(2),vr=new v(3),_r=new v(5),ft=new v(10),qr=new v(100),Ur=new v(1e3),Gr=new v(1e4);function Ae(n,e=1,t=[]){let r=[...n];if(e<=0)return t;for(;r.length;)t.push(r.splice(0,e));return t}import{PublicKey as mi}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as di}from"@solana/spl-token";import{ComputeBudgetProgram as He,Keypair as Ye,PublicKey as ti,Transaction as Je,TransactionMessage as wt,VersionedTransaction as Ze}from"@solana/web3.js";var te={CreateAccount:"CreateAccount",InitAccount:"InitAccount",CreateATA:"CreateATA",CloseAccount:"CloseAccount",TransferAmount:"TransferAmount",InitMint:"InitMint",MintTo:"MintTo",InitMarket:"InitMarket",Util1216OwnerClaim:"Util1216OwnerClaim",SetComputeUnitPrice:"SetComputeUnitPrice",SetComputeUnitLimit:"SetComputeUnitLimit",ClmmCreatePool:"ClmmCreatePool",ClmmOpenPosition:"ClmmOpenPosition",ClmmIncreasePosition:"ClmmIncreasePosition",ClmmDecreasePosition:"ClmmDecreasePosition",ClmmClosePosition:"ClmmClosePosition",ClmmSwapBaseIn:"ClmmSwapBaseIn",ClmmSwapBaseOut:"ClmmSwapBaseOut",ClmmInitReward:"ClmmInitReward",ClmmSetReward:"ClmmSetReward",ClmmCollectReward:"ClmmCollectReward",ClmmLockPosition:"ClmmLockPosition",ClmmHarvestLockPosition:"ClmmHarvestLockPosition",AmmV4Swap:"AmmV4Swap",AmmV4AddLiquidity:"AmmV4AddLiquidity",AmmV4RemoveLiquidity:"AmmV4RemoveLiquidity",AmmV4SimulatePoolInfo:"AmmV4SimulatePoolInfo",AmmV4SwapBaseIn:"AmmV4SwapBaseIn",AmmV4SwapBaseOut:"AmmV4SwapBaseOut",AmmV4CreatePool:"AmmV4CreatePool",AmmV4InitPool:"AmmV4InitPool",AmmV5AddLiquidity:"AmmV5AddLiquidity",AmmV5RemoveLiquidity:"AmmV5RemoveLiquidity",AmmV5SimulatePoolInfo:"AmmV5SimulatePoolInfo",AmmV5SwapBaseIn:"AmmV5SwapBaseIn",AmmV5SwapBaseOut:"AmmV5SwapBaseOut",RouteSwap:"RouteSwap",RouteSwap1:"RouteSwap1",RouteSwap2:"RouteSwap2",FarmV3Deposit:"FarmV3Deposit",FarmV3Withdraw:"FarmV3Withdraw",FarmV3CreateLedger:"FarmV3CreateLedger",FarmV4Withdraw:"FarmV4Withdraw",FarmV5Deposit:"FarmV5Deposit",FarmV5Withdraw:"FarmV5Withdraw",FarmV5CreateLedger:"FarmV5CreateLedger",FarmV6Deposit:"FarmV6Deposit",FarmV6Withdraw:"FarmV6Withdraw",FarmV6Create:"FarmV6Create",FarmV6Restart:"FarmV6Restart",FarmV6CreatorAddReward:"FarmV6CreatorAddReward",FarmV6CreatorWithdraw:"FarmV6CreatorWithdraw",CpmmCreatePool:"CpmmCreatePool",CpmmAddLiquidity:"CpmmAddLiquidity",CpmmWithdrawLiquidity:"CpmmWithdrawLiquidity",CpmmSwapBaseIn:"CpmmSwapBaseIn",CpmmSwapBaseOut:"CpmmSwapBaseOut",CpmmLockLp:"CpmmLockLp",CpmmCollectLockFee:"CpmmCollectLockFee",TransferTip:"TransferTip"};import{TOKEN_PROGRAM_ID as Pt}from"@solana/spl-token";var ze=E("Sega_txUtil"),Xe=1644;function fe(n){let e=[],t=[];return n.microLamports&&(e.push(He.setComputeUnitPrice({microLamports:n.microLamports})),t.push(te.SetComputeUnitPrice)),n.units&&(e.push(He.setComputeUnitLimit({units:n.units})),t.push(te.SetComputeUnitLimit)),{instructions:e,instructionTypes:t}}function Y(n,e){return h(this,null,function*(){var r,b;let t=e!=null?e:"confirmed";return(b=yield(r=n.getLatestBlockhash)==null?void 0:r.call(n,{commitment:t}))==null?void 0:b.blockhash})}function ge(n,e){return h(this,null,function*(){return n.getSignatureStatuses([e]),new Promise((t,r)=>{let b=setTimeout(r,6e4);n.onSignature(e,u=>{if(clearTimeout(b),!u.err){t("");return}r(Object.assign(u.err,{txId:e}))},"confirmed")})})}function St(n,e){n.length<1&&ze.logWithError(`no instructions provided: ${n.toString()}`),e.length<1&&ze.logWithError(`no signers provided:, ${e.toString()}`);let t=new Je;t.recentBlockhash="11111111111111111111111111111111",t.feePayer=e[0],t.add(...n);try{return Buffer.from(t.serialize({verifySignatures:!1})).toString("base64").length<Xe}catch(r){return!1}}function ne({instructions:n,payer:e,signers:t}){return St(n,[e,...t])}function re({instructions:n,payer:e,lookupTableAddressAccount:t,recentBlockhash:r=Ye.generate().publicKey.toString()}){let u=new wt({payerKey:e,recentBlockhash:r,instructions:n}).compileToV0Message(Object.values(t!=null?t:{}));try{return Buffer.from(new Ze(u).serialize()).toString("base64").length<Xe}catch(p){return!1}}var kt=n=>Buffer.isBuffer(n)?n:n instanceof Uint8Array?Buffer.from(n.buffer,n.byteOffset,n.byteLength):Buffer.from(n),At=n=>{let e=n.serialize({requireAllSignatures:!1,verifySignatures:!1});n instanceof Ze&&(e=kt(e));try{return e instanceof Buffer?e.toString("base64"):Buffer.from(e).toString("base64")}catch(t){return e.toString("base64")}};function H(n){let e=[];return n.forEach(t=>{t instanceof Je&&(t.recentBlockhash||(t.recentBlockhash=Pt.toBase58()),t.feePayer||(t.feePayer=Ye.generate().publicKey)),e.push(At(t))}),console.log("simulate tx string:",e),e}import{PublicKey as q}from"@solana/web3.js";var Ti=new q("SegazTQwbYWknDZkJ6j2Kgvm5gw3MrHGKtWstZdoNKZ"),yi=new q("Ajk8d9bERSaFdeoT1d8JUVfaDayrYLnAdgeB47TFMUaG"),xi=new q("2HbjxVVKJ7Ct72Rcd8WK4VTqmwTXL5aAggkH1CHGFGmh"),Bt=new q("auetiVUVJkRxvNPLYEvVnz8UJSqQ1VgoA83PcicHVD1"),Ct=new q("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y"),It=new q("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y");var wi={SERUM_MARKET:q.default,UTIL1216:q.default,CREATE_CPMM_POOL_PROGRAM:Bt,CREATE_CPMM_POOL_AUTH:Ct,CREATE_CPMM_POOL_FEE_ACC:It};import ki from"bn.js";import{Connection as Ii}from"@solana/web3.js";import{MINT_SIZE as ro,TOKEN_PROGRAM_ID as io,getTransferFeeConfig as oo,unpackMint as so}from"@solana/spl-token";var Be=E("Sega_accountInfo_util");function $e(n,e,t){return h(this,null,function*(){let{batchRequest:r,commitment:b="confirmed",chunkCount:u=100}=F({batchRequest:!1},t),p=Ae(e,u),i=new Array(p.length).fill([]);if(r){let w=p.map(P=>({methodName:"getMultipleAccounts",args:n._buildArgs([P.map(x=>x.toBase58())],b,"base64")})),y=Ae(w,10);i=(yield(yield Promise.all(y.map(P=>h(this,null,function*(){return yield n._rpcBatchRequest(P)})))).flat()).map(P=>(P.error&&Be.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${P.error.message}`),P.result.value.map(B=>{if(B){let{data:x,executable:l,lamports:g,owner:o,rentEpoch:S}=B;return x.length!==2&&x[1]!=="base64"&&Be.logWithError("info must be base64 encoded, RPC_ERROR"),{data:Buffer.from(x[0],"base64"),executable:l,lamports:g,owner:new Nt(o),rentEpoch:S}}return null})))}else try{i=yield Promise.all(p.map(w=>n.getMultipleAccountsInfo(w,b)))}catch(w){w instanceof Error&&Be.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${w.message}`)}return i.flat()})}function Ce(t){return h(this,arguments,function*({connection:n,address:e}){let r=yield $e(n,[...new Set(e.map(u=>u.toString()))].map(u=>new Rt(u))),b={};for(let u=0;u<e.length;u++){let p=r[u],i=e[u];if(!p)continue;let w=new Qe({key:i,state:Qe.deserialize(p.data)});b[i.toString()]=w,he[i.toString()]=w}return b})}var he={};var be=2e3,Te=class{constructor(e){this.instructions=[];this.endInstructions=[];this.lookupTableAddress=[];this.signers=[];this.instructionTypes=[];this.endInstructionTypes=[];this.connection=e.connection,this.feePayer=e.feePayer,this.signAllTransactions=e.signAllTransactions,this.owner=e.owner,this.cluster=e.cluster,this.blockhashCommitment=e.blockhashCommitment,this.loopMultiTxStatus=!!e.loopMultiTxStatus}get AllTxData(){return{instructions:this.instructions,endInstructions:this.endInstructions,signers:this.signers,instructionTypes:this.instructionTypes,endInstructionTypes:this.endInstructionTypes,lookupTableAddress:this.lookupTableAddress}}get allInstructions(){return[...this.instructions,...this.endInstructions]}getComputeBudgetConfig(){return h(this,null,function*(){var r;let e=(yield Dt.get("https://solanacompass.com/api/fees?cacheFreshTime=300000")).data,{avg:t}=(r=e==null?void 0:e[15])!=null?r:{};if(t)return{units:6e5,microLamports:Math.min(Math.ceil(t*1e6/6e5),25e3)}})}addCustomComputeBudget(e){if(e){let{instructions:t,instructionTypes:r}=fe(e);return this.instructions.unshift(...t),this.instructionTypes.unshift(...r),!0}return!1}addTipInstruction(e){var t;return e?(this.endInstructions.push(Mt.transfer({fromPubkey:(t=e.feePayer)!=null?t:this.feePayer,toPubkey:new J(e.address),lamports:BigInt(e.amount.toString())})),this.endInstructionTypes.push(te.TransferTip),!0):!1}calComputeBudget(r){return h(this,arguments,function*({config:e,defaultIns:t}){try{let b=e||(yield this.getComputeBudgetConfig());if(this.addCustomComputeBudget(b))return;t&&this.instructions.unshift(...t)}catch(b){t&&this.instructions.unshift(...t)}})}addInstruction({instructions:e=[],endInstructions:t=[],signers:r=[],instructionTypes:b=[],endInstructionTypes:u=[],lookupTableAddress:p=[]}){return this.instructions.push(...e),this.endInstructions.push(...t),this.signers.push(...r),this.instructionTypes.push(...b),this.endInstructionTypes.push(...u),this.lookupTableAddress.push(...p.filter(i=>i!==J.default.toString())),this}versionBuild(r){return h(this,arguments,function*({txVersion:e,extInfo:t}){return e===0?yield this.buildV0(F({},t||{})):this.build(t)})}build(e){var r;let t=new ie;return this.allInstructions.length&&t.add(...this.allInstructions),t.feePayer=this.feePayer,(r=this.owner)!=null&&r.signer&&!this.signers.some(b=>b.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer),{builder:this,transaction:t,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:b=>h(this,null,function*(){var y;let{recentBlockHash:u,skipPreflight:p=!0,sendAndConfirm:i}=b||{},w=u!=null?u:yield Y(this.connection,this.blockhashCommitment);if(t.recentBlockhash=w,this.signers.length&&t.sign(...this.signers),H([t]),(y=this.owner)!=null&&y.isKeyPair)return{txId:i?yield Ie(this.connection,t,this.signers.find(P=>P.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:p}):yield this.connection.sendRawTransaction(t.serialize(),{skipPreflight:p}),signedTx:t};if(this.signAllTransactions){let f=yield this.signAllTransactions([t]);if(this.signers.length)for(let P of f)try{P.sign(...this.signers)}catch(B){}return{txId:yield this.connection.sendRawTransaction(f[0].serialize(),{skipPreflight:p}),signedTx:f[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:e||{}}}buildMultiTx(e){var y;let{extraPreBuildData:t=[],extInfo:r}=e,{transaction:b}=this.build(r),u=t.filter(f=>f.transaction.instructions.length>0),p=[b,...u.map(f=>f.transaction)],i=[this.signers,...u.map(f=>f.signers)],w=[...this.instructionTypes,...u.map(f=>f.instructionTypes).flat()];return(y=this.owner)!=null&&y.signer&&i.forEach(f=>{f.some(P=>P.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),{builder:this,transactions:p,signers:i,instructionTypes:w,execute:f=>h(this,null,function*(){var S;let{sequentially:P,onTxUpdate:B,skipTxCount:x=0,recentBlockHash:l,skipPreflight:g=!0}=f||{},o=l!=null?l:yield Y(this.connection,this.blockhashCommitment);if((S=this.owner)!=null&&S.isKeyPair){if(P){let m=[],k=0;for(let c of p){if(++k,k<=x)continue;let a=yield Ie(this.connection,c,this.signers.find(s=>s.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:g});m.push(a)}return{txIds:m,signedTxs:p}}return{txIds:yield yield Promise.all(p.map(m=>h(this,null,function*(){return m.recentBlockhash=o,yield this.connection.sendRawTransaction(m.serialize(),{skipPreflight:g})}))),signedTxs:p}}if(this.signAllTransactions){let m=p.map((c,a)=>(c.recentBlockhash=o,i[a].length&&c.sign(...i[a]),c));H(m);let k=yield this.signAllTransactions(m);if(P){let c=0,a=[],s=()=>h(this,null,function*(){if(!k[c])return;let T=yield this.connection.sendRawTransaction(k[c].serialize(),{skipPreflight:g});a.push({txId:T,status:"sent",signedTx:k[c]}),B==null||B([...a]),c++;let d=!1,A=null,I=null,M=C=>{A!==null&&clearInterval(A),I!==null&&this.connection.removeSignatureListener(I);let N=a.findIndex(D=>D.txId===T);if(N>-1){if(a[N].status==="error"||a[N].status==="success")return;a[N].status=C.err?"error":"success"}B==null||B([...a]),C.err||s()};this.loopMultiTxStatus&&(A=setInterval(()=>h(this,null,function*(){var C;if(d){clearInterval(A);return}try{let N=yield this.connection.getTransaction(T,{commitment:"confirmed",maxSupportedTransactionVersion:0});N&&(d=!0,clearInterval(A),M({err:((C=N.meta)==null?void 0:C.err)||null}),console.log("tx status from getTransaction:",T))}catch(N){d=!0,clearInterval(A),console.error("getTransaction timeout:",N,T)}}),be)),I=this.connection.onSignature(T,C=>{if(d){this.connection.removeSignatureListener(I);return}d=!0,M(C)},"confirmed"),this.connection.getSignatureStatus(T)});return yield s(),{txIds:a.map(T=>T.txId),signedTxs:k}}else{let c=[];for(let a=0;a<k.length;a+=1){let s=yield this.connection.sendRawTransaction(k[a].serialize(),{skipPreflight:g});c.push(s)}return{txIds:c,signedTxs:k}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:r||{}}}versionMultiBuild(b){return h(this,arguments,function*({extraPreBuildData:e,txVersion:t,extInfo:r}){return t===0?yield this.buildV0MultiTx({extraPreBuildData:e,buildProps:r||{}}):this.buildMultiTx({extraPreBuildData:e,extInfo:r})})}buildV0(e){return h(this,null,function*(){var g;let l=e||{},{lookupTableCache:t={},lookupTableAddress:r=[],forerunCreate:b,recentBlockhash:u}=l,p=ue(l,["lookupTableCache","lookupTableAddress","forerunCreate","recentBlockhash"]),i=F(F({},this.cluster==="devnet"?{}:he),t),w=Array.from(new Set([...r,...this.lookupTableAddress])),y=[];for(let o of w)i[o]===void 0&&y.push(new J(o));let f=yield Ce({connection:this.connection,address:y});for(let[o,S]of Object.entries(f))i[o]=S;let P=b?J.default.toBase58():u!=null?u:yield Y(this.connection,this.blockhashCommitment),B=new oe({payerKey:this.feePayer,recentBlockhash:P,instructions:[...this.allInstructions]}).compileToV0Message(Object.values(i));(g=this.owner)!=null&&g.signer&&!this.signers.some(o=>o.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer);let x=new se(B);return x.sign(this.signers),{builder:this,transaction:x,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:o=>h(this,null,function*(){var k;let{skipPreflight:S=!0,sendAndConfirm:m}=o||{};if(H([x]),(k=this.owner)!=null&&k.isKeyPair){let c=yield this.connection.sendTransaction(x,{skipPreflight:S});return m&&(yield ge(this.connection,c)),{txId:c,signedTx:x}}if(this.signAllTransactions){let c=yield this.signAllTransactions([x]);if(this.signers.length)for(let a of c)try{a.sign(this.signers)}catch(s){}return{txId:yield this.connection.sendTransaction(c[0],{skipPreflight:S}),signedTx:c[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:p||{}}})}buildV0MultiTx(e){return h(this,null,function*(){var y;let{extraPreBuildData:t=[],buildProps:r}=e,{transaction:b}=yield this.buildV0(r),u=t.filter(f=>f.builder.instructions.length>0),p=[b,...u.map(f=>f.transaction)],i=[this.signers,...u.map(f=>f.signers)],w=[...this.instructionTypes,...u.map(f=>f.instructionTypes).flat()];return(y=this.owner)!=null&&y.signer&&i.forEach(f=>{f.some(P=>P.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),p.forEach((f,P)=>h(this,null,function*(){f.sign(i[P])})),{builder:this,transactions:p,signers:i,instructionTypes:w,buildProps:r,execute:f=>h(this,null,function*(){var g;let{sequentially:P,onTxUpdate:B,recentBlockHash:x,skipPreflight:l=!0}=f||{};if(x&&p.forEach(o=>o.message.recentBlockhash=x),H(p),(g=this.owner)!=null&&g.isKeyPair){if(P){let o=[];for(let S of p){let m=yield this.connection.sendTransaction(S,{skipPreflight:l});yield ge(this.connection,m),o.push(m)}return{txIds:o,signedTxs:p}}return{txIds:yield Promise.all(p.map(o=>h(this,null,function*(){return yield this.connection.sendTransaction(o,{skipPreflight:l})}))),signedTxs:p}}if(this.signAllTransactions){let o=yield this.signAllTransactions(p);if(P){let S=0,m=[],k=()=>h(this,null,function*(){if(!o[S])return;let c=yield this.connection.sendTransaction(o[S],{skipPreflight:l});m.push({txId:c,status:"sent",signedTx:o[S]}),B==null||B([...m]),S++;let a=!1,s=null,T=null,d=A=>{s!==null&&clearInterval(s),T!==null&&this.connection.removeSignatureListener(T);let I=m.findIndex(M=>M.txId===c);if(I>-1){if(m[I].status==="error"||m[I].status==="success")return;m[I].status=A.err?"error":"success"}B==null||B([...m]),A.err||k()};this.loopMultiTxStatus&&(s=setInterval(()=>h(this,null,function*(){var A;if(a){clearInterval(s);return}try{let I=yield this.connection.getTransaction(c,{commitment:"confirmed",maxSupportedTransactionVersion:0});I&&(a=!0,clearInterval(s),d({err:((A=I.meta)==null?void 0:A.err)||null}),console.log("tx status from getTransaction:",c))}catch(I){a=!0,clearInterval(s),console.error("getTransaction timeout:",I,c)}}),be)),T=this.connection.onSignature(c,A=>{if(a){this.connection.removeSignatureListener(T);return}a=!0,d(A)},"confirmed"),this.connection.getSignatureStatus(c)});return k(),{txIds:[],signedTxs:o}}else{let S=[];for(let m=0;m<o.length;m+=1){let k=yield this.connection.sendTransaction(o[m],{skipPreflight:l});S.push(k)}return{txIds:S,signedTxs:o}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:r||{}}})}sizeCheckBuild(e){return h(this,null,function*(){var B;let P=e||{},{splitIns:t=[],computeBudgetConfig:r}=P,b=ue(P,["splitIns","computeBudgetConfig"]),u=r?fe(r):{instructions:[],instructionTypes:[]},p=this.signers.reduce((x,l)=>_(F({},x),{[l.publicKey.toBase58()]:l}),{}),i=[],w=[],y=[],f=0;if(this.allInstructions.forEach(x=>{let l=[...y,x],g=r?[...u.instructions,...l]:l,S=[...new Set(l.map(m=>m.keys.filter(k=>k.isSigner).map(k=>k.pubkey.toString())).flat()).values()].map(m=>new J(m));if(x!==t[f]&&y.length<12&&(ne({instructions:g,payer:this.feePayer,signers:S})||ne({instructions:l,payer:this.feePayer,signers:S})))y.push(x);else{if(y.length===0)throw Error("item ins too big");f+=x===t[f]?1:0,ne({instructions:r?[...u.instructions,...y]:[...y],payer:this.feePayer,signers:S})?i.push(new ie().add(...u.instructions,...y)):i.push(new ie().add(...y)),w.push(Array.from(new Set(y.map(m=>m.keys.filter(k=>k.isSigner).map(k=>k.pubkey.toString())).flat())).map(m=>p[m]).filter(m=>m!==void 0)),y=[x]}}),y.length>0){let l=[...new Set(y.map(g=>g.keys.filter(o=>o.isSigner).map(o=>o.pubkey.toString())).flat()).values()].map(g=>p[g]).filter(g=>g!==void 0);ne({instructions:r?[...u.instructions,...y]:[...y],payer:this.feePayer,signers:l.map(g=>g.publicKey)})?i.push(new ie().add(...u.instructions,...y)):i.push(new ie().add(...y)),w.push(l)}return i.forEach(x=>x.feePayer=this.feePayer),(B=this.owner)!=null&&B.signer&&w.forEach(x=>{x.some(l=>l.publicKey.equals(this.owner.publicKey))||x.push(this.owner.signer)}),{builder:this,transactions:i,signers:w,instructionTypes:this.instructionTypes,execute:x=>h(this,null,function*(){var c;let{sequentially:l,onTxUpdate:g,skipTxCount:o=0,recentBlockHash:S,skipPreflight:m=!0}=x||{},k=S!=null?S:yield Y(this.connection,this.blockhashCommitment);if(i.forEach((a,s)=>h(this,null,function*(){a.recentBlockhash=k,w[s].length&&a.sign(...w[s])})),H(i),(c=this.owner)!=null&&c.isKeyPair){if(l){let a=0,s=[];for(let T of i){if(++a,a<=o){s.push("tx skipped");continue}let d=yield Ie(this.connection,T,this.signers.find(A=>A.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:m});s.push(d)}return{txIds:s,signedTxs:i}}return{txIds:yield Promise.all(i.map(a=>h(this,null,function*(){return yield this.connection.sendRawTransaction(a.serialize(),{skipPreflight:m})}))),signedTxs:i}}if(this.signAllTransactions){let a=yield this.signAllTransactions(i.slice(o,i.length)),s=[...i.slice(0,o),...a];if(l){let T=0,d=[],A=()=>h(this,null,function*(){if(!s[T])return;T<o&&(d.push({txId:"",status:"success",signedTx:s[T]}),g==null||g([...d]),T++,A());let I=yield this.connection.sendRawTransaction(s[T].serialize(),{skipPreflight:m});d.push({txId:I,status:"sent",signedTx:s[T]}),g==null||g([...d]),T++;let M=!1,C=null,N=null,D=O=>{C!==null&&clearInterval(C),N!==null&&this.connection.removeSignatureListener(N);let L=d.findIndex(U=>U.txId===I);if(L>-1){if(d[L].status==="error"||d[L].status==="success")return;d[L].status=O.err?"error":"success"}g==null||g([...d]),O.err||A()};this.loopMultiTxStatus&&(C=setInterval(()=>h(this,null,function*(){var O;if(M){clearInterval(C);return}try{let L=yield this.connection.getTransaction(I,{commitment:"confirmed",maxSupportedTransactionVersion:0});L&&(M=!0,clearInterval(C),D({err:((O=L.meta)==null?void 0:O.err)||null}),console.log("tx status from getTransaction:",I))}catch(L){M=!0,clearInterval(C),console.error("getTransaction timeout:",L,I)}}),be)),N=this.connection.onSignature(I,O=>{if(M){this.connection.removeSignatureListener(N);return}M=!0,D(O)},"confirmed"),this.connection.getSignatureStatus(I)});return yield A(),{txIds:d.map(I=>I.txId),signedTxs:s}}else{let T=[];for(let d=0;d<s.length;d+=1){let A=yield this.connection.sendRawTransaction(s[d].serialize(),{skipPreflight:m});T.push(A)}return{txIds:T,signedTxs:s}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:b||{}}})}sizeCheckBuildV0(e){return h(this,null,function*(){var k;let m=e||{},{computeBudgetConfig:t,splitIns:r=[],lookupTableCache:b={},lookupTableAddress:u=[]}=m,p=ue(m,["computeBudgetConfig","splitIns","lookupTableCache","lookupTableAddress"]),i=F(F({},this.cluster==="devnet"?{}:he),b),w=Array.from(new Set([...this.lookupTableAddress,...u])),y=[];for(let c of w)i[c]===void 0&&y.push(new J(c));let f=yield Ce({connection:this.connection,address:y});for(let[c,a]of Object.entries(f))i[c]=a;let P=t?fe(t):{instructions:[],instructionTypes:[]},B=yield Y(this.connection,this.blockhashCommitment),x=this.signers.reduce((c,a)=>_(F({},c),{[a.publicKey.toBase58()]:a}),{}),l=[],g=[],o=[],S=0;if(this.allInstructions.forEach(c=>{let a=[...o,c],s=t?[...P.instructions,...a]:a;if(c!==r[S]&&o.length<12&&(re({instructions:s,payer:this.feePayer,lookupTableAddressAccount:i})||re({instructions:a,payer:this.feePayer,lookupTableAddressAccount:i})))o.push(c);else{if(o.length===0)throw Error("item ins too big");S+=c===r[S]?1:0;let T={};for(let d of[...new Set(w)])i[d]!==void 0&&(T[d]=i[d]);if(t&&re({instructions:[...P.instructions,...o],payer:this.feePayer,lookupTableAddressAccount:i,recentBlockhash:B})){let d=new oe({payerKey:this.feePayer,recentBlockhash:B,instructions:[...P.instructions,...o]}).compileToV0Message(Object.values(i));l.push(new se(d))}else{let d=new oe({payerKey:this.feePayer,recentBlockhash:B,instructions:[...o]}).compileToV0Message(Object.values(i));l.push(new se(d))}g.push(Array.from(new Set(o.map(d=>d.keys.filter(A=>A.isSigner).map(A=>A.pubkey.toString())).flat())).map(d=>x[d]).filter(d=>d!==void 0)),o=[c]}}),o.length>0){let a=[...new Set(o.map(s=>s.keys.filter(T=>T.isSigner).map(T=>T.pubkey.toString())).flat()).values()].map(s=>x[s]).filter(s=>s!==void 0);if(t&&re({instructions:[...P.instructions,...o],payer:this.feePayer,lookupTableAddressAccount:i,recentBlockhash:B})){let s=new oe({payerKey:this.feePayer,recentBlockhash:B,instructions:[...P.instructions,...o]}).compileToV0Message(Object.values(i));l.push(new se(s))}else{let s=new oe({payerKey:this.feePayer,recentBlockhash:B,instructions:[...o]}).compileToV0Message(Object.values(i));l.push(new se(s))}g.push(a)}return(k=this.owner)!=null&&k.signer&&g.forEach(c=>{c.some(a=>a.publicKey.equals(this.owner.publicKey))||c.push(this.owner.signer)}),{builder:this,transactions:l,buildProps:e,signers:g,instructionTypes:this.instructionTypes,execute:c=>h(this,null,function*(){var I;let{sequentially:a,onTxUpdate:s,skipTxCount:T=0,recentBlockHash:d,skipPreflight:A=!0}=c||{};if(l.map((M,C)=>h(this,null,function*(){g[C].length&&M.sign(g[C]),d&&(M.message.recentBlockhash=d)})),H(l),(I=this.owner)!=null&&I.isKeyPair){if(a){let M=0,C=[];for(let N of l){if(++M,M<=T){console.log("skip tx: ",M),C.push("tx skipped");continue}let D=yield this.connection.sendTransaction(N,{skipPreflight:A});yield ge(this.connection,D),C.push(D)}return{txIds:C,signedTxs:l}}return{txIds:yield Promise.all(l.map(M=>h(this,null,function*(){return yield this.connection.sendTransaction(M,{skipPreflight:A})}))),signedTxs:l}}if(this.signAllTransactions){let M=yield this.signAllTransactions(l.slice(T,l.length)),C=[...l.slice(0,T),...M];if(a){let N=0,D=[],O=()=>h(this,null,function*(){if(!C[N])return;if(N<T){D.push({txId:"",status:"success",signedTx:C[N]}),s==null||s([...D]),N++,O();return}let L=yield this.connection.sendTransaction(C[N],{skipPreflight:A});D.push({txId:L,status:"sent",signedTx:C[N]}),s==null||s([...D]),N++;let U=!1,z=null,ae=null,Me=G=>{z!==null&&clearInterval(z),ae!==null&&this.connection.removeSignatureListener(ae);let V=D.findIndex(et=>et.txId===L);if(V>-1){if(D[V].status==="error"||D[V].status==="success")return;D[V].status=G.err?"error":"success"}s==null||s([...D]),G.err||O()};this.loopMultiTxStatus&&(z=setInterval(()=>h(this,null,function*(){var G;if(U){clearInterval(z);return}try{let V=yield this.connection.getTransaction(L,{commitment:"confirmed",maxSupportedTransactionVersion:0});V&&(U=!0,clearInterval(z),Me({err:((G=V.meta)==null?void 0:G.err)||null}),console.log("tx status from getTransaction:",L))}catch(V){U=!0,clearInterval(z),console.error("getTransaction timeout:",V,L)}}),be)),ae=this.connection.onSignature(L,G=>{if(U){this.connection.removeSignatureListener(ae);return}U=!0,Me(G)},"confirmed"),this.connection.getSignatureStatus(L)});return O(),{txIds:[],signedTxs:C}}else{let N=[];for(let D=0;D<C.length;D+=1){let O=yield this.connection.sendTransaction(C[D],{skipPreflight:A});N.push(O)}return{txIds:N,signedTxs:C}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:p||{}}})}};var Ne=(...n)=>n.map(e=>{try{return typeof e=="object"?JSON.stringify(e):e}catch(t){return e}}).join(", "),Re=class{constructor({scope:e,moduleName:t}){this.disabled=!1;this.scope=e,this.logger=E(t)}createTxBuilder(e){return this.scope.checkOwner(),new Te({connection:this.scope.connection,feePayer:e||this.scope.ownerPubKey,cluster:this.scope.cluster,owner:this.scope.owner,blockhashCommitment:this.scope.blockhashCommitment,loopMultiTxStatus:this.scope.loopMultiTxStatus,api:this.scope.api,signAllTransactions:this.scope.signAllTransactions})}logDebug(...e){this.logger.debug(Ne(e))}logInfo(...e){this.logger.info(Ne(e))}logAndCreateError(...e){let t=Ne(e);throw new Error(t)}checkDisabled(){(this.disabled||!this.scope)&&this.logAndCreateError("module not working")}};export{Re as default}; //# sourceMappingURL=moduleBase.mjs.map