UNPKG

@sega-so/sega-sdk

Version:

An SDK for building applications on top of SEGA.

1 lines 103 kB
"use strict";var Io=Object.create;var He=Object.defineProperty,So=Object.defineProperties,Bo=Object.getOwnPropertyDescriptor,Co=Object.getOwnPropertyDescriptors,Ko=Object.getOwnPropertyNames,Tt=Object.getOwnPropertySymbols,Lo=Object.getPrototypeOf,Ut=Object.prototype.hasOwnProperty,_n=Object.prototype.propertyIsEnumerable;var se=Math.pow,Ln=(o,e,t)=>e in o?He(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,L=(o,e)=>{for(var t in e||(e={}))Ut.call(e,t)&&Ln(o,t,e[t]);if(Tt)for(var t of Tt(e))_n.call(e,t)&&Ln(o,t,e[t]);return o},E=(o,e)=>So(o,Co(e));var te=(o,e)=>{var t={};for(var n in o)Ut.call(o,n)&&e.indexOf(n)<0&&(t[n]=o[n]);if(o!=null&&Tt)for(var n of Tt(o))e.indexOf(n)<0&&_n.call(o,n)&&(t[n]=o[n]);return t};var _o=(o,e)=>{for(var t in e)He(o,t,{get:e[t],enumerable:!0})},On=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ko(e))!Ut.call(o,r)&&r!==t&&He(o,r,{get:()=>e[r],enumerable:!(n=Bo(e,r))||n.enumerable});return o};var q=(o,e,t)=>(t=o!=null?Io(Lo(o)):{},On(e||!o||!o.__esModule?He(t,"default",{value:o,enumerable:!0}):t,o)),Oo=o=>On(He({},"__esModule",{value:!0}),o);var b=(o,e,t)=>new Promise((n,r)=>{var i=c=>{try{s(t.next(c))}catch(u){r(u)}},a=c=>{try{s(t.throw(c))}catch(u){r(u)}},s=c=>c.done?n(c.value):Promise.resolve(c.value).then(i,a);s((t=t.apply(o,e)).next())});var Pr={};_o(Pr,{ConstantProductCurve:()=>mt,CpmmConfigInfoLayout:()=>In,CpmmFee:()=>pt,CpmmPoolInfoLayout:()=>Sn,CurveCalculator:()=>ft,FEE_RATE_DENOMINATOR_VALUE:()=>vt,LOCK_LIQUIDITY_SEED:()=>To,RoundDirection:()=>fn,SOL_INFO:()=>de,SPL_MINT_LAYOUT:()=>er,Sega:()=>Cn,TOKEN_WSOL:()=>ae,ceilDiv:()=>yo,closeAccountInstruction:()=>We,collectCpFeeInstruction:()=>br,cpmmLockPositionInstruction:()=>Po,createWSolAccountInstructions:()=>Ft,floorDiv:()=>gn,generatePubKey:()=>ct,getCpLockPda:()=>Tn,getCpmmPdaAmmConfigId:()=>dr,getCpmmPdaPoolId:()=>Vt,getCreatePoolKeys:()=>hn,getPdaLpMint:()=>ho,getPdaObservationId:()=>Ge,getPdaPoolAuthority:()=>yt,getPdaVault:()=>bn,initTokenAccountInstruction:()=>Et,makeCpmmLockInstruction:()=>yr,makeCreateCpmmPoolInInstruction:()=>Pn,makeDepositCpmmInInstruction:()=>An,makeSwapCpmmBaseInInstruction:()=>xn,makeSwapCpmmBaseOutInstruction:()=>kn,makeTransferInstruction:()=>dn,makeWithdrawCpmmInInstruction:()=>wn,parseTokenAccountResp:()=>pn,parseTokenInfo:()=>tr,solToWSolToken:()=>ir,splAccountLayout:()=>ve,toApiV3Token:()=>Re,toFeeConfig:()=>qe,toToken:()=>or,toTokenAmount:()=>rr,toTokenInfo:()=>nr,unionArr:()=>Tr,wSolToSolToken:()=>sr});module.exports=Oo(Pr);var xo=require("lodash");var sn=q(require("axios"));var Ht=require("@solana/web3.js");var ze=require("lodash");var qt=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(n=>typeof n=="object"?JSON.stringify(n):n).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}},Rn={},Ro={};function G(o){let e=(0,ze.get)(Rn,o);if(!e){let t=(0,ze.get)(Ro,o);e=new qt({name:o,logLevel:t}),(0,ze.set)(Rn,o,e)}return e}var xe=require("@solana/spl-token");var Gt=G("Sega_accountInfo_util");function Ye(o,e,t){return b(this,null,function*(){let{batchRequest:n,commitment:r="confirmed",chunkCount:i=100}=L({batchRequest:!1},t),a=jt(e,i),s=new Array(a.length).fill([]);if(n){let c=a.map(l=>({methodName:"getMultipleAccounts",args:o._buildArgs([l.map(d=>d.toBase58())],r,"base64")})),u=jt(c,10);s=(yield(yield Promise.all(u.map(l=>b(this,null,function*(){return yield o._rpcBatchRequest(l)})))).flat()).map(l=>(l.error&&Gt.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${l.error.message}`),l.result.value.map(p=>{if(p){let{data:d,executable:f,lamports:y,owner:g,rentEpoch:x}=p;return d.length!==2&&d[1]!=="base64"&&Gt.logWithError("info must be base64 encoded, RPC_ERROR"),{data:Buffer.from(d[0],"base64"),executable:f,lamports:y,owner:new Ht.PublicKey(g),rentEpoch:x}}return null})))}else try{s=yield Promise.all(a.map(c=>o.getMultipleAccountsInfo(c,r)))}catch(c){c instanceof Error&&Gt.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${c.message}`)}return s.flat()})}function Je(o,e,t){return b(this,null,function*(){let n=yield Ye(o,e.map(r=>r.pubkey),t);return e.map((r,i)=>E(L({},r),{accountInfo:n[i]}))})}function Nn(n){return b(this,arguments,function*({connection:o,mints:e,config:t}){var a,s,c;if(e.length===0)return{};let r=yield Je(o,e.map(u=>({pubkey:$e(u)})),t),i={};for(let u of r){if(!u.accountInfo||u.accountInfo.data.length<xe.MINT_SIZE){console.log("invalid mint account",u.pubkey.toBase58());continue}let m=(0,xe.unpackMint)(u.pubkey,u.accountInfo,(a=u.accountInfo)==null?void 0:a.owner);i[u.pubkey.toString()]=E(L({},m),{programId:((s=u.accountInfo)==null?void 0:s.owner)||xe.TOKEN_PROGRAM_ID,feeConfig:(c=(0,xe.getTransferFeeConfig)(m))!=null?c:void 0})}return i[Ht.PublicKey.default.toBase58()]=i[oe.toBase58()],i})}var be=q(require("bn.js")),Uo=q(require("decimal.js"));var Wn=q(require("big.js")),et=q(require("bn.js"));var Mn=q(require("toformat")),No=Mn.default,Ze=No;var Xe=q(require("big.js")),Fn=q(require("bn.js")),Dn=q(require("decimal.js-light"));var Me=q(require("bn.js"));var En=9007199254740991;function re(o){let e=G("Sega_parseBigNumberish");if(o instanceof Me.default)return o;if(typeof o=="string"){if(o.match(/^-?[0-9]+$/))return new Me.default(o);e.logWithError(`invalid BigNumberish string: ${o}`)}return typeof o=="number"?(o%1&&e.logWithError(`BigNumberish number underflow: ${o}`),(o>=En||o<=-En)&&e.logWithError(`BigNumberish number overflow: ${o}`),new Me.default(String(o))):typeof o=="bigint"?new Me.default(o.toString()):(e.error(`invalid BigNumberish value: ${o}`),new Me.default(0))}var Pt=G("module/fraction"),zt=Ze(Xe.default),Qe=Ze(Dn.default),Eo={0:Qe.ROUND_DOWN,1:Qe.ROUND_HALF_UP,2:Qe.ROUND_UP},Fo={0:Xe.default.roundDown,1:Xe.default.roundHalfUp,2:Xe.default.roundUp},pe=class o{constructor(e,t=new Fn.default(1)){this.numerator=re(e),this.denominator=re(t)}get quotient(){return this.numerator.div(this.denominator)}invert(){return new o(this.denominator,this.numerator)}add(e){let t=e instanceof o?e:new o(re(e));return this.denominator.eq(t.denominator)?new o(this.numerator.add(t.numerator),this.denominator):new o(this.numerator.mul(t.denominator).add(t.numerator.mul(this.denominator)),this.denominator.mul(t.denominator))}sub(e){let t=e instanceof o?e:new o(re(e));return this.denominator.eq(t.denominator)?new o(this.numerator.sub(t.numerator),this.denominator):new o(this.numerator.mul(t.denominator).sub(t.numerator.mul(this.denominator)),this.denominator.mul(t.denominator))}mul(e){let t=e instanceof o?e:new o(re(e));return new o(this.numerator.mul(t.numerator),this.denominator.mul(t.denominator))}div(e){let t=e instanceof o?e:new o(re(e));return new o(this.numerator.mul(t.denominator),this.denominator.mul(t.numerator))}toSignificant(e,t={groupSeparator:""},n=1){Number.isInteger(e)||Pt.logWithError(`${e} is not an integer.`),e<=0&&Pt.logWithError(`${e} is not positive.`),Qe.set({precision:e+1,rounding:Eo[n]});let r=new Qe(this.numerator.toString()).div(this.denominator.toString()).toSignificantDigits(e);return r.toFormat(r.decimalPlaces(),t)}toFixed(e,t={groupSeparator:""},n=1){return Number.isInteger(e)||Pt.logWithError(`${e} is not an integer.`),e<0&&Pt.logWithError(`${e} is negative.`),zt.DP=e,zt.RM=Fo[n]||1,new zt(this.numerator.toString()).div(this.denominator.toString()).toFormat(e,t)}isZero(){return this.numerator.isZero()}};var Do=G("Sega_amount"),vn=Ze(Wn.default);function vo(o,e){let t="0",n="0";if(o.includes(".")){let r=o.split(".");r.length===2?([t,n]=r,n=n.padEnd(e,"0")):Do.logWithError(`invalid number string, num: ${o}`)}else t=o;return[t,n.slice(0,e)||n]}var Ce=class o extends pe{constructor(e,t,n=!0,r){let i=new et.default(0),a=Vn.pow(new et.default(e.decimals));if(n)i=re(t);else{let s=new et.default(0),c=new et.default(0);if(typeof t=="string"||typeof t=="number"||typeof t=="bigint"){let[u,m]=vo(t.toString(),e.decimals);s=re(u),c=re(m)}s=s.mul(a),i=s.add(c)}super(i,a),this.logger=G(r||"TokenAmount"),this.token=e}get raw(){return this.numerator}isZero(){return this.raw.isZero()}gt(e){return this.token.equals(e.token)||this.logger.logWithError("gt token not equals"),this.raw.gt(e.raw)}lt(e){return this.token.equals(e.token)||this.logger.logWithError("lt token not equals"),this.raw.lt(e.raw)}add(e){return this.token.equals(e.token)||this.logger.logWithError("add token not equals"),new o(this.token,this.raw.add(e.raw))}subtract(e){return this.token.equals(e.token)||this.logger.logWithError("sub token not equals"),new o(this.token,this.raw.sub(e.raw))}toSignificant(e=this.token.decimals,t,n=0){return super.toSignificant(e,t,n)}toFixed(e=this.token.decimals,t,n=0){return e>this.token.decimals&&this.logger.logWithError("decimals overflow"),super.toFixed(e,t,n)}toExact(e={groupSeparator:""}){return vn.DP=this.token.decimals,new vn(this.numerator.toString()).div(this.denominator.toString()).toFormat(e)}};var Un=require("@solana/web3.js"),Yt=require("@solana/spl-token"),de={chainId:101,address:Un.PublicKey.default.toBase58(),programId:Yt.TOKEN_PROGRAM_ID.toBase58(),decimals:9,symbol:"SOL",name:"solana",logoURI:"https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"sega",extensions:{coingeckoId:"solana"}},ae={chainId:101,address:"So11111111111111111111111111111111111111112",programId:Yt.TOKEN_PROGRAM_ID.toBase58(),decimals:9,symbol:"WSOL",name:"Wrapped SOL",logoURI:"https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"sega",extensions:{coingeckoId:"solana"}};var At=require("@solana/web3.js");var v=require("@solana/web3.js"),qn=require("@solana/spl-token");function Jt({pubkey:o,isSigner:e=!1,isWritable:t=!0}){return{pubkey:o,isWritable:t,isSigner:e}}var Jr=[Jt({pubkey:qn.TOKEN_PROGRAM_ID,isWritable:!1}),Jt({pubkey:v.SystemProgram.programId,isWritable:!1}),Jt({pubkey:v.SYSVAR_RENT_PUBKEY,isWritable:!1})];function $t({publicKey:o,transformSol:e}){let t=Gn(o.toString());if(t instanceof v.PublicKey)return e&&t.equals(tt)?oe:t;if(e&&t.toString()===tt.toBase58())return oe;if(typeof t=="string"){if(t===v.PublicKey.default.toBase58())return v.PublicKey.default;try{return new v.PublicKey(t)}catch(n){throw new Error("invalid public key")}}throw new Error("invalid public key")}function Gn(o){try{return new v.PublicKey(o)}catch(e){return o}}var $r=new v.PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),Zt=new v.PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),Xt=new v.PublicKey("SysvarRent111111111111111111111111111111111"),Zr=new v.PublicKey("SysvarC1ock11111111111111111111111111111111"),nt=new v.PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),Xr=new v.PublicKey("Sysvar1nstructions1111111111111111111111111"),jn=v.SystemProgram.programId,Qr=new v.PublicKey("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),ei=new v.PublicKey("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),ti=new v.PublicKey("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),ni=new v.PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),oi=new v.PublicKey("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),ri=new v.PublicKey("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),ii=new v.PublicKey("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),si=new v.PublicKey("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),ai=new v.PublicKey("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),ui=new v.PublicKey("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),ci=new v.PublicKey("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),oe=new v.PublicKey("So11111111111111111111111111111111111111112"),tt=v.PublicKey.default;function $e(o){return $t({publicKey:o,transformSol:!0})}var wt=class wt{constructor({mint:e,decimals:t,symbol:n,name:r,skipMint:i=!1,isToken2022:a=!1}){if(e===tt.toBase58()||e instanceof At.PublicKey&&tt.equals(e)){this.decimals=ae.decimals,this.symbol=ae.symbol,this.name=ae.name,this.mint=new At.PublicKey(ae.address),this.isToken2022=!1;return}this.decimals=t,this.symbol=n||e.toString().substring(0,6),this.name=r||e.toString().substring(0,6),this.mint=i?At.PublicKey.default:$t({publicKey:e}),this.isToken2022=a}equals(e){return this===e?!0:this.mint.equals(e.mint)}};wt.WSOL=new wt(E(L({},ae),{mint:ae.address}));var ne=wt;var xt=class xt{constructor({decimals:e,symbol:t="UNKNOWN",name:n="UNKNOWN"}){this.decimals=e,this.symbol=t,this.name=n}equals(e){return this===e}};xt.SOL=new xt(de);var Qt=xt;var zn=q(require("bn.js"));var Hn=new pe(new zn.default(100)),fe=class extends pe{toSignificant(e=5,t,n){return this.mul(Hn).toSignificant(e,t,n)}toFixed(e=2,t,n){return this.mul(Hn).toFixed(e,t,n)}};var Ii=G("Sega_price");var Wo=require("@solana/web3.js"),Vo=q(require("bn.js"));var en=new be.default(0),os=new be.default(1),rs=new be.default(2),is=new be.default(3),ss=new be.default(5),Vn=new be.default(10),as=new be.default(100),us=new be.default(1e3),cs=new be.default(1e4);function jt(o,e=1,t=[]){let n=[...o];if(e<=0)return t;for(;n.length;)t.push(n.splice(0,e));return t}var ot=class o{constructor(e){this._owner=e}get publicKey(){return o.isKeyPair(this._owner)?this._owner.publicKey:this._owner}get signer(){return o.isKeyPair(this._owner)?this._owner:void 0}get isKeyPair(){return o.isKeyPair(this._owner)}get isPublicKey(){return o.isPublicKey(this._owner)}static isKeyPair(e){return e.secretKey!==void 0}static isPublicKey(e){return!o.isKeyPair(e)}};var Xn=require("@solana/web3.js"),Qn=require("@solana/spl-token");var Q=require("@solana/web3.js");var V={CreateAccount:"CreateAccount",InitAccount:"InitAccount",CreateATA:"CreateATA",CloseAccount:"CloseAccount",TransferAmount:"TransferAmount",InitMint:"InitMint",MintTo:"MintTo",InitMarket:"InitMarket",Util1216OwnerClaim:"Util1216OwnerClaim",SetComputeUnitPrice:"SetComputeUnitPrice",SetComputeUnitLimit:"SetComputeUnitLimit",ClmmCreatePool:"ClmmCreatePool",ClmmOpenPosition:"ClmmOpenPosition",ClmmIncreasePosition:"ClmmIncreasePosition",ClmmDecreasePosition:"ClmmDecreasePosition",ClmmClosePosition:"ClmmClosePosition",ClmmSwapBaseIn:"ClmmSwapBaseIn",ClmmSwapBaseOut:"ClmmSwapBaseOut",ClmmInitReward:"ClmmInitReward",ClmmSetReward:"ClmmSetReward",ClmmCollectReward:"ClmmCollectReward",ClmmLockPosition:"ClmmLockPosition",ClmmHarvestLockPosition:"ClmmHarvestLockPosition",AmmV4Swap:"AmmV4Swap",AmmV4AddLiquidity:"AmmV4AddLiquidity",AmmV4RemoveLiquidity:"AmmV4RemoveLiquidity",AmmV4SimulatePoolInfo:"AmmV4SimulatePoolInfo",AmmV4SwapBaseIn:"AmmV4SwapBaseIn",AmmV4SwapBaseOut:"AmmV4SwapBaseOut",AmmV4CreatePool:"AmmV4CreatePool",AmmV4InitPool:"AmmV4InitPool",AmmV5AddLiquidity:"AmmV5AddLiquidity",AmmV5RemoveLiquidity:"AmmV5RemoveLiquidity",AmmV5SimulatePoolInfo:"AmmV5SimulatePoolInfo",AmmV5SwapBaseIn:"AmmV5SwapBaseIn",AmmV5SwapBaseOut:"AmmV5SwapBaseOut",RouteSwap:"RouteSwap",RouteSwap1:"RouteSwap1",RouteSwap2:"RouteSwap2",FarmV3Deposit:"FarmV3Deposit",FarmV3Withdraw:"FarmV3Withdraw",FarmV3CreateLedger:"FarmV3CreateLedger",FarmV4Withdraw:"FarmV4Withdraw",FarmV5Deposit:"FarmV5Deposit",FarmV5Withdraw:"FarmV5Withdraw",FarmV5CreateLedger:"FarmV5CreateLedger",FarmV6Deposit:"FarmV6Deposit",FarmV6Withdraw:"FarmV6Withdraw",FarmV6Create:"FarmV6Create",FarmV6Restart:"FarmV6Restart",FarmV6CreatorAddReward:"FarmV6CreatorAddReward",FarmV6CreatorWithdraw:"FarmV6CreatorWithdraw",CpmmCreatePool:"CpmmCreatePool",CpmmAddLiquidity:"CpmmAddLiquidity",CpmmWithdrawLiquidity:"CpmmWithdrawLiquidity",CpmmSwapBaseIn:"CpmmSwapBaseIn",CpmmSwapBaseOut:"CpmmSwapBaseOut",CpmmLockLp:"CpmmLockLp",CpmmCollectLockFee:"CpmmCollectLockFee",TransferTip:"TransferTip"};var $n=require("@solana/spl-token");var Jn=G("Sega_txUtil"),Zn=1644;function kt(o){let e=[],t=[];return o.microLamports&&(e.push(Q.ComputeBudgetProgram.setComputeUnitPrice({microLamports:o.microLamports})),t.push(V.SetComputeUnitPrice)),o.units&&(e.push(Q.ComputeBudgetProgram.setComputeUnitLimit({units:o.units})),t.push(V.SetComputeUnitLimit)),{instructions:e,instructionTypes:t}}function Ee(o,e){return b(this,null,function*(){var n,r;let t=e!=null?e:"confirmed";return(r=yield(n=o.getLatestBlockhash)==null?void 0:n.call(o,{commitment:t}))==null?void 0:r.blockhash})}function It(o,e){return b(this,null,function*(){return o.getSignatureStatuses([e]),new Promise((t,n)=>{let r=setTimeout(n,6e4);o.onSignature(e,i=>{if(clearTimeout(r),!i.err){t("");return}n(Object.assign(i.err,{txId:e}))},"confirmed")})})}function tn(o,e){o.length<1&&Jn.logWithError(`no instructions provided: ${o.toString()}`),e.length<1&&Jn.logWithError(`no signers provided:, ${e.toString()}`);let t=new Q.Transaction;t.recentBlockhash="11111111111111111111111111111111",t.feePayer=e[0],t.add(...o);try{return Buffer.from(t.serialize({verifySignatures:!1})).toString("base64").length<Zn}catch(n){return!1}}function ie(o,e){let[t,n]=Q.PublicKey.findProgramAddressSync(o,e);return{publicKey:t,nonce:n}}function rt({instructions:o,payer:e,signers:t}){return tn(o,[e,...t])}function it({instructions:o,payer:e,lookupTableAddressAccount:t,recentBlockhash:n=Q.Keypair.generate().publicKey.toString()}){let i=new Q.TransactionMessage({payerKey:e,recentBlockhash:n,instructions:o}).compileToV0Message(Object.values(t!=null?t:{}));try{return Buffer.from(new Q.VersionedTransaction(i).serialize()).toString("base64").length<Zn}catch(a){return!1}}var qo=o=>Buffer.isBuffer(o)?o:o instanceof Uint8Array?Buffer.from(o.buffer,o.byteOffset,o.byteLength):Buffer.from(o),Go=o=>{let e=o.serialize({requireAllSignatures:!1,verifySignatures:!1});o instanceof Q.VersionedTransaction&&(e=qo(e));try{return e instanceof Buffer?e.toString("base64"):Buffer.from(e).toString("base64")}catch(t){return e.toString("base64")}};function Ke(o){let e=[];return o.forEach(t=>{t instanceof Q.Transaction&&(t.recentBlockhash||(t.recentBlockhash=$n.TOKEN_PROGRAM_ID.toBase58()),t.feePayer||(t.feePayer=Q.Keypair.generate().publicKey)),e.push(Go(t))}),console.log("simulate tx string:",e),e}function he(o,e,t){return ie([o.toBuffer(),(t!=null?t:Qn.TOKEN_PROGRAM_ID).toBuffer(),e.toBuffer()],new Xn.PublicKey("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"))}function eo(o){return ie([Buffer.from("metadata","utf8"),nt.toBuffer(),o.toBuffer()],nt)}var Ae=require("@solana/web3.js"),to=new Ae.PublicKey("SegazTQwbYWknDZkJ6j2Kgvm5gw3MrHGKtWstZdoNKZ"),no=new Ae.PublicKey("Ajk8d9bERSaFdeoT1d8JUVfaDayrYLnAdgeB47TFMUaG"),Cs=new Ae.PublicKey("2HbjxVVKJ7Ct72Rcd8WK4VTqmwTXL5aAggkH1CHGFGmh"),jo=new Ae.PublicKey("auetiVUVJkRxvNPLYEvVnz8UJSqQ1VgoA83PcicHVD1"),Ho=new Ae.PublicKey("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y"),zo=new Ae.PublicKey("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y");var Ks={SERUM_MARKET:Ae.PublicKey.default,UTIL1216:Ae.PublicKey.default,CREATE_CPMM_POOL_PROGRAM:jo,CREATE_CPMM_POOL_AUTH:Ho,CREATE_CPMM_POOL_FEE_ACC:zo};var le=q(require("bn.js"));var st=1e4;function Le(o,e,t,n){if(e===void 0)return{amount:o,fee:void 0,expirationTime:void 0};let r=E(L({},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<r.newerTransferFee.epoch?r.olderTransferFee:r.newerTransferFee,a=new le.default(i.maximumFee.toString()),s=t.epoch<r.newerTransferFee.epoch?(Number(r.newerTransferFee.epoch)*t.slotsInEpoch-t.absoluteSlot)*400/1e3:void 0;if(n)if(i.transferFeeBasisPoints===st){let c=new le.default(i.maximumFee.toString());return{amount:o.add(c),fee:c,expirationTime:s}}else{let c=Fe(o.mul(new le.default(st)),new le.default(st-i.transferFeeBasisPoints)),u=new le.default(i.maximumFee.toString()),m=c.sub(o).gt(u)?o.add(u):c,l=Fe(m.mul(new le.default(i.transferFeeBasisPoints)),new le.default(st)),p=l.gt(a)?a:l;return{amount:m,fee:p,expirationTime:s}}else{let c=Fe(o.mul(new le.default(i.transferFeeBasisPoints)),new le.default(st)),u=c.gt(a)?a:c;return{amount:o,fee:u,expirationTime:s}}}function Fe(o,e){let{div:t,mod:n}=o.divmod(e);return n.gt(new le.default(0))?t.add(new le.default(1)):t}var at=require("@solana/web3.js");function nn(t){return b(this,arguments,function*({connection:o,address:e}){let n=yield Ye(o,[...new Set(e.map(i=>i.toString()))].map(i=>new at.PublicKey(i))),r={};for(let i=0;i<e.length;i++){let a=n[i],s=e[i];if(!a)continue;let c=new at.AddressLookupTableAccount({key:s,state:at.AddressLookupTableAccount.deserialize(a.data)});r[s.toString()]=c,St[s.toString()]=c}return r})}var St={};var D=require("@solana/web3.js"),oo=q(require("axios"));var Bt=2e3,Ct=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 b(this,null,function*(){var n;let e=(yield oo.default.get("https://solanacompass.com/api/fees?cacheFreshTime=300000")).data,{avg:t}=(n=e==null?void 0:e[15])!=null?n:{};if(t)return{units:6e5,microLamports:Math.min(Math.ceil(t*1e6/6e5),25e3)}})}addCustomComputeBudget(e){if(e){let{instructions:t,instructionTypes:n}=kt(e);return this.instructions.unshift(...t),this.instructionTypes.unshift(...n),!0}return!1}addTipInstruction(e){var t;return e?(this.endInstructions.push(D.SystemProgram.transfer({fromPubkey:(t=e.feePayer)!=null?t:this.feePayer,toPubkey:new D.PublicKey(e.address),lamports:BigInt(e.amount.toString())})),this.endInstructionTypes.push(V.TransferTip),!0):!1}calComputeBudget(n){return b(this,arguments,function*({config:e,defaultIns:t}){try{let r=e||(yield this.getComputeBudgetConfig());if(this.addCustomComputeBudget(r))return;t&&this.instructions.unshift(...t)}catch(r){t&&this.instructions.unshift(...t)}})}addInstruction({instructions:e=[],endInstructions:t=[],signers:n=[],instructionTypes:r=[],endInstructionTypes:i=[],lookupTableAddress:a=[]}){return this.instructions.push(...e),this.endInstructions.push(...t),this.signers.push(...n),this.instructionTypes.push(...r),this.endInstructionTypes.push(...i),this.lookupTableAddress.push(...a.filter(s=>s!==D.PublicKey.default.toString())),this}versionBuild(n){return b(this,arguments,function*({txVersion:e,extInfo:t}){return e===0?yield this.buildV0(L({},t||{})):this.build(t)})}build(e){var n;let t=new D.Transaction;return this.allInstructions.length&&t.add(...this.allInstructions),t.feePayer=this.feePayer,(n=this.owner)!=null&&n.signer&&!this.signers.some(r=>r.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer),{builder:this,transaction:t,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:r=>b(this,null,function*(){var u;let{recentBlockHash:i,skipPreflight:a=!0,sendAndConfirm:s}=r||{},c=i!=null?i:yield Ee(this.connection,this.blockhashCommitment);if(t.recentBlockhash=c,this.signers.length&&t.sign(...this.signers),Ke([t]),(u=this.owner)!=null&&u.isKeyPair)return{txId:s?yield(0,D.sendAndConfirmTransaction)(this.connection,t,this.signers.find(l=>l.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 m=yield this.signAllTransactions([t]);if(this.signers.length)for(let l of m)try{l.sign(...this.signers)}catch(p){}return{txId:yield this.connection.sendRawTransaction(m[0].serialize(),{skipPreflight:a}),signedTx:m[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:e||{}}}buildMultiTx(e){var u;let{extraPreBuildData:t=[],extInfo:n}=e,{transaction:r}=this.build(n),i=t.filter(m=>m.transaction.instructions.length>0),a=[r,...i.map(m=>m.transaction)],s=[this.signers,...i.map(m=>m.signers)],c=[...this.instructionTypes,...i.map(m=>m.instructionTypes).flat()];return(u=this.owner)!=null&&u.signer&&s.forEach(m=>{m.some(l=>l.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),{builder:this,transactions:a,signers:s,instructionTypes:c,execute:m=>b(this,null,function*(){var x;let{sequentially:l,onTxUpdate:p,skipTxCount:d=0,recentBlockHash:f,skipPreflight:y=!0}=m||{},g=f!=null?f:yield Ee(this.connection,this.blockhashCommitment);if((x=this.owner)!=null&&x.isKeyPair){if(l){let h=[],A=0;for(let T of a){if(++A,A<=d)continue;let P=yield(0,D.sendAndConfirmTransaction)(this.connection,T,this.signers.find(w=>w.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:y});h.push(P)}return{txIds:h,signedTxs:a}}return{txIds:yield yield Promise.all(a.map(h=>b(this,null,function*(){return h.recentBlockhash=g,yield this.connection.sendRawTransaction(h.serialize(),{skipPreflight:y})}))),signedTxs:a}}if(this.signAllTransactions){let h=a.map((T,P)=>(T.recentBlockhash=g,s[P].length&&T.sign(...s[P]),T));Ke(h);let A=yield this.signAllTransactions(h);if(l){let T=0,P=[],w=()=>b(this,null,function*(){if(!A[T])return;let k=yield this.connection.sendRawTransaction(A[T].serialize(),{skipPreflight:y});P.push({txId:k,status:"sent",signedTx:A[T]}),p==null||p([...P]),T++;let I=!1,B=null,C=null,N=O=>{B!==null&&clearInterval(B),C!==null&&this.connection.removeSignatureListener(C);let R=P.findIndex(F=>F.txId===k);if(R>-1){if(P[R].status==="error"||P[R].status==="success")return;P[R].status=O.err?"error":"success"}p==null||p([...P]),O.err||w()};this.loopMultiTxStatus&&(B=setInterval(()=>b(this,null,function*(){var O;if(I){clearInterval(B);return}try{let R=yield this.connection.getTransaction(k,{commitment:"confirmed",maxSupportedTransactionVersion:0});R&&(I=!0,clearInterval(B),N({err:((O=R.meta)==null?void 0:O.err)||null}),console.log("tx status from getTransaction:",k))}catch(R){I=!0,clearInterval(B),console.error("getTransaction timeout:",R,k)}}),Bt)),C=this.connection.onSignature(k,O=>{if(I){this.connection.removeSignatureListener(C);return}I=!0,N(O)},"confirmed"),this.connection.getSignatureStatus(k)});return yield w(),{txIds:P.map(k=>k.txId),signedTxs:A}}else{let T=[];for(let P=0;P<A.length;P+=1){let w=yield this.connection.sendRawTransaction(A[P].serialize(),{skipPreflight:y});T.push(w)}return{txIds:T,signedTxs:A}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:n||{}}}versionMultiBuild(r){return b(this,arguments,function*({extraPreBuildData:e,txVersion:t,extInfo:n}){return t===0?yield this.buildV0MultiTx({extraPreBuildData:e,buildProps:n||{}}):this.buildMultiTx({extraPreBuildData:e,extInfo:n})})}buildV0(e){return b(this,null,function*(){var y;let f=e||{},{lookupTableCache:t={},lookupTableAddress:n=[],forerunCreate:r,recentBlockhash:i}=f,a=te(f,["lookupTableCache","lookupTableAddress","forerunCreate","recentBlockhash"]),s=L(L({},this.cluster==="devnet"?{}:St),t),c=Array.from(new Set([...n,...this.lookupTableAddress])),u=[];for(let g of c)s[g]===void 0&&u.push(new D.PublicKey(g));let m=yield nn({connection:this.connection,address:u});for(let[g,x]of Object.entries(m))s[g]=x;let l=r?D.PublicKey.default.toBase58():i!=null?i:yield Ee(this.connection,this.blockhashCommitment),p=new D.TransactionMessage({payerKey:this.feePayer,recentBlockhash:l,instructions:[...this.allInstructions]}).compileToV0Message(Object.values(s));(y=this.owner)!=null&&y.signer&&!this.signers.some(g=>g.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer);let d=new D.VersionedTransaction(p);return d.sign(this.signers),{builder:this,transaction:d,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:g=>b(this,null,function*(){var A;let{skipPreflight:x=!0,sendAndConfirm:h}=g||{};if(Ke([d]),(A=this.owner)!=null&&A.isKeyPair){let T=yield this.connection.sendTransaction(d,{skipPreflight:x});return h&&(yield It(this.connection,T)),{txId:T,signedTx:d}}if(this.signAllTransactions){let T=yield this.signAllTransactions([d]);if(this.signers.length)for(let P of T)try{P.sign(this.signers)}catch(w){}return{txId:yield this.connection.sendTransaction(T[0],{skipPreflight:x}),signedTx:T[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:a||{}}})}buildV0MultiTx(e){return b(this,null,function*(){var u;let{extraPreBuildData:t=[],buildProps:n}=e,{transaction:r}=yield this.buildV0(n),i=t.filter(m=>m.builder.instructions.length>0),a=[r,...i.map(m=>m.transaction)],s=[this.signers,...i.map(m=>m.signers)],c=[...this.instructionTypes,...i.map(m=>m.instructionTypes).flat()];return(u=this.owner)!=null&&u.signer&&s.forEach(m=>{m.some(l=>l.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),a.forEach((m,l)=>b(this,null,function*(){m.sign(s[l])})),{builder:this,transactions:a,signers:s,instructionTypes:c,buildProps:n,execute:m=>b(this,null,function*(){var y;let{sequentially:l,onTxUpdate:p,recentBlockHash:d,skipPreflight:f=!0}=m||{};if(d&&a.forEach(g=>g.message.recentBlockhash=d),Ke(a),(y=this.owner)!=null&&y.isKeyPair){if(l){let g=[];for(let x of a){let h=yield this.connection.sendTransaction(x,{skipPreflight:f});yield It(this.connection,h),g.push(h)}return{txIds:g,signedTxs:a}}return{txIds:yield Promise.all(a.map(g=>b(this,null,function*(){return yield this.connection.sendTransaction(g,{skipPreflight:f})}))),signedTxs:a}}if(this.signAllTransactions){let g=yield this.signAllTransactions(a);if(l){let x=0,h=[],A=()=>b(this,null,function*(){if(!g[x])return;let T=yield this.connection.sendTransaction(g[x],{skipPreflight:f});h.push({txId:T,status:"sent",signedTx:g[x]}),p==null||p([...h]),x++;let P=!1,w=null,k=null,I=B=>{w!==null&&clearInterval(w),k!==null&&this.connection.removeSignatureListener(k);let C=h.findIndex(N=>N.txId===T);if(C>-1){if(h[C].status==="error"||h[C].status==="success")return;h[C].status=B.err?"error":"success"}p==null||p([...h]),B.err||A()};this.loopMultiTxStatus&&(w=setInterval(()=>b(this,null,function*(){var B;if(P){clearInterval(w);return}try{let C=yield this.connection.getTransaction(T,{commitment:"confirmed",maxSupportedTransactionVersion:0});C&&(P=!0,clearInterval(w),I({err:((B=C.meta)==null?void 0:B.err)||null}),console.log("tx status from getTransaction:",T))}catch(C){P=!0,clearInterval(w),console.error("getTransaction timeout:",C,T)}}),Bt)),k=this.connection.onSignature(T,B=>{if(P){this.connection.removeSignatureListener(k);return}P=!0,I(B)},"confirmed"),this.connection.getSignatureStatus(T)});return A(),{txIds:[],signedTxs:g}}else{let x=[];for(let h=0;h<g.length;h+=1){let A=yield this.connection.sendTransaction(g[h],{skipPreflight:f});x.push(A)}return{txIds:x,signedTxs:g}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:n||{}}})}sizeCheckBuild(e){return b(this,null,function*(){var p;let l=e||{},{splitIns:t=[],computeBudgetConfig:n}=l,r=te(l,["splitIns","computeBudgetConfig"]),i=n?kt(n):{instructions:[],instructionTypes:[]},a=this.signers.reduce((d,f)=>E(L({},d),{[f.publicKey.toBase58()]:f}),{}),s=[],c=[],u=[],m=0;if(this.allInstructions.forEach(d=>{let f=[...u,d],y=n?[...i.instructions,...f]:f,x=[...new Set(f.map(h=>h.keys.filter(A=>A.isSigner).map(A=>A.pubkey.toString())).flat()).values()].map(h=>new D.PublicKey(h));if(d!==t[m]&&u.length<12&&(rt({instructions:y,payer:this.feePayer,signers:x})||rt({instructions:f,payer:this.feePayer,signers:x})))u.push(d);else{if(u.length===0)throw Error("item ins too big");m+=d===t[m]?1:0,rt({instructions:n?[...i.instructions,...u]:[...u],payer:this.feePayer,signers:x})?s.push(new D.Transaction().add(...i.instructions,...u)):s.push(new D.Transaction().add(...u)),c.push(Array.from(new Set(u.map(h=>h.keys.filter(A=>A.isSigner).map(A=>A.pubkey.toString())).flat())).map(h=>a[h]).filter(h=>h!==void 0)),u=[d]}}),u.length>0){let f=[...new Set(u.map(y=>y.keys.filter(g=>g.isSigner).map(g=>g.pubkey.toString())).flat()).values()].map(y=>a[y]).filter(y=>y!==void 0);rt({instructions:n?[...i.instructions,...u]:[...u],payer:this.feePayer,signers:f.map(y=>y.publicKey)})?s.push(new D.Transaction().add(...i.instructions,...u)):s.push(new D.Transaction().add(...u)),c.push(f)}return s.forEach(d=>d.feePayer=this.feePayer),(p=this.owner)!=null&&p.signer&&c.forEach(d=>{d.some(f=>f.publicKey.equals(this.owner.publicKey))||d.push(this.owner.signer)}),{builder:this,transactions:s,signers:c,instructionTypes:this.instructionTypes,execute:d=>b(this,null,function*(){var T;let{sequentially:f,onTxUpdate:y,skipTxCount:g=0,recentBlockHash:x,skipPreflight:h=!0}=d||{},A=x!=null?x:yield Ee(this.connection,this.blockhashCommitment);if(s.forEach((P,w)=>b(this,null,function*(){P.recentBlockhash=A,c[w].length&&P.sign(...c[w])})),Ke(s),(T=this.owner)!=null&&T.isKeyPair){if(f){let P=0,w=[];for(let k of s){if(++P,P<=g){w.push("tx skipped");continue}let I=yield(0,D.sendAndConfirmTransaction)(this.connection,k,this.signers.find(B=>B.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:h});w.push(I)}return{txIds:w,signedTxs:s}}return{txIds:yield Promise.all(s.map(P=>b(this,null,function*(){return yield this.connection.sendRawTransaction(P.serialize(),{skipPreflight:h})}))),signedTxs:s}}if(this.signAllTransactions){let P=yield this.signAllTransactions(s.slice(g,s.length)),w=[...s.slice(0,g),...P];if(f){let k=0,I=[],B=()=>b(this,null,function*(){if(!w[k])return;k<g&&(I.push({txId:"",status:"success",signedTx:w[k]}),y==null||y([...I]),k++,B());let C=yield this.connection.sendRawTransaction(w[k].serialize(),{skipPreflight:h});I.push({txId:C,status:"sent",signedTx:w[k]}),y==null||y([...I]),k++;let N=!1,O=null,R=null,F=M=>{O!==null&&clearInterval(O),R!==null&&this.connection.removeSignatureListener(R);let W=I.findIndex(J=>J.txId===C);if(W>-1){if(I[W].status==="error"||I[W].status==="success")return;I[W].status=M.err?"error":"success"}y==null||y([...I]),M.err||B()};this.loopMultiTxStatus&&(O=setInterval(()=>b(this,null,function*(){var M;if(N){clearInterval(O);return}try{let W=yield this.connection.getTransaction(C,{commitment:"confirmed",maxSupportedTransactionVersion:0});W&&(N=!0,clearInterval(O),F({err:((M=W.meta)==null?void 0:M.err)||null}),console.log("tx status from getTransaction:",C))}catch(W){N=!0,clearInterval(O),console.error("getTransaction timeout:",W,C)}}),Bt)),R=this.connection.onSignature(C,M=>{if(N){this.connection.removeSignatureListener(R);return}N=!0,F(M)},"confirmed"),this.connection.getSignatureStatus(C)});return yield B(),{txIds:I.map(C=>C.txId),signedTxs:w}}else{let k=[];for(let I=0;I<w.length;I+=1){let B=yield this.connection.sendRawTransaction(w[I].serialize(),{skipPreflight:h});k.push(B)}return{txIds:k,signedTxs:w}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:r||{}}})}sizeCheckBuildV0(e){return b(this,null,function*(){var A;let h=e||{},{computeBudgetConfig:t,splitIns:n=[],lookupTableCache:r={},lookupTableAddress:i=[]}=h,a=te(h,["computeBudgetConfig","splitIns","lookupTableCache","lookupTableAddress"]),s=L(L({},this.cluster==="devnet"?{}:St),r),c=Array.from(new Set([...this.lookupTableAddress,...i])),u=[];for(let T of c)s[T]===void 0&&u.push(new D.PublicKey(T));let m=yield nn({connection:this.connection,address:u});for(let[T,P]of Object.entries(m))s[T]=P;let l=t?kt(t):{instructions:[],instructionTypes:[]},p=yield Ee(this.connection,this.blockhashCommitment),d=this.signers.reduce((T,P)=>E(L({},T),{[P.publicKey.toBase58()]:P}),{}),f=[],y=[],g=[],x=0;if(this.allInstructions.forEach(T=>{let P=[...g,T],w=t?[...l.instructions,...P]:P;if(T!==n[x]&&g.length<12&&(it({instructions:w,payer:this.feePayer,lookupTableAddressAccount:s})||it({instructions:P,payer:this.feePayer,lookupTableAddressAccount:s})))g.push(T);else{if(g.length===0)throw Error("item ins too big");x+=T===n[x]?1:0;let k={};for(let I of[...new Set(c)])s[I]!==void 0&&(k[I]=s[I]);if(t&&it({instructions:[...l.instructions,...g],payer:this.feePayer,lookupTableAddressAccount:s,recentBlockhash:p})){let I=new D.TransactionMessage({payerKey:this.feePayer,recentBlockhash:p,instructions:[...l.instructions,...g]}).compileToV0Message(Object.values(s));f.push(new D.VersionedTransaction(I))}else{let I=new D.TransactionMessage({payerKey:this.feePayer,recentBlockhash:p,instructions:[...g]}).compileToV0Message(Object.values(s));f.push(new D.VersionedTransaction(I))}y.push(Array.from(new Set(g.map(I=>I.keys.filter(B=>B.isSigner).map(B=>B.pubkey.toString())).flat())).map(I=>d[I]).filter(I=>I!==void 0)),g=[T]}}),g.length>0){let P=[...new Set(g.map(w=>w.keys.filter(k=>k.isSigner).map(k=>k.pubkey.toString())).flat()).values()].map(w=>d[w]).filter(w=>w!==void 0);if(t&&it({instructions:[...l.instructions,...g],payer:this.feePayer,lookupTableAddressAccount:s,recentBlockhash:p})){let w=new D.TransactionMessage({payerKey:this.feePayer,recentBlockhash:p,instructions:[...l.instructions,...g]}).compileToV0Message(Object.values(s));f.push(new D.VersionedTransaction(w))}else{let w=new D.TransactionMessage({payerKey:this.feePayer,recentBlockhash:p,instructions:[...g]}).compileToV0Message(Object.values(s));f.push(new D.VersionedTransaction(w))}y.push(P)}return(A=this.owner)!=null&&A.signer&&y.forEach(T=>{T.some(P=>P.publicKey.equals(this.owner.publicKey))||T.push(this.owner.signer)}),{builder:this,transactions:f,buildProps:e,signers:y,instructionTypes:this.instructionTypes,execute:T=>b(this,null,function*(){var C;let{sequentially:P,onTxUpdate:w,skipTxCount:k=0,recentBlockHash:I,skipPreflight:B=!0}=T||{};if(f.map((N,O)=>b(this,null,function*(){y[O].length&&N.sign(y[O]),I&&(N.message.recentBlockhash=I)})),Ke(f),(C=this.owner)!=null&&C.isKeyPair){if(P){let N=0,O=[];for(let R of f){if(++N,N<=k){console.log("skip tx: ",N),O.push("tx skipped");continue}let F=yield this.connection.sendTransaction(R,{skipPreflight:B});yield It(this.connection,F),O.push(F)}return{txIds:O,signedTxs:f}}return{txIds:yield Promise.all(f.map(N=>b(this,null,function*(){return yield this.connection.sendTransaction(N,{skipPreflight:B})}))),signedTxs:f}}if(this.signAllTransactions){let N=yield this.signAllTransactions(f.slice(k,f.length)),O=[...f.slice(0,k),...N];if(P){let R=0,F=[],M=()=>b(this,null,function*(){if(!O[R])return;if(R<k){F.push({txId:"",status:"success",signedTx:O[R]}),w==null||w([...F]),R++,M();return}let W=yield this.connection.sendTransaction(O[R],{skipPreflight:B});F.push({txId:W,status:"sent",signedTx:O[R]}),w==null||w([...F]),R++;let J=!1,me=null,Se=null,Kn=Be=>{me!==null&&clearInterval(me),Se!==null&&this.connection.removeSignatureListener(Se);let Pe=F.findIndex(ko=>ko.txId===W);if(Pe>-1){if(F[Pe].status==="error"||F[Pe].status==="success")return;F[Pe].status=Be.err?"error":"success"}w==null||w([...F]),Be.err||M()};this.loopMultiTxStatus&&(me=setInterval(()=>b(this,null,function*(){var Be;if(J){clearInterval(me);return}try{let Pe=yield this.connection.getTransaction(W,{commitment:"confirmed",maxSupportedTransactionVersion:0});Pe&&(J=!0,clearInterval(me),Kn({err:((Be=Pe.meta)==null?void 0:Be.err)||null}),console.log("tx status from getTransaction:",W))}catch(Pe){J=!0,clearInterval(me),console.error("getTransaction timeout:",Pe,W)}}),Bt)),Se=this.connection.onSignature(W,Be=>{if(J){this.connection.removeSignatureListener(Se);return}J=!0,Kn(Be)},"confirmed"),this.connection.getSignatureStatus(W)});return M(),{txIds:[],signedTxs:O}}else{let R=[];for(let F=0;F<O.length;F+=1){let M=yield this.connection.sendTransaction(O[F],{skipPreflight:B});R.push(M)}return{txIds:R,signedTxs:O}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:a||{}}})}};var Yo=require("@solana/web3.js");var ge={BASE_HOST:"https://api.sega.so/api",SEND_TRANSACTION:"/send-transaction",FARM_ARP:"/main/farm/info",FARM_ARP_LINE:"/main/farm-apr-tv",CLMM_CONFIG:"/main/clmm-config",CPMM_CONFIG:"/main/cpmm-config",VERSION:"/main/version",CHECK_AVAILABILITY:"/v3/main/AvailabilityCheckAPI",RPCS:"/main/rpcs",INFO:"/main/info",STAKE_POOLS:"/main/stake-pools",CHAIN_TIME:"/main/chain-time",TOKEN_LIST:"/mint/list",MINT_INFO_ID:"/mint/ids",JUP_TOKEN_LIST:"https://tokens.jup.ag/tokens?tags=lst,community",POOL_LIST:"/pools/info/list",POOL_SEARCH_BY_ID:"/pools/info/ids",POOL_SEARCH_MINT:"/pools/info/mint",POOL_SEARCH_LP:"/pools/info/lps",POOL_KEY_BY_ID:"/pools/key/ids",POOL_LIQUIDITY_LINE:"/pools/line/liquidity",POOL_POSITION_LINE:"/pools/line/position",FARM_INFO:"/farms/info/ids",FARM_LP_INFO:"/farms/info/lp",FARM_KEYS:"/farms/key/ids",OWNER_CREATED_FARM:"/create-pool/{owner}",OWNER_IDO:"/main/ido/{owner}",OWNER_STAKE_FARMS:"/position/stake/{owner}",OWNER_LOCK_POSITION:"/position/clmm-lock/{owner}",IDO_KEYS:"/ido/key/ids",SWAP_COMPUTE:"/compute/",SWAP_TX:"/transaction/",MINT_PRICE:"/mint/price",MIGRATE_CONFIG:"/main/migrate-lp",PRIORITY_FEE:"/main/auto-fee"},ga=L({},ge);var ro="ray_tab_hash",on="ray_req_hash",Jo=()=>{if(typeof window===void 0)return"";let o=sessionStorage.getItem(ro);return o||(o=`ray-${Date.now()}`,sessionStorage.setItem(ro,o)),o},Kt=n=>b(void 0,null,function*(){var r=n,{logCount:o=1e3,removeLastLog:e}=r,t=te(r,["logCount","removeLastLog"]);if(typeof window===void 0)return new Promise(a=>a());let i=JSON.parse(localStorage.getItem(on)||"[]").slice(0,o-1);e&&i.pop(),new Blob([JSON.stringify(t.data)]).size>1024&&(t.data=JSON.stringify(t.data).substring(0,200)+"..."),i.unshift(E(L({},t),{time:Date.now(),session:Jo()}));try{localStorage.setItem(on,JSON.stringify(i))}catch(a){if(e){let s=!1,c=JSON.stringify(t.data).substring(0,100);for(i[0].data=c+(c.length>100?"...":"");!s;){i.pop();let u=JSON.stringify(t.data).substring(0,100);i[0].data=u+(u.length>100?"...":"");try{localStorage.setItem(on,JSON.stringify(i)),s=!0}catch(m){s=!1}}return new Promise(u=>u())}return Kt(E(L({},t),{logCount:o,removeLastLog:!0}))}});var Lt=G("Sega_Api"),rn=new Map;var _t=class{constructor({cluster:e,timeout:t,logRequests:n,logCount:r,urlConfigs:i}){this.cluster=e,this.urlConfigs=i||{},this.logCount=r||1e3,this.api=sn.default.create({baseURL:this.urlConfigs.BASE_HOST||ge.BASE_HOST,timeout:t}),this.api.interceptors.request.use(a=>{let{method:s,baseURL:c,url:u}=a;return Lt.debug(`${s==null?void 0:s.toUpperCase()} ${c}${u}`),a},a=>(Lt.error("Request failed"),Promise.reject(a))),this.api.interceptors.response.use(a=>{let{config:s,data:c,status:u}=a,{method:m,baseURL:l,url:p}=s;return n&&Kt({status:u,url:`${l}${p}`,params:s.params,data:c,logCount:this.logCount}),Lt.debug(`${m==null?void 0:m.toUpperCase()} ${l}${p} ${u}`),c},a=>{let{config:s,response:c={}}=a,{status:u}=c,{method:m,baseURL:l,url:p}=s;return n&&Kt({status:u,url:`${l}${p}`,params:s.params,data:a.message,logCount:this.logCount}),Lt.error(`${m.toUpperCase()} ${l}${p} ${u||a.message}`),Promise.reject(a)})}getCpmmConfigs(){return b(this,null,function*(){return(yield this.api.get(this.urlConfigs.CPMM_CONFIG||ge.CPMM_CONFIG)).data})}getBlockSlotCountForSecond(e){return b(this,null,function*(){if(!e)return 2;let n=(yield sn.default.post(e,{id:"getRecentPerformanceSamples",jsonrpc:"2.0",method:"getRecentPerformanceSamples",params:[4]})).result.map(r=>r.numSlots);return n.reduce((r,i)=>r+i,0)/n.length/60})}getChainTimeOffset(){return b(this,null,function*(){return(yield this.api.get(this.urlConfigs.CHAIN_TIME||ge.CHAIN_TIME)).data})}fetchPoolKeysById(e){return b(this,null,function*(){let{idList:t}=e,n=[],r=t.filter(a=>rn.has(a)?(n.push(rn.get(a)),!1):!0),i=[];return r.length&&(i=(yield this.api.get((this.urlConfigs.POOL_KEY_BY_ID||ge.POOL_KEY_BY_ID)+`?ids=${r.join(",")}`)).data.filter(Boolean),i.forEach(s=>{rn.set(s.id,s)})),n.concat(i)})}getRpcs(){return b(this,null,function*(){return this.api.get(this.urlConfigs.RPCS||ge.RPCS)})}getTokenList(){return b(this,null,function*(){return(yield this.api.get(this.urlConfigs.TOKEN_LIST||ge.TOKEN_LIST)).data})}getJupTokenList(){return b(this,null,function*(){return this.api.get("",{baseURL:this.urlConfigs.JUP_TOKEN_LIST||ge.JUP_TOKEN_LIST})})}getTokenInfo(e){return b(this,null,function*(){return(yield this.api.get((this.urlConfigs.MINT_INFO_ID||ge.MINT_INFO_ID)+`?mints=${e.map(n=>n.toString()).join(",")}`)).data})}fetchAvailabilityStatus(){return b(this,null,function*(){return(yield this.api.get(this.urlConfigs.CHECK_AVAILABILITY||ge.CHECK_AVAILABILITY)).data})}};var Ot="please provide owner in load() initialization or you can set by calling sega.setOwner(owner)",io="please provide connection in load() initialization or set it by sega.setConnection(connection)";var Oe=require("@solana/web3.js");var H=require("@solana/spl-token");var an=(...o)=>o.map(e=>{try{return typeof e=="object"?JSON.stringify(e):e}catch(t){return e}}).join(", "),ye=class{constructor({scope:e,moduleName:t}){this.disabled=!1;this.scope=e,this.logger=G(t)}createTxBuilder(e){return this.scope.checkOwner(),new Ct({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(an(e))}logInfo(...e){this.logger.info(an(e))}logAndCreateError(...e){let t=an(e);throw new Error(t)}checkDisabled(){(this.disabled||!this.scope)&&this.logAndCreateError("module not working")}};var Mt=require("@solana/web3.js"),go=q(require("bn.js"));var ue=require("@solana/spl-token");var ut=require("@solana/web3.js"),mo=q(require("bn.js"));var po=require("@solana/spl-token"),fo=require("@noble/hashes/sha256");var lo=require("@solana/web3.js"),De=q(require("bn.js"));var K=require("@solana/buffer-layout"),un=K.Layout,so=K.Structure;var cn=K.UInt;var ao=K.u8,uo=K.u16;var co=K.seq;var we=K.blob;var ln=class extends un{constructor(e,t,n){super(e,n),this.blob=we(e),this.signed=t}decode(e,t=0){let n=new De.default(this.blob.decode(e,t),10,"le");return this.signed?n.fromTwos(this.span*8).clone():n}encode(e,t,n=0){return typeof e=="number"&&(e=new De.default(e)),this.signed&&(e=e.toTwos(this.span*8)),this.blob.encode(e.toArrayLike(Buffer,"le",this.span),t,n)}};function $(o){return new cn(1,o)}function _e(o){return new cn(4,o)}function _(o){return new ln(8,!1,o)}var Rt=class extends un{constructor(e,t,n,r){super(e.span,r),this.layout=e,this.decoder=t,this.encoder=n}decode(e,t){return this.decoder(this.layout.decode(e,t))}encode(e,t,n){return this.layout.encode(this.encoder(e),t,n)}getSpan(e,t){return this.layout.getSpan(e,t)}};function U(o){return new Rt(we(32),e=>new lo.PublicKey(e),e=>e.toBuffer(),o)}function Nt(o){return new Rt(ao(),$o,Zo,o)}function $o(o){if(o===0)return!1;if(o===1)return!0;throw new Error("Invalid bool: "+o)}function Zo(o){return o?1:0}var mn=class extends so{decode(e,t){return super.decode(e,t)}};function Y(o,e,t){return new mn(o,e,t)}function ke(o,e,t){let n,r=typeof e=="number"?e:(0,De.isBN)(e)?e.toNumber():new Proxy(e,{get(i,a){if(!n){let s=Reflect.get(i,"count");n=(0,De.isBN)(s)?s.toNumber():s,Reflect.set(i,"count",n)}return Reflect.get(i,a)},set(i,a,s){return a==="count"&&(n=s),Reflect.set(i,a,s)}});return co(o,r,t)}var ve=Y([U("mint"),U("owner"),_("amount"),_e("delegateOption"),U("delegate"),$("state"),_e("isNativeOption"),_("isNative"),_("delegatedAmount"),_e("closeAuthorityOption"),U("closeAuthority")]);var ou=G("Sega_Util");function pn({owner:o,solAccountResp:e,tokenAccountResp:t}){let n=[],r=[];for(let{pubkey:i,account:a}of t.value){let s=ve.decode(a.data),{mint:c,amount:u}=s;n.push({publicKey:i,mint:c,amount:u,isAssociated:he(o,c,a.owner).publicKey.equals(i),isNative:!1,programId:a.owner}),r.push({pubkey:i,accountInfo:s,programId:a.owner})}return e&&n.push({mint:ut.PublicKey.default,amount:new mo.default(String(e.lamports)),isNative:!0,programId:e.owner}),{tokenAccounts:n,tokenAccountRawInfos:r}}function ct({fromPublicKey:o,programId:e=po.TOKEN_PROGRAM_ID,assignSeed:t}){let n=t?btoa(t).slice(0,32):ut.Keypair.generate().publicKey.toBase58().slice(0,32);return{publicKey:Xo(o,n,e),seed:n}}function Xo(o,e,t){let n=Buffer.concat([o.toBuffer(),Buffer.from(e),t.toBuffer()]),r=(0,fo.sha256)(n);return new ut.PublicKey(r)}function Et(o){let{mint:e,tokenAccount:t,owner:n,programId:r=ue.TOKEN_PROGRAM_ID}=o;return(0,ue.createInitializeAccountInstruction)(t,e,n,r)}function We(o){let{tokenAccount:e,payer:t,multiSigners:n=[],owner:r,programId:i=ue.TOKEN_PROGRAM_ID}=o;return(0,ue.createCloseAccountInstruction)(e,t,r,n,i)}function Ft(o){return b(this,null,function*(){let{connection:e,amount:t,commitment:n,payer:r,owner:i,skipCloseAccount:a}=o,s=yield e.getMinimumBalanceForRentExemption(ve.span,n),c=re(t).add(new go.default(s)),u=ct({fromPublicKey:r,programId:ue.TOKEN_PROGRAM_ID});return{addresses:{newAccount:u.publicKey},signers:[],instructions:[Mt.SystemProgram.createAccountWithSeed({fromPubkey:r,basePubkey:r,seed:u.seed,newAccountPubkey:u.publicKey,lamports:c.toNumber(),space:ve.span,programId:ue.TOKEN_PROGRAM_ID}),Et({mint:new Mt.PublicKey(ae.address),tokenAccount:u.publicKey,owner