UNPKG

@sega-so/sega-sdk

Version:

An SDK for building applications on top of SEGA.

1 lines 95.1 kB
"use strict";var mo=Object.create;var We=Object.defineProperty,po=Object.defineProperties,fo=Object.getOwnPropertyDescriptor,go=Object.getOwnPropertyDescriptors,bo=Object.getOwnPropertyNames,ct=Object.getOwnPropertySymbols,yo=Object.getPrototypeOf,Nt=Object.prototype.hasOwnProperty,pn=Object.prototype.propertyIsEnumerable;var te=Math.pow,mn=(o,t,e)=>t in o?We(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e,L=(o,t)=>{for(var e in t||(t={}))Nt.call(t,e)&&mn(o,e,t[e]);if(ct)for(var e of ct(t))pn.call(t,e)&&mn(o,e,t[e]);return o},D=(o,t)=>po(o,go(t));var Q=(o,t)=>{var e={};for(var n in o)Nt.call(o,n)&&t.indexOf(n)<0&&(e[n]=o[n]);if(o!=null&&ct)for(var n of ct(o))t.indexOf(n)<0&&pn.call(o,n)&&(e[n]=o[n]);return e};var ho=(o,t)=>{for(var e in t)We(o,e,{get:t[e],enumerable:!0})},dn=(o,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of bo(t))!Nt.call(o,r)&&r!==e&&We(o,r,{get:()=>t[r],enumerable:!(n=fo(t,r))||n.enumerable});return o};var q=(o,t,e)=>(e=o!=null?mo(yo(o)):{},dn(t||!o||!o.__esModule?We(e,"default",{value:o,enumerable:!0}):e,o)),To=o=>dn(We({},"__esModule",{value:!0}),o);var y=(o,t,e)=>new Promise((n,r)=>{var i=c=>{try{s(e.next(c))}catch(u){r(u)}},a=c=>{try{s(e.throw(c))}catch(u){r(u)}},s=c=>c.done?n(c.value):Promise.resolve(c.value).then(i,a);s((e=e.apply(o,t)).next())});var Qo={};ho(Qo,{Sega:()=>cn});module.exports=To(Qo);var co=require("lodash");var Jt=q(require("axios"));var Et=require("@solana/web3.js");var Ve=require("lodash");var Rt=class{constructor(t){this.logLevel=t.logLevel!==void 0?t.logLevel:0,this.name=t.name}set level(t){this.logLevel=t}get time(){return Date.now().toString()}get moduleName(){return this.name}isLogLevel(t){return t<=this.logLevel}error(...t){return this.isLogLevel(0)?(console.error(this.time,this.name,"sdk logger error",...t),this):this}logWithError(...t){let e=t.map(n=>typeof n=="object"?JSON.stringify(n):n).join(", ");throw new Error(e)}warning(...t){return this.isLogLevel(1)?(console.warn(this.time,this.name,"sdk logger warning",...t),this):this}info(...t){return this.isLogLevel(2)?(console.info(this.time,this.name,"sdk logger info",...t),this):this}debug(...t){return this.isLogLevel(3)?(console.debug(this.time,this.name,"sdk logger debug",...t),this):this}},fn={},Po={};function j(o){let t=(0,Ve.get)(fn,o);if(!t){let e=(0,Ve.get)(Po,o);t=new Rt({name:o,logLevel:e}),(0,Ve.set)(fn,o,t)}return t}var we=require("@solana/spl-token");var Mt=j("Sega_accountInfo_util");function Ue(o,t,e){return y(this,null,function*(){let{batchRequest:n,commitment:r="confirmed",chunkCount:i=100}=L({batchRequest:!1},e),a=Dt(t,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=Dt(c,10);s=(yield(yield Promise.all(u.map(l=>y(this,null,function*(){return yield o._rpcBatchRequest(l)})))).flat()).map(l=>(l.error&&Mt.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:h,owner:g,rentEpoch:k}=p;return d.length!==2&&d[1]!=="base64"&&Mt.logWithError("info must be base64 encoded, RPC_ERROR"),{data:Buffer.from(d[0],"base64"),executable:f,lamports:h,owner:new Et.PublicKey(g),rentEpoch:k}}return null})))}else try{s=yield Promise.all(a.map(c=>o.getMultipleAccountsInfo(c,r)))}catch(c){c instanceof Error&&Mt.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${c.message}`)}return s.flat()})}function qe(o,t,e){return y(this,null,function*(){let n=yield Ue(o,t.map(r=>r.pubkey),e);return t.map((r,i)=>D(L({},r),{accountInfo:n[i]}))})}function gn(n){return y(this,arguments,function*({connection:o,mints:t,config:e}){var a,s,c;if(t.length===0)return{};let r=yield qe(o,t.map(u=>({pubkey:lt(u)})),e),i={};for(let u of r){if(!u.accountInfo||u.accountInfo.data.length<we.MINT_SIZE){console.log("invalid mint account",u.pubkey.toBase58());continue}let m=(0,we.unpackMint)(u.pubkey,u.accountInfo,(a=u.accountInfo)==null?void 0:a.owner);i[u.pubkey.toString()]=D(L({},m),{programId:((s=u.accountInfo)==null?void 0:s.owner)||we.TOKEN_PROGRAM_ID,feeConfig:(c=(0,we.getTransferFeeConfig)(m))!=null?c:void 0})}return i[Et.PublicKey.default.toBase58()]=i[ee.toBase58()],i})}var fe=q(require("bn.js")),Ko=q(require("decimal.js"));var Pn=q(require("big.js")),Io=q(require("bn.js"));var bn=q(require("toformat")),wo=bn.default,Ge=wo;var je=q(require("big.js")),hn=q(require("bn.js")),Tn=q(require("decimal.js-light"));var Oe=q(require("bn.js"));var yn=9007199254740991;function ae(o){let t=j("Sega_parseBigNumberish");if(o instanceof Oe.default)return o;if(typeof o=="string"){if(o.match(/^-?[0-9]+$/))return new Oe.default(o);t.logWithError(`invalid BigNumberish string: ${o}`)}return typeof o=="number"?(o%1&&t.logWithError(`BigNumberish number underflow: ${o}`),(o>=yn||o<=-yn)&&t.logWithError(`BigNumberish number overflow: ${o}`),new Oe.default(String(o))):typeof o=="bigint"?new Oe.default(o.toString()):(t.error(`invalid BigNumberish value: ${o}`),new Oe.default(0))}var mt=j("module/fraction"),Ft=Ge(je.default),He=Ge(Tn.default),ko={0:He.ROUND_DOWN,1:He.ROUND_HALF_UP,2:He.ROUND_UP},xo={0:je.default.roundDown,1:je.default.roundHalfUp,2:je.default.roundUp},pe=class o{constructor(t,e=new hn.default(1)){this.numerator=ae(t),this.denominator=ae(e)}get quotient(){return this.numerator.div(this.denominator)}invert(){return new o(this.denominator,this.numerator)}add(t){let e=t instanceof o?t:new o(ae(t));return this.denominator.eq(e.denominator)?new o(this.numerator.add(e.numerator),this.denominator):new o(this.numerator.mul(e.denominator).add(e.numerator.mul(this.denominator)),this.denominator.mul(e.denominator))}sub(t){let e=t instanceof o?t:new o(ae(t));return this.denominator.eq(e.denominator)?new o(this.numerator.sub(e.numerator),this.denominator):new o(this.numerator.mul(e.denominator).sub(e.numerator.mul(this.denominator)),this.denominator.mul(e.denominator))}mul(t){let e=t instanceof o?t:new o(ae(t));return new o(this.numerator.mul(e.numerator),this.denominator.mul(e.denominator))}div(t){let e=t instanceof o?t:new o(ae(t));return new o(this.numerator.mul(e.denominator),this.denominator.mul(e.numerator))}toSignificant(t,e={groupSeparator:""},n=1){Number.isInteger(t)||mt.logWithError(`${t} is not an integer.`),t<=0&&mt.logWithError(`${t} is not positive.`),He.set({precision:t+1,rounding:ko[n]});let r=new He(this.numerator.toString()).div(this.denominator.toString()).toSignificantDigits(t);return r.toFormat(r.decimalPlaces(),e)}toFixed(t,e={groupSeparator:""},n=1){return Number.isInteger(t)||mt.logWithError(`${t} is not an integer.`),t<0&&mt.logWithError(`${t} is negative.`),Ft.DP=t,Ft.RM=xo[n]||1,new Ft(this.numerator.toString()).div(this.denominator.toString()).toFormat(t,e)}isZero(){return this.numerator.isZero()}};var Ir=j("Sega_amount"),Sr=Ge(Pn.default);var wn=require("@solana/web3.js"),vt=require("@solana/spl-token"),Ae={chainId:101,address:wn.PublicKey.default.toBase58(),programId:vt.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"}},de={chainId:101,address:"So11111111111111111111111111111111111111112",programId:vt.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 pt=require("@solana/web3.js");var v=require("@solana/web3.js"),An=require("@solana/spl-token");function Wt({pubkey:o,isSigner:t=!1,isWritable:e=!0}){return{pubkey:o,isWritable:e,isSigner:t}}var Lr=[Wt({pubkey:An.TOKEN_PROGRAM_ID,isWritable:!1}),Wt({pubkey:v.SystemProgram.programId,isWritable:!1}),Wt({pubkey:v.SYSVAR_RENT_PUBKEY,isWritable:!1})];function Vt({publicKey:o,transformSol:t}){let e=kn(o.toString());if(e instanceof v.PublicKey)return t&&e.equals(ze)?ee:e;if(t&&e.toString()===ze.toBase58())return ee;if(typeof e=="string"){if(e===v.PublicKey.default.toBase58())return v.PublicKey.default;try{return new v.PublicKey(e)}catch(n){throw new Error("invalid public key")}}throw new Error("invalid public key")}function kn(o){try{return new v.PublicKey(o)}catch(t){return o}}var _r=new v.PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),xn=new v.PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),In=new v.PublicKey("SysvarRent111111111111111111111111111111111"),Or=new v.PublicKey("SysvarC1ock11111111111111111111111111111111"),Sn=new v.PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),Nr=new v.PublicKey("Sysvar1nstructions1111111111111111111111111"),Bn=v.SystemProgram.programId,Rr=new v.PublicKey("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),Mr=new v.PublicKey("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),Dr=new v.PublicKey("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),Er=new v.PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),Fr=new v.PublicKey("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),vr=new v.PublicKey("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),Wr=new v.PublicKey("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),Vr=new v.PublicKey("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),Ur=new v.PublicKey("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),qr=new v.PublicKey("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),Gr=new v.PublicKey("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),ee=new v.PublicKey("So11111111111111111111111111111111111111112"),ze=v.PublicKey.default;function lt(o){return Vt({publicKey:o,transformSol:!0})}var dt=class dt{constructor({mint:t,decimals:e,symbol:n,name:r,skipMint:i=!1,isToken2022:a=!1}){if(t===ze.toBase58()||t instanceof pt.PublicKey&&ze.equals(t)){this.decimals=de.decimals,this.symbol=de.symbol,this.name=de.name,this.mint=new pt.PublicKey(de.address),this.isToken2022=!1;return}this.decimals=e,this.symbol=n||t.toString().substring(0,6),this.name=r||t.toString().substring(0,6),this.mint=i?pt.PublicKey.default:Vt({publicKey:t}),this.isToken2022=a}equals(t){return this===t?!0:this.mint.equals(t.mint)}};dt.WSOL=new dt(D(L({},de),{mint:de.address}));var ne=dt;var ft=class ft{constructor({decimals:t,symbol:e="UNKNOWN",name:n="UNKNOWN"}){this.decimals=t,this.symbol=e,this.name=n}equals(t){return this===t}};ft.SOL=new ft(Ae);var Ut=ft;var Kn=q(require("bn.js"));var Cn=new pe(new Kn.default(100)),ue=class extends pe{toSignificant(t=5,e,n){return this.mul(Cn).toSignificant(t,e,n)}toFixed(t=2,e,n){return this.mul(Cn).toFixed(t,e,n)}};var si=j("Sega_price");var Bo=require("@solana/web3.js"),Co=q(require("bn.js"));var Gt=new fe.default(0),Fi=new fe.default(1),vi=new fe.default(2),Wi=new fe.default(3),Vi=new fe.default(5),So=new fe.default(10),Ui=new fe.default(100),qi=new fe.default(1e3),Gi=new fe.default(1e4);function Dt(o,t=1,e=[]){let n=[...o];if(t<=0)return e;for(;n.length;)e.push(n.splice(0,t));return e}var Ye=class o{constructor(t){this._owner=t}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(t){return t.secretKey!==void 0}static isPublicKey(t){return!o.isKeyPair(t)}};var Rn=require("@solana/web3.js"),Mn=require("@solana/spl-token");var X=require("@solana/web3.js");var U={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 On=require("@solana/spl-token");var _n=j("Sega_txUtil"),Nn=1644;function gt(o){let t=[],e=[];return o.microLamports&&(t.push(X.ComputeBudgetProgram.setComputeUnitPrice({microLamports:o.microLamports})),e.push(U.SetComputeUnitPrice)),o.units&&(t.push(X.ComputeBudgetProgram.setComputeUnitLimit({units:o.units})),e.push(U.SetComputeUnitLimit)),{instructions:t,instructionTypes:e}}function Ne(o,t){return y(this,null,function*(){var n,r;let e=t!=null?t:"confirmed";return(r=yield(n=o.getLatestBlockhash)==null?void 0:n.call(o,{commitment:e}))==null?void 0:r.blockhash})}function bt(o,t){return y(this,null,function*(){return o.getSignatureStatuses([t]),new Promise((e,n)=>{let r=setTimeout(n,6e4);o.onSignature(t,i=>{if(clearTimeout(r),!i.err){e("");return}n(Object.assign(i.err,{txId:t}))},"confirmed")})})}function jt(o,t){o.length<1&&_n.logWithError(`no instructions provided: ${o.toString()}`),t.length<1&&_n.logWithError(`no signers provided:, ${t.toString()}`);let e=new X.Transaction;e.recentBlockhash="11111111111111111111111111111111",e.feePayer=t[0],e.add(...o);try{return Buffer.from(e.serialize({verifySignatures:!1})).toString("base64").length<Nn}catch(n){return!1}}function ce(o,t){let[e,n]=X.PublicKey.findProgramAddressSync(o,t);return{publicKey:e,nonce:n}}function Je({instructions:o,payer:t,signers:e}){return jt(o,[t,...e])}function $e({instructions:o,payer:t,lookupTableAddressAccount:e,recentBlockhash:n=X.Keypair.generate().publicKey.toString()}){let i=new X.TransactionMessage({payerKey:t,recentBlockhash:n,instructions:o}).compileToV0Message(Object.values(e!=null?e:{}));try{return Buffer.from(new X.VersionedTransaction(i).serialize()).toString("base64").length<Nn}catch(a){return!1}}var Lo=o=>Buffer.isBuffer(o)?o:o instanceof Uint8Array?Buffer.from(o.buffer,o.byteOffset,o.byteLength):Buffer.from(o),_o=o=>{let t=o.serialize({requireAllSignatures:!1,verifySignatures:!1});o instanceof X.VersionedTransaction&&(t=Lo(t));try{return t instanceof Buffer?t.toString("base64"):Buffer.from(t).toString("base64")}catch(e){return t.toString("base64")}};function Be(o){let t=[];return o.forEach(e=>{e instanceof X.Transaction&&(e.recentBlockhash||(e.recentBlockhash=On.TOKEN_PROGRAM_ID.toBase58()),e.feePayer||(e.feePayer=X.Keypair.generate().publicKey)),t.push(_o(e))}),console.log("simulate tx string:",t),t}function Ce(o,t,e){return ce([o.toBuffer(),(e!=null?e:Mn.TOKEN_PROGRAM_ID).toBuffer(),t.toBuffer()],new Rn.PublicKey("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"))}var ye=require("@solana/web3.js"),Oo=new ye.PublicKey("SegazTQwbYWknDZkJ6j2Kgvm5gw3MrHGKtWstZdoNKZ"),No=new ye.PublicKey("Ajk8d9bERSaFdeoT1d8JUVfaDayrYLnAdgeB47TFMUaG"),cs=new ye.PublicKey("2HbjxVVKJ7Ct72Rcd8WK4VTqmwTXL5aAggkH1CHGFGmh"),Ro=new ye.PublicKey("auetiVUVJkRxvNPLYEvVnz8UJSqQ1VgoA83PcicHVD1"),Mo=new ye.PublicKey("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y"),Do=new ye.PublicKey("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y");var ls={SERUM_MARKET:ye.PublicKey.default,UTIL1216:ye.PublicKey.default,CREATE_CPMM_POOL_PROGRAM:Ro,CREATE_CPMM_POOL_AUTH:Mo,CREATE_CPMM_POOL_FEE_ACC:Do};var ie=q(require("bn.js"));var Ze=1e4;function Ke(o,t,e,n){if(t===void 0)return{amount:o,fee:void 0,expirationTime:void 0};let r=D(L({},t),{olderTransferFee:{epoch:BigInt(t.olderTransferFee.epoch),maximumFee:BigInt(t.olderTransferFee.maximumFee),transferFeeBasisPoints:t.olderTransferFee.transferFeeBasisPoints},newerTransferFee:{epoch:BigInt(t.newerTransferFee.epoch),maximumFee:BigInt(t.newerTransferFee.maximumFee),transferFeeBasisPoints:t.newerTransferFee.transferFeeBasisPoints}}),i=e.epoch<r.newerTransferFee.epoch?r.olderTransferFee:r.newerTransferFee,a=new ie.default(i.maximumFee.toString()),s=e.epoch<r.newerTransferFee.epoch?(Number(r.newerTransferFee.epoch)*e.slotsInEpoch-e.absoluteSlot)*400/1e3:void 0;if(n)if(i.transferFeeBasisPoints===Ze){let c=new ie.default(i.maximumFee.toString());return{amount:o.add(c),fee:c,expirationTime:s}}else{let c=Re(o.mul(new ie.default(Ze)),new ie.default(Ze-i.transferFeeBasisPoints)),u=new ie.default(i.maximumFee.toString()),m=c.sub(o).gt(u)?o.add(u):c,l=Re(m.mul(new ie.default(i.transferFeeBasisPoints)),new ie.default(Ze)),p=l.gt(a)?a:l;return{amount:m,fee:p,expirationTime:s}}else{let c=Re(o.mul(new ie.default(i.transferFeeBasisPoints)),new ie.default(Ze)),u=c.gt(a)?a:c;return{amount:o,fee:u,expirationTime:s}}}function Re(o,t){let{div:e,mod:n}=o.divmod(t);return n.gt(new ie.default(0))?e.add(new ie.default(1)):e}var Xe=require("@solana/web3.js");function Ht(e){return y(this,arguments,function*({connection:o,address:t}){let n=yield Ue(o,[...new Set(t.map(i=>i.toString()))].map(i=>new Xe.PublicKey(i))),r={};for(let i=0;i<t.length;i++){let a=n[i],s=t[i];if(!a)continue;let c=new Xe.AddressLookupTableAccount({key:s,state:Xe.AddressLookupTableAccount.deserialize(a.data)});r[s.toString()]=c,yt[s.toString()]=c}return r})}var yt={};var F=require("@solana/web3.js"),Dn=q(require("axios"));var ht=2e3,Tt=class{constructor(t){this.instructions=[];this.endInstructions=[];this.lookupTableAddress=[];this.signers=[];this.instructionTypes=[];this.endInstructionTypes=[];this.connection=t.connection,this.feePayer=t.feePayer,this.signAllTransactions=t.signAllTransactions,this.owner=t.owner,this.cluster=t.cluster,this.blockhashCommitment=t.blockhashCommitment,this.loopMultiTxStatus=!!t.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 y(this,null,function*(){var n;let t=(yield Dn.default.get("https://solanacompass.com/api/fees?cacheFreshTime=300000")).data,{avg:e}=(n=t==null?void 0:t[15])!=null?n:{};if(e)return{units:6e5,microLamports:Math.min(Math.ceil(e*1e6/6e5),25e3)}})}addCustomComputeBudget(t){if(t){let{instructions:e,instructionTypes:n}=gt(t);return this.instructions.unshift(...e),this.instructionTypes.unshift(...n),!0}return!1}addTipInstruction(t){var e;return t?(this.endInstructions.push(F.SystemProgram.transfer({fromPubkey:(e=t.feePayer)!=null?e:this.feePayer,toPubkey:new F.PublicKey(t.address),lamports:BigInt(t.amount.toString())})),this.endInstructionTypes.push(U.TransferTip),!0):!1}calComputeBudget(n){return y(this,arguments,function*({config:t,defaultIns:e}){try{let r=t||(yield this.getComputeBudgetConfig());if(this.addCustomComputeBudget(r))return;e&&this.instructions.unshift(...e)}catch(r){e&&this.instructions.unshift(...e)}})}addInstruction({instructions:t=[],endInstructions:e=[],signers:n=[],instructionTypes:r=[],endInstructionTypes:i=[],lookupTableAddress:a=[]}){return this.instructions.push(...t),this.endInstructions.push(...e),this.signers.push(...n),this.instructionTypes.push(...r),this.endInstructionTypes.push(...i),this.lookupTableAddress.push(...a.filter(s=>s!==F.PublicKey.default.toString())),this}versionBuild(n){return y(this,arguments,function*({txVersion:t,extInfo:e}){return t===0?yield this.buildV0(L({},e||{})):this.build(e)})}build(t){var n;let e=new F.Transaction;return this.allInstructions.length&&e.add(...this.allInstructions),e.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:e,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:r=>y(this,null,function*(){var u;let{recentBlockHash:i,skipPreflight:a=!0,sendAndConfirm:s}=r||{},c=i!=null?i:yield Ne(this.connection,this.blockhashCommitment);if(e.recentBlockhash=c,this.signers.length&&e.sign(...this.signers),Be([e]),(u=this.owner)!=null&&u.isKeyPair)return{txId:s?yield(0,F.sendAndConfirmTransaction)(this.connection,e,this.signers.find(l=>l.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:a}):yield this.connection.sendRawTransaction(e.serialize(),{skipPreflight:a}),signedTx:e};if(this.signAllTransactions){let m=yield this.signAllTransactions([e]);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:t||{}}}buildMultiTx(t){var u;let{extraPreBuildData:e=[],extInfo:n}=t,{transaction:r}=this.build(n),i=e.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=>y(this,null,function*(){var k;let{sequentially:l,onTxUpdate:p,skipTxCount:d=0,recentBlockHash:f,skipPreflight:h=!0}=m||{},g=f!=null?f:yield Ne(this.connection,this.blockhashCommitment);if((k=this.owner)!=null&&k.isKeyPair){if(l){let P=[],A=0;for(let T of a){if(++A,A<=d)continue;let b=yield(0,F.sendAndConfirmTransaction)(this.connection,T,this.signers.find(w=>w.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:h});P.push(b)}return{txIds:P,signedTxs:a}}return{txIds:yield yield Promise.all(a.map(P=>y(this,null,function*(){return P.recentBlockhash=g,yield this.connection.sendRawTransaction(P.serialize(),{skipPreflight:h})}))),signedTxs:a}}if(this.signAllTransactions){let P=a.map((T,b)=>(T.recentBlockhash=g,s[b].length&&T.sign(...s[b]),T));Be(P);let A=yield this.signAllTransactions(P);if(l){let T=0,b=[],w=()=>y(this,null,function*(){if(!A[T])return;let x=yield this.connection.sendRawTransaction(A[T].serialize(),{skipPreflight:h});b.push({txId:x,status:"sent",signedTx:A[T]}),p==null||p([...b]),T++;let I=!1,B=null,C=null,R=_=>{B!==null&&clearInterval(B),C!==null&&this.connection.removeSignatureListener(C);let N=b.findIndex(E=>E.txId===x);if(N>-1){if(b[N].status==="error"||b[N].status==="success")return;b[N].status=_.err?"error":"success"}p==null||p([...b]),_.err||w()};this.loopMultiTxStatus&&(B=setInterval(()=>y(this,null,function*(){var _;if(I){clearInterval(B);return}try{let N=yield this.connection.getTransaction(x,{commitment:"confirmed",maxSupportedTransactionVersion:0});N&&(I=!0,clearInterval(B),R({err:((_=N.meta)==null?void 0:_.err)||null}),console.log("tx status from getTransaction:",x))}catch(N){I=!0,clearInterval(B),console.error("getTransaction timeout:",N,x)}}),ht)),C=this.connection.onSignature(x,_=>{if(I){this.connection.removeSignatureListener(C);return}I=!0,R(_)},"confirmed"),this.connection.getSignatureStatus(x)});return yield w(),{txIds:b.map(x=>x.txId),signedTxs:A}}else{let T=[];for(let b=0;b<A.length;b+=1){let w=yield this.connection.sendRawTransaction(A[b].serialize(),{skipPreflight:h});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 y(this,arguments,function*({extraPreBuildData:t,txVersion:e,extInfo:n}){return e===0?yield this.buildV0MultiTx({extraPreBuildData:t,buildProps:n||{}}):this.buildMultiTx({extraPreBuildData:t,extInfo:n})})}buildV0(t){return y(this,null,function*(){var h;let f=t||{},{lookupTableCache:e={},lookupTableAddress:n=[],forerunCreate:r,recentBlockhash:i}=f,a=Q(f,["lookupTableCache","lookupTableAddress","forerunCreate","recentBlockhash"]),s=L(L({},this.cluster==="devnet"?{}:yt),e),c=Array.from(new Set([...n,...this.lookupTableAddress])),u=[];for(let g of c)s[g]===void 0&&u.push(new F.PublicKey(g));let m=yield Ht({connection:this.connection,address:u});for(let[g,k]of Object.entries(m))s[g]=k;let l=r?F.PublicKey.default.toBase58():i!=null?i:yield Ne(this.connection,this.blockhashCommitment),p=new F.TransactionMessage({payerKey:this.feePayer,recentBlockhash:l,instructions:[...this.allInstructions]}).compileToV0Message(Object.values(s));(h=this.owner)!=null&&h.signer&&!this.signers.some(g=>g.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer);let d=new F.VersionedTransaction(p);return d.sign(this.signers),{builder:this,transaction:d,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:g=>y(this,null,function*(){var A;let{skipPreflight:k=!0,sendAndConfirm:P}=g||{};if(Be([d]),(A=this.owner)!=null&&A.isKeyPair){let T=yield this.connection.sendTransaction(d,{skipPreflight:k});return P&&(yield bt(this.connection,T)),{txId:T,signedTx:d}}if(this.signAllTransactions){let T=yield this.signAllTransactions([d]);if(this.signers.length)for(let b of T)try{b.sign(this.signers)}catch(w){}return{txId:yield this.connection.sendTransaction(T[0],{skipPreflight:k}),signedTx:T[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:a||{}}})}buildV0MultiTx(t){return y(this,null,function*(){var u;let{extraPreBuildData:e=[],buildProps:n}=t,{transaction:r}=yield this.buildV0(n),i=e.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)=>y(this,null,function*(){m.sign(s[l])})),{builder:this,transactions:a,signers:s,instructionTypes:c,buildProps:n,execute:m=>y(this,null,function*(){var h;let{sequentially:l,onTxUpdate:p,recentBlockHash:d,skipPreflight:f=!0}=m||{};if(d&&a.forEach(g=>g.message.recentBlockhash=d),Be(a),(h=this.owner)!=null&&h.isKeyPair){if(l){let g=[];for(let k of a){let P=yield this.connection.sendTransaction(k,{skipPreflight:f});yield bt(this.connection,P),g.push(P)}return{txIds:g,signedTxs:a}}return{txIds:yield Promise.all(a.map(g=>y(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 k=0,P=[],A=()=>y(this,null,function*(){if(!g[k])return;let T=yield this.connection.sendTransaction(g[k],{skipPreflight:f});P.push({txId:T,status:"sent",signedTx:g[k]}),p==null||p([...P]),k++;let b=!1,w=null,x=null,I=B=>{w!==null&&clearInterval(w),x!==null&&this.connection.removeSignatureListener(x);let C=P.findIndex(R=>R.txId===T);if(C>-1){if(P[C].status==="error"||P[C].status==="success")return;P[C].status=B.err?"error":"success"}p==null||p([...P]),B.err||A()};this.loopMultiTxStatus&&(w=setInterval(()=>y(this,null,function*(){var B;if(b){clearInterval(w);return}try{let C=yield this.connection.getTransaction(T,{commitment:"confirmed",maxSupportedTransactionVersion:0});C&&(b=!0,clearInterval(w),I({err:((B=C.meta)==null?void 0:B.err)||null}),console.log("tx status from getTransaction:",T))}catch(C){b=!0,clearInterval(w),console.error("getTransaction timeout:",C,T)}}),ht)),x=this.connection.onSignature(T,B=>{if(b){this.connection.removeSignatureListener(x);return}b=!0,I(B)},"confirmed"),this.connection.getSignatureStatus(T)});return A(),{txIds:[],signedTxs:g}}else{let k=[];for(let P=0;P<g.length;P+=1){let A=yield this.connection.sendTransaction(g[P],{skipPreflight:f});k.push(A)}return{txIds:k,signedTxs:g}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:n||{}}})}sizeCheckBuild(t){return y(this,null,function*(){var p;let l=t||{},{splitIns:e=[],computeBudgetConfig:n}=l,r=Q(l,["splitIns","computeBudgetConfig"]),i=n?gt(n):{instructions:[],instructionTypes:[]},a=this.signers.reduce((d,f)=>D(L({},d),{[f.publicKey.toBase58()]:f}),{}),s=[],c=[],u=[],m=0;if(this.allInstructions.forEach(d=>{let f=[...u,d],h=n?[...i.instructions,...f]:f,k=[...new Set(f.map(P=>P.keys.filter(A=>A.isSigner).map(A=>A.pubkey.toString())).flat()).values()].map(P=>new F.PublicKey(P));if(d!==e[m]&&u.length<12&&(Je({instructions:h,payer:this.feePayer,signers:k})||Je({instructions:f,payer:this.feePayer,signers:k})))u.push(d);else{if(u.length===0)throw Error("item ins too big");m+=d===e[m]?1:0,Je({instructions:n?[...i.instructions,...u]:[...u],payer:this.feePayer,signers:k})?s.push(new F.Transaction().add(...i.instructions,...u)):s.push(new F.Transaction().add(...u)),c.push(Array.from(new Set(u.map(P=>P.keys.filter(A=>A.isSigner).map(A=>A.pubkey.toString())).flat())).map(P=>a[P]).filter(P=>P!==void 0)),u=[d]}}),u.length>0){let f=[...new Set(u.map(h=>h.keys.filter(g=>g.isSigner).map(g=>g.pubkey.toString())).flat()).values()].map(h=>a[h]).filter(h=>h!==void 0);Je({instructions:n?[...i.instructions,...u]:[...u],payer:this.feePayer,signers:f.map(h=>h.publicKey)})?s.push(new F.Transaction().add(...i.instructions,...u)):s.push(new F.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=>y(this,null,function*(){var T;let{sequentially:f,onTxUpdate:h,skipTxCount:g=0,recentBlockHash:k,skipPreflight:P=!0}=d||{},A=k!=null?k:yield Ne(this.connection,this.blockhashCommitment);if(s.forEach((b,w)=>y(this,null,function*(){b.recentBlockhash=A,c[w].length&&b.sign(...c[w])})),Be(s),(T=this.owner)!=null&&T.isKeyPair){if(f){let b=0,w=[];for(let x of s){if(++b,b<=g){w.push("tx skipped");continue}let I=yield(0,F.sendAndConfirmTransaction)(this.connection,x,this.signers.find(B=>B.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:P});w.push(I)}return{txIds:w,signedTxs:s}}return{txIds:yield Promise.all(s.map(b=>y(this,null,function*(){return yield this.connection.sendRawTransaction(b.serialize(),{skipPreflight:P})}))),signedTxs:s}}if(this.signAllTransactions){let b=yield this.signAllTransactions(s.slice(g,s.length)),w=[...s.slice(0,g),...b];if(f){let x=0,I=[],B=()=>y(this,null,function*(){if(!w[x])return;x<g&&(I.push({txId:"",status:"success",signedTx:w[x]}),h==null||h([...I]),x++,B());let C=yield this.connection.sendRawTransaction(w[x].serialize(),{skipPreflight:P});I.push({txId:C,status:"sent",signedTx:w[x]}),h==null||h([...I]),x++;let R=!1,_=null,N=null,E=M=>{_!==null&&clearInterval(_),N!==null&&this.connection.removeSignatureListener(N);let W=I.findIndex(Y=>Y.txId===C);if(W>-1){if(I[W].status==="error"||I[W].status==="success")return;I[W].status=M.err?"error":"success"}h==null||h([...I]),M.err||B()};this.loopMultiTxStatus&&(_=setInterval(()=>y(this,null,function*(){var M;if(R){clearInterval(_);return}try{let W=yield this.connection.getTransaction(C,{commitment:"confirmed",maxSupportedTransactionVersion:0});W&&(R=!0,clearInterval(_),E({err:((M=W.meta)==null?void 0:M.err)||null}),console.log("tx status from getTransaction:",C))}catch(W){R=!0,clearInterval(_),console.error("getTransaction timeout:",W,C)}}),ht)),N=this.connection.onSignature(C,M=>{if(R){this.connection.removeSignatureListener(N);return}R=!0,E(M)},"confirmed"),this.connection.getSignatureStatus(C)});return yield B(),{txIds:I.map(C=>C.txId),signedTxs:w}}else{let x=[];for(let I=0;I<w.length;I+=1){let B=yield this.connection.sendRawTransaction(w[I].serialize(),{skipPreflight:P});x.push(B)}return{txIds:x,signedTxs:w}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:r||{}}})}sizeCheckBuildV0(t){return y(this,null,function*(){var A;let P=t||{},{computeBudgetConfig:e,splitIns:n=[],lookupTableCache:r={},lookupTableAddress:i=[]}=P,a=Q(P,["computeBudgetConfig","splitIns","lookupTableCache","lookupTableAddress"]),s=L(L({},this.cluster==="devnet"?{}:yt),r),c=Array.from(new Set([...this.lookupTableAddress,...i])),u=[];for(let T of c)s[T]===void 0&&u.push(new F.PublicKey(T));let m=yield Ht({connection:this.connection,address:u});for(let[T,b]of Object.entries(m))s[T]=b;let l=e?gt(e):{instructions:[],instructionTypes:[]},p=yield Ne(this.connection,this.blockhashCommitment),d=this.signers.reduce((T,b)=>D(L({},T),{[b.publicKey.toBase58()]:b}),{}),f=[],h=[],g=[],k=0;if(this.allInstructions.forEach(T=>{let b=[...g,T],w=e?[...l.instructions,...b]:b;if(T!==n[k]&&g.length<12&&($e({instructions:w,payer:this.feePayer,lookupTableAddressAccount:s})||$e({instructions:b,payer:this.feePayer,lookupTableAddressAccount:s})))g.push(T);else{if(g.length===0)throw Error("item ins too big");k+=T===n[k]?1:0;let x={};for(let I of[...new Set(c)])s[I]!==void 0&&(x[I]=s[I]);if(e&&$e({instructions:[...l.instructions,...g],payer:this.feePayer,lookupTableAddressAccount:s,recentBlockhash:p})){let I=new F.TransactionMessage({payerKey:this.feePayer,recentBlockhash:p,instructions:[...l.instructions,...g]}).compileToV0Message(Object.values(s));f.push(new F.VersionedTransaction(I))}else{let I=new F.TransactionMessage({payerKey:this.feePayer,recentBlockhash:p,instructions:[...g]}).compileToV0Message(Object.values(s));f.push(new F.VersionedTransaction(I))}h.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 b=[...new Set(g.map(w=>w.keys.filter(x=>x.isSigner).map(x=>x.pubkey.toString())).flat()).values()].map(w=>d[w]).filter(w=>w!==void 0);if(e&&$e({instructions:[...l.instructions,...g],payer:this.feePayer,lookupTableAddressAccount:s,recentBlockhash:p})){let w=new F.TransactionMessage({payerKey:this.feePayer,recentBlockhash:p,instructions:[...l.instructions,...g]}).compileToV0Message(Object.values(s));f.push(new F.VersionedTransaction(w))}else{let w=new F.TransactionMessage({payerKey:this.feePayer,recentBlockhash:p,instructions:[...g]}).compileToV0Message(Object.values(s));f.push(new F.VersionedTransaction(w))}h.push(b)}return(A=this.owner)!=null&&A.signer&&h.forEach(T=>{T.some(b=>b.publicKey.equals(this.owner.publicKey))||T.push(this.owner.signer)}),{builder:this,transactions:f,buildProps:t,signers:h,instructionTypes:this.instructionTypes,execute:T=>y(this,null,function*(){var C;let{sequentially:b,onTxUpdate:w,skipTxCount:x=0,recentBlockHash:I,skipPreflight:B=!0}=T||{};if(f.map((R,_)=>y(this,null,function*(){h[_].length&&R.sign(h[_]),I&&(R.message.recentBlockhash=I)})),Be(f),(C=this.owner)!=null&&C.isKeyPair){if(b){let R=0,_=[];for(let N of f){if(++R,R<=x){console.log("skip tx: ",R),_.push("tx skipped");continue}let E=yield this.connection.sendTransaction(N,{skipPreflight:B});yield bt(this.connection,E),_.push(E)}return{txIds:_,signedTxs:f}}return{txIds:yield Promise.all(f.map(R=>y(this,null,function*(){return yield this.connection.sendTransaction(R,{skipPreflight:B})}))),signedTxs:f}}if(this.signAllTransactions){let R=yield this.signAllTransactions(f.slice(x,f.length)),_=[...f.slice(0,x),...R];if(b){let N=0,E=[],M=()=>y(this,null,function*(){if(!_[N])return;if(N<x){E.push({txId:"",status:"success",signedTx:_[N]}),w==null||w([...E]),N++,M();return}let W=yield this.connection.sendTransaction(_[N],{skipPreflight:B});E.push({txId:W,status:"sent",signedTx:_[N]}),w==null||w([...E]),N++;let Y=!1,se=null,Ie=null,ln=Se=>{se!==null&&clearInterval(se),Ie!==null&&this.connection.removeSignatureListener(Ie);let be=E.findIndex(lo=>lo.txId===W);if(be>-1){if(E[be].status==="error"||E[be].status==="success")return;E[be].status=Se.err?"error":"success"}w==null||w([...E]),Se.err||M()};this.loopMultiTxStatus&&(se=setInterval(()=>y(this,null,function*(){var Se;if(Y){clearInterval(se);return}try{let be=yield this.connection.getTransaction(W,{commitment:"confirmed",maxSupportedTransactionVersion:0});be&&(Y=!0,clearInterval(se),ln({err:((Se=be.meta)==null?void 0:Se.err)||null}),console.log("tx status from getTransaction:",W))}catch(be){Y=!0,clearInterval(se),console.error("getTransaction timeout:",be,W)}}),ht)),Ie=this.connection.onSignature(W,Se=>{if(Y){this.connection.removeSignatureListener(Ie);return}Y=!0,ln(Se)},"confirmed"),this.connection.getSignatureStatus(W)});return M(),{txIds:[],signedTxs:_}}else{let N=[];for(let E=0;E<_.length;E+=1){let M=yield this.connection.sendTransaction(_[E],{skipPreflight:B});N.push(M)}return{txIds:N,signedTxs:_}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:a||{}}})}};var Eo=require("@solana/web3.js");var le={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"},$s=L({},le);var En="ray_tab_hash",zt="ray_req_hash",Fo=()=>{if(typeof window===void 0)return"";let o=sessionStorage.getItem(En);return o||(o=`ray-${Date.now()}`,sessionStorage.setItem(En,o)),o},Pt=n=>y(void 0,null,function*(){var r=n,{logCount:o=1e3,removeLastLog:t}=r,e=Q(r,["logCount","removeLastLog"]);if(typeof window===void 0)return new Promise(a=>a());let i=JSON.parse(localStorage.getItem(zt)||"[]").slice(0,o-1);t&&i.pop(),new Blob([JSON.stringify(e.data)]).size>1024&&(e.data=JSON.stringify(e.data).substring(0,200)+"..."),i.unshift(D(L({},e),{time:Date.now(),session:Fo()}));try{localStorage.setItem(zt,JSON.stringify(i))}catch(a){if(t){let s=!1,c=JSON.stringify(e.data).substring(0,100);for(i[0].data=c+(c.length>100?"...":"");!s;){i.pop();let u=JSON.stringify(e.data).substring(0,100);i[0].data=u+(u.length>100?"...":"");try{localStorage.setItem(zt,JSON.stringify(i)),s=!0}catch(m){s=!1}}return new Promise(u=>u())}return Pt(D(L({},e),{logCount:o,removeLastLog:!0}))}});var wt=j("Sega_Api"),Yt=new Map;var At=class{constructor({cluster:t,timeout:e,logRequests:n,logCount:r,urlConfigs:i}){this.cluster=t,this.urlConfigs=i||{},this.logCount=r||1e3,this.api=Jt.default.create({baseURL:this.urlConfigs.BASE_HOST||le.BASE_HOST,timeout:e}),this.api.interceptors.request.use(a=>{let{method:s,baseURL:c,url:u}=a;return wt.debug(`${s==null?void 0:s.toUpperCase()} ${c}${u}`),a},a=>(wt.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&&Pt({status:u,url:`${l}${p}`,params:s.params,data:c,logCount:this.logCount}),wt.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&&Pt({status:u,url:`${l}${p}`,params:s.params,data:a.message,logCount:this.logCount}),wt.error(`${m.toUpperCase()} ${l}${p} ${u||a.message}`),Promise.reject(a)})}getCpmmConfigs(){return y(this,null,function*(){return(yield this.api.get(this.urlConfigs.CPMM_CONFIG||le.CPMM_CONFIG)).data})}getBlockSlotCountForSecond(t){return y(this,null,function*(){if(!t)return 2;let n=(yield Jt.default.post(t,{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 y(this,null,function*(){return(yield this.api.get(this.urlConfigs.CHAIN_TIME||le.CHAIN_TIME)).data})}fetchPoolKeysById(t){return y(this,null,function*(){let{idList:e}=t,n=[],r=e.filter(a=>Yt.has(a)?(n.push(Yt.get(a)),!1):!0),i=[];return r.length&&(i=(yield this.api.get((this.urlConfigs.POOL_KEY_BY_ID||le.POOL_KEY_BY_ID)+`?ids=${r.join(",")}`)).data.filter(Boolean),i.forEach(s=>{Yt.set(s.id,s)})),n.concat(i)})}getRpcs(){return y(this,null,function*(){return this.api.get(this.urlConfigs.RPCS||le.RPCS)})}getTokenList(){return y(this,null,function*(){return(yield this.api.get(this.urlConfigs.TOKEN_LIST||le.TOKEN_LIST)).data})}getJupTokenList(){return y(this,null,function*(){return this.api.get("",{baseURL:this.urlConfigs.JUP_TOKEN_LIST||le.JUP_TOKEN_LIST})})}getTokenInfo(t){return y(this,null,function*(){return(yield this.api.get((this.urlConfigs.MINT_INFO_ID||le.MINT_INFO_ID)+`?mints=${t.map(n=>n.toString()).join(",")}`)).data})}fetchAvailabilityStatus(){return y(this,null,function*(){return(yield this.api.get(this.urlConfigs.CHECK_AVAILABILITY||le.CHECK_AVAILABILITY)).data})}};var kt="please provide owner in load() initialization or you can set by calling sega.setOwner(owner)",Fn="please provide connection in load() initialization or set it by sega.setConnection(connection)";var _e=require("@solana/web3.js");var H=require("@solana/spl-token");var $t=(...o)=>o.map(t=>{try{return typeof t=="object"?JSON.stringify(t):t}catch(e){return t}}).join(", "),me=class{constructor({scope:t,moduleName:e}){this.disabled=!1;this.scope=t,this.logger=j(e)}createTxBuilder(t){return this.scope.checkOwner(),new Tt({connection:this.scope.connection,feePayer:t||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(...t){this.logger.debug($t(t))}logInfo(...t){this.logger.info($t(t))}logAndCreateError(...t){let e=$t(t);throw new Error(e)}checkDisabled(){(this.disabled||!this.scope)&&this.logAndCreateError("module not working")}};var St=require("@solana/web3.js"),Yn=q(require("bn.js"));var oe=require("@solana/spl-token");var et=require("@solana/web3.js"),Gn=q(require("bn.js"));var jn=require("@solana/spl-token"),Hn=require("@noble/hashes/sha256");var qn=require("@solana/web3.js"),Me=q(require("bn.js"));var K=require("@solana/buffer-layout"),Zt=K.Layout,vn=K.Structure;var Xt=K.UInt;var Wn=K.u8,Vn=K.u16;var Un=K.seq;var he=K.blob;var Qt=class extends Zt{constructor(t,e,n){super(t,n),this.blob=he(t),this.signed=e}decode(t,e=0){let n=new Me.default(this.blob.decode(t,e),10,"le");return this.signed?n.fromTwos(this.span*8).clone():n}encode(t,e,n=0){return typeof t=="number"&&(t=new Me.default(t)),this.signed&&(t=t.toTwos(this.span*8)),this.blob.encode(t.toArrayLike(Buffer,"le",this.span),e,n)}};function $(o){return new Xt(1,o)}function Le(o){return new Xt(4,o)}function O(o){return new Qt(8,!1,o)}var xt=class extends Zt{constructor(t,e,n,r){super(t.span,r),this.layout=t,this.decoder=e,this.encoder=n}decode(t,e){return this.decoder(this.layout.decode(t,e))}encode(t,e,n){return this.layout.encode(this.encoder(t),e,n)}getSpan(t,e){return this.layout.getSpan(t,e)}};function V(o){return new xt(he(32),t=>new qn.PublicKey(t),t=>t.toBuffer(),o)}function tn(o){return new xt(Wn(),vo,Wo,o)}function vo(o){if(o===0)return!1;if(o===1)return!0;throw new Error("Invalid bool: "+o)}function Wo(o){return o?1:0}var en=class extends vn{decode(t,e){return super.decode(t,e)}};function J(o,t,e){return new en(o,t,e)}function ke(o,t,e){let n,r=typeof t=="number"?t:(0,Me.isBN)(t)?t.toNumber():new Proxy(t,{get(i,a){if(!n){let s=Reflect.get(i,"count");n=(0,Me.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 Un(o,r,e)}var Qe=J([V("mint"),V("owner"),O("amount"),Le("delegateOption"),V("delegate"),$("state"),Le("isNativeOption"),O("isNative"),O("delegatedAmount"),Le("closeAuthorityOption"),V("closeAuthority")]);var Fa=j("Sega_Util");function zn({owner:o,solAccountResp:t,tokenAccountResp:e}){let n=[],r=[];for(let{pubkey:i,account:a}of e.value){let s=Qe.decode(a.data),{mint:c,amount:u}=s;n.push({publicKey:i,mint:c,amount:u,isAssociated:Ce(o,c,a.owner).publicKey.equals(i),isNative:!1,programId:a.owner}),r.push({pubkey:i,accountInfo:s,programId:a.owner})}return t&&n.push({mint:et.PublicKey.default,amount:new Gn.default(String(t.lamports)),isNative:!0,programId:t.owner}),{tokenAccounts:n,tokenAccountRawInfos:r}}function It({fromPublicKey:o,programId:t=jn.TOKEN_PROGRAM_ID,assignSeed:e}){let n=e?btoa(e).slice(0,32):et.Keypair.generate().publicKey.toBase58().slice(0,32);return{publicKey:Vo(o,n,t),seed:n}}function Vo(o,t,e){let n=Buffer.concat([o.toBuffer(),Buffer.from(t),e.toBuffer()]),r=(0,Hn.sha256)(n);return new et.PublicKey(r)}function nn(o){let{mint:t,tokenAccount:e,owner:n,programId:r=oe.TOKEN_PROGRAM_ID}=o;return(0,oe.createInitializeAccountInstruction)(e,t,n,r)}function tt(o){let{tokenAccount:t,payer:e,multiSigners:n=[],owner:r,programId:i=oe.TOKEN_PROGRAM_ID}=o;return(0,oe.createCloseAccountInstruction)(t,e,r,n,i)}function on(o){return y(this,null,function*(){let{connection:t,amount:e,commitment:n,payer:r,owner:i,skipCloseAccount:a}=o,s=yield t.getMinimumBalanceForRentExemption(Qe.span,n),c=ae(e).add(new Yn.default(s)),u=It({fromPublicKey:r,programId:oe.TOKEN_PROGRAM_ID});return{addresses:{newAccount:u.publicKey},signers:[],instructions:[St.SystemProgram.createAccountWithSeed({fromPubkey:r,basePubkey:r,seed:u.seed,newAccountPubkey:u.publicKey,lamports:c.toNumber(),space:Qe.span,programId:oe.TOKEN_PROGRAM_ID}),nn({mint:new St.PublicKey(de.address),tokenAccount:u.publicKey,owner:i,programId:oe.TOKEN_PROGRAM_ID})],instructionTypes:[U.CreateAccount,U.InitAccount],endInstructionTypes:a?[]:[U.CloseAccount],endInstructions:a?[]:[tt({tokenAccount:u.publicKey,payer:r,owner:i})]}})}function Jn({source:o,destination:t,owner:e,amount:n,multiSigners:r=[],tokenProgram:i=oe.TOKEN_PROGRAM_ID}){return(0,oe.createTransferInstruction)(o,t,e,BigInt(String(n)),r,i)}var nt=class extends me{constructor(e){super(e);this._tokenAccounts=[];this._tokenAccountRawInfos=[];this._accountListener=[];this._clientOwnedToken=!1;this._notSubscribeAccountChange=!1;this._accountFetchTime=0;let{tokenAccounts:n,tokenAccountRawInfos:r,notSubscribeAccountChange:i}=e;this._tokenAccounts=n||[],this._tokenAccountRawInfos=r||[],this._notSubscribeAccountChange=i!=null?i:!0,this._clientOwnedToken=!!(n||r)}get tokenAccounts(){return this._tokenAccounts}get tokenAccountRawInfos(){return this._tokenAccountRawInfos}set notSubscribeAccountChange(e){this._notSubscribeAccountChange=e}updateTokenAccount({tokenAccounts:e,tokenAccountRawInfos:n}){return e&&(this._tokenAccounts=e),n&&(this._tokenAccountRawInfos=n),this._accountChangeListenerId&&this.scope.connection.removeAccountChangeListener(this._accountChangeListenerId),this._accountChangeListenerId=void 0,this._clientOwnedToken=!0,this}addAccountChangeListener(e){return this._accountListener.push(e),this}removeAccountChangeListener(e){return this._accountListener=this._accountListener.filter(n=>n!==e),this}getAssociatedTokenAccount(e,n){return Ce(this.scope.ownerPubKey,e,n).publicKey}resetTokenAccounts(){this._clientOwnedToken||(this._tokenAccounts=[],this._tokenAccountRawInfos=[])}fetchWalletTokenAccounts(e){return y(this,null,function*(){if(this._clientOwnedToken||!(e!=null&&e.forceUpdate)&&this._tokenAccounts.length&&Date.now()-this._accountFetchTime<(this._notSubscribeAccountChange?1e3*5:1e3*60*3))return{tokenAccounts:this._tokenAccounts,tokenAccountRawInfos:this._tokenAccountRawInfos};this.scope.checkOwner();let r=L(L({},{}),e),[i,a,s]=yield Promise.all([this.scope.connection.getAccountInfo(this.scope.ownerPubKey,r.commitment),this.scope.connection.getTokenAccountsByOwner(this.scope.ownerPubKey,{programId:H.TOKEN_PROGRAM_ID},r.commitment),this.scope.connection.getTokenAccountsByOwner(this.scope.ownerPubKey,{programId:H.TOKEN_2022_PROGRAM_ID},r.commitment)]),{tokenAccounts:c,tokenAccountRawInfos:u}=zn({owner:this.scope.ownerPubKey,solAccountResp:i,tokenAccountResp:{context:a.context,value:[...a.value,...s.value]}});return this._tokenAccounts=c,this._tokenAccountRawInfos=u,this._accountFetchTime=Date.now(),this._notSubscribeAccountChange||(this._accountChangeListenerId&&this.scope.connection.removeAccountChangeListener(this._accountChan