@sega-so/sega-sdk
Version:
An SDK for building applications on top of SEGA.
2 lines • 34.6 kB
JavaScript
var tt=Object.defineProperty,nt=Object.defineProperties;var rt=Object.getOwnPropertyDescriptors;var ce=Object.getOwnPropertySymbols;var Le=Object.prototype.hasOwnProperty,Oe=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,O=(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))Oe.call(e,t)&&De(n,t,e[t]);return n},q=(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&&Oe.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}},Fe={},ot={};function E(n){let e=Ee(Fe,n);if(!e){let t=Ee(ot,n);e=new ye({name:n,logLevel:t}),it(Fe,n,e)}return e}import{PublicKey as J,sendAndConfirmTransaction as Ie,SystemProgram as Dt,Transaction as ie,TransactionMessage as oe,VersionedTransaction as se}from"@solana/web3.js";import Lt from"axios";import{PublicKey as Nt,AddressLookupTableAccount as Qe}from"@solana/web3.js";import{PublicKey as Mt}from"@solana/web3.js";import v from"bn.js";import Rr from"decimal.js";import dt from"big.js";import $t 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 _e=9007199254740991;function V(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>=_e||n<=-_e)&&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},W=class n{constructor(e,t=new ut(1)){this.numerator=V(e),this.denominator=V(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(V(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(V(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(V(e));return new n(this.numerator.mul(t.numerator),this.denominator.mul(t.denominator))}div(e){let t=e instanceof n?e:new n(V(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 cn=E("Sega_amount"),un=Z(dt);import{PublicKey as gt}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as Ke}from"@solana/spl-token";var Ve={chainId:101,address:gt.default.toBase58(),programId:Ke.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:Ke.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 M,SystemProgram as We,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 bn=[we({pubkey:bt,isWritable:!1}),we({pubkey:We.programId,isWritable:!1}),we({pubkey:ht,isWritable:!1})];function ve({publicKey:n,transformSol:e}){let t=qe(n.toString());if(t instanceof M)return e&&t.equals(Q)?Pe:t;if(e&&t.toString()===Q.toBase58())return Pe;if(typeof t=="string"){if(t===M.default.toBase58())return M.default;try{return new M(t)}catch(r){throw new Error("invalid public key")}}throw new Error("invalid public key")}function qe(n){try{return new M(n)}catch(e){return n}}var Tn=new M("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),yn=new M("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),xn=new M("SysvarRent111111111111111111111111111111111"),wn=new M("SysvarC1ock11111111111111111111111111111111"),Tt=new M("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),Pn=new M("Sysvar1nstructions1111111111111111111111111"),Sn=We.programId,An=new M("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),kn=new M("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),Cn=new M("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),Bn=new M("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),In=new M("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),Rn=new M("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),Mn=new M("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),Nn=new M("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),Dn=new M("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),Ln=new M("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),On=new M("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),Pe=new M("So11111111111111111111111111111111111111112"),Q=M.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:ve({publicKey:e}),this.isToken2022=p}equals(e){return this===e?!0:this.mint.equals(e.mint)}};pe.WSOL=new pe(q(O({},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(Ve);var Ae=de;import yt from"bn.js";var Yn=new W(new yt(100));var Qn=E("Sega_price");import{PublicKey as hr}from"@solana/web3.js";import Tr from"bn.js";var xt=new v(0),Vr=new v(1),Wr=new v(2),vr=new v(3),qr=new v(5),ft=new v(10),Ur=new v(100),Gr=new v(1e3),jr=new v(1e4);function ke(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 pi}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as fi}from"@solana/spl-token";import{ComputeBudgetProgram as He,Keypair as ze,PublicKey as ni,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 Ye=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 z(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&&Ye.logWithError(`no instructions provided: ${n.toString()}`),e.length<1&&Ye.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=ze.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 At=n=>Buffer.isBuffer(n)?n:n instanceof Uint8Array?Buffer.from(n.buffer,n.byteOffset,n.byteLength):Buffer.from(n),kt=n=>{let e=n.serialize({requireAllSignatures:!1,verifySignatures:!1});n instanceof Ze&&(e=At(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=ze.generate().publicKey)),e.push(kt(t))}),console.log("simulate tx string:",e),e}import{PublicKey as _}from"@solana/web3.js";var yi=new _("SegazTQwbYWknDZkJ6j2Kgvm5gw3MrHGKtWstZdoNKZ"),xi=new _("Ajk8d9bERSaFdeoT1d8JUVfaDayrYLnAdgeB47TFMUaG"),wi=new _("2HbjxVVKJ7Ct72Rcd8WK4VTqmwTXL5aAggkH1CHGFGmh"),Ct=new _("TegaRdjn9Qeh9DfUU28X19aPPpJtj9gs8ntSYrR5H4K "),Bt=new _("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y"),It=new _("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y"),Pi=new _("SegaXNnoXYTZiqUt9Xn2XqGcL56b25yzXLuJSpadcMu"),Si=new _("2t1hV2YqnDCPuJZqr7Fy8oAygGwZE5Q9uaQzpLC1QryJ"),Ai=new _("BLxynZeHE123MmQgNJZiV1pwW4VYh46oZYyC66xwmtTY");var Rt={SERUM_MARKET:_.default,UTIL1216:_.default,CREATE_CPMM_POOL_PROGRAM:Ct,CREATE_CPMM_POOL_AUTH:Bt,CREATE_CPMM_POOL_FEE_ACC:It};import Bi from"bn.js";import{Connection as Li}from"@solana/web3.js";import{MINT_SIZE as lo,TOKEN_PROGRAM_ID as mo,getTransferFeeConfig as po,unpackMint as fo}from"@solana/spl-token";var Ce=E("Sega_accountInfo_util");function $e(n,e,t){return h(this,null,function*(){let{batchRequest:r,commitment:b="confirmed",chunkCount:u=100}=O({batchRequest:!1},t),p=ke(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=ke(w,10);i=(yield(yield Promise.all(y.map(P=>h(this,null,function*(){return yield n._rpcBatchRequest(P)})))).flat()).map(P=>(P.error&&Ce.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${P.error.message}`),P.result.value.map(C=>{if(C){let{data:x,executable:l,lamports:g,owner:o,rentEpoch:S}=C;return x.length!==2&&x[1]!=="base64"&&Ce.logWithError("info must be base64 encoded, RPC_ERROR"),{data:Buffer.from(x[0],"base64"),executable:l,lamports:g,owner:new Mt(o),rentEpoch:S}}return null})))}else try{i=yield Promise.all(p.map(w=>n.getMultipleAccountsInfo(w,b)))}catch(w){w instanceof Error&&Ce.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${w.message}`)}return i.flat()})}function Be(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 Nt(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 Lt.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(Dt.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(O({},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 z(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(C){}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:C,skipTxCount:x=0,recentBlockHash:l,skipPreflight:g=!0}=f||{},o=l!=null?l:yield z(this.connection,this.blockhashCommitment);if((S=this.owner)!=null&&S.isKeyPair){if(P){let m=[],A=0;for(let c of p){if(++A,A<=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 A=yield this.signAllTransactions(m);if(P){let c=0,a=[],s=()=>h(this,null,function*(){if(!A[c])return;let T=yield this.connection.sendRawTransaction(A[c].serialize(),{skipPreflight:g});a.push({txId:T,status:"sent",signedTx:A[c]}),C==null||C([...a]),c++;let d=!1,k=null,I=null,N=B=>{k!==null&&clearInterval(k),I!==null&&this.connection.removeSignatureListener(I);let R=a.findIndex(D=>D.txId===T);if(R>-1){if(a[R].status==="error"||a[R].status==="success")return;a[R].status=B.err?"error":"success"}C==null||C([...a]),B.err||s()};this.loopMultiTxStatus&&(k=setInterval(()=>h(this,null,function*(){var B;if(d){clearInterval(k);return}try{let R=yield this.connection.getTransaction(T,{commitment:"confirmed",maxSupportedTransactionVersion:0});R&&(d=!0,clearInterval(k),N({err:((B=R.meta)==null?void 0:B.err)||null}),console.log("tx status from getTransaction:",T))}catch(R){d=!0,clearInterval(k),console.error("getTransaction timeout:",R,T)}}),be)),I=this.connection.onSignature(T,B=>{if(d){this.connection.removeSignatureListener(I);return}d=!0,N(B)},"confirmed"),this.connection.getSignatureStatus(T)});return yield s(),{txIds:a.map(T=>T.txId),signedTxs:A}}else{let c=[];for(let a=0;a<A.length;a+=1){let s=yield this.connection.sendRawTransaction(A[a].serialize(),{skipPreflight:g});c.push(s)}return{txIds:c,signedTxs:A}}}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=O(O({},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 Be({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 z(this.connection,this.blockhashCommitment),C=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(C);return x.sign(this.signers),{builder:this,transaction:x,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:o=>h(this,null,function*(){var A;let{skipPreflight:S=!0,sendAndConfirm:m}=o||{};if(H([x]),(A=this.owner)!=null&&A.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:C,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=[],A=()=>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]}),C==null||C([...m]),S++;let a=!1,s=null,T=null,d=k=>{s!==null&&clearInterval(s),T!==null&&this.connection.removeSignatureListener(T);let I=m.findIndex(N=>N.txId===c);if(I>-1){if(m[I].status==="error"||m[I].status==="success")return;m[I].status=k.err?"error":"success"}C==null||C([...m]),k.err||A()};this.loopMultiTxStatus&&(s=setInterval(()=>h(this,null,function*(){var k;if(a){clearInterval(s);return}try{let I=yield this.connection.getTransaction(c,{commitment:"confirmed",maxSupportedTransactionVersion:0});I&&(a=!0,clearInterval(s),d({err:((k=I.meta)==null?void 0:k.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,k=>{if(a){this.connection.removeSignatureListener(T);return}a=!0,d(k)},"confirmed"),this.connection.getSignatureStatus(c)});return A(),{txIds:[],signedTxs:o}}else{let S=[];for(let m=0;m<o.length;m+=1){let A=yield this.connection.sendTransaction(o[m],{skipPreflight:l});S.push(A)}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 C;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)=>q(O({},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(A=>A.isSigner).map(A=>A.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(A=>A.isSigner).map(A=>A.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),(C=this.owner)!=null&&C.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||{},A=S!=null?S:yield z(this.connection,this.blockhashCommitment);if(i.forEach((a,s)=>h(this,null,function*(){a.recentBlockhash=A,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(k=>k.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=[],k=()=>h(this,null,function*(){if(!s[T])return;T<o&&(d.push({txId:"",status:"success",signedTx:s[T]}),g==null||g([...d]),T++,k());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 N=!1,B=null,R=null,D=F=>{B!==null&&clearInterval(B),R!==null&&this.connection.removeSignatureListener(R);let L=d.findIndex(U=>U.txId===I);if(L>-1){if(d[L].status==="error"||d[L].status==="success")return;d[L].status=F.err?"error":"success"}g==null||g([...d]),F.err||k()};this.loopMultiTxStatus&&(B=setInterval(()=>h(this,null,function*(){var F;if(N){clearInterval(B);return}try{let L=yield this.connection.getTransaction(I,{commitment:"confirmed",maxSupportedTransactionVersion:0});L&&(N=!0,clearInterval(B),D({err:((F=L.meta)==null?void 0:F.err)||null}),console.log("tx status from getTransaction:",I))}catch(L){N=!0,clearInterval(B),console.error("getTransaction timeout:",L,I)}}),be)),R=this.connection.onSignature(I,F=>{if(N){this.connection.removeSignatureListener(R);return}N=!0,D(F)},"confirmed"),this.connection.getSignatureStatus(I)});return yield k(),{txIds:d.map(I=>I.txId),signedTxs:s}}else{let T=[];for(let d=0;d<s.length;d+=1){let k=yield this.connection.sendRawTransaction(s[d].serialize(),{skipPreflight:m});T.push(k)}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 A;let m=e||{},{computeBudgetConfig:t,splitIns:r=[],lookupTableCache:b={},lookupTableAddress:u=[]}=m,p=ue(m,["computeBudgetConfig","splitIns","lookupTableCache","lookupTableAddress"]),i=O(O({},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 Be({connection:this.connection,address:y});for(let[c,a]of Object.entries(f))i[c]=a;let P=t?fe(t):{instructions:[],instructionTypes:[]},C=yield z(this.connection,this.blockhashCommitment),x=this.signers.reduce((c,a)=>q(O({},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:C})){let d=new oe({payerKey:this.feePayer,recentBlockhash:C,instructions:[...P.instructions,...o]}).compileToV0Message(Object.values(i));l.push(new se(d))}else{let d=new oe({payerKey:this.feePayer,recentBlockhash:C,instructions:[...o]}).compileToV0Message(Object.values(i));l.push(new se(d))}g.push(Array.from(new Set(o.map(d=>d.keys.filter(k=>k.isSigner).map(k=>k.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:C})){let s=new oe({payerKey:this.feePayer,recentBlockhash:C,instructions:[...P.instructions,...o]}).compileToV0Message(Object.values(i));l.push(new se(s))}else{let s=new oe({payerKey:this.feePayer,recentBlockhash:C,instructions:[...o]}).compileToV0Message(Object.values(i));l.push(new se(s))}g.push(a)}return(A=this.owner)!=null&&A.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:k=!0}=c||{};if(l.map((N,B)=>h(this,null,function*(){g[B].length&&N.sign(g[B]),d&&(N.message.recentBlockhash=d)})),H(l),(I=this.owner)!=null&&I.isKeyPair){if(a){let N=0,B=[];for(let R of l){if(++N,N<=T){console.log("skip tx: ",N),B.push("tx skipped");continue}let D=yield this.connection.sendTransaction(R,{skipPreflight:k});yield ge(this.connection,D),B.push(D)}return{txIds:B,signedTxs:l}}return{txIds:yield Promise.all(l.map(N=>h(this,null,function*(){return yield this.connection.sendTransaction(N,{skipPreflight:k})}))),signedTxs:l}}if(this.signAllTransactions){let N=yield this.signAllTransactions(l.slice(T,l.length)),B=[...l.slice(0,T),...N];if(a){let R=0,D=[],F=()=>h(this,null,function*(){if(!B[R])return;if(R<T){D.push({txId:"",status:"success",signedTx:B[R]}),s==null||s([...D]),R++,F();return}let L=yield this.connection.sendTransaction(B[R],{skipPreflight:k});D.push({txId:L,status:"sent",signedTx:B[R]}),s==null||s([...D]),R++;let U=!1,Y=null,ae=null,Ne=G=>{Y!==null&&clearInterval(Y),ae!==null&&this.connection.removeSignatureListener(ae);let K=D.findIndex(et=>et.txId===L);if(K>-1){if(D[K].status==="error"||D[K].status==="success")return;D[K].status=G.err?"error":"success"}s==null||s([...D]),G.err||F()};this.loopMultiTxStatus&&(Y=setInterval(()=>h(this,null,function*(){var G;if(U){clearInterval(Y);return}try{let K=yield this.connection.getTransaction(L,{commitment:"confirmed",maxSupportedTransactionVersion:0});K&&(U=!0,clearInterval(Y),Ne({err:((G=K.meta)==null?void 0:G.err)||null}),console.log("tx status from getTransaction:",L))}catch(K){U=!0,clearInterval(Y),console.error("getTransaction timeout:",K,L)}}),be)),ae=this.connection.onSignature(L,G=>{if(U){this.connection.removeSignatureListener(ae);return}U=!0,Ne(G)},"confirmed"),this.connection.getSignatureStatus(L)});return F(),{txIds:[],signedTxs:B}}else{let R=[];for(let D=0;D<B.length;D+=1){let F=yield this.connection.sendTransaction(B[D],{skipPreflight:k});R.push(F)}return{txIds:R,signedTxs:B}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:p||{}}})}};var Re=(...n)=>n.map(e=>{try{return typeof e=="object"?JSON.stringify(e):e}catch(t){return e}}).join(", "),Me=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(Re(e))}logInfo(...e){this.logger.info(Re(e))}logAndCreateError(...e){let t=Re(e);throw new Error(t)}checkDisabled(){(this.disabled||!this.scope)&&this.logAndCreateError("module not working")}};export{Me as default};
//# sourceMappingURL=moduleBase.mjs.map