UNPKG

@sega-so/sega-sdk

Version:

An SDK for building applications on top of SEGA.

2 lines 48 kB
"use strict";var Ut=Object.create;var se=Object.defineProperty,Gt=Object.defineProperties,jt=Object.getOwnPropertyDescriptor,Ht=Object.getOwnPropertyDescriptors,zt=Object.getOwnPropertyNames,we=Object.getOwnPropertySymbols,Yt=Object.getPrototypeOf,We=Object.prototype.hasOwnProperty,st=Object.prototype.propertyIsEnumerable;var it=(n,e,t)=>e in n?se(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,E=(n,e)=>{for(var t in e||(e={}))We.call(e,t)&&it(n,t,e[t]);if(we)for(var t of we(e))st.call(e,t)&&it(n,t,e[t]);return n},Z=(n,e)=>Gt(n,Ht(e));var ee=(n,e)=>{var t={};for(var r in n)We.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&we)for(var r of we(n))e.indexOf(r)<0&&st.call(n,r)&&(t[r]=n[r]);return t};var Jt=(n,e)=>{for(var t in e)se(n,t,{get:e[t],enumerable:!0})},at=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of zt(e))!We.call(n,o)&&o!==t&&se(n,o,{get:()=>e[o],enumerable:!(r=jt(e,o))||r.enumerable});return n};var v=(n,e,t)=>(t=n!=null?Ut(Yt(n)):{},at(e||!n||!n.__esModule?se(t,"default",{value:n,enumerable:!0}):t,n)),Zt=n=>at(se({},"__esModule",{value:!0}),n);var x=(n,e,t)=>new Promise((r,o)=>{var a=m=>{try{i(t.next(m))}catch(u){o(u)}},s=m=>{try{i(t.throw(m))}catch(u){o(u)}},i=m=>m.done?r(m.value):Promise.resolve(m.value).then(a,s);i((t=t.apply(n,e)).next())});var Tn={};Jt(Tn,{default:()=>ve});module.exports=Zt(Tn);var ne=require("@solana/web3.js");var ut=require("@solana/web3.js");var ae=require("lodash");var Ve=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}},ct={},$t={};function W(n){let e=(0,ae.get)(ct,n);if(!e){let t=(0,ae.get)($t,n);e=new Ve({name:n,logLevel:t}),(0,ae.set)(ct,n,e)}return e}var Ae=require("@solana/spl-token");var qe=W("Sega_accountInfo_util");function lt(n,e,t){return x(this,null,function*(){let{batchRequest:r,commitment:o="confirmed",chunkCount:a=100}=E({batchRequest:!1},t),s=Ue(e,a),i=new Array(s.length).fill([]);if(r){let m=s.map(y=>({methodName:"getMultipleAccounts",args:n._buildArgs([y.map(h=>h.toBase58())],o,"base64")})),u=Ue(m,10);i=(yield(yield Promise.all(u.map(y=>x(this,null,function*(){return yield n._rpcBatchRequest(y)})))).flat()).map(y=>(y.error&&qe.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${y.error.message}`),y.result.value.map(T=>{if(T){let{data:h,executable:c,lamports:P,owner:f,rentEpoch:I}=T;return h.length!==2&&h[1]!=="base64"&&qe.logWithError("info must be base64 encoded, RPC_ERROR"),{data:Buffer.from(h[0],"base64"),executable:c,lamports:P,owner:new ut.PublicKey(f),rentEpoch:I}}return null})))}else try{i=yield Promise.all(s.map(m=>n.getMultipleAccountsInfo(m,o)))}catch(m){m instanceof Error&&qe.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${m.message}`)}return i.flat()})}var j=v(require("bn.js")),un=v(require("decimal.js"));var gt=v(require("big.js")),nn=v(require("bn.js"));var mt=v(require("toformat")),Xt=mt.default,ce=Xt;var ue=v(require("big.js")),dt=v(require("bn.js")),ft=v(require("decimal.js-light"));var oe=v(require("bn.js"));var pt=9007199254740991;function G(n){let e=W("Sega_parseBigNumberish");if(n instanceof oe.default)return n;if(typeof n=="string"){if(n.match(/^-?[0-9]+$/))return new oe.default(n);e.logWithError(`invalid BigNumberish string: ${n}`)}return typeof n=="number"?(n%1&&e.logWithError(`BigNumberish number underflow: ${n}`),(n>=pt||n<=-pt)&&e.logWithError(`BigNumberish number overflow: ${n}`),new oe.default(String(n))):typeof n=="bigint"?new oe.default(n.toString()):(e.error(`invalid BigNumberish value: ${n}`),new oe.default(0))}var ke=W("module/fraction"),Ge=ce(ue.default),le=ce(ft.default),en={0:le.ROUND_DOWN,1:le.ROUND_HALF_UP,2:le.ROUND_UP},tn={0:ue.default.roundDown,1:ue.default.roundHalfUp,2:ue.default.roundUp},z=class n{constructor(e,t=new dt.default(1)){this.numerator=G(e),this.denominator=G(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(G(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(G(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(G(e));return new n(this.numerator.mul(t.numerator),this.denominator.mul(t.denominator))}div(e){let t=e instanceof n?e:new n(G(e));return new n(this.numerator.mul(t.denominator),this.denominator.mul(t.numerator))}toSignificant(e,t={groupSeparator:""},r=1){Number.isInteger(e)||ke.logWithError(`${e} is not an integer.`),e<=0&&ke.logWithError(`${e} is not positive.`),le.set({precision:e+1,rounding:en[r]});let o=new le(this.numerator.toString()).div(this.denominator.toString()).toSignificantDigits(e);return o.toFormat(o.decimalPlaces(),t)}toFixed(e,t={groupSeparator:""},r=1){return Number.isInteger(e)||ke.logWithError(`${e} is not an integer.`),e<0&&ke.logWithError(`${e} is negative.`),Ge.DP=e,Ge.RM=tn[r]||1,new Ge(this.numerator.toString()).div(this.denominator.toString()).toFormat(e,t)}isZero(){return this.numerator.isZero()}};var Hn=W("Sega_amount"),zn=ce(gt.default);var ht=require("@solana/web3.js"),je=require("@solana/spl-token"),yt={chainId:101,address:ht.PublicKey.default.toBase58(),programId:je.TOKEN_PROGRAM_ID.toBase58(),decimals:9,symbol:"SOL",name:"solana",logoURI:"https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"sega",extensions:{coingeckoId:"solana"}},Y={chainId:101,address:"So11111111111111111111111111111111111111112",programId:je.TOKEN_PROGRAM_ID.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"}};var Se=require("@solana/web3.js");var R=require("@solana/web3.js"),bt=require("@solana/spl-token");function He({pubkey:n,isSigner:e=!1,isWritable:t=!0}){return{pubkey:n,isWritable:t,isSigner:e}}var $n=[He({pubkey:bt.TOKEN_PROGRAM_ID,isWritable:!1}),He({pubkey:R.SystemProgram.programId,isWritable:!1}),He({pubkey:R.SYSVAR_RENT_PUBKEY,isWritable:!1})];function Tt({publicKey:n,transformSol:e}){let t=xt(n.toString());if(t instanceof R.PublicKey)return e&&t.equals(me)?$:t;if(e&&t.toString()===me.toBase58())return $;if(typeof t=="string"){if(t===R.PublicKey.default.toBase58())return R.PublicKey.default;try{return new R.PublicKey(t)}catch(r){throw new Error("invalid public key")}}throw new Error("invalid public key")}function xt(n){try{return new R.PublicKey(n)}catch(e){return n}}var Xn=new R.PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),Qn=new R.PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),er=new R.PublicKey("SysvarRent111111111111111111111111111111111"),tr=new R.PublicKey("SysvarC1ock11111111111111111111111111111111"),on=new R.PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),nr=new R.PublicKey("Sysvar1nstructions1111111111111111111111111"),rr=R.SystemProgram.programId,or=new R.PublicKey("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),ir=new R.PublicKey("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),sr=new R.PublicKey("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),ar=new R.PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),cr=new R.PublicKey("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),ur=new R.PublicKey("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),lr=new R.PublicKey("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),mr=new R.PublicKey("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),pr=new R.PublicKey("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),dr=new R.PublicKey("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),fr=new R.PublicKey("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),$=new R.PublicKey("So11111111111111111111111111111111111111112"),me=R.PublicKey.default;var Ie=class Ie{constructor({mint:e,decimals:t,symbol:r,name:o,skipMint:a=!1,isToken2022:s=!1}){if(e===me.toBase58()||e instanceof Se.PublicKey&&me.equals(e)){this.decimals=Y.decimals,this.symbol=Y.symbol,this.name=Y.name,this.mint=new Se.PublicKey(Y.address),this.isToken2022=!1;return}this.decimals=t,this.symbol=r||e.toString().substring(0,6),this.name=o||e.toString().substring(0,6),this.mint=a?Se.PublicKey.default:Tt({publicKey:e}),this.isToken2022=s}equals(e){return this===e?!0:this.mint.equals(e.mint)}};Ie.WSOL=new Ie(Z(E({},Y),{mint:Y.address}));var pe=Ie;var Be=class Be{constructor({decimals:e,symbol:t="UNKNOWN",name:r="UNKNOWN"}){this.decimals=e,this.symbol=t,this.name=r}equals(e){return this===e}};Be.SOL=new Be(yt);var ze=Be;var Pt=v(require("bn.js"));var Sr=new z(new Pt.default(100));var _r=W("Sega_price");var an=require("@solana/web3.js"),cn=v(require("bn.js"));var sn=new j.default(0),lo=new j.default(1),mo=new j.default(2),po=new j.default(3),fo=new j.default(5),rn=new j.default(10),go=new j.default(100),ho=new j.default(1e3),yo=new j.default(1e4);function Ue(n,e=1,t=[]){let r=[...n];if(e<=0)return t;for(;r.length;)t.push(r.splice(0,e));return t}var Lt=require("@solana/web3.js"),Rt=require("@solana/spl-token");var V=require("@solana/web3.js");var M={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"};var It=require("@solana/spl-token");var St=W("Sega_txUtil"),Bt=1644;function Ce(n){let e=[],t=[];return n.microLamports&&(e.push(V.ComputeBudgetProgram.setComputeUnitPrice({microLamports:n.microLamports})),t.push(M.SetComputeUnitPrice)),n.units&&(e.push(V.ComputeBudgetProgram.setComputeUnitLimit({units:n.units})),t.push(M.SetComputeUnitLimit)),{instructions:e,instructionTypes:t}}function ie(n,e){return x(this,null,function*(){var r,o;let t=e!=null?e:"confirmed";return(o=yield(r=n.getLatestBlockhash)==null?void 0:r.call(n,{commitment:t}))==null?void 0:o.blockhash})}function Le(n,e){return x(this,null,function*(){return n.getSignatureStatuses([e]),new Promise((t,r)=>{let o=setTimeout(r,6e4);n.onSignature(e,a=>{if(clearTimeout(o),!a.err){t("");return}r(Object.assign(a.err,{txId:e}))},"confirmed")})})}function ln(n,e){n.length<1&&St.logWithError(`no instructions provided: ${n.toString()}`),e.length<1&&St.logWithError(`no signers provided:, ${e.toString()}`);let t=new V.Transaction;t.recentBlockhash="11111111111111111111111111111111",t.feePayer=e[0],t.add(...n);try{return Buffer.from(t.serialize({verifySignatures:!1})).toString("base64").length<Bt}catch(r){return!1}}function Ct(n,e){let[t,r]=V.PublicKey.findProgramAddressSync(n,e);return{publicKey:t,nonce:r}}function de({instructions:n,payer:e,signers:t}){return ln(n,[e,...t])}function fe({instructions:n,payer:e,lookupTableAddressAccount:t,recentBlockhash:r=V.Keypair.generate().publicKey.toString()}){let a=new V.TransactionMessage({payerKey:e,recentBlockhash:r,instructions:n}).compileToV0Message(Object.values(t!=null?t:{}));try{return Buffer.from(new V.VersionedTransaction(a).serialize()).toString("base64").length<Bt}catch(s){return!1}}var mn=n=>Buffer.isBuffer(n)?n:n instanceof Uint8Array?Buffer.from(n.buffer,n.byteOffset,n.byteLength):Buffer.from(n),pn=n=>{let e=n.serialize({requireAllSignatures:!1,verifySignatures:!1});n instanceof V.VersionedTransaction&&(e=mn(e));try{return e instanceof Buffer?e.toString("base64"):Buffer.from(e).toString("base64")}catch(t){return e.toString("base64")}};function te(n){let e=[];return n.forEach(t=>{t instanceof V.Transaction&&(t.recentBlockhash||(t.recentBlockhash=It.TOKEN_PROGRAM_ID.toBase58()),t.feePayer||(t.feePayer=V.Keypair.generate().publicKey)),e.push(pn(t))}),console.log("simulate tx string:",e),e}function Re(n,e,t){return Ct([n.toBuffer(),(t!=null?t:Rt.TOKEN_PROGRAM_ID).toBuffer(),e.toBuffer()],new Lt.PublicKey("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"))}var J=require("@solana/web3.js"),Eo=new J.PublicKey("SegazTQwbYWknDZkJ6j2Kgvm5gw3MrHGKtWstZdoNKZ"),Mo=new J.PublicKey("Ajk8d9bERSaFdeoT1d8JUVfaDayrYLnAdgeB47TFMUaG"),Fo=new J.PublicKey("2HbjxVVKJ7Ct72Rcd8WK4VTqmwTXL5aAggkH1CHGFGmh"),dn=new J.PublicKey("auetiVUVJkRxvNPLYEvVnz8UJSqQ1VgoA83PcicHVD1"),fn=new J.PublicKey("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y"),gn=new J.PublicKey("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y");var vo={SERUM_MARKET:J.PublicKey.default,UTIL1216:J.PublicKey.default,CREATE_CPMM_POOL_PROGRAM:dn,CREATE_CPMM_POOL_AUTH:fn,CREATE_CPMM_POOL_FEE_ACC:gn};var hn=v(require("bn.js"));var ge=require("@solana/web3.js");function Ye(t){return x(this,arguments,function*({connection:n,address:e}){let r=yield lt(n,[...new Set(e.map(a=>a.toString()))].map(a=>new ge.PublicKey(a))),o={};for(let a=0;a<e.length;a++){let s=r[a],i=e[a];if(!s)continue;let m=new ge.AddressLookupTableAccount({key:i,state:ge.AddressLookupTableAccount.deserialize(s.data)});o[i.toString()]=m,_e[i.toString()]=m}return o})}var _e={};var C=require("@solana/web3.js"),_t=v(require("axios"));var Ne=2e3,Ke=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 x(this,null,function*(){var r;let e=(yield _t.default.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}=Ce(e);return this.instructions.unshift(...t),this.instructionTypes.unshift(...r),!0}return!1}addTipInstruction(e){var t;return e?(this.endInstructions.push(C.SystemProgram.transfer({fromPubkey:(t=e.feePayer)!=null?t:this.feePayer,toPubkey:new C.PublicKey(e.address),lamports:BigInt(e.amount.toString())})),this.endInstructionTypes.push(M.TransferTip),!0):!1}calComputeBudget(r){return x(this,arguments,function*({config:e,defaultIns:t}){try{let o=e||(yield this.getComputeBudgetConfig());if(this.addCustomComputeBudget(o))return;t&&this.instructions.unshift(...t)}catch(o){t&&this.instructions.unshift(...t)}})}addInstruction({instructions:e=[],endInstructions:t=[],signers:r=[],instructionTypes:o=[],endInstructionTypes:a=[],lookupTableAddress:s=[]}){return this.instructions.push(...e),this.endInstructions.push(...t),this.signers.push(...r),this.instructionTypes.push(...o),this.endInstructionTypes.push(...a),this.lookupTableAddress.push(...s.filter(i=>i!==C.PublicKey.default.toString())),this}versionBuild(r){return x(this,arguments,function*({txVersion:e,extInfo:t}){return e===0?yield this.buildV0(E({},t||{})):this.build(t)})}build(e){var r;let t=new C.Transaction;return this.allInstructions.length&&t.add(...this.allInstructions),t.feePayer=this.feePayer,(r=this.owner)!=null&&r.signer&&!this.signers.some(o=>o.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer),{builder:this,transaction:t,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:o=>x(this,null,function*(){var u;let{recentBlockHash:a,skipPreflight:s=!0,sendAndConfirm:i}=o||{},m=a!=null?a:yield ie(this.connection,this.blockhashCommitment);if(t.recentBlockhash=m,this.signers.length&&t.sign(...this.signers),te([t]),(u=this.owner)!=null&&u.isKeyPair)return{txId:i?yield(0,C.sendAndConfirmTransaction)(this.connection,t,this.signers.find(y=>y.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:s}):yield this.connection.sendRawTransaction(t.serialize(),{skipPreflight:s}),signedTx:t};if(this.signAllTransactions){let d=yield this.signAllTransactions([t]);if(this.signers.length)for(let y of d)try{y.sign(...this.signers)}catch(T){}return{txId:yield this.connection.sendRawTransaction(d[0].serialize(),{skipPreflight:s}),signedTx:d[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:e||{}}}buildMultiTx(e){var u;let{extraPreBuildData:t=[],extInfo:r}=e,{transaction:o}=this.build(r),a=t.filter(d=>d.transaction.instructions.length>0),s=[o,...a.map(d=>d.transaction)],i=[this.signers,...a.map(d=>d.signers)],m=[...this.instructionTypes,...a.map(d=>d.instructionTypes).flat()];return(u=this.owner)!=null&&u.signer&&i.forEach(d=>{d.some(y=>y.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),{builder:this,transactions:s,signers:i,instructionTypes:m,execute:d=>x(this,null,function*(){var I;let{sequentially:y,onTxUpdate:T,skipTxCount:h=0,recentBlockHash:c,skipPreflight:P=!0}=d||{},f=c!=null?c:yield ie(this.connection,this.blockhashCommitment);if((I=this.owner)!=null&&I.isKeyPair){if(y){let w=[],A=0;for(let p of s){if(++A,A<=h)continue;let l=yield(0,C.sendAndConfirmTransaction)(this.connection,p,this.signers.find(g=>g.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:P});w.push(l)}return{txIds:w,signedTxs:s}}return{txIds:yield yield Promise.all(s.map(w=>x(this,null,function*(){return w.recentBlockhash=f,yield this.connection.sendRawTransaction(w.serialize(),{skipPreflight:P})}))),signedTxs:s}}if(this.signAllTransactions){let w=s.map((p,l)=>(p.recentBlockhash=f,i[l].length&&p.sign(...i[l]),p));te(w);let A=yield this.signAllTransactions(w);if(y){let p=0,l=[],g=()=>x(this,null,function*(){if(!A[p])return;let S=yield this.connection.sendRawTransaction(A[p].serialize(),{skipPreflight:P});l.push({txId:S,status:"sent",signedTx:A[p]}),T==null||T([...l]),p++;let k=!1,B=null,_=null,D=L=>{B!==null&&clearInterval(B),_!==null&&this.connection.removeSignatureListener(_);let N=l.findIndex(O=>O.txId===S);if(N>-1){if(l[N].status==="error"||l[N].status==="success")return;l[N].status=L.err?"error":"success"}T==null||T([...l]),L.err||g()};this.loopMultiTxStatus&&(B=setInterval(()=>x(this,null,function*(){var L;if(k){clearInterval(B);return}try{let N=yield this.connection.getTransaction(S,{commitment:"confirmed",maxSupportedTransactionVersion:0});N&&(k=!0,clearInterval(B),D({err:((L=N.meta)==null?void 0:L.err)||null}),console.log("tx status from getTransaction:",S))}catch(N){k=!0,clearInterval(B),console.error("getTransaction timeout:",N,S)}}),Ne)),_=this.connection.onSignature(S,L=>{if(k){this.connection.removeSignatureListener(_);return}k=!0,D(L)},"confirmed"),this.connection.getSignatureStatus(S)});return yield g(),{txIds:l.map(S=>S.txId),signedTxs:A}}else{let p=[];for(let l=0;l<A.length;l+=1){let g=yield this.connection.sendRawTransaction(A[l].serialize(),{skipPreflight:P});p.push(g)}return{txIds:p,signedTxs:A}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:r||{}}}versionMultiBuild(o){return x(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 x(this,null,function*(){var P;let c=e||{},{lookupTableCache:t={},lookupTableAddress:r=[],forerunCreate:o,recentBlockhash:a}=c,s=ee(c,["lookupTableCache","lookupTableAddress","forerunCreate","recentBlockhash"]),i=E(E({},this.cluster==="devnet"?{}:_e),t),m=Array.from(new Set([...r,...this.lookupTableAddress])),u=[];for(let f of m)i[f]===void 0&&u.push(new C.PublicKey(f));let d=yield Ye({connection:this.connection,address:u});for(let[f,I]of Object.entries(d))i[f]=I;let y=o?C.PublicKey.default.toBase58():a!=null?a:yield ie(this.connection,this.blockhashCommitment),T=new C.TransactionMessage({payerKey:this.feePayer,recentBlockhash:y,instructions:[...this.allInstructions]}).compileToV0Message(Object.values(i));(P=this.owner)!=null&&P.signer&&!this.signers.some(f=>f.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer);let h=new C.VersionedTransaction(T);return h.sign(this.signers),{builder:this,transaction:h,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:f=>x(this,null,function*(){var A;let{skipPreflight:I=!0,sendAndConfirm:w}=f||{};if(te([h]),(A=this.owner)!=null&&A.isKeyPair){let p=yield this.connection.sendTransaction(h,{skipPreflight:I});return w&&(yield Le(this.connection,p)),{txId:p,signedTx:h}}if(this.signAllTransactions){let p=yield this.signAllTransactions([h]);if(this.signers.length)for(let l of p)try{l.sign(this.signers)}catch(g){}return{txId:yield this.connection.sendTransaction(p[0],{skipPreflight:I}),signedTx:p[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:s||{}}})}buildV0MultiTx(e){return x(this,null,function*(){var u;let{extraPreBuildData:t=[],buildProps:r}=e,{transaction:o}=yield this.buildV0(r),a=t.filter(d=>d.builder.instructions.length>0),s=[o,...a.map(d=>d.transaction)],i=[this.signers,...a.map(d=>d.signers)],m=[...this.instructionTypes,...a.map(d=>d.instructionTypes).flat()];return(u=this.owner)!=null&&u.signer&&i.forEach(d=>{d.some(y=>y.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),s.forEach((d,y)=>x(this,null,function*(){d.sign(i[y])})),{builder:this,transactions:s,signers:i,instructionTypes:m,buildProps:r,execute:d=>x(this,null,function*(){var P;let{sequentially:y,onTxUpdate:T,recentBlockHash:h,skipPreflight:c=!0}=d||{};if(h&&s.forEach(f=>f.message.recentBlockhash=h),te(s),(P=this.owner)!=null&&P.isKeyPair){if(y){let f=[];for(let I of s){let w=yield this.connection.sendTransaction(I,{skipPreflight:c});yield Le(this.connection,w),f.push(w)}return{txIds:f,signedTxs:s}}return{txIds:yield Promise.all(s.map(f=>x(this,null,function*(){return yield this.connection.sendTransaction(f,{skipPreflight:c})}))),signedTxs:s}}if(this.signAllTransactions){let f=yield this.signAllTransactions(s);if(y){let I=0,w=[],A=()=>x(this,null,function*(){if(!f[I])return;let p=yield this.connection.sendTransaction(f[I],{skipPreflight:c});w.push({txId:p,status:"sent",signedTx:f[I]}),T==null||T([...w]),I++;let l=!1,g=null,S=null,k=B=>{g!==null&&clearInterval(g),S!==null&&this.connection.removeSignatureListener(S);let _=w.findIndex(D=>D.txId===p);if(_>-1){if(w[_].status==="error"||w[_].status==="success")return;w[_].status=B.err?"error":"success"}T==null||T([...w]),B.err||A()};this.loopMultiTxStatus&&(g=setInterval(()=>x(this,null,function*(){var B;if(l){clearInterval(g);return}try{let _=yield this.connection.getTransaction(p,{commitment:"confirmed",maxSupportedTransactionVersion:0});_&&(l=!0,clearInterval(g),k({err:((B=_.meta)==null?void 0:B.err)||null}),console.log("tx status from getTransaction:",p))}catch(_){l=!0,clearInterval(g),console.error("getTransaction timeout:",_,p)}}),Ne)),S=this.connection.onSignature(p,B=>{if(l){this.connection.removeSignatureListener(S);return}l=!0,k(B)},"confirmed"),this.connection.getSignatureStatus(p)});return A(),{txIds:[],signedTxs:f}}else{let I=[];for(let w=0;w<f.length;w+=1){let A=yield this.connection.sendTransaction(f[w],{skipPreflight:c});I.push(A)}return{txIds:I,signedTxs:f}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:r||{}}})}sizeCheckBuild(e){return x(this,null,function*(){var T;let y=e||{},{splitIns:t=[],computeBudgetConfig:r}=y,o=ee(y,["splitIns","computeBudgetConfig"]),a=r?Ce(r):{instructions:[],instructionTypes:[]},s=this.signers.reduce((h,c)=>Z(E({},h),{[c.publicKey.toBase58()]:c}),{}),i=[],m=[],u=[],d=0;if(this.allInstructions.forEach(h=>{let c=[...u,h],P=r?[...a.instructions,...c]:c,I=[...new Set(c.map(w=>w.keys.filter(A=>A.isSigner).map(A=>A.pubkey.toString())).flat()).values()].map(w=>new C.PublicKey(w));if(h!==t[d]&&u.length<12&&(de({instructions:P,payer:this.feePayer,signers:I})||de({instructions:c,payer:this.feePayer,signers:I})))u.push(h);else{if(u.length===0)throw Error("item ins too big");d+=h===t[d]?1:0,de({instructions:r?[...a.instructions,...u]:[...u],payer:this.feePayer,signers:I})?i.push(new C.Transaction().add(...a.instructions,...u)):i.push(new C.Transaction().add(...u)),m.push(Array.from(new Set(u.map(w=>w.keys.filter(A=>A.isSigner).map(A=>A.pubkey.toString())).flat())).map(w=>s[w]).filter(w=>w!==void 0)),u=[h]}}),u.length>0){let c=[...new Set(u.map(P=>P.keys.filter(f=>f.isSigner).map(f=>f.pubkey.toString())).flat()).values()].map(P=>s[P]).filter(P=>P!==void 0);de({instructions:r?[...a.instructions,...u]:[...u],payer:this.feePayer,signers:c.map(P=>P.publicKey)})?i.push(new C.Transaction().add(...a.instructions,...u)):i.push(new C.Transaction().add(...u)),m.push(c)}return i.forEach(h=>h.feePayer=this.feePayer),(T=this.owner)!=null&&T.signer&&m.forEach(h=>{h.some(c=>c.publicKey.equals(this.owner.publicKey))||h.push(this.owner.signer)}),{builder:this,transactions:i,signers:m,instructionTypes:this.instructionTypes,execute:h=>x(this,null,function*(){var p;let{sequentially:c,onTxUpdate:P,skipTxCount:f=0,recentBlockHash:I,skipPreflight:w=!0}=h||{},A=I!=null?I:yield ie(this.connection,this.blockhashCommitment);if(i.forEach((l,g)=>x(this,null,function*(){l.recentBlockhash=A,m[g].length&&l.sign(...m[g])})),te(i),(p=this.owner)!=null&&p.isKeyPair){if(c){let l=0,g=[];for(let S of i){if(++l,l<=f){g.push("tx skipped");continue}let k=yield(0,C.sendAndConfirmTransaction)(this.connection,S,this.signers.find(B=>B.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:w});g.push(k)}return{txIds:g,signedTxs:i}}return{txIds:yield Promise.all(i.map(l=>x(this,null,function*(){return yield this.connection.sendRawTransaction(l.serialize(),{skipPreflight:w})}))),signedTxs:i}}if(this.signAllTransactions){let l=yield this.signAllTransactions(i.slice(f,i.length)),g=[...i.slice(0,f),...l];if(c){let S=0,k=[],B=()=>x(this,null,function*(){if(!g[S])return;S<f&&(k.push({txId:"",status:"success",signedTx:g[S]}),P==null||P([...k]),S++,B());let _=yield this.connection.sendRawTransaction(g[S].serialize(),{skipPreflight:w});k.push({txId:_,status:"sent",signedTx:g[S]}),P==null||P([...k]),S++;let D=!1,L=null,N=null,O=q=>{L!==null&&clearInterval(L),N!==null&&this.connection.removeSignatureListener(N);let F=k.findIndex(X=>X.txId===_);if(F>-1){if(k[F].status==="error"||k[F].status==="success")return;k[F].status=q.err?"error":"success"}P==null||P([...k]),q.err||B()};this.loopMultiTxStatus&&(L=setInterval(()=>x(this,null,function*(){var q;if(D){clearInterval(L);return}try{let F=yield this.connection.getTransaction(_,{commitment:"confirmed",maxSupportedTransactionVersion:0});F&&(D=!0,clearInterval(L),O({err:((q=F.meta)==null?void 0:q.err)||null}),console.log("tx status from getTransaction:",_))}catch(F){D=!0,clearInterval(L),console.error("getTransaction timeout:",F,_)}}),Ne)),N=this.connection.onSignature(_,q=>{if(D){this.connection.removeSignatureListener(N);return}D=!0,O(q)},"confirmed"),this.connection.getSignatureStatus(_)});return yield B(),{txIds:k.map(_=>_.txId),signedTxs:g}}else{let S=[];for(let k=0;k<g.length;k+=1){let B=yield this.connection.sendRawTransaction(g[k].serialize(),{skipPreflight:w});S.push(B)}return{txIds:S,signedTxs:g}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:o||{}}})}sizeCheckBuildV0(e){return x(this,null,function*(){var A;let w=e||{},{computeBudgetConfig:t,splitIns:r=[],lookupTableCache:o={},lookupTableAddress:a=[]}=w,s=ee(w,["computeBudgetConfig","splitIns","lookupTableCache","lookupTableAddress"]),i=E(E({},this.cluster==="devnet"?{}:_e),o),m=Array.from(new Set([...this.lookupTableAddress,...a])),u=[];for(let p of m)i[p]===void 0&&u.push(new C.PublicKey(p));let d=yield Ye({connection:this.connection,address:u});for(let[p,l]of Object.entries(d))i[p]=l;let y=t?Ce(t):{instructions:[],instructionTypes:[]},T=yield ie(this.connection,this.blockhashCommitment),h=this.signers.reduce((p,l)=>Z(E({},p),{[l.publicKey.toBase58()]:l}),{}),c=[],P=[],f=[],I=0;if(this.allInstructions.forEach(p=>{let l=[...f,p],g=t?[...y.instructions,...l]:l;if(p!==r[I]&&f.length<12&&(fe({instructions:g,payer:this.feePayer,lookupTableAddressAccount:i})||fe({instructions:l,payer:this.feePayer,lookupTableAddressAccount:i})))f.push(p);else{if(f.length===0)throw Error("item ins too big");I+=p===r[I]?1:0;let S={};for(let k of[...new Set(m)])i[k]!==void 0&&(S[k]=i[k]);if(t&&fe({instructions:[...y.instructions,...f],payer:this.feePayer,lookupTableAddressAccount:i,recentBlockhash:T})){let k=new C.TransactionMessage({payerKey:this.feePayer,recentBlockhash:T,instructions:[...y.instructions,...f]}).compileToV0Message(Object.values(i));c.push(new C.VersionedTransaction(k))}else{let k=new C.TransactionMessage({payerKey:this.feePayer,recentBlockhash:T,instructions:[...f]}).compileToV0Message(Object.values(i));c.push(new C.VersionedTransaction(k))}P.push(Array.from(new Set(f.map(k=>k.keys.filter(B=>B.isSigner).map(B=>B.pubkey.toString())).flat())).map(k=>h[k]).filter(k=>k!==void 0)),f=[p]}}),f.length>0){let l=[...new Set(f.map(g=>g.keys.filter(S=>S.isSigner).map(S=>S.pubkey.toString())).flat()).values()].map(g=>h[g]).filter(g=>g!==void 0);if(t&&fe({instructions:[...y.instructions,...f],payer:this.feePayer,lookupTableAddressAccount:i,recentBlockhash:T})){let g=new C.TransactionMessage({payerKey:this.feePayer,recentBlockhash:T,instructions:[...y.instructions,...f]}).compileToV0Message(Object.values(i));c.push(new C.VersionedTransaction(g))}else{let g=new C.TransactionMessage({payerKey:this.feePayer,recentBlockhash:T,instructions:[...f]}).compileToV0Message(Object.values(i));c.push(new C.VersionedTransaction(g))}P.push(l)}return(A=this.owner)!=null&&A.signer&&P.forEach(p=>{p.some(l=>l.publicKey.equals(this.owner.publicKey))||p.push(this.owner.signer)}),{builder:this,transactions:c,buildProps:e,signers:P,instructionTypes:this.instructionTypes,execute:p=>x(this,null,function*(){var _;let{sequentially:l,onTxUpdate:g,skipTxCount:S=0,recentBlockHash:k,skipPreflight:B=!0}=p||{};if(c.map((D,L)=>x(this,null,function*(){P[L].length&&D.sign(P[L]),k&&(D.message.recentBlockhash=k)})),te(c),(_=this.owner)!=null&&_.isKeyPair){if(l){let D=0,L=[];for(let N of c){if(++D,D<=S){console.log("skip tx: ",D),L.push("tx skipped");continue}let O=yield this.connection.sendTransaction(N,{skipPreflight:B});yield Le(this.connection,O),L.push(O)}return{txIds:L,signedTxs:c}}return{txIds:yield Promise.all(c.map(D=>x(this,null,function*(){return yield this.connection.sendTransaction(D,{skipPreflight:B})}))),signedTxs:c}}if(this.signAllTransactions){let D=yield this.signAllTransactions(c.slice(S,c.length)),L=[...c.slice(0,S),...D];if(l){let N=0,O=[],q=()=>x(this,null,function*(){if(!L[N])return;if(N<S){O.push({txId:"",status:"success",signedTx:L[N]}),g==null||g([...O]),N++,q();return}let F=yield this.connection.sendTransaction(L[N],{skipPreflight:B});O.push({txId:F,status:"sent",signedTx:L[N]}),g==null||g([...O]),N++;let X=!1,re=null,Pe=null,ot=Q=>{re!==null&&clearInterval(re),Pe!==null&&this.connection.removeSignatureListener(Pe);let H=O.findIndex(qt=>qt.txId===F);if(H>-1){if(O[H].status==="error"||O[H].status==="success")return;O[H].status=Q.err?"error":"success"}g==null||g([...O]),Q.err||q()};this.loopMultiTxStatus&&(re=setInterval(()=>x(this,null,function*(){var Q;if(X){clearInterval(re);return}try{let H=yield this.connection.getTransaction(F,{commitment:"confirmed",maxSupportedTransactionVersion:0});H&&(X=!0,clearInterval(re),ot({err:((Q=H.meta)==null?void 0:Q.err)||null}),console.log("tx status from getTransaction:",F))}catch(H){X=!0,clearInterval(re),console.error("getTransaction timeout:",H,F)}}),Ne)),Pe=this.connection.onSignature(F,Q=>{if(X){this.connection.removeSignatureListener(Pe);return}X=!0,ot(Q)},"confirmed"),this.connection.getSignatureStatus(F)});return q(),{txIds:[],signedTxs:L}}else{let N=[];for(let O=0;O<L.length;O+=1){let q=yield this.connection.sendTransaction(L[O],{skipPreflight:B});N.push(q)}return{txIds:N,signedTxs:L}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:s||{}}})}};var yn=require("@solana/web3.js");var K=require("@solana/spl-token");var Je=(...n)=>n.map(e=>{try{return typeof e=="object"?JSON.stringify(e):e}catch(t){return e}}).join(", "),he=class{constructor({scope:e,moduleName:t}){this.disabled=!1;this.scope=e,this.logger=W(t)}createTxBuilder(e){return this.scope.checkOwner(),new Ke({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(Je(e))}logInfo(...e){this.logger.info(Je(e))}logAndCreateError(...e){let t=Je(e);throw new Error(t)}checkDisabled(){(this.disabled||!this.scope)&&this.logAndCreateError("module not working")}};var Fe=require("@solana/web3.js"),Wt=v(require("bn.js"));var U=require("@solana/spl-token");var Te=require("@solana/web3.js"),Et=v(require("bn.js"));var Mt=require("@solana/spl-token"),Ft=require("@noble/hashes/sha256");var Kt=require("@solana/web3.js"),De=v(require("bn.js"));var b=require("@solana/buffer-layout"),Ze=b.Layout,Nt=b.Structure;var $e=b.UInt;var Xe=b.blob;var Qe=class extends Ze{constructor(e,t,r){super(e,r),this.blob=Xe(e),this.signed=t}decode(e,t=0){let r=new De.default(this.blob.decode(e,t),10,"le");return this.signed?r.fromTwos(this.span*8).clone():r}encode(e,t,r=0){return typeof e=="number"&&(e=new De.default(e)),this.signed&&(e=e.toTwos(this.span*8)),this.blob.encode(e.toArrayLike(Buffer,"le",this.span),t,r)}};function Dt(n){return new $e(1,n)}function Oe(n){return new $e(4,n)}function Ee(n){return new Qe(8,!1,n)}var et=class extends Ze{constructor(e,t,r,o){super(e.span,o),this.layout=e,this.decoder=t,this.encoder=r}decode(e,t){return this.decoder(this.layout.decode(e,t))}encode(e,t,r){return this.layout.encode(this.encoder(e),t,r)}getSpan(e,t){return this.layout.getSpan(e,t)}};function ye(n){return new et(Xe(32),e=>new Kt.PublicKey(e),e=>e.toBuffer(),n)}var tt=class extends Nt{decode(e,t){return super.decode(e,t)}};function Ot(n,e,t){return new tt(n,e,t)}var be=Ot([ye("mint"),ye("owner"),Ee("amount"),Oe("delegateOption"),ye("delegate"),Dt("state"),Oe("isNativeOption"),Ee("isNative"),Ee("delegatedAmount"),Oe("closeAuthorityOption"),ye("closeAuthority")]);var Ji=W("Sega_Util");function vt({owner:n,solAccountResp:e,tokenAccountResp:t}){let r=[],o=[];for(let{pubkey:a,account:s}of t.value){let i=be.decode(s.data),{mint:m,amount:u}=i;r.push({publicKey:a,mint:m,amount:u,isAssociated:Re(n,m,s.owner).publicKey.equals(a),isNative:!1,programId:s.owner}),o.push({pubkey:a,accountInfo:i,programId:s.owner})}return e&&r.push({mint:Te.PublicKey.default,amount:new Et.default(String(e.lamports)),isNative:!0,programId:e.owner}),{tokenAccounts:r,tokenAccountRawInfos:o}}function Me({fromPublicKey:n,programId:e=Mt.TOKEN_PROGRAM_ID,assignSeed:t}){let r=t?btoa(t).slice(0,32):Te.Keypair.generate().publicKey.toBase58().slice(0,32);return{publicKey:bn(n,r,e),seed:r}}function bn(n,e,t){let r=Buffer.concat([n.toBuffer(),Buffer.from(e),t.toBuffer()]),o=(0,Ft.sha256)(r);return new Te.PublicKey(o)}function nt(n){let{mint:e,tokenAccount:t,owner:r,programId:o=U.TOKEN_PROGRAM_ID}=n;return(0,U.createInitializeAccountInstruction)(t,e,r,o)}function xe(n){let{tokenAccount:e,payer:t,multiSigners:r=[],owner:o,programId:a=U.TOKEN_PROGRAM_ID}=n;return(0,U.createCloseAccountInstruction)(e,t,o,r,a)}function rt(n){return x(this,null,function*(){let{connection:e,amount:t,commitment:r,payer:o,owner:a,skipCloseAccount:s}=n,i=yield e.getMinimumBalanceForRentExemption(be.span,r),m=G(t).add(new Wt.default(i)),u=Me({fromPublicKey:o,programId:U.TOKEN_PROGRAM_ID});return{addresses:{newAccount:u.publicKey},signers:[],instructions:[Fe.SystemProgram.createAccountWithSeed({fromPubkey:o,basePubkey:o,seed:u.seed,newAccountPubkey:u.publicKey,lamports:m.toNumber(),space:be.span,programId:U.TOKEN_PROGRAM_ID}),nt({mint:new Fe.PublicKey(Y.address),tokenAccount:u.publicKey,owner:a,programId:U.TOKEN_PROGRAM_ID})],instructionTypes:[M.CreateAccount,M.InitAccount],endInstructionTypes:s?[]:[M.CloseAccount],endInstructions:s?[]:[xe({tokenAccount:u.publicKey,payer:o,owner:a})]}})}function Vt({source:n,destination:e,owner:t,amount:r,multiSigners:o=[],tokenProgram:a=U.TOKEN_PROGRAM_ID}){return(0,U.createTransferInstruction)(n,e,t,BigInt(String(r)),o,a)}var ve=class extends he{constructor(t){super(t);this._tokenAccounts=[];this._tokenAccountRawInfos=[];this._accountListener=[];this._clientOwnedToken=!1;this._notSubscribeAccountChange=!1;this._accountFetchTime=0;let{tokenAccounts:r,tokenAccountRawInfos:o,notSubscribeAccountChange:a}=t;this._tokenAccounts=r||[],this._tokenAccountRawInfos=o||[],this._notSubscribeAccountChange=a!=null?a:!0,this._clientOwnedToken=!!(r||o)}get tokenAccounts(){return this._tokenAccounts}get tokenAccountRawInfos(){return this._tokenAccountRawInfos}set notSubscribeAccountChange(t){this._notSubscribeAccountChange=t}updateTokenAccount({tokenAccounts:t,tokenAccountRawInfos:r}){return t&&(this._tokenAccounts=t),r&&(this._tokenAccountRawInfos=r),this._accountChangeListenerId&&this.scope.connection.removeAccountChangeListener(this._accountChangeListenerId),this._accountChangeListenerId=void 0,this._clientOwnedToken=!0,this}addAccountChangeListener(t){return this._accountListener.push(t),this}removeAccountChangeListener(t){return this._accountListener=this._accountListener.filter(r=>r!==t),this}getAssociatedTokenAccount(t,r){return Re(this.scope.ownerPubKey,t,r).publicKey}resetTokenAccounts(){this._clientOwnedToken||(this._tokenAccounts=[],this._tokenAccountRawInfos=[])}fetchWalletTokenAccounts(t){return x(this,null,function*(){if(this._clientOwnedToken||!(t!=null&&t.forceUpdate)&&this._tokenAccounts.length&&Date.now()-this._accountFetchTime<(this._notSubscribeAccountChange?1e3*5:1e3*60*3))return{tokenAccounts:this._tokenAccounts,tokenAccountRawInfos:this._tokenAccountRawInfos};this.scope.checkOwner();let o=E(E({},{}),t),[a,s,i]=yield Promise.all([this.scope.connection.getAccountInfo(this.scope.ownerPubKey,o.commitment),this.scope.connection.getTokenAccountsByOwner(this.scope.ownerPubKey,{programId:K.TOKEN_PROGRAM_ID},o.commitment),this.scope.connection.getTokenAccountsByOwner(this.scope.ownerPubKey,{programId:K.TOKEN_2022_PROGRAM_ID},o.commitment)]),{tokenAccounts:m,tokenAccountRawInfos:u}=vt({owner:this.scope.ownerPubKey,solAccountResp:a,tokenAccountResp:{context:s.context,value:[...s.value,...i.value]}});return this._tokenAccounts=m,this._tokenAccountRawInfos=u,this._accountFetchTime=Date.now(),this._notSubscribeAccountChange||(this._accountChangeListenerId&&this.scope.connection.removeAccountChangeListener(this._accountChangeListenerId),this._accountChangeListenerId=this.scope.connection.onAccountChange(this.scope.ownerPubKey,()=>{this.fetchWalletTokenAccounts({forceUpdate:!0}),this._accountListener.forEach(d=>d({tokenAccounts:this._tokenAccounts,tokenAccountRawInfos:this._tokenAccountRawInfos}))},{commitment:t==null?void 0:t.commitment})),{tokenAccounts:m,tokenAccountRawInfos:u}})}clearAccountChangeCkb(){this._accountChangeListenerId!==void 0&&this.scope.connection.removeAccountChangeListener(this._accountChangeListenerId)}getCreatedTokenAccount(a){return x(this,arguments,function*({mint:t,programId:r=K.TOKEN_PROGRAM_ID,associatedOnly:o=!0}){yield this.fetchWalletTokenAccounts();let s=this._tokenAccounts.filter(({mint:m})=>m==null?void 0:m.equals(t)).sort((m,u)=>m.amount.lt(u.amount)?1:-1),i=this.getAssociatedTokenAccount(t,r);for(let m of s){let{publicKey:u}=m;if(u&&(!o||o&&i.equals(u)))return u}})}getOrCreateTokenAccount(t){return x(this,null,function*(){var P,f,I,w;yield this.fetchWalletTokenAccounts();let{mint:r,createInfo:o,associatedOnly:a,owner:s,notUseTokenAccount:i=!1,skipCloseAccount:m=!1,checkCreateATAOwner:u=!1,assignSeed:d}=t,y=new ne.PublicKey(t.tokenProgram||K.TOKEN_PROGRAM_ID),T=this.getAssociatedTokenAccount(r,new ne.PublicKey(y)),h=(i?[]:this.tokenAccountRawInfos).filter(A=>A.accountInfo.mint.equals(r)&&(!a||A.pubkey.equals(T))).sort((A,p)=>A.accountInfo.amount.lt(p.accountInfo.amount)?1:-1);if(o===void 0||h.length>0)return h.length>0?{account:h[0].pubkey}:{};let c={instructions:[],endInstructions:[],signers:[],instructionTypes:[],endInstructionTypes:[]};if(a){let A=(0,K.createAssociatedTokenAccountInstruction)(s,T,s,r,y),p=this.tokenAccountRawInfos.find(l=>l.pubkey.equals(T));if(u){let l=yield this.scope.connection.getAccountInfo(T);if(l===null)(P=c.instructions)==null||P.push(A),c.instructionTypes.push(M.CreateATA);else if(!(l.owner.equals(y)&&K.AccountLayout.decode(l.data).mint.equals(r)&&K.AccountLayout.decode(l.data).owner.equals(s)))throw Error(`create ata check error -> mint: ${r.toString()}, ata: ${T.toString()}`)}else p===void 0&&(c.instructions.push(A),c.instructionTypes.push(M.CreateATA));if(r.equals($)&&o.amount){let l=yield rt({connection:this.scope.connection,owner:this.scope.ownerPubKey,payer:o.payer||this.scope.ownerPubKey,amount:(f=o.amount)!=null?f:0,skipCloseAccount:m});c.instructions.push(...l.instructions||[]),c.endInstructions.push(...l.endInstructions||[]),c.instructionTypes.push(...l.instructionTypes||[]),c.endInstructionTypes.push(...l.endInstructionTypes||[]),o.amount&&(c.instructions.push(Vt({source:l.addresses.newAccount,destination:T,owner:this.scope.ownerPubKey,amount:o.amount,tokenProgram:K.TOKEN_PROGRAM_ID})),c.instructionTypes.push(M.TransferAmount))}return!m&&p===void 0&&(c.endInstructions.push(xe({owner:s,payer:o.payer||s,tokenAccount:T,programId:y})),c.endInstructionTypes.push(M.CloseAccount)),{account:T,instructionParams:c}}else{let A=Me({fromPublicKey:s,programId:y,assignSeed:d}),p=yield this.scope.connection.getMinimumBalanceForRentExemption(K.AccountLayout.span),l=ne.SystemProgram.createAccountWithSeed({fromPubkey:s,basePubkey:s,seed:A.seed,newAccountPubkey:A.publicKey,lamports:p+Number((w=(I=o.amount)==null?void 0:I.toString())!=null?w:0),space:K.AccountLayout.span,programId:y});return c.instructions.push(l,nt({mint:r,tokenAccount:A.publicKey,owner:this.scope.ownerPubKey,programId:y})),c.instructionTypes.push(M.CreateAccount),c.instructionTypes.push(M.InitAccount),m||(c.endInstructions.push(xe({owner:s,payer:o.payer||s,tokenAccount:A.publicKey,programId:y})),c.endInstructionTypes.push(M.CloseAccount)),{account:A.publicKey,instructionParams:c}}})}checkOrCreateAta(a){return x(this,arguments,function*({mint:t,programId:r=K.TOKEN_PROGRAM_ID,autoUnwrapWSOLToSOL:o}){var u;yield this.fetchWalletTokenAccounts();let s=(u=this.scope.account.tokenAccounts.find(({mint:d})=>(d==null?void 0:d.toBase58())===t.toBase58()))==null?void 0:u.publicKey,i=this.scope.ownerPubKey,m={};if(!s){let d=this.getAssociatedTokenAccount(t,r),y=yield(0,K.createAssociatedTokenAccountInstruction)(i,d,i,t,r);m.instructions=[y],m.instructionTypes=[M.CreateATA],s=d}return o&&$.toBase58()===t.toBase58()&&(m.endInstructions=[xe({owner:i,payer:i,tokenAccount:s,programId:r})],m.endInstructionTypes=[M.CloseAccount]),{pubKey:s,newInstructions:m}})}handleTokenAccount(t){return x(this,null,function*(){let{side:r,amount:o,mint:a,programId:s=K.TOKEN_PROGRAM_ID,tokenAccount:i,payer:m=this.scope.ownerPubKey,bypassAssociatedCheck:u,skipCloseAccount:d,checkCreateATAOwner:y}=t,T=this.getAssociatedTokenAccount(a,s);if(new ne.PublicKey($).equals(a)){let h=yield rt({connection:this.scope.connection,owner:this.scope.ownerPubKey,payer:m,amount:o,skipCloseAccount:d});return E({tokenAccount:h.addresses.newAccount},h)}else if(!i||r==="out"&&!T.equals(i)&&!u){let h=[],c=(0,K.createAssociatedTokenAccountInstruction)(this.scope.ownerPubKey,T,this.scope.ownerPubKey,a,s);if(y){let P=yield this.scope.connection.getAccountInfo(T);if(P===null)h.push(c);else if(!(P.owner.equals(K.TOKEN_PROGRAM_ID)&&K.AccountLayout.decode(P.data).mint.equals(a)&&K.AccountLayout.decode(P.data).owner.equals(this.scope.ownerPubKey)))throw Error(`create ata check error -> mint: ${a.toString()}, ata: ${T.toString()}`)}else h.push(c);return{tokenAccount:T,instructions:h,instructionTypes:[M.CreateATA]}}return{tokenAccount:i}})}processTokenAccount(t){return x(this,null,function*(){let{mint:r,programId:o=K.TOKEN_PROGRAM_ID,amount:a,useSOLBalance:s,handleTokenAccount:i,feePayer:m}=t,u,d=this.createTxBuilder(m);if(r.equals(new ne.PublicKey($))&&s){let y=yield this.handleTokenAccount({side:"in",amount:a||0,mint:r,bypassAssociatedCheck:!0,programId:o}),{tokenAccount:h}=y,c=ee(y,["tokenAccount"]);u=h,d.addInstruction(c)}else if(u=yield this.getCreatedTokenAccount({mint:r,associatedOnly:!1,programId:o}),!u&&i){let T=yield this.scope.account.handleTokenAccount({side:"in",amount:0,mint:r,bypassAssociatedCheck:!0,programId:o}),{tokenAccount:h}=T,c=ee(T,["tokenAccount"]);u=h,d.addInstruction(c)}return E({tokenAccount:u},d.AllTxData)})}}; //# sourceMappingURL=account.js.map