@sega-so/sega-sdk
Version:
An SDK for building applications on top of SEGA.
1 lines • 64.4 kB
JavaScript
var Tn=Object.defineProperty,Pn=Object.defineProperties;var wn=Object.getOwnPropertyDescriptors;var Fe=Object.getOwnPropertySymbols;var Kt=Object.prototype.hasOwnProperty,Nt=Object.prototype.propertyIsEnumerable;var U=Math.pow,Lt=(n,e,t)=>e in n?Tn(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(Fe)for(var t of Fe(e))Nt.call(e,t)&&Lt(n,t,e[t]);return n},_=(n,e)=>Pn(n,wn(e));var Q=(n,e)=>{var t={};for(var r in n)Kt.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&Fe)for(var r of Fe(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 B}from"@solana/web3.js";import{AccountLayout as Ar,NATIVE_MINT as Qe,TOKEN_PROGRAM_ID as re}from"@solana/spl-token";import ne from"bn.js";import _s from"decimal.js";import tr from"big.js";import ws 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 Dt}from"@solana/web3.js";import{MINT_SIZE as Bn,TOKEN_PROGRAM_ID as Sn,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:T,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:T,owner:new Dt(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)=>_(R({},s),{accountInfo:r[i]}))})}function Ft(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:Oe(u)})),t),i={};for(let u of s){if(!u.accountInfo||u.accountInfo.data.length<Bn){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()]=_(R({},f),{programId:((o=u.accountInfo)==null?void 0:o.owner)||Sn,feeConfig:(l=kn(f))!=null?l:void 0})}return i[Dt.default.toBase58()]=i[ee.toBase58()],i})}import Te from"bn.js";var Ot=9007199254740991;function te(n){let e=V("Sega_parseBigNumberish");if(n instanceof Te)return n;if(typeof n=="string"){if(n.match(/^-?[0-9]+$/))return new Te(n);e.logWithError(`invalid BigNumberish string: ${n}`)}return typeof n=="number"?(n%1&&e.logWithError(`BigNumberish number underflow: ${n}`),(n>=Ot||n<=-Ot)&&e.logWithError(`BigNumberish number overflow: ${n}`),new Te(String(n))):typeof n=="bigint"?new Te(n.toString()):(e.error(`invalid BigNumberish value: ${n}`),new Te(0))}import{PublicKey as Cn}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as Wt}from"@solana/spl-token";var ot={chainId:101,address:Cn.default.toBase58(),programId:Wt.toBase58(),decimals:9,symbol:"SOL",name:"solana",logoURI:"https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"sega",extensions:{coingeckoId:"solana"}},oe={chainId:101,address:"So11111111111111111111111111111111111111112",programId:Wt.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 W,SystemProgram as _t,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 Hr=[it({pubkey:Kn,isWritable:!1}),it({pubkey:_t.programId,isWritable:!1}),it({pubkey:Ln,isWritable:!1})];function st({publicKey:n,transformSol:e}){let t=Et(n.toString());if(t instanceof W)return e&&t.equals(Pe)?ee:t;if(e&&t.toString()===Pe.toBase58())return ee;if(typeof t=="string"){if(t===W.default.toBase58())return W.default;try{return new W(t)}catch(r){throw new Error("invalid public key")}}throw new Error("invalid public key")}function Et(n){try{return new W(n)}catch(e){return n}}var Yr=new W("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),vt=new W("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),Vt=new W("SysvarRent111111111111111111111111111111111"),Zr=new W("SysvarC1ock11111111111111111111111111111111"),qt=new W("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),Jr=new W("Sysvar1nstructions1111111111111111111111111"),Ut=_t.programId,Xr=new W("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),$r=new W("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),Qr=new W("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),eo=new W("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),to=new W("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),no=new W("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),ro=new W("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),oo=new W("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),io=new W("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),so=new W("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),ao=new W("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),ee=new W("So11111111111111111111111111111111111111112"),Pe=W.default;function Oe(n){return st({publicKey:n,transformSol:!0})}var We=class We{constructor({mint:e,decimals:t,symbol:r,name:s,skipMint:i=!1,isToken2022:a=!1}){if(e===Pe.toBase58()||e instanceof at&&Pe.equals(e)){this.decimals=oe.decimals,this.symbol=oe.symbol,this.name=oe.name,this.mint=new at(oe.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)}};We.WSOL=new We(_(R({},oe),{mint:oe.address}));var me=We;var _e=class _e{constructor({decimals:e,symbol:t="UNKNOWN",name:r="UNKNOWN"}){this.decimals=e,this.symbol=t,this.name=r}equals(e){return this===e}};_e.SOL=new _e(ot);var ut=_e;import Nn from"toformat";var Mn=Nn,we=Mn;import ve from"big.js";import Dn from"bn.js";import Fn from"decimal.js-light";var Ee=V("module/fraction"),ct=we(ve),xe=we(Fn),On={0:xe.ROUND_DOWN,1:xe.ROUND_HALF_UP,2:xe.ROUND_UP},Wn={0:ve.roundDown,1:ve.roundHalfUp,2:ve.roundUp},J=class n{constructor(e,t=new Dn(1)){this.numerator=te(e),this.denominator=te(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(te(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(te(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(te(e));return new n(this.numerator.mul(t.numerator),this.denominator.mul(t.denominator))}div(e){let t=e instanceof n?e:new n(te(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:On[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=Wn[r]||1,new ct(this.numerator.toString()).div(this.denominator.toString()).toFormat(e,t)}isZero(){return this.numerator.isZero()}};import _n from"bn.js";var Gt=new J(new _n(100)),H=class extends J{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 Oo=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 ie(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 Be({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 ie([n.toBuffer(),(t!=null?t:zn).toBuffer(),e.toBuffer()],new jn("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"))}import{PublicKey as se}from"@solana/web3.js";var Hn=new se("SegazTQwbYWknDZkJ6j2Kgvm5gw3MrHGKtWstZdoNKZ"),Yn=new se("Ajk8d9bERSaFdeoT1d8JUVfaDayrYLnAdgeB47TFMUaG"),hi=new se("2HbjxVVKJ7Ct72Rcd8WK4VTqmwTXL5aAggkH1CHGFGmh"),Zn=new se("auetiVUVJkRxvNPLYEvVnz8UJSqQ1VgoA83PcicHVD1"),Jn=new se("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y"),Xn=new se("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y");var Ti={SERUM_MARKET:se.default,UTIL1216:se.default,CREATE_CPMM_POOL_PROGRAM:Zn,CREATE_CPMM_POOL_AUTH:Jn,CREATE_CPMM_POOL_FEE_ACC:Xn};import Y from"bn.js";var Se=1e4;function le(n,e,t,r){if(e===void 0)return{amount:n,fee:void 0,expirationTime:void 0};let s=_(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 Y(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===Se){let l=new Y(i.maximumFee.toString());return{amount:n.add(l),fee:l,expirationTime:o}}else{let l=de(n.mul(new Y(Se)),new Y(Se-i.transferFeeBasisPoints)),u=new Y(i.maximumFee.toString()),f=l.sub(n).gt(u)?n.add(u):l,m=de(f.mul(new Y(i.transferFeeBasisPoints)),new Y(Se)),d=m.gt(a)?a:m;return{amount:f,fee:d,expirationTime:o}}else{let l=de(n.mul(new Y(i.transferFeeBasisPoints)),new Y(Se)),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 Y(0))?t.add(new Y(1)):t}import{PublicKey as $n,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 $n(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 Qn,Transaction as ke,TransactionMessage as Ie,VersionedTransaction as Ce}from"@solana/web3.js";import er 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 er.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(Qn.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: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 ft(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));ce(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,C=null,I=null,N=L=>{C!==null&&clearInterval(C),I!==null&&this.connection.removeSignatureListener(I);let K=P.findIndex(D=>D.txId===w);if(K>-1){if(P[K].status==="error"||P[K].status==="success")return;P[K].status=L.err?"error":"success"}d==null||d([...P]),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: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=Q(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));(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 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 S;let{skipPreflight:x=!0,sendAndConfirm:h}=p||{};if(ce([c]),(S=this.owner)!=null&&S.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 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),ce(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 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=[],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=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||S()};this.loopMultiTxStatus&&(b=setInterval(()=>k(this,null,function*(){var C;if(P){clearInterval(b);return}try{let I=yield this.connection.getTransaction(g,{commitment:"confirmed",maxSupportedTransactionVersion:0});I&&(P=!0,clearInterval(b),A({err:((C=I.meta)==null?void 0:C.err)||null}),console.log("tx status from getTransaction:",g))}catch(I){P=!0,clearInterval(b),console.error("getTransaction timeout:",I,g)}}),Ge)),w=this.connection.onSignature(g,C=>{if(P){this.connection.removeSignatureListener(w);return}P=!0,A(C)},"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=Q(m,["splitIns","computeBudgetConfig"]),i=r?Ve(r):{instructions:[],instructionTypes:[]},a=this.signers.reduce((c,y)=>_(R({},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 fe(h));if(c!==t[f]&&u.length<12&&(Ae({instructions:T,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(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);Ae({instructions:r?[...i.instructions,...u]:[...u],payer:this.feePayer,signers:y.map(T=>T.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: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])})),ce(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 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(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=[],C=()=>k(this,null,function*(){if(!b[w])return;w<p&&(A.push({txId:"",status:"success",signedTx:b[w]}),T==null||T([...A]),w++,C());let I=yield this.connection.sendRawTransaction(b[w].serialize(),{skipPreflight:h});A.push({txId:I,status:"sent",signedTx:b[w]}),T==null||T([...A]),w++;let N=!1,L=null,K=null,D=M=>{L!==null&&clearInterval(L),K!==null&&this.connection.removeSignatureListener(K);let O=A.findIndex(v=>v.txId===I);if(O>-1){if(A[O].status==="error"||A[O].status==="success")return;A[O].status=M.err?"error":"success"}T==null||T([...A]),M.err||C()};this.loopMultiTxStatus&&(L=setInterval(()=>k(this,null,function*(){var M;if(N){clearInterval(L);return}try{let O=yield this.connection.getTransaction(I,{commitment:"confirmed",maxSupportedTransactionVersion:0});O&&(N=!0,clearInterval(L),D({err:((M=O.meta)==null?void 0:M.err)||null}),console.log("tx status from getTransaction:",I))}catch(O){N=!0,clearInterval(L),console.error("getTransaction timeout:",O,I)}}),Ge)),K=this.connection.onSignature(I,M=>{if(N){this.connection.removeSignatureListener(K);return}N=!0,D(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 S;let h=e||{},{computeBudgetConfig:t,splitIns:r=[],lookupTableCache:s={},lookupTableAddress:i=[]}=h,a=Q(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,P]of Object.entries(f))o[g]=P;let m=t?Ve(t):{instructions:[],instructionTypes:[]},d=yield pe(this.connection,this.blockhashCommitment),c=this.signers.reduce((g,P)=>_(R({},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&&(Be({instructions:b,payer:this.feePayer,lookupTableAddressAccount:o})||Be({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&&Be({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))}T.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 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&&Be({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))}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 I;let{sequentially:P,onTxUpdate:b,skipTxCount:w=0,recentBlockHash:A,skipPreflight:C=!0}=g||{};if(y.map((N,L)=>k(this,null,function*(){T[L].length&&N.sign(T[L]),A&&(N.message.recentBlockhash=A)})),ce(y),(I=this.owner)!=null&&I.isKeyPair){if(P){let N=0,L=[];for(let K of y){if(++N,N<=w){console.log("skip tx: ",N),L.push("tx skipped");continue}let D=yield this.connection.sendTransaction(K,{skipPreflight:C});yield qe(this.connection,D),L.push(D)}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(P){let K=0,D=[],M=()=>k(this,null,function*(){if(!L[K])return;if(K<w){D.push({txId:"",status:"success",signedTx:L[K]}),b==null||b([...D]),K++,M();return}let O=yield this.connection.sendTransaction(L[K],{skipPreflight:C});D.push({txId:O,status:"sent",signedTx:L[K]}),b==null||b([...D]),K++;let v=!1,z=null,ae=null,Ct=ue=>{z!==null&&clearInterval(z),ae!==null&&this.connection.removeSignatureListener(ae);let $=D.findIndex(hn=>hn.txId===O);if($>-1){if(D[$].status==="error"||D[$].status==="success")return;D[$].status=ue.err?"error":"success"}b==null||b([...D]),ue.err||M()};this.loopMultiTxStatus&&(z=setInterval(()=>k(this,null,function*(){var ue;if(v){clearInterval(z);return}try{let $=yield this.connection.getTransaction(O,{commitment:"confirmed",maxSupportedTransactionVersion:0});$&&(v=!0,clearInterval(z),Ct({err:((ue=$.meta)==null?void 0:ue.err)||null}),console.log("tx status from getTransaction:",O))}catch($){v=!0,clearInterval(z),console.error("getTransaction timeout:",$,O)}}),Ge)),ae=this.connection.onSignature(O,ue=>{if(v){this.connection.removeSignatureListener(ae);return}v=!0,Ct(ue)},"confirmed"),this.connection.getSignatureStatus(O)});return M(),{txIds:[],signedTxs:L}}else{let K=[];for(let D=0;D<L.length;D+=1){let M=yield this.connection.sendTransaction(L[D],{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 Gi}from"@solana/web3.js";import zi from"bn.js";import{Connection as $i}from"@solana/web3.js";var Ks=V("Sega_amount"),Ns=we(tr);var mt=new ne(0),Ys=new ne(1),Zs=new ne(2),Js=new ne(3),Xs=new ne(5),nr=new ne(10),$s=new ne(100),Qs=new ne(1e3),ea=new ne(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 rr(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]=rr(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 or(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 or(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,T=u.sub(y),p=de(l.mul(y),T),x=de(p.mul(new bt(1e6)),new bt(1e6).sub(r)),h=x.sub(p),S=new Ze(y.toString()).div(U(10,m)).div(new Ze(x.toString()).div(U(10,f))),g=c.isZero()?0:S.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 pr}from"@solana/web3.js";import sn,{isBN as an}from"bn.js";import{bits as Aa,BitStructure as Ba,blob as ir,Blob as Sa,cstr as ka,f32 as Ia,f32be as Ca,f64 as La,f64be as Ka,greedy as Na,Layout as sr,ns64 as Ma,ns64be as Ra,nu64 as Da,nu64be as Fa,offset as Oa,s16 as Wa,s16be as _a,s24 as Ea,s24be as va,s32 as Va,s32be as qa,s40 as Ua,s40be as Ga,s48 as ja,s48be as za,s8 as Ha,seq as ar,struct as Ya,Structure as ur,u16 as cr,u16be as Za,u24 as Ja,u24be as Xa,u32 as $a,u32be as Qa,u40 as eu,u40be as tu,u48 as nu,u48be as ru,u8 as lr,UInt as mr,union as ou,Union as iu,unionLayoutDiscriminator as su,utf8 as au}from"@solana/buffer-layout";var ht=sr,tn=ur;var Tt=mr;var nn=lr,rn=cr;var on=ar;var be=ir;var Pt=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 X(n){return new Tt(1,n)}function xt(n){return new Tt(4,n)}function F(n){return new Pt(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 pr(e),e=>e.toBuffer(),n)}function At(n){return new Xe(nn(),dr,fr,n)}function dr(n){if(n===0)return!1;if(n===1)return!0;throw new Error("Invalid bool: "+n)}function fr(n){return n?1:0}var wt=class extends tn{decode(e,t){return super.decode(e,t)}};function Z(n,e,t){return new wt(n,e,t)}function Bt(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 xu=Z([xt("mintAuthorityOption"),q("mintAuthority"),F("supply"),X("decimals"),X("isInitialized"),xt("freezeAuthorityOption"),q("freezeAuthority")]);import{PublicKey as ku}from"@solana/web3.js";import{MintLayout as Cu,TOKEN_PROGRAM_ID as Ku}from"@solana/spl-token";var ye=s=>{var i=s,{address:n,programId:e,decimals:t}=i,r=Q(i,["address","programId","decimals"]);return R({chainId:101,address:Oe(n).toBase58(),programId:e,logoURI:"",symbol:"",name:"",decimals:t,tags:[],extensions:r.extensions||{}},r)},Ne=n=>n?_(R({},n),{transferFeeConfigAuthority:n.transferFeeConfigAuthority.toBase58(),withdrawWithheldAuthority:n.withdrawWithheldAuthority.toBase58(),withheldAmount:n.withheldAmount.toString(),olderTransferFee:_(R({},n.olderTransferFee),{epoch:n.olderTransferFee.epoch.toString(),maximumFee:n.olderTransferFee.maximumFee.toString()}),newerTransferFee:_(R({},n.newerTransferFee),{epoch:n.newerTransferFee.epoch.toString(),maximumFee:n.newerTransferFee.maximumFee.toString()})}):void 0;import{PublicKey as Ju,TransactionInstruction as Re,Keypair as $u,SystemProgram as Qu}from"@solana/web3.js";import{ASSOCIATED_TOKEN_PROGRAM_ID as wr,TOKEN_2022_PROGRAM_ID as ln,TOKEN_PROGRAM_ID as kt}from"@solana/spl-token";var gr=Buffer.from("vault_and_lp_mint_auth_seed","utf8"),Uu=Buffer.from("amm_config","utf8"),br=Buffer.from("pool","utf8"),yr=Buffer.from("pool_lp_mint","utf8"),hr=Buffer.from("pool_vault","utf8"),Tr=Buffer.from("observation","utf8");function $e(n){return ie([gr],n)}function St(n,e,t,r){return ie([br,e.toBuffer(),t.toBuffer(),r.toBuffer()],n)}function Pr(n,e){return ie([yr,e.toBuffer()],n)}function un(n,e,t){return ie([hr,e.toBuffer(),t.toBuffer()],n)}function Me(n,e){return ie([Tr,e.toBuffer()],n)}function cn({poolId:n,programId:e,configId:t,mintA:r,mintB:s}){let i=$e(e).publicKey,a=n||St(e,t,r,s).publicKey,o=Pr(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 Gu=Buffer.from("locked_liquidity","utf8");var xr=V("Sega_cpmm"),De={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,T,p,x,h,S){let g=Z([F("amountMaxA"),F("amountMaxB"),F("openTime")]),P=St(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:kt,isSigner:!1,isWritable:!1},{pubkey:y,isSigner:!1,isWritable:!1},{pubkey:T,isSigner:!1,isWritable:!1},{pubkey:wr,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:S},w),new Re({keys:b,programId:n,data:Buffer.from([...De.initialize,...w])})}function pn(n,e,t,r,s,i,a,o,l,u,f,m,d,c,y){let T=Z([F("lpAmount"),F("amountMaxA"),F("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(T.span);return xr.debug("cpmm deposit data",{lpAmount:d.toString(),amountMaxA:c.toString(),amountMaxB:y.toString()}),T.encode({lpAmount:d,amountMaxA:c,amountMaxB:y},x),new Re({keys:p,programId:n,data:Buffer.from([...De.deposit,...x])})}function dn(n,e,t,r,s,i,a,o,l,u,f,m,d,c,y){let T=Z([F("lpAmount"),F("amountMinA"),F("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(T.span);return T.encode({lpAmount:d,amountMinA:c,amountMinB:y},x),new Re({keys:p,programId:n,data:Buffer.from([...De.withdraw,...x])})}function fn(n,e,t,r,s,i,a,o,l,u,f,m,d,c,y,T){let p=Z([F("amountIn"),F("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 Re({keys:x,programId:n,data:Buffer.from([...De.swapBaseInput,...h])})}function gn(n,e,t,r,s,i,a,o,l,u,f,m,d,c,y,T){let p=Z([F("amountInMax"),F("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 Re({keys:x,programId:n,data:Buffer.from([...De.swapBaseOutput,...h])})}var bn=Z([be(8),X("bump"),At("disableCreatePool"),rn("index"),F("tradeFeeRate"),F("protocolFeeRate"),F("fundFeeRate"),F("createPoolFee"),q("protocolOwner"),q("fundOwner"),Bt(F(),16)]),yn=Z([be(8),q("configId"),q("poolCreator"),q("vaultA"),q("vaultB"),q("mintLp"),q("mintA"),q("mintB"),q("mintProgramA"),q("mintProgramB"),q("observationId"),X("bump"),X("status"),X("lpDecimals"),X("mintDecimalA"),X("mintDecimalB"),F("lpAmount"),F("protocolFeesMintA"),F("protocolFeesMintB"),F("fundFeesMintA"),F("fundFeesMintB"),F("openTime"),Bt(F(),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 B(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])]=_(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 B(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 B(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(Ar.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]=_(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.toString()).div(new j(10).pow(d.mintDecimalA)))})}return f})}toComputePoolInfos({pools:e,mintInfos:t}){return Object.keys(e).reduce((r,s)=>{var l,u,f,m;let i=e[s],[a,o]=[i.