UNPKG

@sega-so/sega-sdk

Version:

An SDK for building applications on top of SEGA.

2 lines 47.1 kB
var _t=Object.defineProperty,Rt=Object.defineProperties;var Nt=Object.getOwnPropertyDescriptors;var ye=Object.getOwnPropertySymbols;var et=Object.prototype.hasOwnProperty,tt=Object.prototype.propertyIsEnumerable;var Qe=(n,e,t)=>e in n?_t(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,K=(n,e)=>{for(var t in e||(e={}))et.call(e,t)&&Qe(n,t,e[t]);if(ye)for(var t of ye(e))tt.call(e,t)&&Qe(n,t,e[t]);return n},G=(n,e)=>Rt(n,Nt(e));var J=(n,e)=>{var t={};for(var r in n)et.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&ye)for(var r of ye(n))e.indexOf(r)<0&&tt.call(n,r)&&(t[r]=n[r]);return t};var T=(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())});import{PublicKey as Re,SystemProgram as Ln}from"@solana/web3.js";import{PublicKey as Dt}from"@solana/web3.js";import{get as nt,set as Kt}from"lodash";var Ne=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}},rt={},Ot={};function M(n){let e=nt(rt,n);if(!e){let t=nt(Ot,n);e=new Ne({name:n,logLevel:t}),Kt(rt,n,e)}return e}import{MINT_SIZE as Vn,TOKEN_PROGRAM_ID as qn,getTransferFeeConfig as Un,unpackMint as Gn}from"@solana/spl-token";var Ke=M("Sega_accountInfo_util");function ot(n,e,t){return T(this,null,function*(){let{batchRequest:r,commitment:o="confirmed",chunkCount:a=100}=K({batchRequest:!1},t),s=Oe(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=Oe(m,10);i=(yield(yield Promise.all(u.map(y=>T(this,null,function*(){return yield n._rpcBatchRequest(y)})))).flat()).map(y=>(y.error&&Ke.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${y.error.message}`),y.result.value.map(b=>{if(b){let{data:h,executable:c,lamports:x,owner:f,rentEpoch:S}=b;return h.length!==2&&h[1]!=="base64"&&Ke.logWithError("info must be base64 encoded, RPC_ERROR"),{data:Buffer.from(h[0],"base64"),executable:c,lamports:x,owner:new Dt(f),rentEpoch:S}}return null})))}else try{i=yield Promise.all(s.map(m=>n.getMultipleAccountsInfo(m,o)))}catch(m){m instanceof Error&&Ke.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${m.message}`)}return i.flat()})}import U from"bn.js";import Wo from"decimal.js";import Ut from"big.js";import ur from"bn.js";import Mt from"toformat";var Et=Mt,ne=Et;import Te from"big.js";import vt from"bn.js";import Wt from"decimal.js-light";import re from"bn.js";var it=9007199254740991;function F(n){let e=M("Sega_parseBigNumberish");if(n instanceof re)return n;if(typeof n=="string"){if(n.match(/^-?[0-9]+$/))return new re(n);e.logWithError(`invalid BigNumberish string: ${n}`)}return typeof n=="number"?(n%1&&e.logWithError(`BigNumberish number underflow: ${n}`),(n>=it||n<=-it)&&e.logWithError(`BigNumberish number overflow: ${n}`),new re(String(n))):typeof n=="bigint"?new re(n.toString()):(e.error(`invalid BigNumberish value: ${n}`),new re(0))}var be=M("module/fraction"),De=ne(Te),oe=ne(Wt),Vt={0:oe.ROUND_DOWN,1:oe.ROUND_HALF_UP,2:oe.ROUND_UP},qt={0:Te.roundDown,1:Te.roundHalfUp,2:Te.roundUp},V=class n{constructor(e,t=new vt(1)){this.numerator=F(e),this.denominator=F(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(F(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(F(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(F(e));return new n(this.numerator.mul(t.numerator),this.denominator.mul(t.denominator))}div(e){let t=e instanceof n?e:new n(F(e));return new n(this.numerator.mul(t.denominator),this.denominator.mul(t.numerator))}toSignificant(e,t={groupSeparator:""},r=1){Number.isInteger(e)||be.logWithError(`${e} is not an integer.`),e<=0&&be.logWithError(`${e} is not positive.`),oe.set({precision:e+1,rounding:Vt[r]});let o=new oe(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)||be.logWithError(`${e} is not an integer.`),e<0&&be.logWithError(`${e} is negative.`),De.DP=e,De.RM=qt[r]||1,new De(this.numerator.toString()).div(this.denominator.toString()).toFormat(e,t)}isZero(){return this.numerator.isZero()}};var br=M("Sega_amount"),Tr=ne(Ut);import{PublicKey as jt}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as st}from"@solana/spl-token";var at={chainId:101,address:jt.default.toBase58(),programId:st.toBase58(),decimals:9,symbol:"SOL",name:"solana",logoURI:"https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"sega",extensions:{coingeckoId:"solana"}},q={chainId:101,address:"So11111111111111111111111111111111111111112",programId:st.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 Ee}from"@solana/web3.js";import{PublicKey as _,SystemProgram as ct,SYSVAR_RENT_PUBKEY as Ht}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as zt}from"@solana/spl-token";function Me({pubkey:n,isSigner:e=!1,isWritable:t=!0}){return{pubkey:n,isWritable:t,isSigner:e}}var Br=[Me({pubkey:zt,isWritable:!1}),Me({pubkey:ct.programId,isWritable:!1}),Me({pubkey:Ht,isWritable:!1})];function ut({publicKey:n,transformSol:e}){let t=lt(n.toString());if(t instanceof _)return e&&t.equals(ie)?j:t;if(e&&t.toString()===ie.toBase58())return j;if(typeof t=="string"){if(t===_.default.toBase58())return _.default;try{return new _(t)}catch(r){throw new Error("invalid public key")}}throw new Error("invalid public key")}function lt(n){try{return new _(n)}catch(e){return n}}var Cr=new _("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),Lr=new _("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),_r=new _("SysvarRent111111111111111111111111111111111"),Rr=new _("SysvarC1ock11111111111111111111111111111111"),Yt=new _("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),Nr=new _("Sysvar1nstructions1111111111111111111111111"),Kr=ct.programId,Or=new _("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),Dr=new _("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),Mr=new _("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),Er=new _("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),Fr=new _("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),vr=new _("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),Wr=new _("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),Vr=new _("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),qr=new _("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),Ur=new _("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),Gr=new _("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),j=new _("So11111111111111111111111111111111111111112"),ie=_.default;var xe=class xe{constructor({mint:e,decimals:t,symbol:r,name:o,skipMint:a=!1,isToken2022:s=!1}){if(e===ie.toBase58()||e instanceof Ee&&ie.equals(e)){this.decimals=q.decimals,this.symbol=q.symbol,this.name=q.name,this.mint=new Ee(q.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?Ee.default:ut({publicKey:e}),this.isToken2022=s}equals(e){return this===e?!0:this.mint.equals(e.mint)}};xe.WSOL=new xe(G(K({},q),{mint:q.address}));var se=xe;var Pe=class Pe{constructor({decimals:e,symbol:t="UNKNOWN",name:r="UNKNOWN"}){this.decimals=e,this.symbol=t,this.name=r}equals(e){return this===e}};Pe.SOL=new Pe(at);var Fe=Pe;import Jt from"bn.js";var ro=new V(new Jt(100));var uo=M("Sega_price");import{PublicKey as Bo}from"@solana/web3.js";import Lo from"bn.js";var Zt=new U(0),Zo=new U(1),Xo=new U(2),$o=new U(3),Qo=new U(5),Gt=new U(10),ei=new U(100),ti=new U(1e3),ni=new U(1e4);function Oe(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 rn}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as on}from"@solana/spl-token";import{ComputeBudgetProgram as ft,Keypair as ht,PublicKey as Xt,Transaction as yt,TransactionMessage as $t,VersionedTransaction as bt}from"@solana/web3.js";var O={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 Qt}from"@solana/spl-token";var gt=M("Sega_txUtil"),Tt=1644;function we(n){let e=[],t=[];return n.microLamports&&(e.push(ft.setComputeUnitPrice({microLamports:n.microLamports})),t.push(O.SetComputeUnitPrice)),n.units&&(e.push(ft.setComputeUnitLimit({units:n.units})),t.push(O.SetComputeUnitLimit)),{instructions:e,instructionTypes:t}}function $(n,e){return T(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 Ae(n,e){return T(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 en(n,e){n.length<1&&gt.logWithError(`no instructions provided: ${n.toString()}`),e.length<1&&gt.logWithError(`no signers provided:, ${e.toString()}`);let t=new yt;t.recentBlockhash="11111111111111111111111111111111",t.feePayer=e[0],t.add(...n);try{return Buffer.from(t.serialize({verifySignatures:!1})).toString("base64").length<Tt}catch(r){return!1}}function xt(n,e){let[t,r]=Xt.findProgramAddressSync(n,e);return{publicKey:t,nonce:r}}function ae({instructions:n,payer:e,signers:t}){return en(n,[e,...t])}function ce({instructions:n,payer:e,lookupTableAddressAccount:t,recentBlockhash:r=ht.generate().publicKey.toString()}){let a=new $t({payerKey:e,recentBlockhash:r,instructions:n}).compileToV0Message(Object.values(t!=null?t:{}));try{return Buffer.from(new bt(a).serialize()).toString("base64").length<Tt}catch(s){return!1}}var tn=n=>Buffer.isBuffer(n)?n:n instanceof Uint8Array?Buffer.from(n.buffer,n.byteOffset,n.byteLength):Buffer.from(n),nn=n=>{let e=n.serialize({requireAllSignatures:!1,verifySignatures:!1});n instanceof bt&&(e=tn(e));try{return e instanceof Buffer?e.toString("base64"):Buffer.from(e).toString("base64")}catch(t){return e.toString("base64")}};function Z(n){let e=[];return n.forEach(t=>{t instanceof yt&&(t.recentBlockhash||(t.recentBlockhash=Qt.toBase58()),t.feePayer||(t.feePayer=ht.generate().publicKey)),e.push(nn(t))}),console.log("simulate tx string:",e),e}function ke(n,e,t){return xt([n.toBuffer(),(t!=null?t:on).toBuffer(),e.toBuffer()],new rn("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"))}import{PublicKey as v}from"@solana/web3.js";var Ii=new v("SegazTQwbYWknDZkJ6j2Kgvm5gw3MrHGKtWstZdoNKZ"),Bi=new v("Ajk8d9bERSaFdeoT1d8JUVfaDayrYLnAdgeB47TFMUaG"),Ci=new v("2HbjxVVKJ7Ct72Rcd8WK4VTqmwTXL5aAggkH1CHGFGmh"),sn=new v("TegaRdjn9Qeh9DfUU28X19aPPpJtj9gs8ntSYrR5H4K "),an=new v("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y"),cn=new v("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y"),Li=new v("SegaXNnoXYTZiqUt9Xn2XqGcL56b25yzXLuJSpadcMu"),_i=new v("2t1hV2YqnDCPuJZqr7Fy8oAygGwZE5Q9uaQzpLC1QryJ"),Ri=new v("BLxynZeHE123MmQgNJZiV1pwW4VYh46oZYyC66xwmtTY");var un={SERUM_MARKET:v.default,UTIL1216:v.default,CREATE_CPMM_POOL_PROGRAM:sn,CREATE_CPMM_POOL_AUTH:an,CREATE_CPMM_POOL_FEE_ACC:cn};import Oi from"bn.js";import{PublicKey as ln,AddressLookupTableAccount as Pt}from"@solana/web3.js";function ve(t){return T(this,arguments,function*({connection:n,address:e}){let r=yield ot(n,[...new Set(e.map(a=>a.toString()))].map(a=>new ln(a))),o={};for(let a=0;a<e.length;a++){let s=r[a],i=e[a];if(!s)continue;let m=new Pt({key:i,state:Pt.deserialize(s.data)});o[i.toString()]=m,Se[i.toString()]=m}return o})}var Se={};import{PublicKey as Q,sendAndConfirmTransaction as We,SystemProgram as mn,Transaction as ue,TransactionMessage as le,VersionedTransaction as me}from"@solana/web3.js";import pn from"axios";var Ie=2e3,Be=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 T(this,null,function*(){var r;let e=(yield pn.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}=we(e);return this.instructions.unshift(...t),this.instructionTypes.unshift(...r),!0}return!1}addTipInstruction(e){var t;return e?(this.endInstructions.push(mn.transfer({fromPubkey:(t=e.feePayer)!=null?t:this.feePayer,toPubkey:new Q(e.address),lamports:BigInt(e.amount.toString())})),this.endInstructionTypes.push(O.TransferTip),!0):!1}calComputeBudget(r){return T(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!==Q.default.toString())),this}versionBuild(r){return T(this,arguments,function*({txVersion:e,extInfo:t}){return e===0?yield this.buildV0(K({},t||{})):this.build(t)})}build(e){var r;let t=new ue;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=>T(this,null,function*(){var u;let{recentBlockHash:a,skipPreflight:s=!0,sendAndConfirm:i}=o||{},m=a!=null?a:yield $(this.connection,this.blockhashCommitment);if(t.recentBlockhash=m,this.signers.length&&t.sign(...this.signers),Z([t]),(u=this.owner)!=null&&u.isKeyPair)return{txId:i?yield We(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(b){}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=>T(this,null,function*(){var S;let{sequentially:y,onTxUpdate:b,skipTxCount:h=0,recentBlockHash:c,skipPreflight:x=!0}=d||{},f=c!=null?c:yield $(this.connection,this.blockhashCommitment);if((S=this.owner)!=null&&S.isKeyPair){if(y){let P=[],w=0;for(let p of s){if(++w,w<=h)continue;let l=yield We(this.connection,p,this.signers.find(g=>g.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:x});P.push(l)}return{txIds:P,signedTxs:s}}return{txIds:yield yield Promise.all(s.map(P=>T(this,null,function*(){return P.recentBlockhash=f,yield this.connection.sendRawTransaction(P.serialize(),{skipPreflight:x})}))),signedTxs:s}}if(this.signAllTransactions){let P=s.map((p,l)=>(p.recentBlockhash=f,i[l].length&&p.sign(...i[l]),p));Z(P);let w=yield this.signAllTransactions(P);if(y){let p=0,l=[],g=()=>T(this,null,function*(){if(!w[p])return;let k=yield this.connection.sendRawTransaction(w[p].serialize(),{skipPreflight:x});l.push({txId:k,status:"sent",signedTx:w[p]}),b==null||b([...l]),p++;let A=!1,I=null,C=null,R=B=>{I!==null&&clearInterval(I),C!==null&&this.connection.removeSignatureListener(C);let L=l.findIndex(N=>N.txId===k);if(L>-1){if(l[L].status==="error"||l[L].status==="success")return;l[L].status=B.err?"error":"success"}b==null||b([...l]),B.err||g()};this.loopMultiTxStatus&&(I=setInterval(()=>T(this,null,function*(){var B;if(A){clearInterval(I);return}try{let L=yield this.connection.getTransaction(k,{commitment:"confirmed",maxSupportedTransactionVersion:0});L&&(A=!0,clearInterval(I),R({err:((B=L.meta)==null?void 0:B.err)||null}),console.log("tx status from getTransaction:",k))}catch(L){A=!0,clearInterval(I),console.error("getTransaction timeout:",L,k)}}),Ie)),C=this.connection.onSignature(k,B=>{if(A){this.connection.removeSignatureListener(C);return}A=!0,R(B)},"confirmed"),this.connection.getSignatureStatus(k)});return yield g(),{txIds:l.map(k=>k.txId),signedTxs:w}}else{let p=[];for(let l=0;l<w.length;l+=1){let g=yield this.connection.sendRawTransaction(w[l].serialize(),{skipPreflight:x});p.push(g)}return{txIds:p,signedTxs:w}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:r||{}}}versionMultiBuild(o){return T(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 T(this,null,function*(){var x;let c=e||{},{lookupTableCache:t={},lookupTableAddress:r=[],forerunCreate:o,recentBlockhash:a}=c,s=J(c,["lookupTableCache","lookupTableAddress","forerunCreate","recentBlockhash"]),i=K(K({},this.cluster==="devnet"?{}:Se),t),m=Array.from(new Set([...r,...this.lookupTableAddress])),u=[];for(let f of m)i[f]===void 0&&u.push(new Q(f));let d=yield ve({connection:this.connection,address:u});for(let[f,S]of Object.entries(d))i[f]=S;let y=o?Q.default.toBase58():a!=null?a:yield $(this.connection,this.blockhashCommitment),b=new le({payerKey:this.feePayer,recentBlockhash:y,instructions:[...this.allInstructions]}).compileToV0Message(Object.values(i));(x=this.owner)!=null&&x.signer&&!this.signers.some(f=>f.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer);let h=new me(b);return h.sign(this.signers),{builder:this,transaction:h,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:f=>T(this,null,function*(){var w;let{skipPreflight:S=!0,sendAndConfirm:P}=f||{};if(Z([h]),(w=this.owner)!=null&&w.isKeyPair){let p=yield this.connection.sendTransaction(h,{skipPreflight:S});return P&&(yield Ae(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:S}),signedTx:p[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:s||{}}})}buildV0MultiTx(e){return T(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)=>T(this,null,function*(){d.sign(i[y])})),{builder:this,transactions:s,signers:i,instructionTypes:m,buildProps:r,execute:d=>T(this,null,function*(){var x;let{sequentially:y,onTxUpdate:b,recentBlockHash:h,skipPreflight:c=!0}=d||{};if(h&&s.forEach(f=>f.message.recentBlockhash=h),Z(s),(x=this.owner)!=null&&x.isKeyPair){if(y){let f=[];for(let S of s){let P=yield this.connection.sendTransaction(S,{skipPreflight:c});yield Ae(this.connection,P),f.push(P)}return{txIds:f,signedTxs:s}}return{txIds:yield Promise.all(s.map(f=>T(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 S=0,P=[],w=()=>T(this,null,function*(){if(!f[S])return;let p=yield this.connection.sendTransaction(f[S],{skipPreflight:c});P.push({txId:p,status:"sent",signedTx:f[S]}),b==null||b([...P]),S++;let l=!1,g=null,k=null,A=I=>{g!==null&&clearInterval(g),k!==null&&this.connection.removeSignatureListener(k);let C=P.findIndex(R=>R.txId===p);if(C>-1){if(P[C].status==="error"||P[C].status==="success")return;P[C].status=I.err?"error":"success"}b==null||b([...P]),I.err||w()};this.loopMultiTxStatus&&(g=setInterval(()=>T(this,null,function*(){var I;if(l){clearInterval(g);return}try{let C=yield this.connection.getTransaction(p,{commitment:"confirmed",maxSupportedTransactionVersion:0});C&&(l=!0,clearInterval(g),A({err:((I=C.meta)==null?void 0:I.err)||null}),console.log("tx status from getTransaction:",p))}catch(C){l=!0,clearInterval(g),console.error("getTransaction timeout:",C,p)}}),Ie)),k=this.connection.onSignature(p,I=>{if(l){this.connection.removeSignatureListener(k);return}l=!0,A(I)},"confirmed"),this.connection.getSignatureStatus(p)});return w(),{txIds:[],signedTxs:f}}else{let S=[];for(let P=0;P<f.length;P+=1){let w=yield this.connection.sendTransaction(f[P],{skipPreflight:c});S.push(w)}return{txIds:S,signedTxs:f}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:r||{}}})}sizeCheckBuild(e){return T(this,null,function*(){var b;let y=e||{},{splitIns:t=[],computeBudgetConfig:r}=y,o=J(y,["splitIns","computeBudgetConfig"]),a=r?we(r):{instructions:[],instructionTypes:[]},s=this.signers.reduce((h,c)=>G(K({},h),{[c.publicKey.toBase58()]:c}),{}),i=[],m=[],u=[],d=0;if(this.allInstructions.forEach(h=>{let c=[...u,h],x=r?[...a.instructions,...c]:c,S=[...new Set(c.map(P=>P.keys.filter(w=>w.isSigner).map(w=>w.pubkey.toString())).flat()).values()].map(P=>new Q(P));if(h!==t[d]&&u.length<12&&(ae({instructions:x,payer:this.feePayer,signers:S})||ae({instructions:c,payer:this.feePayer,signers:S})))u.push(h);else{if(u.length===0)throw Error("item ins too big");d+=h===t[d]?1:0,ae({instructions:r?[...a.instructions,...u]:[...u],payer:this.feePayer,signers:S})?i.push(new ue().add(...a.instructions,...u)):i.push(new ue().add(...u)),m.push(Array.from(new Set(u.map(P=>P.keys.filter(w=>w.isSigner).map(w=>w.pubkey.toString())).flat())).map(P=>s[P]).filter(P=>P!==void 0)),u=[h]}}),u.length>0){let c=[...new Set(u.map(x=>x.keys.filter(f=>f.isSigner).map(f=>f.pubkey.toString())).flat()).values()].map(x=>s[x]).filter(x=>x!==void 0);ae({instructions:r?[...a.instructions,...u]:[...u],payer:this.feePayer,signers:c.map(x=>x.publicKey)})?i.push(new ue().add(...a.instructions,...u)):i.push(new ue().add(...u)),m.push(c)}return i.forEach(h=>h.feePayer=this.feePayer),(b=this.owner)!=null&&b.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=>T(this,null,function*(){var p;let{sequentially:c,onTxUpdate:x,skipTxCount:f=0,recentBlockHash:S,skipPreflight:P=!0}=h||{},w=S!=null?S:yield $(this.connection,this.blockhashCommitment);if(i.forEach((l,g)=>T(this,null,function*(){l.recentBlockhash=w,m[g].length&&l.sign(...m[g])})),Z(i),(p=this.owner)!=null&&p.isKeyPair){if(c){let l=0,g=[];for(let k of i){if(++l,l<=f){g.push("tx skipped");continue}let A=yield We(this.connection,k,this.signers.find(I=>I.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:P});g.push(A)}return{txIds:g,signedTxs:i}}return{txIds:yield Promise.all(i.map(l=>T(this,null,function*(){return yield this.connection.sendRawTransaction(l.serialize(),{skipPreflight:P})}))),signedTxs:i}}if(this.signAllTransactions){let l=yield this.signAllTransactions(i.slice(f,i.length)),g=[...i.slice(0,f),...l];if(c){let k=0,A=[],I=()=>T(this,null,function*(){if(!g[k])return;k<f&&(A.push({txId:"",status:"success",signedTx:g[k]}),x==null||x([...A]),k++,I());let C=yield this.connection.sendRawTransaction(g[k].serialize(),{skipPreflight:P});A.push({txId:C,status:"sent",signedTx:g[k]}),x==null||x([...A]),k++;let R=!1,B=null,L=null,N=E=>{B!==null&&clearInterval(B),L!==null&&this.connection.removeSignatureListener(L);let D=A.findIndex(z=>z.txId===C);if(D>-1){if(A[D].status==="error"||A[D].status==="success")return;A[D].status=E.err?"error":"success"}x==null||x([...A]),E.err||I()};this.loopMultiTxStatus&&(B=setInterval(()=>T(this,null,function*(){var E;if(R){clearInterval(B);return}try{let D=yield this.connection.getTransaction(C,{commitment:"confirmed",maxSupportedTransactionVersion:0});D&&(R=!0,clearInterval(B),N({err:((E=D.meta)==null?void 0:E.err)||null}),console.log("tx status from getTransaction:",C))}catch(D){R=!0,clearInterval(B),console.error("getTransaction timeout:",D,C)}}),Ie)),L=this.connection.onSignature(C,E=>{if(R){this.connection.removeSignatureListener(L);return}R=!0,N(E)},"confirmed"),this.connection.getSignatureStatus(C)});return yield I(),{txIds:A.map(C=>C.txId),signedTxs:g}}else{let k=[];for(let A=0;A<g.length;A+=1){let I=yield this.connection.sendRawTransaction(g[A].serialize(),{skipPreflight:P});k.push(I)}return{txIds:k,signedTxs:g}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:o||{}}})}sizeCheckBuildV0(e){return T(this,null,function*(){var w;let P=e||{},{computeBudgetConfig:t,splitIns:r=[],lookupTableCache:o={},lookupTableAddress:a=[]}=P,s=J(P,["computeBudgetConfig","splitIns","lookupTableCache","lookupTableAddress"]),i=K(K({},this.cluster==="devnet"?{}:Se),o),m=Array.from(new Set([...this.lookupTableAddress,...a])),u=[];for(let p of m)i[p]===void 0&&u.push(new Q(p));let d=yield ve({connection:this.connection,address:u});for(let[p,l]of Object.entries(d))i[p]=l;let y=t?we(t):{instructions:[],instructionTypes:[]},b=yield $(this.connection,this.blockhashCommitment),h=this.signers.reduce((p,l)=>G(K({},p),{[l.publicKey.toBase58()]:l}),{}),c=[],x=[],f=[],S=0;if(this.allInstructions.forEach(p=>{let l=[...f,p],g=t?[...y.instructions,...l]:l;if(p!==r[S]&&f.length<12&&(ce({instructions:g,payer:this.feePayer,lookupTableAddressAccount:i})||ce({instructions:l,payer:this.feePayer,lookupTableAddressAccount:i})))f.push(p);else{if(f.length===0)throw Error("item ins too big");S+=p===r[S]?1:0;let k={};for(let A of[...new Set(m)])i[A]!==void 0&&(k[A]=i[A]);if(t&&ce({instructions:[...y.instructions,...f],payer:this.feePayer,lookupTableAddressAccount:i,recentBlockhash:b})){let A=new le({payerKey:this.feePayer,recentBlockhash:b,instructions:[...y.instructions,...f]}).compileToV0Message(Object.values(i));c.push(new me(A))}else{let A=new le({payerKey:this.feePayer,recentBlockhash:b,instructions:[...f]}).compileToV0Message(Object.values(i));c.push(new me(A))}x.push(Array.from(new Set(f.map(A=>A.keys.filter(I=>I.isSigner).map(I=>I.pubkey.toString())).flat())).map(A=>h[A]).filter(A=>A!==void 0)),f=[p]}}),f.length>0){let l=[...new Set(f.map(g=>g.keys.filter(k=>k.isSigner).map(k=>k.pubkey.toString())).flat()).values()].map(g=>h[g]).filter(g=>g!==void 0);if(t&&ce({instructions:[...y.instructions,...f],payer:this.feePayer,lookupTableAddressAccount:i,recentBlockhash:b})){let g=new le({payerKey:this.feePayer,recentBlockhash:b,instructions:[...y.instructions,...f]}).compileToV0Message(Object.values(i));c.push(new me(g))}else{let g=new le({payerKey:this.feePayer,recentBlockhash:b,instructions:[...f]}).compileToV0Message(Object.values(i));c.push(new me(g))}x.push(l)}return(w=this.owner)!=null&&w.signer&&x.forEach(p=>{p.some(l=>l.publicKey.equals(this.owner.publicKey))||p.push(this.owner.signer)}),{builder:this,transactions:c,buildProps:e,signers:x,instructionTypes:this.instructionTypes,execute:p=>T(this,null,function*(){var C;let{sequentially:l,onTxUpdate:g,skipTxCount:k=0,recentBlockHash:A,skipPreflight:I=!0}=p||{};if(c.map((R,B)=>T(this,null,function*(){x[B].length&&R.sign(x[B]),A&&(R.message.recentBlockhash=A)})),Z(c),(C=this.owner)!=null&&C.isKeyPair){if(l){let R=0,B=[];for(let L of c){if(++R,R<=k){console.log("skip tx: ",R),B.push("tx skipped");continue}let N=yield this.connection.sendTransaction(L,{skipPreflight:I});yield Ae(this.connection,N),B.push(N)}return{txIds:B,signedTxs:c}}return{txIds:yield Promise.all(c.map(R=>T(this,null,function*(){return yield this.connection.sendTransaction(R,{skipPreflight:I})}))),signedTxs:c}}if(this.signAllTransactions){let R=yield this.signAllTransactions(c.slice(k,c.length)),B=[...c.slice(0,k),...R];if(l){let L=0,N=[],E=()=>T(this,null,function*(){if(!B[L])return;if(L<k){N.push({txId:"",status:"success",signedTx:B[L]}),g==null||g([...N]),L++,E();return}let D=yield this.connection.sendTransaction(B[L],{skipPreflight:I});N.push({txId:D,status:"sent",signedTx:B[L]}),g==null||g([...N]),L++;let z=!1,X=null,he=null,$e=Y=>{X!==null&&clearInterval(X),he!==null&&this.connection.removeSignatureListener(he);let W=N.findIndex(Lt=>Lt.txId===D);if(W>-1){if(N[W].status==="error"||N[W].status==="success")return;N[W].status=Y.err?"error":"success"}g==null||g([...N]),Y.err||E()};this.loopMultiTxStatus&&(X=setInterval(()=>T(this,null,function*(){var Y;if(z){clearInterval(X);return}try{let W=yield this.connection.getTransaction(D,{commitment:"confirmed",maxSupportedTransactionVersion:0});W&&(z=!0,clearInterval(X),$e({err:((Y=W.meta)==null?void 0:Y.err)||null}),console.log("tx status from getTransaction:",D))}catch(W){z=!0,clearInterval(X),console.error("getTransaction timeout:",W,D)}}),Ie)),he=this.connection.onSignature(D,Y=>{if(z){this.connection.removeSignatureListener(he);return}z=!0,$e(Y)},"confirmed"),this.connection.getSignatureStatus(D)});return E(),{txIds:[],signedTxs:B}}else{let L=[];for(let N=0;N<B.length;N+=1){let E=yield this.connection.sendTransaction(B[N],{skipPreflight:I});L.push(E)}return{txIds:L,signedTxs:B}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:s||{}}})}};import{Connection as is}from"@solana/web3.js";import{AccountLayout as te,createAssociatedTokenAccountInstruction as Ze,TOKEN_PROGRAM_ID as H,TOKEN_2022_PROGRAM_ID as _n}from"@solana/spl-token";var Ve=(...n)=>n.map(e=>{try{return typeof e=="object"?JSON.stringify(e):e}catch(t){return e}}).join(", "),pe=class{constructor({scope:e,moduleName:t}){this.disabled=!1;this.scope=e,this.logger=M(t)}createTxBuilder(e){return this.scope.checkOwner(),new Be({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(Ve(e))}logInfo(...e){this.logger.info(Ve(e))}logAndCreateError(...e){let t=Ve(e);throw new Error(t)}checkDisabled(){(this.disabled||!this.scope)&&this.logAndCreateError("module not working")}};import{PublicKey as An,SystemProgram as kn}from"@solana/web3.js";import Sn from"bn.js";import{createCloseAccountInstruction as In,createInitializeAccountInstruction as Bn,createTransferInstruction as Cn,TOKEN_PROGRAM_ID as ee}from"@solana/spl-token";import{Keypair as bn,PublicKey as It}from"@solana/web3.js";import Tn from"bn.js";import{TOKEN_PROGRAM_ID as xn}from"@solana/spl-token";import{sha256 as Pn}from"@noble/hashes/sha256";import{PublicKey as yn}from"@solana/web3.js";import At,{isBN as Na}from"bn.js";import{bits as Ks,BitStructure as Os,blob as dn,Blob as Ds,cstr as Ms,f32 as Es,f32be as Fs,f64 as vs,f64be as Ws,greedy as Vs,Layout as fn,ns64 as qs,ns64be as Us,nu64 as Gs,nu64be as js,offset as Hs,s16 as zs,s16be as Ys,s24 as Js,s24be as Zs,s32 as Xs,s32be as $s,s40 as Qs,s40be as ea,s48 as ta,s48be as na,s8 as ra,seq as oa,struct as ia,Structure as gn,u16 as sa,u16be as aa,u24 as ca,u24be as ua,u32 as la,u32be as ma,u40 as pa,u40be as da,u48 as fa,u48be as ga,u8 as ha,UInt as hn,union as ya,Union as ba,unionLayoutDiscriminator as Ta,utf8 as xa}from"@solana/buffer-layout";var qe=fn,wt=gn;var Ue=hn;var Ge=dn;var je=class extends qe{constructor(e,t,r){super(e,r),this.blob=Ge(e),this.signed=t}decode(e,t=0){let r=new At(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 At(e)),this.signed&&(e=e.toTwos(this.span*8)),this.blob.encode(e.toArrayLike(Buffer,"le",this.span),t,r)}};function kt(n){return new Ue(1,n)}function Ce(n){return new Ue(4,n)}function Le(n){return new je(8,!1,n)}var He=class extends qe{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 de(n){return new He(Ge(32),e=>new yn(e),e=>e.toBuffer(),n)}var ze=class extends wt{decode(e,t){return super.decode(e,t)}};function St(n,e,t){return new ze(n,e,t)}var fe=St([de("mint"),de("owner"),Le("amount"),Ce("delegateOption"),de("delegate"),kt("state"),Ce("isNativeOption"),Le("isNative"),Le("delegatedAmount"),Ce("closeAuthorityOption"),de("closeAuthority")]);var Ya=M("Sega_Util");function Bt({owner:n,solAccountResp:e,tokenAccountResp:t}){let r=[],o=[];for(let{pubkey:a,account:s}of t.value){let i=fe.decode(s.data),{mint:m,amount:u}=i;r.push({publicKey:a,mint:m,amount:u,isAssociated:ke(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:It.default,amount:new Tn(String(e.lamports)),isNative:!0,programId:e.owner}),{tokenAccounts:r,tokenAccountRawInfos:o}}function _e({fromPublicKey:n,programId:e=xn,assignSeed:t}){let r=t?btoa(t).slice(0,32):bn.generate().publicKey.toBase58().slice(0,32);return{publicKey:wn(n,r,e),seed:r}}function wn(n,e,t){let r=Buffer.concat([n.toBuffer(),Buffer.from(e),t.toBuffer()]),o=Pn(r);return new It(o)}function Ye(n){let{mint:e,tokenAccount:t,owner:r,programId:o=ee}=n;return Bn(t,e,r,o)}function ge(n){let{tokenAccount:e,payer:t,multiSigners:r=[],owner:o,programId:a=ee}=n;return In(e,t,o,r,a)}function Je(n){return T(this,null,function*(){let{connection:e,amount:t,commitment:r,payer:o,owner:a,skipCloseAccount:s}=n,i=yield e.getMinimumBalanceForRentExemption(fe.span,r),m=F(t).add(new Sn(i)),u=_e({fromPublicKey:o,programId:ee});return{addresses:{newAccount:u.publicKey},signers:[],instructions:[kn.createAccountWithSeed({fromPubkey:o,basePubkey:o,seed:u.seed,newAccountPubkey:u.publicKey,lamports:m.toNumber(),space:fe.span,programId:ee}),Ye({mint:new An(q.address),tokenAccount:u.publicKey,owner:a,programId:ee})],instructionTypes:[O.CreateAccount,O.InitAccount],endInstructionTypes:s?[]:[O.CloseAccount],endInstructions:s?[]:[ge({tokenAccount:u.publicKey,payer:o,owner:a})]}})}function Ct({source:n,destination:e,owner:t,amount:r,multiSigners:o=[],tokenProgram:a=ee}){return Cn(n,e,t,BigInt(String(r)),o,a)}var Xe=class extends pe{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 ke(this.scope.ownerPubKey,t,r).publicKey}resetTokenAccounts(){this._clientOwnedToken||(this._tokenAccounts=[],this._tokenAccountRawInfos=[])}fetchWalletTokenAccounts(t){return T(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=K(K({},{}),t),[a,s,i]=yield Promise.all([this.scope.connection.getAccountInfo(this.scope.ownerPubKey,o.commitment),this.scope.connection.getTokenAccountsByOwner(this.scope.ownerPubKey,{programId:H},o.commitment),this.scope.connection.getTokenAccountsByOwner(this.scope.ownerPubKey,{programId:_n},o.commitment)]),{tokenAccounts:m,tokenAccountRawInfos:u}=Bt({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 T(this,arguments,function*({mint:t,programId:r=H,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 T(this,null,function*(){var x,f,S,P;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 Re(t.tokenProgram||H),b=this.getAssociatedTokenAccount(r,new Re(y)),h=(i?[]:this.tokenAccountRawInfos).filter(w=>w.accountInfo.mint.equals(r)&&(!a||w.pubkey.equals(b))).sort((w,p)=>w.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 w=Ze(s,b,s,r,y),p=this.tokenAccountRawInfos.find(l=>l.pubkey.equals(b));if(u){let l=yield this.scope.connection.getAccountInfo(b);if(l===null)(x=c.instructions)==null||x.push(w),c.instructionTypes.push(O.CreateATA);else if(!(l.owner.equals(y)&&te.decode(l.data).mint.equals(r)&&te.decode(l.data).owner.equals(s)))throw Error(`create ata check error -> mint: ${r.toString()}, ata: ${b.toString()}`)}else p===void 0&&(c.instructions.push(w),c.instructionTypes.push(O.CreateATA));if(r.equals(j)&&o.amount){let l=yield Je({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(Ct({source:l.addresses.newAccount,destination:b,owner:this.scope.ownerPubKey,amount:o.amount,tokenProgram:H})),c.instructionTypes.push(O.TransferAmount))}return!m&&p===void 0&&(c.endInstructions.push(ge({owner:s,payer:o.payer||s,tokenAccount:b,programId:y})),c.endInstructionTypes.push(O.CloseAccount)),{account:b,instructionParams:c}}else{let w=_e({fromPublicKey:s,programId:y,assignSeed:d}),p=yield this.scope.connection.getMinimumBalanceForRentExemption(te.span),l=Ln.createAccountWithSeed({fromPubkey:s,basePubkey:s,seed:w.seed,newAccountPubkey:w.publicKey,lamports:p+Number((P=(S=o.amount)==null?void 0:S.toString())!=null?P:0),space:te.span,programId:y});return c.instructions.push(l,Ye({mint:r,tokenAccount:w.publicKey,owner:this.scope.ownerPubKey,programId:y})),c.instructionTypes.push(O.CreateAccount),c.instructionTypes.push(O.InitAccount),m||(c.endInstructions.push(ge({owner:s,payer:o.payer||s,tokenAccount:w.publicKey,programId:y})),c.endInstructionTypes.push(O.CloseAccount)),{account:w.publicKey,instructionParams:c}}})}checkOrCreateAta(a){return T(this,arguments,function*({mint:t,programId:r=H,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 Ze(i,d,i,t,r);m.instructions=[y],m.instructionTypes=[O.CreateATA],s=d}return o&&j.toBase58()===t.toBase58()&&(m.endInstructions=[ge({owner:i,payer:i,tokenAccount:s,programId:r})],m.endInstructionTypes=[O.CloseAccount]),{pubKey:s,newInstructions:m}})}handleTokenAccount(t){return T(this,null,function*(){let{side:r,amount:o,mint:a,programId:s=H,tokenAccount:i,payer:m=this.scope.ownerPubKey,bypassAssociatedCheck:u,skipCloseAccount:d,checkCreateATAOwner:y}=t,b=this.getAssociatedTokenAccount(a,s);if(new Re(j).equals(a)){let h=yield Je({connection:this.scope.connection,owner:this.scope.ownerPubKey,payer:m,amount:o,skipCloseAccount:d});return K({tokenAccount:h.addresses.newAccount},h)}else if(!i||r==="out"&&!b.equals(i)&&!u){let h=[],c=Ze(this.scope.ownerPubKey,b,this.scope.ownerPubKey,a,s);if(y){let x=yield this.scope.connection.getAccountInfo(b);if(x===null)h.push(c);else if(!(x.owner.equals(H)&&te.decode(x.data).mint.equals(a)&&te.decode(x.data).owner.equals(this.scope.ownerPubKey)))throw Error(`create ata check error -> mint: ${a.toString()}, ata: ${b.toString()}`)}else h.push(c);return{tokenAccount:b,instructions:h,instructionTypes:[O.CreateATA]}}return{tokenAccount:i}})}processTokenAccount(t){return T(this,null,function*(){let{mint:r,programId:o=H,amount:a,useSOLBalance:s,handleTokenAccount:i,feePayer:m}=t,u,d=this.createTxBuilder(m);if(r.equals(new Re(j))&&s){let y=yield this.handleTokenAccount({side:"in",amount:a||0,mint:r,bypassAssociatedCheck:!0,programId:o}),{tokenAccount:h}=y,c=J(y,["tokenAccount"]);u=h,d.addInstruction(c)}else if(u=yield this.getCreatedTokenAccount({mint:r,associatedOnly:!1,programId:o}),!u&&i){let b=yield this.scope.account.handleTokenAccount({side:"in",amount:0,mint:r,bypassAssociatedCheck:!0,programId:o}),{tokenAccount:h}=b,c=J(b,["tokenAccount"]);u=h,d.addInstruction(c)}return K({tokenAccount:u},d.AllTxData)})}};export{Xe as default}; //# sourceMappingURL=account.mjs.map