@sega-so/sega-sdk
Version:
An SDK for building applications on top of SEGA.
1 lines • 66.6 kB
JavaScript
"use strict";var kn=Object.create;var Ie=Object.defineProperty,In=Object.defineProperties,Cn=Object.getOwnPropertyDescriptor,Ln=Object.getOwnPropertyDescriptors,Kn=Object.getOwnPropertyNames,Ue=Object.getOwnPropertySymbols,Nn=Object.getPrototypeOf,ut=Object.prototype.hasOwnProperty,Wt=Object.prototype.propertyIsEnumerable;var Y=Math.pow,Ot=(n,e,t)=>e in n?Ie(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,D=(n,e)=>{for(var t in e||(e={}))ut.call(e,t)&&Ot(n,t,e[t]);if(Ue)for(var t of Ue(e))Wt.call(e,t)&&Ot(n,t,e[t]);return n},V=(n,e)=>In(n,Ln(e));var ie=(n,e)=>{var t={};for(var r in n)ut.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&Ue)for(var r of Ue(n))e.indexOf(r)<0&&Wt.call(n,r)&&(t[r]=n[r]);return t};var Mn=(n,e)=>{for(var t in e)Ie(n,t,{get:e[t],enumerable:!0})},_t=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Kn(e))!ut.call(n,s)&&s!==t&&Ie(n,s,{get:()=>e[s],enumerable:!(r=Cn(e,s))||r.enumerable});return n};var q=(n,e,t)=>(t=n!=null?kn(Nn(n)):{},_t(e||!n||!n.__esModule?Ie(t,"default",{value:n,enumerable:!0}):t,n)),Rn=n=>_t(Ie({},"__esModule",{value:!0}),n);var k=(n,e,t)=>new Promise((r,s)=>{var i=l=>{try{o(t.next(l))}catch(u){s(u)}},a=l=>{try{o(t.throw(l))}catch(u){s(u)}},o=l=>l.done?r(l.value):Promise.resolve(l.value).then(i,a);o((t=t.apply(n,e)).next())});var pr={};Mn(pr,{default:()=>at});module.exports=Rn(pr);var B=require("@solana/web3.js"),G=require("@solana/spl-token");var ne=q(require("bn.js")),$n=q(require("decimal.js"));var un=q(require("big.js")),Jn=q(require("bn.js"));var Ce=require("lodash");var ct=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}},Et={},Dn={};function j(n){let e=(0,Ce.get)(Et,n);if(!e){let t=(0,Ce.get)(Dn,n);e=new ct({name:n,logLevel:t}),(0,Ce.set)(Et,n,e)}return e}var pt=require("@solana/web3.js");var me=require("@solana/spl-token");var lt=j("Sega_accountInfo_util");function dt(n,e,t){return k(this,null,function*(){let{batchRequest:r,commitment:s="confirmed",chunkCount:i=100}=D({batchRequest:!1},t),a=mt(e,i),o=new Array(a.length).fill([]);if(r){let l=a.map(m=>({methodName:"getMultipleAccounts",args:n._buildArgs([m.map(c=>c.toBase58())],s,"base64")})),u=mt(l,10);o=(yield(yield Promise.all(u.map(m=>k(this,null,function*(){return yield n._rpcBatchRequest(m)})))).flat()).map(m=>(m.error&<.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${m.error.message}`),m.result.value.map(d=>{if(d){let{data:c,executable:y,lamports:T,owner:p,rentEpoch:x}=d;return c.length!==2&&c[1]!=="base64"&<.logWithError("info must be base64 encoded, RPC_ERROR"),{data:Buffer.from(c[0],"base64"),executable:y,lamports:T,owner:new pt.PublicKey(p),rentEpoch:x}}return null})))}else try{o=yield Promise.all(a.map(l=>n.getMultipleAccountsInfo(l,s)))}catch(l){l instanceof Error&<.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${l.message}`)}return o.flat()})}function Le(n,e,t){return k(this,null,function*(){let r=yield dt(n,e.map(s=>s.pubkey),t);return e.map((s,i)=>V(D({},s),{accountInfo:r[i]}))})}function vt(r){return k(this,arguments,function*({connection:n,mints:e,config:t}){var a,o,l;if(e.length===0)return{};let s=yield Le(n,e.map(u=>({pubkey:Ge(u)})),t),i={};for(let u of s){if(!u.accountInfo||u.accountInfo.data.length<me.MINT_SIZE){console.log("invalid mint account",u.pubkey.toBase58());continue}let f=(0,me.unpackMint)(u.pubkey,u.accountInfo,(a=u.accountInfo)==null?void 0:a.owner);i[u.pubkey.toString()]=V(D({},f),{programId:((o=u.accountInfo)==null?void 0:o.owner)||me.TOKEN_PROGRAM_ID,feeConfig:(l=(0,me.getTransferFeeConfig)(f))!=null?l:void 0})}return i[pt.PublicKey.default.toBase58()]=i[se.toBase58()],i})}var he=q(require("bn.js"));var Vt=9007199254740991;function ae(n){let e=j("Sega_parseBigNumberish");if(n instanceof he.default)return n;if(typeof n=="string"){if(n.match(/^-?[0-9]+$/))return new he.default(n);e.logWithError(`invalid BigNumberish string: ${n}`)}return typeof n=="number"?(n%1&&e.logWithError(`BigNumberish number underflow: ${n}`),(n>=Vt||n<=-Vt)&&e.logWithError(`BigNumberish number overflow: ${n}`),new he.default(String(n))):typeof n=="bigint"?new he.default(n.toString()):(e.error(`invalid BigNumberish value: ${n}`),new he.default(0))}var qt=require("@solana/web3.js"),ft=require("@solana/spl-token"),gt={chainId:101,address:qt.PublicKey.default.toBase58(),programId:ft.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"}},pe={chainId:101,address:"So11111111111111111111111111111111111111112",programId:ft.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 je=require("@solana/web3.js");var W=require("@solana/web3.js"),Ut=require("@solana/spl-token");function bt({pubkey:n,isSigner:e=!1,isWritable:t=!0}){return{pubkey:n,isWritable:t,isSigner:e}}var Ir=[bt({pubkey:Ut.TOKEN_PROGRAM_ID,isWritable:!1}),bt({pubkey:W.SystemProgram.programId,isWritable:!1}),bt({pubkey:W.SYSVAR_RENT_PUBKEY,isWritable:!1})];function yt({publicKey:n,transformSol:e}){let t=Gt(n.toString());if(t instanceof W.PublicKey)return e&&t.equals(Ke)?se:t;if(e&&t.toString()===Ke.toBase58())return se;if(typeof t=="string"){if(t===W.PublicKey.default.toBase58())return W.PublicKey.default;try{return new W.PublicKey(t)}catch(r){throw new Error("invalid public key")}}throw new Error("invalid public key")}function Gt(n){try{return new W.PublicKey(n)}catch(e){return n}}var Cr=new W.PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),jt=new W.PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),zt=new W.PublicKey("SysvarRent111111111111111111111111111111111"),Lr=new W.PublicKey("SysvarC1ock11111111111111111111111111111111"),Ht=new W.PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),Kr=new W.PublicKey("Sysvar1nstructions1111111111111111111111111"),Yt=W.SystemProgram.programId,Nr=new W.PublicKey("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),Mr=new W.PublicKey("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),Rr=new W.PublicKey("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),Dr=new W.PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),Fr=new W.PublicKey("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),Or=new W.PublicKey("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),Wr=new W.PublicKey("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),_r=new W.PublicKey("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),Er=new W.PublicKey("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),vr=new W.PublicKey("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),Vr=new W.PublicKey("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),se=new W.PublicKey("So11111111111111111111111111111111111111112"),Ke=W.PublicKey.default;function Ge(n){return yt({publicKey:n,transformSol:!0})}var ze=class ze{constructor({mint:e,decimals:t,symbol:r,name:s,skipMint:i=!1,isToken2022:a=!1}){if(e===Ke.toBase58()||e instanceof je.PublicKey&&Ke.equals(e)){this.decimals=pe.decimals,this.symbol=pe.symbol,this.name=pe.name,this.mint=new je.PublicKey(pe.address),this.isToken2022=!1;return}this.decimals=t,this.symbol=r||e.toString().substring(0,6),this.name=s||e.toString().substring(0,6),this.mint=i?je.PublicKey.default:yt({publicKey:e}),this.isToken2022=a}equals(e){return this===e?!0:this.mint.equals(e.mint)}};ze.WSOL=new ze(V(D({},pe),{mint:pe.address}));var Te=ze;var He=class He{constructor({decimals:e,symbol:t="UNKNOWN",name:r="UNKNOWN"}){this.decimals=e,this.symbol=t,this.name=r}equals(e){return this===e}};He.SOL=new He(gt);var ht=He;var Zt=q(require("toformat")),Fn=Zt.default,Ne=Fn;var Me=q(require("big.js")),Jt=q(require("bn.js")),Xt=q(require("decimal.js-light"));var Ye=j("module/fraction"),Tt=Ne(Me.default),Re=Ne(Xt.default),Wn={0:Re.ROUND_DOWN,1:Re.ROUND_HALF_UP,2:Re.ROUND_UP},_n={0:Me.default.roundDown,1:Me.default.roundHalfUp,2:Me.default.roundUp},te=class n{constructor(e,t=new Jt.default(1)){this.numerator=ae(e),this.denominator=ae(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(ae(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(ae(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(ae(e));return new n(this.numerator.mul(t.numerator),this.denominator.mul(t.denominator))}div(e){let t=e instanceof n?e:new n(ae(e));return new n(this.numerator.mul(t.denominator),this.denominator.mul(t.numerator))}toSignificant(e,t={groupSeparator:""},r=1){Number.isInteger(e)||Ye.logWithError(`${e} is not an integer.`),e<=0&&Ye.logWithError(`${e} is not positive.`),Re.set({precision:e+1,rounding:Wn[r]});let s=new Re(this.numerator.toString()).div(this.denominator.toString()).toSignificantDigits(e);return s.toFormat(s.decimalPlaces(),t)}toFixed(e,t={groupSeparator:""},r=1){return Number.isInteger(e)||Ye.logWithError(`${e} is not an integer.`),e<0&&Ye.logWithError(`${e} is negative.`),Tt.DP=e,Tt.RM=_n[r]||1,new Tt(this.numerator.toString()).div(this.denominator.toString()).toFormat(e,t)}isZero(){return this.numerator.isZero()}};var Qt=q(require("bn.js"));var $t=new te(new Qt.default(100)),Q=class extends te{toSignificant(e=5,t,r){return this.mul($t).toSignificant(e,t,r)}toFixed(e=2,t,r){return this.mul($t).toFixed(e,t,r)}};var co=j("Sega_price");function mt(n,e=1,t=[]){let r=[...n];if(e<=0)return t;for(;r.length;)t.push(r.splice(0,e));return t}var on=require("@solana/web3.js"),sn=require("@solana/spl-token");var z=require("@solana/web3.js");var J={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 nn=require("@solana/spl-token");var tn=j("Sega_txUtil"),rn=1644;function Ze(n){let e=[],t=[];return n.microLamports&&(e.push(z.ComputeBudgetProgram.setComputeUnitPrice({microLamports:n.microLamports})),t.push(J.SetComputeUnitPrice)),n.units&&(e.push(z.ComputeBudgetProgram.setComputeUnitLimit({units:n.units})),t.push(J.SetComputeUnitLimit)),{instructions:e,instructionTypes:t}}function Pe(n,e){return k(this,null,function*(){var r,s;let t=e!=null?e:"confirmed";return(s=yield(r=n.getLatestBlockhash)==null?void 0:r.call(n,{commitment:t}))==null?void 0:s.blockhash})}function Je(n,e){return k(this,null,function*(){return n.getSignatureStatuses([e]),new Promise((t,r)=>{let s=setTimeout(r,6e4);n.onSignature(e,i=>{if(clearTimeout(s),!i.err){t("");return}r(Object.assign(i.err,{txId:e}))},"confirmed")})})}function En(n,e){n.length<1&&tn.logWithError(`no instructions provided: ${n.toString()}`),e.length<1&&tn.logWithError(`no signers provided:, ${e.toString()}`);let t=new z.Transaction;t.recentBlockhash="11111111111111111111111111111111",t.feePayer=e[0],t.add(...n);try{return Buffer.from(t.serialize({verifySignatures:!1})).toString("base64").length<rn}catch(r){return!1}}function de(n,e){let[t,r]=z.PublicKey.findProgramAddressSync(n,e);return{publicKey:t,nonce:r}}function De({instructions:n,payer:e,signers:t}){return En(n,[e,...t])}function Fe({instructions:n,payer:e,lookupTableAddressAccount:t,recentBlockhash:r=z.Keypair.generate().publicKey.toString()}){let i=new z.TransactionMessage({payerKey:e,recentBlockhash:r,instructions:n}).compileToV0Message(Object.values(t!=null?t:{}));try{return Buffer.from(new z.VersionedTransaction(i).serialize()).toString("base64").length<rn}catch(a){return!1}}var vn=n=>Buffer.isBuffer(n)?n:n instanceof Uint8Array?Buffer.from(n.buffer,n.byteOffset,n.byteLength):Buffer.from(n),Vn=n=>{let e=n.serialize({requireAllSignatures:!1,verifySignatures:!1});n instanceof z.VersionedTransaction&&(e=vn(e));try{return e instanceof Buffer?e.toString("base64"):Buffer.from(e).toString("base64")}catch(t){return e.toString("base64")}};function be(n){let e=[];return n.forEach(t=>{t instanceof z.Transaction&&(t.recentBlockhash||(t.recentBlockhash=nn.TOKEN_PROGRAM_ID.toBase58()),t.feePayer||(t.feePayer=z.Keypair.generate().publicKey)),e.push(Vn(t))}),console.log("simulate tx string:",e),e}function xt(n,e,t){return de([n.toBuffer(),(t!=null?t:sn.TOKEN_PROGRAM_ID).toBuffer(),e.toBuffer()],new on.PublicKey("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"))}var ue=require("@solana/web3.js"),qn=new ue.PublicKey("SegazTQwbYWknDZkJ6j2Kgvm5gw3MrHGKtWstZdoNKZ"),Un=new ue.PublicKey("Ajk8d9bERSaFdeoT1d8JUVfaDayrYLnAdgeB47TFMUaG"),Vo=new ue.PublicKey("2HbjxVVKJ7Ct72Rcd8WK4VTqmwTXL5aAggkH1CHGFGmh"),Gn=new ue.PublicKey("auetiVUVJkRxvNPLYEvVnz8UJSqQ1VgoA83PcicHVD1"),jn=new ue.PublicKey("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y"),zn=new ue.PublicKey("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y");var qo={SERUM_MARKET:ue.PublicKey.default,UTIL1216:ue.PublicKey.default,CREATE_CPMM_POOL_PROGRAM:Gn,CREATE_CPMM_POOL_AUTH:jn,CREATE_CPMM_POOL_FEE_ACC:zn};var X=q(require("bn.js"));var Oe=1e4;function ye(n,e,t,r){if(e===void 0)return{amount:n,fee:void 0,expirationTime:void 0};let s=V(D({},e),{olderTransferFee:{epoch:BigInt(e.olderTransferFee.epoch),maximumFee:BigInt(e.olderTransferFee.maximumFee),transferFeeBasisPoints:e.olderTransferFee.transferFeeBasisPoints},newerTransferFee:{epoch:BigInt(e.newerTransferFee.epoch),maximumFee:BigInt(e.newerTransferFee.maximumFee),transferFeeBasisPoints:e.newerTransferFee.transferFeeBasisPoints}}),i=t.epoch<s.newerTransferFee.epoch?s.olderTransferFee:s.newerTransferFee,a=new X.default(i.maximumFee.toString()),o=t.epoch<s.newerTransferFee.epoch?(Number(s.newerTransferFee.epoch)*t.slotsInEpoch-t.absoluteSlot)*400/1e3:void 0;if(r)if(i.transferFeeBasisPoints===Oe){let l=new X.default(i.maximumFee.toString());return{amount:n.add(l),fee:l,expirationTime:o}}else{let l=we(n.mul(new X.default(Oe)),new X.default(Oe-i.transferFeeBasisPoints)),u=new X.default(i.maximumFee.toString()),f=l.sub(n).gt(u)?n.add(u):l,m=we(f.mul(new X.default(i.transferFeeBasisPoints)),new X.default(Oe)),d=m.gt(a)?a:m;return{amount:f,fee:d,expirationTime:o}}else{let l=we(n.mul(new X.default(i.transferFeeBasisPoints)),new X.default(Oe)),u=l.gt(a)?a:l;return{amount:n,fee:u,expirationTime:o}}}function we(n,e){let{div:t,mod:r}=n.divmod(e);return r.gt(new X.default(0))?t.add(new X.default(1)):t}var We=require("@solana/web3.js");function At(t){return k(this,arguments,function*({connection:n,address:e}){let r=yield dt(n,[...new Set(e.map(i=>i.toString()))].map(i=>new We.PublicKey(i))),s={};for(let i=0;i<e.length;i++){let a=r[i],o=e[i];if(!a)continue;let l=new We.AddressLookupTableAccount({key:o,state:We.AddressLookupTableAccount.deserialize(a.data)});s[o.toString()]=l,Xe[o.toString()]=l}return s})}var Xe={};var O=require("@solana/web3.js"),an=q(require("axios"));var $e=2e3,Qe=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 k(this,null,function*(){var r;let e=(yield an.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}=Ze(e);return this.instructions.unshift(...t),this.instructionTypes.unshift(...r),!0}return!1}addTipInstruction(e){var t;return e?(this.endInstructions.push(O.SystemProgram.transfer({fromPubkey:(t=e.feePayer)!=null?t:this.feePayer,toPubkey:new O.PublicKey(e.address),lamports:BigInt(e.amount.toString())})),this.endInstructionTypes.push(J.TransferTip),!0):!1}calComputeBudget(r){return k(this,arguments,function*({config:e,defaultIns:t}){try{let s=e||(yield this.getComputeBudgetConfig());if(this.addCustomComputeBudget(s))return;t&&this.instructions.unshift(...t)}catch(s){t&&this.instructions.unshift(...t)}})}addInstruction({instructions:e=[],endInstructions:t=[],signers:r=[],instructionTypes:s=[],endInstructionTypes:i=[],lookupTableAddress:a=[]}){return this.instructions.push(...e),this.endInstructions.push(...t),this.signers.push(...r),this.instructionTypes.push(...s),this.endInstructionTypes.push(...i),this.lookupTableAddress.push(...a.filter(o=>o!==O.PublicKey.default.toString())),this}versionBuild(r){return k(this,arguments,function*({txVersion:e,extInfo:t}){return e===0?yield this.buildV0(D({},t||{})):this.build(t)})}build(e){var r;let t=new O.Transaction;return this.allInstructions.length&&t.add(...this.allInstructions),t.feePayer=this.feePayer,(r=this.owner)!=null&&r.signer&&!this.signers.some(s=>s.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer),{builder:this,transaction:t,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:s=>k(this,null,function*(){var u;let{recentBlockHash:i,skipPreflight:a=!0,sendAndConfirm:o}=s||{},l=i!=null?i:yield Pe(this.connection,this.blockhashCommitment);if(t.recentBlockhash=l,this.signers.length&&t.sign(...this.signers),be([t]),(u=this.owner)!=null&&u.isKeyPair)return{txId:o?yield(0,O.sendAndConfirmTransaction)(this.connection,t,this.signers.find(m=>m.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:a}):yield this.connection.sendRawTransaction(t.serialize(),{skipPreflight:a}),signedTx:t};if(this.signAllTransactions){let f=yield this.signAllTransactions([t]);if(this.signers.length)for(let m of f)try{m.sign(...this.signers)}catch(d){}return{txId:yield this.connection.sendRawTransaction(f[0].serialize(),{skipPreflight:a}),signedTx:f[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:s}=this.build(r),i=t.filter(f=>f.transaction.instructions.length>0),a=[s,...i.map(f=>f.transaction)],o=[this.signers,...i.map(f=>f.signers)],l=[...this.instructionTypes,...i.map(f=>f.instructionTypes).flat()];return(u=this.owner)!=null&&u.signer&&o.forEach(f=>{f.some(m=>m.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),{builder:this,transactions:a,signers:o,instructionTypes:l,execute:f=>k(this,null,function*(){var x;let{sequentially:m,onTxUpdate:d,skipTxCount:c=0,recentBlockHash:y,skipPreflight:T=!0}=f||{},p=y!=null?y:yield Pe(this.connection,this.blockhashCommitment);if((x=this.owner)!=null&&x.isKeyPair){if(m){let h=[],S=0;for(let g of a){if(++S,S<=c)continue;let P=yield(0,O.sendAndConfirmTransaction)(this.connection,g,this.signers.find(b=>b.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:T});h.push(P)}return{txIds:h,signedTxs:a}}return{txIds:yield yield Promise.all(a.map(h=>k(this,null,function*(){return h.recentBlockhash=p,yield this.connection.sendRawTransaction(h.serialize(),{skipPreflight:T})}))),signedTxs:a}}if(this.signAllTransactions){let h=a.map((g,P)=>(g.recentBlockhash=p,o[P].length&&g.sign(...o[P]),g));be(h);let S=yield this.signAllTransactions(h);if(m){let g=0,P=[],b=()=>k(this,null,function*(){if(!S[g])return;let w=yield this.connection.sendRawTransaction(S[g].serialize(),{skipPreflight:T});P.push({txId:w,status:"sent",signedTx:S[g]}),d==null||d([...P]),g++;let A=!1,L=null,C=null,M=K=>{L!==null&&clearInterval(L),C!==null&&this.connection.removeSignatureListener(C);let N=P.findIndex(F=>F.txId===w);if(N>-1){if(P[N].status==="error"||P[N].status==="success")return;P[N].status=K.err?"error":"success"}d==null||d([...P]),K.err||b()};this.loopMultiTxStatus&&(L=setInterval(()=>k(this,null,function*(){var K;if(A){clearInterval(L);return}try{let N=yield this.connection.getTransaction(w,{commitment:"confirmed",maxSupportedTransactionVersion:0});N&&(A=!0,clearInterval(L),M({err:((K=N.meta)==null?void 0:K.err)||null}),console.log("tx status from getTransaction:",w))}catch(N){A=!0,clearInterval(L),console.error("getTransaction timeout:",N,w)}}),$e)),C=this.connection.onSignature(w,K=>{if(A){this.connection.removeSignatureListener(C);return}A=!0,M(K)},"confirmed"),this.connection.getSignatureStatus(w)});return yield b(),{txIds:P.map(w=>w.txId),signedTxs:S}}else{let g=[];for(let P=0;P<S.length;P+=1){let b=yield this.connection.sendRawTransaction(S[P].serialize(),{skipPreflight:T});g.push(b)}return{txIds:g,signedTxs:S}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:r||{}}}versionMultiBuild(s){return k(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 k(this,null,function*(){var T;let y=e||{},{lookupTableCache:t={},lookupTableAddress:r=[],forerunCreate:s,recentBlockhash:i}=y,a=ie(y,["lookupTableCache","lookupTableAddress","forerunCreate","recentBlockhash"]),o=D(D({},this.cluster==="devnet"?{}:Xe),t),l=Array.from(new Set([...r,...this.lookupTableAddress])),u=[];for(let p of l)o[p]===void 0&&u.push(new O.PublicKey(p));let f=yield At({connection:this.connection,address:u});for(let[p,x]of Object.entries(f))o[p]=x;let m=s?O.PublicKey.default.toBase58():i!=null?i:yield Pe(this.connection,this.blockhashCommitment),d=new O.TransactionMessage({payerKey:this.feePayer,recentBlockhash:m,instructions:[...this.allInstructions]}).compileToV0Message(Object.values(o));(T=this.owner)!=null&&T.signer&&!this.signers.some(p=>p.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer);let c=new O.VersionedTransaction(d);return c.sign(this.signers),{builder:this,transaction:c,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:p=>k(this,null,function*(){var S;let{skipPreflight:x=!0,sendAndConfirm:h}=p||{};if(be([c]),(S=this.owner)!=null&&S.isKeyPair){let g=yield this.connection.sendTransaction(c,{skipPreflight:x});return h&&(yield Je(this.connection,g)),{txId:g,signedTx:c}}if(this.signAllTransactions){let g=yield this.signAllTransactions([c]);if(this.signers.length)for(let P of g)try{P.sign(this.signers)}catch(b){}return{txId:yield this.connection.sendTransaction(g[0],{skipPreflight:x}),signedTx:g[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:a||{}}})}buildV0MultiTx(e){return k(this,null,function*(){var u;let{extraPreBuildData:t=[],buildProps:r}=e,{transaction:s}=yield this.buildV0(r),i=t.filter(f=>f.builder.instructions.length>0),a=[s,...i.map(f=>f.transaction)],o=[this.signers,...i.map(f=>f.signers)],l=[...this.instructionTypes,...i.map(f=>f.instructionTypes).flat()];return(u=this.owner)!=null&&u.signer&&o.forEach(f=>{f.some(m=>m.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),a.forEach((f,m)=>k(this,null,function*(){f.sign(o[m])})),{builder:this,transactions:a,signers:o,instructionTypes:l,buildProps:r,execute:f=>k(this,null,function*(){var T;let{sequentially:m,onTxUpdate:d,recentBlockHash:c,skipPreflight:y=!0}=f||{};if(c&&a.forEach(p=>p.message.recentBlockhash=c),be(a),(T=this.owner)!=null&&T.isKeyPair){if(m){let p=[];for(let x of a){let h=yield this.connection.sendTransaction(x,{skipPreflight:y});yield Je(this.connection,h),p.push(h)}return{txIds:p,signedTxs:a}}return{txIds:yield Promise.all(a.map(p=>k(this,null,function*(){return yield this.connection.sendTransaction(p,{skipPreflight:y})}))),signedTxs:a}}if(this.signAllTransactions){let p=yield this.signAllTransactions(a);if(m){let x=0,h=[],S=()=>k(this,null,function*(){if(!p[x])return;let g=yield this.connection.sendTransaction(p[x],{skipPreflight:y});h.push({txId:g,status:"sent",signedTx:p[x]}),d==null||d([...h]),x++;let P=!1,b=null,w=null,A=L=>{b!==null&&clearInterval(b),w!==null&&this.connection.removeSignatureListener(w);let C=h.findIndex(M=>M.txId===g);if(C>-1){if(h[C].status==="error"||h[C].status==="success")return;h[C].status=L.err?"error":"success"}d==null||d([...h]),L.err||S()};this.loopMultiTxStatus&&(b=setInterval(()=>k(this,null,function*(){var L;if(P){clearInterval(b);return}try{let C=yield this.connection.getTransaction(g,{commitment:"confirmed",maxSupportedTransactionVersion:0});C&&(P=!0,clearInterval(b),A({err:((L=C.meta)==null?void 0:L.err)||null}),console.log("tx status from getTransaction:",g))}catch(C){P=!0,clearInterval(b),console.error("getTransaction timeout:",C,g)}}),$e)),w=this.connection.onSignature(g,L=>{if(P){this.connection.removeSignatureListener(w);return}P=!0,A(L)},"confirmed"),this.connection.getSignatureStatus(g)});return S(),{txIds:[],signedTxs:p}}else{let x=[];for(let h=0;h<p.length;h+=1){let S=yield this.connection.sendTransaction(p[h],{skipPreflight:y});x.push(S)}return{txIds:x,signedTxs:p}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:r||{}}})}sizeCheckBuild(e){return k(this,null,function*(){var d;let m=e||{},{splitIns:t=[],computeBudgetConfig:r}=m,s=ie(m,["splitIns","computeBudgetConfig"]),i=r?Ze(r):{instructions:[],instructionTypes:[]},a=this.signers.reduce((c,y)=>V(D({},c),{[y.publicKey.toBase58()]:y}),{}),o=[],l=[],u=[],f=0;if(this.allInstructions.forEach(c=>{let y=[...u,c],T=r?[...i.instructions,...y]:y,x=[...new Set(y.map(h=>h.keys.filter(S=>S.isSigner).map(S=>S.pubkey.toString())).flat()).values()].map(h=>new O.PublicKey(h));if(c!==t[f]&&u.length<12&&(De({instructions:T,payer:this.feePayer,signers:x})||De({instructions:y,payer:this.feePayer,signers:x})))u.push(c);else{if(u.length===0)throw Error("item ins too big");f+=c===t[f]?1:0,De({instructions:r?[...i.instructions,...u]:[...u],payer:this.feePayer,signers:x})?o.push(new O.Transaction().add(...i.instructions,...u)):o.push(new O.Transaction().add(...u)),l.push(Array.from(new Set(u.map(h=>h.keys.filter(S=>S.isSigner).map(S=>S.pubkey.toString())).flat())).map(h=>a[h]).filter(h=>h!==void 0)),u=[c]}}),u.length>0){let y=[...new Set(u.map(T=>T.keys.filter(p=>p.isSigner).map(p=>p.pubkey.toString())).flat()).values()].map(T=>a[T]).filter(T=>T!==void 0);De({instructions:r?[...i.instructions,...u]:[...u],payer:this.feePayer,signers:y.map(T=>T.publicKey)})?o.push(new O.Transaction().add(...i.instructions,...u)):o.push(new O.Transaction().add(...u)),l.push(y)}return o.forEach(c=>c.feePayer=this.feePayer),(d=this.owner)!=null&&d.signer&&l.forEach(c=>{c.some(y=>y.publicKey.equals(this.owner.publicKey))||c.push(this.owner.signer)}),{builder:this,transactions:o,signers:l,instructionTypes:this.instructionTypes,execute:c=>k(this,null,function*(){var g;let{sequentially:y,onTxUpdate:T,skipTxCount:p=0,recentBlockHash:x,skipPreflight:h=!0}=c||{},S=x!=null?x:yield Pe(this.connection,this.blockhashCommitment);if(o.forEach((P,b)=>k(this,null,function*(){P.recentBlockhash=S,l[b].length&&P.sign(...l[b])})),be(o),(g=this.owner)!=null&&g.isKeyPair){if(y){let P=0,b=[];for(let w of o){if(++P,P<=p){b.push("tx skipped");continue}let A=yield(0,O.sendAndConfirmTransaction)(this.connection,w,this.signers.find(L=>L.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:h});b.push(A)}return{txIds:b,signedTxs:o}}return{txIds:yield Promise.all(o.map(P=>k(this,null,function*(){return yield this.connection.sendRawTransaction(P.serialize(),{skipPreflight:h})}))),signedTxs:o}}if(this.signAllTransactions){let P=yield this.signAllTransactions(o.slice(p,o.length)),b=[...o.slice(0,p),...P];if(y){let w=0,A=[],L=()=>k(this,null,function*(){if(!b[w])return;w<p&&(A.push({txId:"",status:"success",signedTx:b[w]}),T==null||T([...A]),w++,L());let C=yield this.connection.sendRawTransaction(b[w].serialize(),{skipPreflight:h});A.push({txId:C,status:"sent",signedTx:b[w]}),T==null||T([...A]),w++;let M=!1,K=null,N=null,F=R=>{K!==null&&clearInterval(K),N!==null&&this.connection.removeSignatureListener(N);let E=A.findIndex(U=>U.txId===C);if(E>-1){if(A[E].status==="error"||A[E].status==="success")return;A[E].status=R.err?"error":"success"}T==null||T([...A]),R.err||L()};this.loopMultiTxStatus&&(K=setInterval(()=>k(this,null,function*(){var R;if(M){clearInterval(K);return}try{let E=yield this.connection.getTransaction(C,{commitment:"confirmed",maxSupportedTransactionVersion:0});E&&(M=!0,clearInterval(K),F({err:((R=E.meta)==null?void 0:R.err)||null}),console.log("tx status from getTransaction:",C))}catch(E){M=!0,clearInterval(K),console.error("getTransaction timeout:",E,C)}}),$e)),N=this.connection.onSignature(C,R=>{if(M){this.connection.removeSignatureListener(N);return}M=!0,F(R)},"confirmed"),this.connection.getSignatureStatus(C)});return yield L(),{txIds:A.map(C=>C.txId),signedTxs:b}}else{let w=[];for(let A=0;A<b.length;A+=1){let L=yield this.connection.sendRawTransaction(b[A].serialize(),{skipPreflight:h});w.push(L)}return{txIds:w,signedTxs:b}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:s||{}}})}sizeCheckBuildV0(e){return k(this,null,function*(){var S;let h=e||{},{computeBudgetConfig:t,splitIns:r=[],lookupTableCache:s={},lookupTableAddress:i=[]}=h,a=ie(h,["computeBudgetConfig","splitIns","lookupTableCache","lookupTableAddress"]),o=D(D({},this.cluster==="devnet"?{}:Xe),s),l=Array.from(new Set([...this.lookupTableAddress,...i])),u=[];for(let g of l)o[g]===void 0&&u.push(new O.PublicKey(g));let f=yield At({connection:this.connection,address:u});for(let[g,P]of Object.entries(f))o[g]=P;let m=t?Ze(t):{instructions:[],instructionTypes:[]},d=yield Pe(this.connection,this.blockhashCommitment),c=this.signers.reduce((g,P)=>V(D({},g),{[P.publicKey.toBase58()]:P}),{}),y=[],T=[],p=[],x=0;if(this.allInstructions.forEach(g=>{let P=[...p,g],b=t?[...m.instructions,...P]:P;if(g!==r[x]&&p.length<12&&(Fe({instructions:b,payer:this.feePayer,lookupTableAddressAccount:o})||Fe({instructions:P,payer:this.feePayer,lookupTableAddressAccount:o})))p.push(g);else{if(p.length===0)throw Error("item ins too big");x+=g===r[x]?1:0;let w={};for(let A of[...new Set(l)])o[A]!==void 0&&(w[A]=o[A]);if(t&&Fe({instructions:[...m.instructions,...p],payer:this.feePayer,lookupTableAddressAccount:o,recentBlockhash:d})){let A=new O.TransactionMessage({payerKey:this.feePayer,recentBlockhash:d,instructions:[...m.instructions,...p]}).compileToV0Message(Object.values(o));y.push(new O.VersionedTransaction(A))}else{let A=new O.TransactionMessage({payerKey:this.feePayer,recentBlockhash:d,instructions:[...p]}).compileToV0Message(Object.values(o));y.push(new O.VersionedTransaction(A))}T.push(Array.from(new Set(p.map(A=>A.keys.filter(L=>L.isSigner).map(L=>L.pubkey.toString())).flat())).map(A=>c[A]).filter(A=>A!==void 0)),p=[g]}}),p.length>0){let P=[...new Set(p.map(b=>b.keys.filter(w=>w.isSigner).map(w=>w.pubkey.toString())).flat()).values()].map(b=>c[b]).filter(b=>b!==void 0);if(t&&Fe({instructions:[...m.instructions,...p],payer:this.feePayer,lookupTableAddressAccount:o,recentBlockhash:d})){let b=new O.TransactionMessage({payerKey:this.feePayer,recentBlockhash:d,instructions:[...m.instructions,...p]}).compileToV0Message(Object.values(o));y.push(new O.VersionedTransaction(b))}else{let b=new O.TransactionMessage({payerKey:this.feePayer,recentBlockhash:d,instructions:[...p]}).compileToV0Message(Object.values(o));y.push(new O.VersionedTransaction(b))}T.push(P)}return(S=this.owner)!=null&&S.signer&&T.forEach(g=>{g.some(P=>P.publicKey.equals(this.owner.publicKey))||g.push(this.owner.signer)}),{builder:this,transactions:y,buildProps:e,signers:T,instructionTypes:this.instructionTypes,execute:g=>k(this,null,function*(){var C;let{sequentially:P,onTxUpdate:b,skipTxCount:w=0,recentBlockHash:A,skipPreflight:L=!0}=g||{};if(y.map((M,K)=>k(this,null,function*(){T[K].length&&M.sign(T[K]),A&&(M.message.recentBlockhash=A)})),be(y),(C=this.owner)!=null&&C.isKeyPair){if(P){let M=0,K=[];for(let N of y){if(++M,M<=w){console.log("skip tx: ",M),K.push("tx skipped");continue}let F=yield this.connection.sendTransaction(N,{skipPreflight:L});yield Je(this.connection,F),K.push(F)}return{txIds:K,signedTxs:y}}return{txIds:yield Promise.all(y.map(M=>k(this,null,function*(){return yield this.connection.sendTransaction(M,{skipPreflight:L})}))),signedTxs:y}}if(this.signAllTransactions){let M=yield this.signAllTransactions(y.slice(w,y.length)),K=[...y.slice(0,w),...M];if(P){let N=0,F=[],R=()=>k(this,null,function*(){if(!K[N])return;if(N<w){F.push({txId:"",status:"success",signedTx:K[N]}),b==null||b([...F]),N++,R();return}let E=yield this.connection.sendTransaction(K[N],{skipPreflight:L});F.push({txId:E,status:"sent",signedTx:K[N]}),b==null||b([...F]),N++;let U=!1,$=null,fe=null,Ft=ge=>{$!==null&&clearInterval($),fe!==null&&this.connection.removeSignatureListener(fe);let oe=F.findIndex(Sn=>Sn.txId===E);if(oe>-1){if(F[oe].status==="error"||F[oe].status==="success")return;F[oe].status=ge.err?"error":"success"}b==null||b([...F]),ge.err||R()};this.loopMultiTxStatus&&($=setInterval(()=>k(this,null,function*(){var ge;if(U){clearInterval($);return}try{let oe=yield this.connection.getTransaction(E,{commitment:"confirmed",maxSupportedTransactionVersion:0});oe&&(U=!0,clearInterval($),Ft({err:((ge=oe.meta)==null?void 0:ge.err)||null}),console.log("tx status from getTransaction:",E))}catch(oe){U=!0,clearInterval($),console.error("getTransaction timeout:",oe,E)}}),$e)),fe=this.connection.onSignature(E,ge=>{if(U){this.connection.removeSignatureListener(fe);return}U=!0,Ft(ge)},"confirmed"),this.connection.getSignatureStatus(E)});return R(),{txIds:[],signedTxs:K}}else{let N=[];for(let F=0;F<K.length;F+=1){let R=yield this.connection.sendTransaction(K[F],{skipPreflight:L});N.push(R)}return{txIds:N,signedTxs:K}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:a||{}}})}};var Hn=require("@solana/web3.js"),Yn=q(require("bn.js"));var Zn=require("@solana/web3.js");var vi=j("Sega_amount"),Vi=Ne(un.default);var wt=new ne.default(0),ts=new ne.default(1),ns=new ne.default(2),rs=new ne.default(3),os=new ne.default(5),Xn=new ne.default(10),is=new ne.default(100),ss=new ne.default(1e3),as=new ne.default(1e4);var rt=q(require("bn.js")),_e=q(require("decimal.js-light"));var Ae=q(require("bn.js"));function et(n,e){if(e.isZero())throw Error("divisor is zero");return n.mod(e)}function Qn(n,e){if(e.isZero())throw Error("rhs is zero");let t=n.div(e);if(t.isZero())throw Error("quotient is zero");let r=et(n,e);return r.gt(xe)&&(t=t.add(new Ae.default(1)),e=n.div(t),r=et(n,t),r.gt(xe)&&(e=e.add(new Ae.default(1)))),[t,e]}var xe=new Ae.default(0),tt=class{static swapWithoutFees(e,t,r){let s=t.mul(r),i=t.add(e),[a]=Qn(s,i),o=r.sub(a);if(o.isZero())throw Error("destinationAmountSwapped is zero");return{destinationAmountSwapped:o}}static lpTokensToTradingTokens(e,t,r,s,i){let a=e.mul(r).div(t),o=e.mul(s).div(t);if(i===0)return{tokenAmount0:a,tokenAmount1:o};if(i===1)return et(e.mul(r),t).gt(xe)&&a.gt(xe)&&(a=a.add(new Ae.default(1))),et(e.mul(s),t).gt(xe)&&o.gt(xe)&&(o=o.add(new Ae.default(1))),{tokenAmount0:a,tokenAmount1:o};throw Error("roundDirection value error")}};var St=q(require("bn.js")),Bt=new St.default(1e6);function er(n,e,t){return n.mul(e).add(t).sub(new St.default(1)).div(t)}function cn(n,e,t){return n.mul(e).div(t)}var nt=class{static tradingFee(e,t){return er(e,t,Bt)}static protocolFee(e,t){return cn(e,t,Bt)}static fundFee(e,t){return cn(e,t,Bt)}};var ot=class{static validate_supply(e,t){if(e.isZero())throw Error("tokenAmount0 is zero");if(t.isZero())throw Error("tokenAmount1 is zero")}static swap(e,t,r,s){let i=nt.tradingFee(e,s),a=e.sub(i),{destinationAmountSwapped:o}=tt.swapWithoutFees(a,t,r);return{newSwapDestinationAmount:r.sub(o),sourceAmountSwapped:e,destinationAmountSwapped:o,tradeFee:i}}static swapBaseOut({poolMintA:e,poolMintB:t,tradeFeeRate:r,baseReserve:s,quoteReserve:i,outputMint:a,outputAmount:o}){let[l,u,f,m,d]=t.address===a.toString()?[s,i,e.decimals,t.decimals,e.address]:[i,s,t.decimals,e.decimals,t.address],c=new _e.default(u.toString()).div(Y(10,m)).div(new _e.default(l.toString()).div(Y(10,f))),y=o.gte(u)?u.sub(new rt.default(1)):o,T=u.sub(y),p=we(l.mul(y),T),x=we(p.mul(new rt.default(1e6)),new rt.default(1e6).sub(r)),h=x.sub(p),S=new _e.default(y.toString()).div(Y(10,m)).div(new _e.default(x.toString()).div(Y(10,f))),g=c.isZero()?0:S.sub(c).div(c).abs().toNumber();return{amountRealOut:y,amountIn:x,amountInWithoutFee:p,tradeFee:h,priceImpact:g}}};var v=q(require("bn.js")),Z=q(require("decimal.js"));var kt=(...n)=>n.map(e=>{try{return typeof e=="object"?JSON.stringify(e):e}catch(t){return e}}).join(", "),Ee=class{constructor({scope:e,moduleName:t}){this.disabled=!1;this.scope=e,this.logger=j(t)}createTxBuilder(e){return this.scope.checkOwner(),new Qe({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(kt(e))}logInfo(...e){this.logger.info(kt(e))}logAndCreateError(...e){let t=kt(e);throw new Error(t)}checkDisabled(){(this.disabled||!this.scope)&&this.logAndCreateError("module not working")}};var fn=require("@solana/web3.js"),Se=q(require("bn.js"));var I=require("@solana/buffer-layout"),It=I.Layout,ln=I.Structure;var Ct=I.UInt;var mn=I.u8,pn=I.u16;var dn=I.seq;var Be=I.blob;var Lt=class extends It{constructor(e,t,r){super(e,r),this.blob=Be(e),this.signed=t}decode(e,t=0){let r=new Se.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 Se.default(e)),this.signed&&(e=e.toTwos(this.span*8)),this.blob.encode(e.toArrayLike(Buffer,"le",this.span),t,r)}};function re(n){return new Ct(1,n)}function Nt(n){return new Ct(4,n)}function _(n){return new Lt(8,!1,n)}var it=class extends It{constructor(e,t,r,s){super(e.span,s),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 H(n){return new it(Be(32),e=>new fn.PublicKey(e),e=>e.toBuffer(),n)}function Mt(n){return new it(mn(),tr,nr,n)}function tr(n){if(n===0)return!1;if(n===1)return!0;throw new Error("Invalid bool: "+n)}function nr(n){return n?1:0}var Kt=class extends ln{decode(e,t){return super.decode(e,t)}};function ee(n,e,t){return new Kt(n,e,t)}function Rt(n,e,t){let r,s=typeof e=="number"?e:(0,Se.isBN)(e)?e.toNumber():new Proxy(e,{get(i,a){if(!r){let o=Reflect.get(i,"count");r=(0,Se.isBN)(o)?o.toNumber():o,Reflect.set(i,"count",r)}return Reflect.get(i,a)},set(i,a,o){return a==="count"&&(r=o),Reflect.set(i,a,o)}});return dn(n,s,t)}var Ws=ee([Nt("mintAuthorityOption"),H("mintAuthority"),_("supply"),re("decimals"),re("isInitialized"),Nt("freezeAuthorityOption"),H("freezeAuthority")]);var rr=require("@solana/web3.js"),gn=require("@solana/spl-token");var ke=s=>{var i=s,{address:n,programId:e,decimals:t}=i,r=ie(i,["address","programId","decimals"]);return D({chainId:101,address:Ge(n).toBase58(),programId:e,logoURI:"",symbol:"",name:"",decimals:t,tags:[],extensions:r.extensions||{}},r)},ve=n=>n?V(D({},n),{transferFeeConfigAuthority:n.transferFeeConfigAuthority.toBase58(),withdrawWithheldAuthority:n.withdrawWithheldAuthority.toBase58(),withheldAmount:n.withheldAmount.toString(),olderTransferFee:V(D({},n.olderTransferFee),{epoch:n.olderTransferFee.epoch.toString(),maximumFee:n.olderTransferFee.maximumFee.toString()}),newerTransferFee:V(D({},n.newerTransferFee),{epoch:n.newerTransferFee.epoch.toString(),maximumFee:n.newerTransferFee.maximumFee.toString()})}):void 0;var ce=require("@solana/web3.js"),le=require("@solana/spl-token");var or=Buffer.from("vault_and_lp_mint_auth_seed","utf8"),Qs=Buffer.from("amm_config","utf8"),ir=Buffer.from("pool","utf8"),sr=Buffer.from("pool_lp_mint","utf8"),ar=Buffer.from("pool_vault","utf8"),ur=Buffer.from("observation","utf8");function st(n){return de([or],n)}function Dt(n,e,t,r){return de([ir,e.toBuffer(),t.toBuffer(),r.toBuffer()],n)}function cr(n,e){return de([sr,e.toBuffer()],n)}function bn(n,e,t){return de([ar,e.toBuffer(),t.toBuffer()],n)}function Ve(n,e){return de([ur,e.toBuffer()],n)}function yn({poolId:n,programId:e,configId:t,mintA:r,mintB:s}){let i=st(e).publicKey,a=n||Dt(e,t,r,s).publicKey,o=cr(e,a).publicKey,l=bn(e,a,r).publicKey,u=bn(e,a,s).publicKey,f=Ve(e,a).publicKey;return{poolId:a,configId:t,authority:i,lpMint:o,vaultA:l,vaultB:u,observationId:f}}var ea=Buffer.from("locked_liquidity","utf8");var lr=j("Sega_cpmm"),qe={initialize:[175,175,109,31,13,152,155,237],deposit:[242,35,198,137,82,225,242,182],withdraw:[183,18,70,156,148,109,161,34],swapBaseInput:[143,190,90,218,196,30,51,222],swapBaseOutput:[55,217,98,86,163,74,180,173],lockCpLiquidity:[216,157,29,78,38,51,31,26],collectCpFee:[8,30,51,199,209,184,247,133]};function hn(n,e,t,r,s,i,a,o,l,u,f,m,d,c,y,T,p,x,h,S){let g=ee([_("amountMaxA"),_("amountMaxB"),_("openTime")]),P=Dt(n,t,i,a).publicKey,b=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!s.equals(P),isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!0},{pubkey:f,isSigner:!1,isWritable:!0},{pubkey:m,isSigner:!1,isWritable:!0},{pubkey:d,isSigner:!1,isWritable:!0},{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:p,isSigner:!1,isWritable:!0},{pubkey:le.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:y,isSigner:!1,isWritable:!1},{pubkey:T,isSigner:!1,isWritable:!1},{pubkey:le.ASSOCIATED_TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:Yt,isSigner:!1,isWritable:!1},{pubkey:zt,isSigner:!1,isWritable:!1}],w=Buffer.alloc(g.span);return g.encode({amountMaxA:x,amountMaxB:h,openTime:S},w),new ce.TransactionInstruction({keys:b,programId:n,data:Buffer.from([...qe.initialize,...w])})}function Tn(n,e,t,r,s,i,a,o,l,u,f,m,d,c,y){let T=ee([_("lpAmount"),_("amountMaxA"),_("amountMaxB")]),p=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:le.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:le.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:f,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!0}],x=Buffer.alloc(T.span);return lr.debug("cpmm deposit data",{lpAmount:d.toString(),amountMaxA:c.toString(),amountMaxB:y.toString()}),T.encode({lpAmount:d,amountMaxA:c,amountMaxB:y},x),new ce.TransactionInstruction({keys:p,programId:n,data:Buffer.from([...qe.deposit,...x])})}function Pn(n,e,t,r,s,i,a,o,l,u,f,m,d,c,y){let T=ee([_("lpAmount"),_("amountMinA"),_("amountMinB")]),p=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:le.TOKEN_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:le.TOKEN_2022_PROGRAM_ID,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:f,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!0},{pubkey:jt,isSigner:!1,isWritable:!1}],x=Buffer.alloc(T.span);return T.encode({lpAmount:d,amountMinA:c,amountMinB:y},x),new ce.TransactionInstruction({keys:p,programId:n,data:Buffer.from([...qe.withdraw,...x])})}function wn(n,e,t,r,s,i,a,o,l,u,f,m,d,c,y,T){let p=ee([_("amountIn"),_("amounOutMin")]),x=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:f,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:c,isSigner:!1,isWritable:!0}],h=Buffer.alloc(p.span);return p.encode({amountIn:y,amounOutMin:T},h),new ce.TransactionInstruction({keys:x,programId:n,data:Buffer.from([...qe.swapBaseInput,...h])})}function xn(n,e,t,r,s,i,a,o,l,u,f,m,d,c,y,T){let p=ee([_("amountInMax"),_("amountOut")]),x=[{pubkey:e,isSigner:!0,isWritable:!1},{pubkey:t,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:i,isSigner:!1,isWritable:!0},{pubkey:a,isSigner:!1,isWritable:!0},{pubkey:o,isSigner:!1,isWritable:!0},{pubkey:l,isSigner:!1,isWritable:!0},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:f,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!1},{pubkey:d,isSigner:!1,isWritable:!1},{pubkey:c,isSigner:!1,isWritable:!0}],h=Buffer.alloc(p.span);return p.encode({amountInMax:y,amountOut:T},h),new ce.TransactionInstruction({keys:x,programId:n,data:Buffer.from([...qe.swapBaseOutput,...h])})}var An=ee([Be(8),re("bump"),Mt("disableCreatePool"),pn("index"),_("tradeFeeRate"),_("protocolFeeRate"),_("fundFeeRate"),_("createPoolFee"),H("protocolOwner"),H("fundOwner"),Rt(_(),16)]),Bn=ee([Be(8),H("configId"),H("poolCreator"),H("vaultA"),H("vaultB"),H("mintLp"),H("mintA"),H("mintB"),H("mintProgramA"),H("mintProgramB"),H("observationId"),re("bump"),re("status"),re("lpDecimals"),re("mintDecimalA"),re("mintDecimalB"),_("lpAmount"),_("protocolFeesMintA"),_("protocolFeesMintB"),_("fundFeesMintA"),_("fundFeesMintB"),_("openTime"),Rt(_(),32)]);var at=class extends Ee{constructor(e){super(e)}load(){return k(this,null,function*(){this.checkDisabled()})}getCpmmPoolKeys(e){return k(this,null,function*(){return(yield this.scope.api.fetchPoolKeysById({idList:[e]}))[0]})}getRpcPoolInfo(e,t){return k(this,null,function*(){return(yield this.getRpcPoolInfos([e],t))[e]})}getRpcPoolInfos(e,t){return k(this,null,function*(){let r=yield Le(this.scope.connection,e.map(m=>({pubkey:new B.PublicKey(m)}))),s={},i=new Set,a=[];for(let m=0;m<e.length;m++){let d=r[m];if(d.accountInfo===null)throw Error("fetch pool info error: "+String(e[m]));let c=Bn.decode(d.accountInfo.data);s[String(e[m])]=V(D({},c),{programId:d.accountInfo.owner}),i.add