UNPKG

@sega-so/sega-sdk

Version:

An SDK for building applications on top of SEGA.

1 lines 64.6 kB
var Pn=Object.defineProperty,Tn=Object.defineProperties;var wn=Object.getOwnPropertyDescriptors;var _e=Object.getOwnPropertySymbols;var Kt=Object.prototype.hasOwnProperty,Nt=Object.prototype.propertyIsEnumerable;var U=Math.pow,Lt=(n,e,t)=>e in n?Pn(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,R=(n,e)=>{for(var t in e||(e={}))Kt.call(e,t)&&Lt(n,t,e[t]);if(_e)for(var t of _e(e))Nt.call(e,t)&&Lt(n,t,e[t]);return n},W=(n,e)=>Tn(n,wn(e));var ee=(n,e)=>{var t={};for(var r in n)Kt.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&_e)for(var r of _e(n))e.indexOf(r)<0&&Nt.call(n,r)&&(t[r]=n[r]);return t};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())});import{PublicKey as S}from"@solana/web3.js";import{AccountLayout as Sr,NATIVE_MINT as Qe,TOKEN_PROGRAM_ID as oe}from"@solana/spl-token";import re from"bn.js";import js from"decimal.js";import nr from"big.js";import Cs from"bn.js";import{get as Mt,set as xn}from"lodash";var et=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={},An={};function V(n){let e=Mt(Rt,n);if(!e){let t=Mt(An,n);e=new et({name:n,logLevel:t}),xn(Rt,n,e)}return e}import{PublicKey as Ot}from"@solana/web3.js";import{MINT_SIZE as Sn,TOKEN_PROGRAM_ID as Bn,getTransferFeeConfig as kn,unpackMint as In}from"@solana/spl-token";var tt=V("Sega_accountInfo_util");function rt(n,e,t){return k(this,null,function*(){let{batchRequest:r,commitment:s="confirmed",chunkCount:i=100}=R({batchRequest:!1},t),a=nt(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=nt(l,10);o=(yield(yield Promise.all(u.map(m=>k(this,null,function*(){return yield n._rpcBatchRequest(m)})))).flat()).map(m=>(m.error&&tt.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:P,owner:p,rentEpoch:x}=d;return c.length!==2&&c[1]!=="base64"&&tt.logWithError("info must be base64 encoded, RPC_ERROR"),{data:Buffer.from(c[0],"base64"),executable:y,lamports:P,owner:new Ot(p),rentEpoch:x}}return null})))}else try{o=yield Promise.all(a.map(l=>n.getMultipleAccountsInfo(l,s)))}catch(l){l instanceof Error&&tt.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${l.message}`)}return o.flat()})}function he(n,e,t){return k(this,null,function*(){let r=yield rt(n,e.map(s=>s.pubkey),t);return e.map((s,i)=>W(R({},s),{accountInfo:r[i]}))})}function _t(r){return k(this,arguments,function*({connection:n,mints:e,config:t}){var a,o,l;if(e.length===0)return{};let s=yield he(n,e.map(u=>({pubkey:De(u)})),t),i={};for(let u of s){if(!u.accountInfo||u.accountInfo.data.length<Sn){console.log("invalid mint account",u.pubkey.toBase58());continue}let f=In(u.pubkey,u.accountInfo,(a=u.accountInfo)==null?void 0:a.owner);i[u.pubkey.toString()]=W(R({},f),{programId:((o=u.accountInfo)==null?void 0:o.owner)||Bn,feeConfig:(l=kn(f))!=null?l:void 0})}return i[Ot.default.toBase58()]=i[te.toBase58()],i})}import Pe from"bn.js";var Dt=9007199254740991;function ne(n){let e=V("Sega_parseBigNumberish");if(n instanceof Pe)return n;if(typeof n=="string"){if(n.match(/^-?[0-9]+$/))return new Pe(n);e.logWithError(`invalid BigNumberish string: ${n}`)}return typeof n=="number"?(n%1&&e.logWithError(`BigNumberish number underflow: ${n}`),(n>=Dt||n<=-Dt)&&e.logWithError(`BigNumberish number overflow: ${n}`),new Pe(String(n))):typeof n=="bigint"?new Pe(n.toString()):(e.error(`invalid BigNumberish value: ${n}`),new Pe(0))}import{PublicKey as Cn}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as Ft}from"@solana/spl-token";var ot={chainId:101,address:Cn.default.toBase58(),programId:Ft.toBase58(),decimals:9,symbol:"SOL",name:"solana",logoURI:"https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"sega",extensions:{coingeckoId:"solana"}},ie={chainId:101,address:"So11111111111111111111111111111111111111112",programId:Ft.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 at}from"@solana/web3.js";import{PublicKey as F,SystemProgram as Wt,SYSVAR_RENT_PUBKEY as Ln}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as Kn}from"@solana/spl-token";function it({pubkey:n,isSigner:e=!1,isWritable:t=!0}){return{pubkey:n,isWritable:t,isSigner:e}}var Yr=[it({pubkey:Kn,isWritable:!1}),it({pubkey:Wt.programId,isWritable:!1}),it({pubkey:Ln,isWritable:!1})];function st({publicKey:n,transformSol:e}){let t=Et(n.toString());if(t instanceof F)return e&&t.equals(Te)?te:t;if(e&&t.toString()===Te.toBase58())return te;if(typeof t=="string"){if(t===F.default.toBase58())return F.default;try{return new F(t)}catch(r){throw new Error("invalid public key")}}throw new Error("invalid public key")}function Et(n){try{return new F(n)}catch(e){return n}}var Zr=new F("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),vt=new F("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),Vt=new F("SysvarRent111111111111111111111111111111111"),Jr=new F("SysvarC1ock11111111111111111111111111111111"),qt=new F("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),Xr=new F("Sysvar1nstructions1111111111111111111111111"),Ut=Wt.programId,$r=new F("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),Qr=new F("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),eo=new F("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),to=new F("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),no=new F("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),ro=new F("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),oo=new F("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),io=new F("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),so=new F("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),ao=new F("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),uo=new F("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),te=new F("So11111111111111111111111111111111111111112"),Te=F.default;function De(n){return st({publicKey:n,transformSol:!0})}var Fe=class Fe{constructor({mint:e,decimals:t,symbol:r,name:s,skipMint:i=!1,isToken2022:a=!1}){if(e===Te.toBase58()||e instanceof at&&Te.equals(e)){this.decimals=ie.decimals,this.symbol=ie.symbol,this.name=ie.name,this.mint=new at(ie.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?at.default:st({publicKey:e}),this.isToken2022=a}equals(e){return this===e?!0:this.mint.equals(e.mint)}};Fe.WSOL=new Fe(W(R({},ie),{mint:ie.address}));var me=Fe;var We=class We{constructor({decimals:e,symbol:t="UNKNOWN",name:r="UNKNOWN"}){this.decimals=e,this.symbol=t,this.name=r}equals(e){return this===e}};We.SOL=new We(ot);var ut=We;import Nn from"toformat";var Mn=Nn,we=Mn;import ve from"big.js";import On from"bn.js";import _n from"decimal.js-light";var Ee=V("module/fraction"),ct=we(ve),xe=we(_n),Dn={0:xe.ROUND_DOWN,1:xe.ROUND_HALF_UP,2:xe.ROUND_UP},Fn={0:ve.roundDown,1:ve.roundHalfUp,2:ve.roundUp},X=class n{constructor(e,t=new On(1)){this.numerator=ne(e),this.denominator=ne(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(ne(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(ne(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(ne(e));return new n(this.numerator.mul(t.numerator),this.denominator.mul(t.denominator))}div(e){let t=e instanceof n?e:new n(ne(e));return new n(this.numerator.mul(t.denominator),this.denominator.mul(t.numerator))}toSignificant(e,t={groupSeparator:""},r=1){Number.isInteger(e)||Ee.logWithError(`${e} is not an integer.`),e<=0&&Ee.logWithError(`${e} is not positive.`),xe.set({precision:e+1,rounding:Dn[r]});let s=new xe(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)||Ee.logWithError(`${e} is not an integer.`),e<0&&Ee.logWithError(`${e} is negative.`),ct.DP=e,ct.RM=Fn[r]||1,new ct(this.numerator.toString()).div(this.denominator.toString()).toFormat(e,t)}isZero(){return this.numerator.isZero()}};import Wn from"bn.js";var Gt=new X(new Wn(100)),H=class extends X{toSignificant(e=5,t,r){return this.mul(Gt).toSignificant(e,t,r)}toFixed(e=2,t,r){return this.mul(Gt).toFixed(e,t,r)}};var Fo=V("Sega_price");function nt(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 jn}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as zn}from"@solana/spl-token";import{ComputeBudgetProgram as zt,Keypair as Yt,PublicKey as En,Transaction as Zt,TransactionMessage as vn,VersionedTransaction as Jt}from"@solana/web3.js";var G={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 Vn}from"@solana/spl-token";var Ht=V("Sega_txUtil"),Xt=1644;function Ve(n){let e=[],t=[];return n.microLamports&&(e.push(zt.setComputeUnitPrice({microLamports:n.microLamports})),t.push(G.SetComputeUnitPrice)),n.units&&(e.push(zt.setComputeUnitLimit({units:n.units})),t.push(G.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 qe(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 qn(n,e){n.length<1&&Ht.logWithError(`no instructions provided: ${n.toString()}`),e.length<1&&Ht.logWithError(`no signers provided:, ${e.toString()}`);let t=new Zt;t.recentBlockhash="11111111111111111111111111111111",t.feePayer=e[0],t.add(...n);try{return Buffer.from(t.serialize({verifySignatures:!1})).toString("base64").length<Xt}catch(r){return!1}}function se(n,e){let[t,r]=En.findProgramAddressSync(n,e);return{publicKey:t,nonce:r}}function Ae({instructions:n,payer:e,signers:t}){return qn(n,[e,...t])}function Se({instructions:n,payer:e,lookupTableAddressAccount:t,recentBlockhash:r=Yt.generate().publicKey.toString()}){let i=new vn({payerKey:e,recentBlockhash:r,instructions:n}).compileToV0Message(Object.values(t!=null?t:{}));try{return Buffer.from(new Jt(i).serialize()).toString("base64").length<Xt}catch(a){return!1}}var Un=n=>Buffer.isBuffer(n)?n:n instanceof Uint8Array?Buffer.from(n.buffer,n.byteOffset,n.byteLength):Buffer.from(n),Gn=n=>{let e=n.serialize({requireAllSignatures:!1,verifySignatures:!1});n instanceof Jt&&(e=Un(e));try{return e instanceof Buffer?e.toString("base64"):Buffer.from(e).toString("base64")}catch(t){return e.toString("base64")}};function ce(n){let e=[];return n.forEach(t=>{t instanceof Zt&&(t.recentBlockhash||(t.recentBlockhash=Vn.toBase58()),t.feePayer||(t.feePayer=Yt.generate().publicKey)),e.push(Gn(t))}),console.log("simulate tx string:",e),e}function pt(n,e,t){return se([n.toBuffer(),(t!=null?t:zn).toBuffer(),e.toBuffer()],new jn("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"))}import{PublicKey as Y}from"@solana/web3.js";var Hn=new Y("SegazTQwbYWknDZkJ6j2Kgvm5gw3MrHGKtWstZdoNKZ"),Yn=new Y("Ajk8d9bERSaFdeoT1d8JUVfaDayrYLnAdgeB47TFMUaG"),Pi=new Y("2HbjxVVKJ7Ct72Rcd8WK4VTqmwTXL5aAggkH1CHGFGmh"),Zn=new Y("TegaRdjn9Qeh9DfUU28X19aPPpJtj9gs8ntSYrR5H4K "),Jn=new Y("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y"),Xn=new Y("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y"),Ti=new Y("SegaXNnoXYTZiqUt9Xn2XqGcL56b25yzXLuJSpadcMu"),wi=new Y("2t1hV2YqnDCPuJZqr7Fy8oAygGwZE5Q9uaQzpLC1QryJ"),xi=new Y("BLxynZeHE123MmQgNJZiV1pwW4VYh46oZYyC66xwmtTY");var $n={SERUM_MARKET:Y.default,UTIL1216:Y.default,CREATE_CPMM_POOL_PROGRAM:Zn,CREATE_CPMM_POOL_AUTH:Jn,CREATE_CPMM_POOL_FEE_ACC:Xn};import Z from"bn.js";var Be=1e4;function le(n,e,t,r){if(e===void 0)return{amount:n,fee:void 0,expirationTime:void 0};let s=W(R({},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 Z(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===Be){let l=new Z(i.maximumFee.toString());return{amount:n.add(l),fee:l,expirationTime:o}}else{let l=de(n.mul(new Z(Be)),new Z(Be-i.transferFeeBasisPoints)),u=new Z(i.maximumFee.toString()),f=l.sub(n).gt(u)?n.add(u):l,m=de(f.mul(new Z(i.transferFeeBasisPoints)),new Z(Be)),d=m.gt(a)?a:m;return{amount:f,fee:d,expirationTime:o}}else{let l=de(n.mul(new Z(i.transferFeeBasisPoints)),new Z(Be)),u=l.gt(a)?a:l;return{amount:n,fee:u,expirationTime:o}}}function de(n,e){let{div:t,mod:r}=n.divmod(e);return r.gt(new Z(0))?t.add(new Z(1)):t}import{PublicKey as Qn,AddressLookupTableAccount as $t}from"@solana/web3.js";function dt(t){return k(this,arguments,function*({connection:n,address:e}){let r=yield rt(n,[...new Set(e.map(i=>i.toString()))].map(i=>new Qn(i))),s={};for(let i=0;i<e.length;i++){let a=r[i],o=e[i];if(!a)continue;let l=new $t({key:o,state:$t.deserialize(a.data)});s[o.toString()]=l,Ue[o.toString()]=l}return s})}var Ue={};import{PublicKey as fe,sendAndConfirmTransaction as ft,SystemProgram as er,Transaction as ke,TransactionMessage as Ie,VersionedTransaction as Ce}from"@solana/web3.js";import tr from"axios";var Ge=2e3,je=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 tr.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}=Ve(e);return this.instructions.unshift(...t),this.instructionTypes.unshift(...r),!0}return!1}addTipInstruction(e){var t;return e?(this.endInstructions.push(er.transfer({fromPubkey:(t=e.feePayer)!=null?t:this.feePayer,toPubkey:new fe(e.address),lamports:BigInt(e.amount.toString())})),this.endInstructionTypes.push(G.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!==fe.default.toString())),this}versionBuild(r){return k(this,arguments,function*({txVersion:e,extInfo:t}){return e===0?yield this.buildV0(R({},t||{})):this.build(t)})}build(e){var r;let t=new ke;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),ce([t]),(u=this.owner)!=null&&u.isKeyPair)return{txId:o?yield ft(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:P=!0}=f||{},p=y!=null?y:yield pe(this.connection,this.blockhashCommitment);if((x=this.owner)!=null&&x.isKeyPair){if(m){let h=[],B=0;for(let g of a){if(++B,B<=c)continue;let T=yield ft(this.connection,g,this.signers.find(b=>b.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:P});h.push(T)}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:P})}))),signedTxs:a}}if(this.signAllTransactions){let h=a.map((g,T)=>(g.recentBlockhash=p,o[T].length&&g.sign(...o[T]),g));ce(h);let B=yield this.signAllTransactions(h);if(m){let g=0,T=[],b=()=>k(this,null,function*(){if(!B[g])return;let w=yield this.connection.sendRawTransaction(B[g].serialize(),{skipPreflight:P});T.push({txId:w,status:"sent",signedTx:B[g]}),d==null||d([...T]),g++;let A=!1,C=null,I=null,N=L=>{C!==null&&clearInterval(C),I!==null&&this.connection.removeSignatureListener(I);let K=T.findIndex(O=>O.txId===w);if(K>-1){if(T[K].status==="error"||T[K].status==="success")return;T[K].status=L.err?"error":"success"}d==null||d([...T]),L.err||b()};this.loopMultiTxStatus&&(C=setInterval(()=>k(this,null,function*(){var L;if(A){clearInterval(C);return}try{let K=yield this.connection.getTransaction(w,{commitment:"confirmed",maxSupportedTransactionVersion:0});K&&(A=!0,clearInterval(C),N({err:((L=K.meta)==null?void 0:L.err)||null}),console.log("tx status from getTransaction:",w))}catch(K){A=!0,clearInterval(C),console.error("getTransaction timeout:",K,w)}}),Ge)),I=this.connection.onSignature(w,L=>{if(A){this.connection.removeSignatureListener(I);return}A=!0,N(L)},"confirmed"),this.connection.getSignatureStatus(w)});return yield b(),{txIds:T.map(w=>w.txId),signedTxs:B}}else{let g=[];for(let T=0;T<B.length;T+=1){let b=yield this.connection.sendRawTransaction(B[T].serialize(),{skipPreflight:P});g.push(b)}return{txIds:g,signedTxs:B}}}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 P;let y=e||{},{lookupTableCache:t={},lookupTableAddress:r=[],forerunCreate:s,recentBlockhash:i}=y,a=ee(y,["lookupTableCache","lookupTableAddress","forerunCreate","recentBlockhash"]),o=R(R({},this.cluster==="devnet"?{}:Ue),t),l=Array.from(new Set([...r,...this.lookupTableAddress])),u=[];for(let p of l)o[p]===void 0&&u.push(new fe(p));let f=yield dt({connection:this.connection,address:u});for(let[p,x]of Object.entries(f))o[p]=x;let m=s?fe.default.toBase58():i!=null?i:yield pe(this.connection,this.blockhashCommitment),d=new Ie({payerKey:this.feePayer,recentBlockhash:m,instructions:[...this.allInstructions]}).compileToV0Message(Object.values(o));(P=this.owner)!=null&&P.signer&&!this.signers.some(p=>p.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer);let c=new Ce(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 B;let{skipPreflight:x=!0,sendAndConfirm:h}=p||{};if(ce([c]),(B=this.owner)!=null&&B.isKeyPair){let g=yield this.connection.sendTransaction(c,{skipPreflight:x});return h&&(yield qe(this.connection,g)),{txId:g,signedTx:c}}if(this.signAllTransactions){let g=yield this.signAllTransactions([c]);if(this.signers.length)for(let T of g)try{T.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 P;let{sequentially:m,onTxUpdate:d,recentBlockHash:c,skipPreflight:y=!0}=f||{};if(c&&a.forEach(p=>p.message.recentBlockhash=c),ce(a),(P=this.owner)!=null&&P.isKeyPair){if(m){let p=[];for(let x of a){let h=yield this.connection.sendTransaction(x,{skipPreflight:y});yield qe(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=[],B=()=>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 T=!1,b=null,w=null,A=C=>{b!==null&&clearInterval(b),w!==null&&this.connection.removeSignatureListener(w);let I=h.findIndex(N=>N.txId===g);if(I>-1){if(h[I].status==="error"||h[I].status==="success")return;h[I].status=C.err?"error":"success"}d==null||d([...h]),C.err||B()};this.loopMultiTxStatus&&(b=setInterval(()=>k(this,null,function*(){var C;if(T){clearInterval(b);return}try{let I=yield this.connection.getTransaction(g,{commitment:"confirmed",maxSupportedTransactionVersion:0});I&&(T=!0,clearInterval(b),A({err:((C=I.meta)==null?void 0:C.err)||null}),console.log("tx status from getTransaction:",g))}catch(I){T=!0,clearInterval(b),console.error("getTransaction timeout:",I,g)}}),Ge)),w=this.connection.onSignature(g,C=>{if(T){this.connection.removeSignatureListener(w);return}T=!0,A(C)},"confirmed"),this.connection.getSignatureStatus(g)});return B(),{txIds:[],signedTxs:p}}else{let x=[];for(let h=0;h<p.length;h+=1){let B=yield this.connection.sendTransaction(p[h],{skipPreflight:y});x.push(B)}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=ee(m,["splitIns","computeBudgetConfig"]),i=r?Ve(r):{instructions:[],instructionTypes:[]},a=this.signers.reduce((c,y)=>W(R({},c),{[y.publicKey.toBase58()]:y}),{}),o=[],l=[],u=[],f=0;if(this.allInstructions.forEach(c=>{let y=[...u,c],P=r?[...i.instructions,...y]:y,x=[...new Set(y.map(h=>h.keys.filter(B=>B.isSigner).map(B=>B.pubkey.toString())).flat()).values()].map(h=>new fe(h));if(c!==t[f]&&u.length<12&&(Ae({instructions:P,payer:this.feePayer,signers:x})||Ae({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,Ae({instructions:r?[...i.instructions,...u]:[...u],payer:this.feePayer,signers:x})?o.push(new ke().add(...i.instructions,...u)):o.push(new ke().add(...u)),l.push(Array.from(new Set(u.map(h=>h.keys.filter(B=>B.isSigner).map(B=>B.pubkey.toString())).flat())).map(h=>a[h]).filter(h=>h!==void 0)),u=[c]}}),u.length>0){let y=[...new Set(u.map(P=>P.keys.filter(p=>p.isSigner).map(p=>p.pubkey.toString())).flat()).values()].map(P=>a[P]).filter(P=>P!==void 0);Ae({instructions:r?[...i.instructions,...u]:[...u],payer:this.feePayer,signers:y.map(P=>P.publicKey)})?o.push(new ke().add(...i.instructions,...u)):o.push(new ke().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:P,skipTxCount:p=0,recentBlockHash:x,skipPreflight:h=!0}=c||{},B=x!=null?x:yield pe(this.connection,this.blockhashCommitment);if(o.forEach((T,b)=>k(this,null,function*(){T.recentBlockhash=B,l[b].length&&T.sign(...l[b])})),ce(o),(g=this.owner)!=null&&g.isKeyPair){if(y){let T=0,b=[];for(let w of o){if(++T,T<=p){b.push("tx skipped");continue}let A=yield ft(this.connection,w,this.signers.find(C=>C.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(T=>k(this,null,function*(){return yield this.connection.sendRawTransaction(T.serialize(),{skipPreflight:h})}))),signedTxs:o}}if(this.signAllTransactions){let T=yield this.signAllTransactions(o.slice(p,o.length)),b=[...o.slice(0,p),...T];if(y){let w=0,A=[],C=()=>k(this,null,function*(){if(!b[w])return;w<p&&(A.push({txId:"",status:"success",signedTx:b[w]}),P==null||P([...A]),w++,C());let I=yield this.connection.sendRawTransaction(b[w].serialize(),{skipPreflight:h});A.push({txId:I,status:"sent",signedTx:b[w]}),P==null||P([...A]),w++;let N=!1,L=null,K=null,O=M=>{L!==null&&clearInterval(L),K!==null&&this.connection.removeSignatureListener(K);let D=A.findIndex(v=>v.txId===I);if(D>-1){if(A[D].status==="error"||A[D].status==="success")return;A[D].status=M.err?"error":"success"}P==null||P([...A]),M.err||C()};this.loopMultiTxStatus&&(L=setInterval(()=>k(this,null,function*(){var M;if(N){clearInterval(L);return}try{let D=yield this.connection.getTransaction(I,{commitment:"confirmed",maxSupportedTransactionVersion:0});D&&(N=!0,clearInterval(L),O({err:((M=D.meta)==null?void 0:M.err)||null}),console.log("tx status from getTransaction:",I))}catch(D){N=!0,clearInterval(L),console.error("getTransaction timeout:",D,I)}}),Ge)),K=this.connection.onSignature(I,M=>{if(N){this.connection.removeSignatureListener(K);return}N=!0,O(M)},"confirmed"),this.connection.getSignatureStatus(I)});return yield C(),{txIds:A.map(I=>I.txId),signedTxs:b}}else{let w=[];for(let A=0;A<b.length;A+=1){let C=yield this.connection.sendRawTransaction(b[A].serialize(),{skipPreflight:h});w.push(C)}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 B;let h=e||{},{computeBudgetConfig:t,splitIns:r=[],lookupTableCache:s={},lookupTableAddress:i=[]}=h,a=ee(h,["computeBudgetConfig","splitIns","lookupTableCache","lookupTableAddress"]),o=R(R({},this.cluster==="devnet"?{}:Ue),s),l=Array.from(new Set([...this.lookupTableAddress,...i])),u=[];for(let g of l)o[g]===void 0&&u.push(new fe(g));let f=yield dt({connection:this.connection,address:u});for(let[g,T]of Object.entries(f))o[g]=T;let m=t?Ve(t):{instructions:[],instructionTypes:[]},d=yield pe(this.connection,this.blockhashCommitment),c=this.signers.reduce((g,T)=>W(R({},g),{[T.publicKey.toBase58()]:T}),{}),y=[],P=[],p=[],x=0;if(this.allInstructions.forEach(g=>{let T=[...p,g],b=t?[...m.instructions,...T]:T;if(g!==r[x]&&p.length<12&&(Se({instructions:b,payer:this.feePayer,lookupTableAddressAccount:o})||Se({instructions:T,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&&Se({instructions:[...m.instructions,...p],payer:this.feePayer,lookupTableAddressAccount:o,recentBlockhash:d})){let A=new Ie({payerKey:this.feePayer,recentBlockhash:d,instructions:[...m.instructions,...p]}).compileToV0Message(Object.values(o));y.push(new Ce(A))}else{let A=new Ie({payerKey:this.feePayer,recentBlockhash:d,instructions:[...p]}).compileToV0Message(Object.values(o));y.push(new Ce(A))}P.push(Array.from(new Set(p.map(A=>A.keys.filter(C=>C.isSigner).map(C=>C.pubkey.toString())).flat())).map(A=>c[A]).filter(A=>A!==void 0)),p=[g]}}),p.length>0){let T=[...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&&Se({instructions:[...m.instructions,...p],payer:this.feePayer,lookupTableAddressAccount:o,recentBlockhash:d})){let b=new Ie({payerKey:this.feePayer,recentBlockhash:d,instructions:[...m.instructions,...p]}).compileToV0Message(Object.values(o));y.push(new Ce(b))}else{let b=new Ie({payerKey:this.feePayer,recentBlockhash:d,instructions:[...p]}).compileToV0Message(Object.values(o));y.push(new Ce(b))}P.push(T)}return(B=this.owner)!=null&&B.signer&&P.forEach(g=>{g.some(T=>T.publicKey.equals(this.owner.publicKey))||g.push(this.owner.signer)}),{builder:this,transactions:y,buildProps:e,signers:P,instructionTypes:this.instructionTypes,execute:g=>k(this,null,function*(){var I;let{sequentially:T,onTxUpdate:b,skipTxCount:w=0,recentBlockHash:A,skipPreflight:C=!0}=g||{};if(y.map((N,L)=>k(this,null,function*(){P[L].length&&N.sign(P[L]),A&&(N.message.recentBlockhash=A)})),ce(y),(I=this.owner)!=null&&I.isKeyPair){if(T){let N=0,L=[];for(let K of y){if(++N,N<=w){console.log("skip tx: ",N),L.push("tx skipped");continue}let O=yield this.connection.sendTransaction(K,{skipPreflight:C});yield qe(this.connection,O),L.push(O)}return{txIds:L,signedTxs:y}}return{txIds:yield Promise.all(y.map(N=>k(this,null,function*(){return yield this.connection.sendTransaction(N,{skipPreflight:C})}))),signedTxs:y}}if(this.signAllTransactions){let N=yield this.signAllTransactions(y.slice(w,y.length)),L=[...y.slice(0,w),...N];if(T){let K=0,O=[],M=()=>k(this,null,function*(){if(!L[K])return;if(K<w){O.push({txId:"",status:"success",signedTx:L[K]}),b==null||b([...O]),K++,M();return}let D=yield this.connection.sendTransaction(L[K],{skipPreflight:C});O.push({txId:D,status:"sent",signedTx:L[K]}),b==null||b([...O]),K++;let v=!1,z=null,ae=null,Ct=ue=>{z!==null&&clearInterval(z),ae!==null&&this.connection.removeSignatureListener(ae);let Q=O.findIndex(hn=>hn.txId===D);if(Q>-1){if(O[Q].status==="error"||O[Q].status==="success")return;O[Q].status=ue.err?"error":"success"}b==null||b([...O]),ue.err||M()};this.loopMultiTxStatus&&(z=setInterval(()=>k(this,null,function*(){var ue;if(v){clearInterval(z);return}try{let Q=yield this.connection.getTransaction(D,{commitment:"confirmed",maxSupportedTransactionVersion:0});Q&&(v=!0,clearInterval(z),Ct({err:((ue=Q.meta)==null?void 0:ue.err)||null}),console.log("tx status from getTransaction:",D))}catch(Q){v=!0,clearInterval(z),console.error("getTransaction timeout:",Q,D)}}),Ge)),ae=this.connection.onSignature(D,ue=>{if(v){this.connection.removeSignatureListener(ae);return}v=!0,Ct(ue)},"confirmed"),this.connection.getSignatureStatus(D)});return M(),{txIds:[],signedTxs:L}}else{let K=[];for(let O=0;O<L.length;O+=1){let M=yield this.connection.sendTransaction(L[O],{skipPreflight:C});K.push(M)}return{txIds:K,signedTxs:L}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:a||{}}})}};import{PublicKey as Hi}from"@solana/web3.js";import Zi from"bn.js";import{Connection as rs}from"@solana/web3.js";var Fs=V("Sega_amount"),Ws=we(nr);var mt=new re(0),ta=new re(1),na=new re(2),ra=new re(3),oa=new re(5),rr=new re(10),ia=new re(100),sa=new re(1e3),aa=new re(1e4);import bt from"bn.js";import Ze from"decimal.js-light";import Le from"bn.js";function ze(n,e){if(e.isZero())throw Error("divisor is zero");return n.mod(e)}function or(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=ze(n,e);return r.gt(ge)&&(t=t.add(new Le(1)),e=n.div(t),r=ze(n,t),r.gt(ge)&&(e=e.add(new Le(1)))),[t,e]}var ge=new Le(0),He=class{static swapWithoutFees(e,t,r){let s=t.mul(r),i=t.add(e),[a]=or(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 ze(e.mul(r),t).gt(ge)&&a.gt(ge)&&(a=a.add(new Le(1))),ze(e.mul(s),t).gt(ge)&&o.gt(ge)&&(o=o.add(new Le(1))),{tokenAmount0:a,tokenAmount1:o};throw Error("roundDirection value error")}};import en from"bn.js";var gt=new en(1e6);function ir(n,e,t){return n.mul(e).add(t).sub(new en(1)).div(t)}function Qt(n,e,t){return n.mul(e).div(t)}var Ye=class{static tradingFee(e,t){return ir(e,t,gt)}static protocolFee(e,t){return Qt(e,t,gt)}static fundFee(e,t){return Qt(e,t,gt)}};var Je=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=Ye.tradingFee(e,s),a=e.sub(i),{destinationAmountSwapped:o}=He.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 Ze(u.toString()).div(U(10,m)).div(new Ze(l.toString()).div(U(10,f))),y=o.gte(u)?u.sub(new bt(1)):o,P=u.sub(y),p=de(l.mul(y),P),x=de(p.mul(new bt(1e6)),new bt(1e6).sub(r)),h=x.sub(p),B=new Ze(y.toString()).div(U(10,m)).div(new Ze(x.toString()).div(U(10,f))),g=c.isZero()?0:B.sub(c).div(c).abs().toNumber();return{amountRealOut:y,amountIn:x,amountInWithoutFee:p,tradeFee:h,priceImpact:g}}};import E from"bn.js";import j from"decimal.js";var yt=(...n)=>n.map(e=>{try{return typeof e=="object"?JSON.stringify(e):e}catch(t){return e}}).join(", "),Ke=class{constructor({scope:e,moduleName:t}){this.disabled=!1;this.scope=e,this.logger=V(t)}createTxBuilder(e){return this.scope.checkOwner(),new je({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(yt(e))}logInfo(...e){this.logger.info(yt(e))}logAndCreateError(...e){let t=yt(e);throw new Error(t)}checkDisabled(){(this.disabled||!this.scope)&&this.logAndCreateError("module not working")}};import{PublicKey as dr}from"@solana/web3.js";import sn,{isBN as an}from"bn.js";import{bits as Ka,BitStructure as Na,blob as sr,Blob as Ma,cstr as Ra,f32 as Oa,f32be as _a,f64 as Da,f64be as Fa,greedy as Wa,Layout as ar,ns64 as Ea,ns64be as va,nu64 as Va,nu64be as qa,offset as Ua,s16 as Ga,s16be as ja,s24 as za,s24be as Ha,s32 as Ya,s32be as Za,s40 as Ja,s40be as Xa,s48 as $a,s48be as Qa,s8 as eu,seq as ur,struct as tu,Structure as cr,u16 as lr,u16be as nu,u24 as ru,u24be as ou,u32 as iu,u32be as su,u40 as au,u40be as uu,u48 as cu,u48be as lu,u8 as mr,UInt as pr,union as mu,Union as pu,unionLayoutDiscriminator as du,utf8 as fu}from"@solana/buffer-layout";var ht=ar,tn=cr;var Pt=pr;var nn=mr,rn=lr;var on=ur;var be=sr;var Tt=class extends ht{constructor(e,t,r){super(e,r),this.blob=be(e),this.signed=t}decode(e,t=0){let r=new sn(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 sn(e)),this.signed&&(e=e.toTwos(this.span*8)),this.blob.encode(e.toArrayLike(Buffer,"le",this.span),t,r)}};function $(n){return new Pt(1,n)}function xt(n){return new Pt(4,n)}function _(n){return new Tt(8,!1,n)}var Xe=class extends ht{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 q(n){return new Xe(be(32),e=>new dr(e),e=>e.toBuffer(),n)}function At(n){return new Xe(nn(),fr,gr,n)}function fr(n){if(n===0)return!1;if(n===1)return!0;throw new Error("Invalid bool: "+n)}function gr(n){return n?1:0}var wt=class extends tn{decode(e,t){return super.decode(e,t)}};function J(n,e,t){return new wt(n,e,t)}function St(n,e,t){let r,s=typeof e=="number"?e:an(e)?e.toNumber():new Proxy(e,{get(i,a){if(!r){let o=Reflect.get(i,"count");r=an(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 on(n,s,t)}var Lu=J([xt("mintAuthorityOption"),q("mintAuthority"),_("supply"),$("decimals"),$("isInitialized"),xt("freezeAuthorityOption"),q("freezeAuthority")]);import{PublicKey as Ru}from"@solana/web3.js";import{MintLayout as _u,TOKEN_PROGRAM_ID as Fu}from"@solana/spl-token";var ye=s=>{var i=s,{address:n,programId:e,decimals:t}=i,r=ee(i,["address","programId","decimals"]);return R({chainId:101,address:De(n).toBase58(),programId:e,logoURI:"",symbol:"",name:"",decimals:t,tags:[],extensions:r.extensions||{}},r)},Ne=n=>n?W(R({},n),{transferFeeConfigAuthority:n.transferFeeConfigAuthority.toBase58(),withdrawWithheldAuthority:n.withdrawWithheldAuthority.toBase58(),withheldAmount:n.withheldAmount.toString(),olderTransferFee:W(R({},n.olderTransferFee),{epoch:n.olderTransferFee.epoch.toString(),maximumFee:n.olderTransferFee.maximumFee.toString()}),newerTransferFee:W(R({},n.newerTransferFee),{epoch:n.newerTransferFee.epoch.toString(),maximumFee:n.newerTransferFee.maximumFee.toString()})}):void 0;import{PublicKey as rc,TransactionInstruction as Re,Keypair as ic,SystemProgram as sc}from"@solana/web3.js";import{ASSOCIATED_TOKEN_PROGRAM_ID as xr,TOKEN_2022_PROGRAM_ID as ln,TOKEN_PROGRAM_ID as kt}from"@solana/spl-token";var br=Buffer.from("vault_and_lp_mint_auth_seed","utf8"),Ju=Buffer.from("amm_config","utf8"),yr=Buffer.from("pool","utf8"),hr=Buffer.from("pool_lp_mint","utf8"),Pr=Buffer.from("pool_vault","utf8"),Tr=Buffer.from("observation","utf8");function $e(n){return se([br],n)}function Bt(n,e,t,r){return se([yr,e.toBuffer(),t.toBuffer(),r.toBuffer()],n)}function wr(n,e){return se([hr,e.toBuffer()],n)}function un(n,e,t){return se([Pr,e.toBuffer(),t.toBuffer()],n)}function Me(n,e){return se([Tr,e.toBuffer()],n)}function cn({poolId:n,programId:e,configId:t,mintA:r,mintB:s}){let i=$e(e).publicKey,a=n||Bt(e,t,r,s).publicKey,o=wr(e,a).publicKey,l=un(e,a,r).publicKey,u=un(e,a,s).publicKey,f=Me(e,a).publicKey;return{poolId:a,configId:t,authority:i,lpMint:o,vaultA:l,vaultB:u,observationId:f}}var Xu=Buffer.from("locked_liquidity","utf8");var Ar=V("Sega_cpmm"),Oe={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 mn(n,e,t,r,s,i,a,o,l,u,f,m,d,c,y,P,p,x,h,B){let g=J([_("amountMaxA"),_("amountMaxB"),_("openTime")]),T=Bt(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(T),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:kt,isSigner:!1,isWritable:!1},{pubkey:y,isSigner:!1,isWritable:!1},{pubkey:P,isSigner:!1,isWritable:!1},{pubkey:xr,isSigner:!1,isWritable:!1},{pubkey:Ut,isSigner:!1,isWritable:!1},{pubkey:Vt,isSigner:!1,isWritable:!1}],w=Buffer.alloc(g.span);return g.encode({amountMaxA:x,amountMaxB:h,openTime:B},w),new Re({keys:b,programId:n,data:Buffer.from([...Oe.initialize,...w])})}function pn(n,e,t,r,s,i,a,o,l,u,f,m,d,c,y){let P=J([_("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:kt,isSigner:!1,isWritable:!1},{pubkey:ln,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(P.span);return Ar.debug("cpmm deposit data",{lpAmount:d.toString(),amountMaxA:c.toString(),amountMaxB:y.toString()}),P.encode({lpAmount:d,amountMaxA:c,amountMaxB:y},x),new Re({keys:p,programId:n,data:Buffer.from([...Oe.deposit,...x])})}function dn(n,e,t,r,s,i,a,o,l,u,f,m,d,c,y){let P=J([_("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:kt,isSigner:!1,isWritable:!1},{pubkey:ln,isSigner:!1,isWritable:!1},{pubkey:u,isSigner:!1,isWritable:!1},{pubkey:f,isSigner:!1,isWritable:!1},{pubkey:m,isSigner:!1,isWritable:!0},{pubkey:vt,isSigner:!1,isWritable:!1}],x=Buffer.alloc(P.span);return P.encode({lpAmount:d,amountMinA:c,amountMinB:y},x),new Re({keys:p,programId:n,data:Buffer.from([...Oe.withdraw,...x])})}function fn(n,e,t,r,s,i,a,o,l,u,f,m,d,c,y,P){let p=J([_("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:P},h),new Re({keys:x,programId:n,data:Buffer.from([...Oe.swapBaseInput,...h])})}function gn(n,e,t,r,s,i,a,o,l,u,f,m,d,c,y,P){let p=J([_("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:P},h),new Re({keys:x,programId:n,data:Buffer.from([...Oe.swapBaseOutput,...h])})}var bn=J([be(8),$("bump"),At("disableCreatePool"),rn("index"),_("tradeFeeRate"),_("protocolFeeRate"),_("fundFeeRate"),_("createPoolFee"),q("protocolOwner"),q("fundOwner"),St(_(),16)]),yn=J([be(8),q("configId"),q("poolCreator"),q("vaultA"),q("vaultB"),q("mintLp"),q("mintA"),q("mintB"),q("mintProgramA"),q("mintProgramB"),q("observationId"),$("bump"),$("status"),$("lpDecimals"),$("mintDecimalA"),$("mintDecimalB"),_("lpAmount"),_("protocolFeesMintA"),_("protocolFeesMintB"),_("fundFeesMintA"),_("fundFeesMintB"),_("openTime"),St(_(),32)]);var It=class extends Ke{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 he(this.scope.connection,e.map(m=>({pubkey:new S(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=yn.decode(d.accountInfo.data);s[String(e[m])]=W(R({},c),{programId:d.accountInfo.owner}),i.add(String(c.configId)),a.push(c.vaultA,c.vaultB)}let o={};if(t){let m=[...i],d=yield he(this.scope.connection,m.map(c=>({pubkey:new S(c)})));for(let c=0;c<m.length;c++){let y=d[c].accountInfo;if(y===null)throw Error("fetch pool config error: "+m[c]);o[m[c]]=bn.decode(y.data)}}let l={},u=yield he(this.scope.connection,a.map(m=>({pubkey:new S(m)})));for(let m=0;m<a.length;m++){let d=u[m].accountInfo;if(d===null)throw Error("fetch vault info error: "+a[m]);l[String(a[m])]=new E(Sr.decode(d.data).amount.toString())}let f={};for(let[m,d]of Object.entries(s)){let c=l[d.vaultA.toString()].sub(d.protocolFeesMintA).sub(d.fundFeesMintA),y=l[d.vaultB.toString()].sub(d.protocolFeesMintB).sub(d.fundFeesMintB);f[m]=W(R({},d),{baseReserve:c,quoteReserve:y,vaultAAmount:l[d.vaultA.toString()],vaultBAmount:l[d.vaultB.toString()],configInfo:o[d.configId.toString()],poolPrice:new j(y.toString()).div(new j(10).pow(d.mintDecimalB)).div(new j(c.toStr