UNPKG

@sega-so/sega-sdk

Version:

An SDK for building applications on top of SEGA.

1 lines 92.4 kB
var Qn=Object.defineProperty,eo=Object.defineProperties;var to=Object.getOwnPropertyDescriptors;var Xe=Object.getOwnPropertySymbols;var nn=Object.prototype.hasOwnProperty,on=Object.prototype.propertyIsEnumerable;var J=Math.pow,tn=(o,t,e)=>t in o?Qn(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e,K=(o,t)=>{for(var e in t||(t={}))nn.call(t,e)&&tn(o,e,t[e]);if(Xe)for(var e of Xe(t))on.call(t,e)&&tn(o,e,t[e]);return o},M=(o,t)=>eo(o,to(t));var z=(o,t)=>{var e={};for(var n in o)nn.call(o,n)&&t.indexOf(n)<0&&(e[n]=o[n]);if(o!=null&&Xe)for(var n of Xe(o))t.indexOf(n)<0&&on.call(o,n)&&(e[n]=o[n]);return e};var y=(o,t,e)=>new Promise((n,i)=>{var r=c=>{try{s(e.next(c))}catch(u){i(u)}},a=c=>{try{s(e.throw(c))}catch(u){i(u)}},s=c=>c.done?n(c.value):Promise.resolve(c.value).then(r,a);s((e=e.apply(o,t)).next())});import{merge as xr}from"lodash";import Bn from"axios";import{PublicKey as an}from"@solana/web3.js";import{get as rn,set as no}from"lodash";var kt=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}},sn={},oo={};function V(o){let t=rn(sn,o);if(!t){let e=rn(oo,o);t=new kt({name:o,logLevel:e}),no(sn,o,t)}return t}import{MINT_SIZE as ro,TOKEN_PROGRAM_ID as io,getTransferFeeConfig as so,unpackMint as ao}from"@solana/spl-token";var xt=V("Sega_accountInfo_util");function Ke(o,t,e){return y(this,null,function*(){let{batchRequest:n,commitment:i="confirmed",chunkCount:r=100}=K({batchRequest:!1},e),a=It(t,r),s=new Array(a.length).fill([]);if(n){let c=a.map(l=>({methodName:"getMultipleAccounts",args:o._buildArgs([l.map(d=>d.toBase58())],i,"base64")})),u=It(c,10);s=(yield(yield Promise.all(u.map(l=>y(this,null,function*(){return yield o._rpcBatchRequest(l)})))).flat()).map(l=>(l.error&&xt.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"&&xt.logWithError("info must be base64 encoded, RPC_ERROR"),{data:Buffer.from(d[0],"base64"),executable:f,lamports:h,owner:new an(g),rentEpoch:k}}return null})))}else try{s=yield Promise.all(a.map(c=>o.getMultipleAccountsInfo(c,i)))}catch(c){c instanceof Error&&xt.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${c.message}`)}return s.flat()})}function Le(o,t,e){return y(this,null,function*(){let n=yield Ke(o,t.map(i=>i.pubkey),e);return t.map((i,r)=>M(K({},i),{accountInfo:n[r]}))})}function un(n){return y(this,arguments,function*({connection:o,mints:t,config:e}){var a,s,c;if(t.length===0)return{};let i=yield Le(o,t.map(u=>({pubkey:Qe(u)})),e),r={};for(let u of i){if(!u.accountInfo||u.accountInfo.data.length<ro){console.log("invalid mint account",u.pubkey.toBase58());continue}let m=ao(u.pubkey,u.accountInfo,(a=u.accountInfo)==null?void 0:a.owner);r[u.pubkey.toString()]=M(K({},m),{programId:((s=u.accountInfo)==null?void 0:s.owner)||io,feeConfig:(c=so(m))!=null?c:void 0})}return r[an.default.toBase58()]=r[Y.toBase58()],r})}import ue from"bn.js";import ks from"decimal.js";import bo from"big.js";import Xr from"bn.js";import uo from"toformat";var co=uo,_e=co;import tt from"big.js";import mo from"bn.js";import po from"decimal.js-light";import Oe from"bn.js";var cn=9007199254740991;function Q(o){let t=V("Sega_parseBigNumberish");if(o instanceof Oe)return o;if(typeof o=="string"){if(o.match(/^-?[0-9]+$/))return new Oe(o);t.logWithError(`invalid BigNumberish string: ${o}`)}return typeof o=="number"?(o%1&&t.logWithError(`BigNumberish number underflow: ${o}`),(o>=cn||o<=-cn)&&t.logWithError(`BigNumberish number overflow: ${o}`),new Oe(String(o))):typeof o=="bigint"?new Oe(o.toString()):(t.error(`invalid BigNumberish value: ${o}`),new Oe(0))}var et=V("module/fraction"),St=_e(tt),Ne=_e(po),fo={0:Ne.ROUND_DOWN,1:Ne.ROUND_HALF_UP,2:Ne.ROUND_UP},go={0:tt.roundDown,1:tt.roundHalfUp,2:tt.roundUp},ie=class o{constructor(t,e=new mo(1)){this.numerator=Q(t),this.denominator=Q(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(Q(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(Q(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(Q(t));return new o(this.numerator.mul(e.numerator),this.denominator.mul(e.denominator))}div(t){let e=t instanceof o?t:new o(Q(t));return new o(this.numerator.mul(e.denominator),this.denominator.mul(e.numerator))}toSignificant(t,e={groupSeparator:""},n=1){Number.isInteger(t)||et.logWithError(`${t} is not an integer.`),t<=0&&et.logWithError(`${t} is not positive.`),Ne.set({precision:t+1,rounding:fo[n]});let i=new Ne(this.numerator.toString()).div(this.denominator.toString()).toSignificantDigits(t);return i.toFormat(i.decimalPlaces(),e)}toFixed(t,e={groupSeparator:""},n=1){return Number.isInteger(t)||et.logWithError(`${t} is not an integer.`),t<0&&et.logWithError(`${t} is negative.`),St.DP=t,St.RM=go[n]||1,new St(this.numerator.toString()).div(this.denominator.toString()).toFormat(t,e)}isZero(){return this.numerator.isZero()}};var ai=V("Sega_amount"),ui=_e(bo);import{PublicKey as ho}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as ln}from"@solana/spl-token";var me={chainId:101,address:ho.default.toBase58(),programId:ln.toBase58(),decimals:9,symbol:"SOL",name:"solana",logoURI:"https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"sega",extensions:{coingeckoId:"solana"}},se={chainId:101,address:"So11111111111111111111111111111111111111112",programId:ln.toBase58(),decimals:9,symbol:"WSOL",name:"Wrapped SOL",logoURI:"https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"sega",extensions:{coingeckoId:"solana"}};import{PublicKey as Kt}from"@solana/web3.js";import{PublicKey as W,SystemProgram as mn,SYSVAR_RENT_PUBKEY as To}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as Po}from"@solana/spl-token";function Bt({pubkey:o,isSigner:t=!1,isWritable:e=!0}){return{pubkey:o,isWritable:e,isSigner:t}}var bi=[Bt({pubkey:Po,isWritable:!1}),Bt({pubkey:mn.programId,isWritable:!1}),Bt({pubkey:To,isWritable:!1})];function Ct({publicKey:o,transformSol:t}){let e=pn(o.toString());if(e instanceof W)return t&&e.equals(Re)?Y:e;if(t&&e.toString()===Re.toBase58())return Y;if(typeof e=="string"){if(e===W.default.toBase58())return W.default;try{return new W(e)}catch(n){throw new Error("invalid public key")}}throw new Error("invalid public key")}function pn(o){try{return new W(o)}catch(t){return o}}var yi=new W("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),dn=new W("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),fn=new W("SysvarRent111111111111111111111111111111111"),hi=new W("SysvarC1ock11111111111111111111111111111111"),gn=new W("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),Ti=new W("Sysvar1nstructions1111111111111111111111111"),bn=mn.programId,Pi=new W("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),wi=new W("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),Ai=new W("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),ki=new W("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),xi=new W("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),Ii=new W("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),Si=new W("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),Bi=new W("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),Ci=new W("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),Ki=new W("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),Li=new W("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),Y=new W("So11111111111111111111111111111111111111112"),Re=W.default;function Qe(o){return Ct({publicKey:o,transformSol:!0})}var nt=class nt{constructor({mint:t,decimals:e,symbol:n,name:i,skipMint:r=!1,isToken2022:a=!1}){if(t===Re.toBase58()||t instanceof Kt&&Re.equals(t)){this.decimals=se.decimals,this.symbol=se.symbol,this.name=se.name,this.mint=new Kt(se.address),this.isToken2022=!1;return}this.decimals=e,this.symbol=n||t.toString().substring(0,6),this.name=i||t.toString().substring(0,6),this.mint=r?Kt.default:Ct({publicKey:t}),this.isToken2022=a}equals(t){return this===t?!0:this.mint.equals(t.mint)}};nt.WSOL=new nt(M(K({},se),{mint:se.address}));var $=nt;var ot=class ot{constructor({decimals:t,symbol:e="UNKNOWN",name:n="UNKNOWN"}){this.decimals=t,this.symbol=e,this.name=n}equals(t){return this===t}};ot.SOL=new ot(me);var Lt=ot;import wo from"bn.js";var yn=new ie(new wo(100)),ee=class extends ie{toSignificant(t=5,e,n){return this.mul(yn).toSignificant(t,e,n)}toFixed(t=2,e,n){return this.mul(yn).toFixed(t,e,n)}};var Yi=V("Sega_price");import{PublicKey as ms}from"@solana/web3.js";import ds from"bn.js";var Ot=new ue(0),Ns=new ue(1),Rs=new ue(2),Ms=new ue(3),Ds=new ue(5),yo=new ue(10),Es=new ue(100),Fs=new ue(1e3),vs=new ue(1e4);function It(o,t=1,e=[]){let n=[...o];if(t<=0)return e;for(;n.length;)e.push(n.splice(0,t));return e}var Me=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)}};import{PublicKey as Bo}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as Co}from"@solana/spl-token";import{ComputeBudgetProgram as Tn,Keypair as wn,PublicKey as Ao,Transaction as An,TransactionMessage as ko,VersionedTransaction as kn}from"@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"};import{TOKEN_PROGRAM_ID as xo}from"@solana/spl-token";var Pn=V("Sega_txUtil"),xn=1644;function rt(o){let t=[],e=[];return o.microLamports&&(t.push(Tn.setComputeUnitPrice({microLamports:o.microLamports})),e.push(v.SetComputeUnitPrice)),o.units&&(t.push(Tn.setComputeUnitLimit({units:o.units})),e.push(v.SetComputeUnitLimit)),{instructions:t,instructionTypes:e}}function we(o,t){return y(this,null,function*(){var n,i;let e=t!=null?t:"confirmed";return(i=yield(n=o.getLatestBlockhash)==null?void 0:n.call(o,{commitment:e}))==null?void 0:i.blockhash})}function it(o,t){return y(this,null,function*(){return o.getSignatureStatuses([t]),new Promise((e,n)=>{let i=setTimeout(n,6e4);o.onSignature(t,r=>{if(clearTimeout(i),!r.err){e("");return}n(Object.assign(r.err,{txId:t}))},"confirmed")})})}function Nt(o,t){o.length<1&&Pn.logWithError(`no instructions provided: ${o.toString()}`),t.length<1&&Pn.logWithError(`no signers provided:, ${t.toString()}`);let e=new An;e.recentBlockhash="11111111111111111111111111111111",e.feePayer=t[0],e.add(...o);try{return Buffer.from(e.serialize({verifySignatures:!1})).toString("base64").length<xn}catch(n){return!1}}function te(o,t){let[e,n]=Ao.findProgramAddressSync(o,t);return{publicKey:e,nonce:n}}function De({instructions:o,payer:t,signers:e}){return Nt(o,[t,...e])}function Ee({instructions:o,payer:t,lookupTableAddressAccount:e,recentBlockhash:n=wn.generate().publicKey.toString()}){let r=new ko({payerKey:t,recentBlockhash:n,instructions:o}).compileToV0Message(Object.values(e!=null?e:{}));try{return Buffer.from(new kn(r).serialize()).toString("base64").length<xn}catch(a){return!1}}var Io=o=>Buffer.isBuffer(o)?o:o instanceof Uint8Array?Buffer.from(o.buffer,o.byteOffset,o.byteLength):Buffer.from(o),So=o=>{let t=o.serialize({requireAllSignatures:!1,verifySignatures:!1});o instanceof kn&&(t=Io(t));try{return t instanceof Buffer?t.toString("base64"):Buffer.from(t).toString("base64")}catch(e){return t.toString("base64")}};function ye(o){let t=[];return o.forEach(e=>{e instanceof An&&(e.recentBlockhash||(e.recentBlockhash=xo.toBase58()),e.feePayer||(e.feePayer=wn.generate().publicKey)),t.push(So(e))}),console.log("simulate tx string:",t),t}function he(o,t,e){return te([o.toBuffer(),(e!=null?e:Co).toBuffer(),t.toBuffer()],new Bo("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"))}import{PublicKey as pe}from"@solana/web3.js";var Ko=new pe("SegazTQwbYWknDZkJ6j2Kgvm5gw3MrHGKtWstZdoNKZ"),Lo=new pe("Ajk8d9bERSaFdeoT1d8JUVfaDayrYLnAdgeB47TFMUaG"),ca=new pe("2HbjxVVKJ7Ct72Rcd8WK4VTqmwTXL5aAggkH1CHGFGmh"),_o=new pe("auetiVUVJkRxvNPLYEvVnz8UJSqQ1VgoA83PcicHVD1"),Oo=new pe("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y"),No=new pe("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y");var la={SERUM_MARKET:pe.default,UTIL1216:pe.default,CREATE_CPMM_POOL_PROGRAM:_o,CREATE_CPMM_POOL_AUTH:Oo,CREATE_CPMM_POOL_FEE_ACC:No};import ne from"bn.js";var Fe=1e4;function Te(o,t,e,n){if(t===void 0)return{amount:o,fee:void 0,expirationTime:void 0};let i=M(K({},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}}),r=e.epoch<i.newerTransferFee.epoch?i.olderTransferFee:i.newerTransferFee,a=new ne(r.maximumFee.toString()),s=e.epoch<i.newerTransferFee.epoch?(Number(i.newerTransferFee.epoch)*e.slotsInEpoch-e.absoluteSlot)*400/1e3:void 0;if(n)if(r.transferFeeBasisPoints===Fe){let c=new ne(r.maximumFee.toString());return{amount:o.add(c),fee:c,expirationTime:s}}else{let c=Ae(o.mul(new ne(Fe)),new ne(Fe-r.transferFeeBasisPoints)),u=new ne(r.maximumFee.toString()),m=c.sub(o).gt(u)?o.add(u):c,l=Ae(m.mul(new ne(r.transferFeeBasisPoints)),new ne(Fe)),p=l.gt(a)?a:l;return{amount:m,fee:p,expirationTime:s}}else{let c=Ae(o.mul(new ne(r.transferFeeBasisPoints)),new ne(Fe)),u=c.gt(a)?a:c;return{amount:o,fee:u,expirationTime:s}}}function Ae(o,t){let{div:e,mod:n}=o.divmod(t);return n.gt(new ne(0))?e.add(new ne(1)):e}import{PublicKey as Ro,AddressLookupTableAccount as In}from"@solana/web3.js";function Rt(e){return y(this,arguments,function*({connection:o,address:t}){let n=yield Ke(o,[...new Set(t.map(r=>r.toString()))].map(r=>new Ro(r))),i={};for(let r=0;r<t.length;r++){let a=n[r],s=t[r];if(!a)continue;let c=new In({key:s,state:In.deserialize(a.data)});i[s.toString()]=c,st[s.toString()]=c}return i})}var st={};import{PublicKey as ke,sendAndConfirmTransaction as Mt,SystemProgram as Mo,Transaction as ve,TransactionMessage as We,VersionedTransaction as Ve}from"@solana/web3.js";import Do from"axios";var at=2e3,ut=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 Do.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}=rt(t);return this.instructions.unshift(...e),this.instructionTypes.unshift(...n),!0}return!1}addTipInstruction(t){var e;return t?(this.endInstructions.push(Mo.transfer({fromPubkey:(e=t.feePayer)!=null?e:this.feePayer,toPubkey:new ke(t.address),lamports:BigInt(t.amount.toString())})),this.endInstructionTypes.push(v.TransferTip),!0):!1}calComputeBudget(n){return y(this,arguments,function*({config:t,defaultIns:e}){try{let i=t||(yield this.getComputeBudgetConfig());if(this.addCustomComputeBudget(i))return;e&&this.instructions.unshift(...e)}catch(i){e&&this.instructions.unshift(...e)}})}addInstruction({instructions:t=[],endInstructions:e=[],signers:n=[],instructionTypes:i=[],endInstructionTypes:r=[],lookupTableAddress:a=[]}){return this.instructions.push(...t),this.endInstructions.push(...e),this.signers.push(...n),this.instructionTypes.push(...i),this.endInstructionTypes.push(...r),this.lookupTableAddress.push(...a.filter(s=>s!==ke.default.toString())),this}versionBuild(n){return y(this,arguments,function*({txVersion:t,extInfo:e}){return t===0?yield this.buildV0(K({},e||{})):this.build(e)})}build(t){var n;let e=new ve;return this.allInstructions.length&&e.add(...this.allInstructions),e.feePayer=this.feePayer,(n=this.owner)!=null&&n.signer&&!this.signers.some(i=>i.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer),{builder:this,transaction:e,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:i=>y(this,null,function*(){var u;let{recentBlockHash:r,skipPreflight:a=!0,sendAndConfirm:s}=i||{},c=r!=null?r:yield we(this.connection,this.blockhashCommitment);if(e.recentBlockhash=c,this.signers.length&&e.sign(...this.signers),ye([e]),(u=this.owner)!=null&&u.isKeyPair)return{txId:s?yield Mt(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:i}=this.build(n),r=e.filter(m=>m.transaction.instructions.length>0),a=[i,...r.map(m=>m.transaction)],s=[this.signers,...r.map(m=>m.signers)],c=[...this.instructionTypes,...r.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 we(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 Mt(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));ye(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,N=L=>{B!==null&&clearInterval(B),C!==null&&this.connection.removeSignatureListener(C);let O=b.findIndex(D=>D.txId===x);if(O>-1){if(b[O].status==="error"||b[O].status==="success")return;b[O].status=L.err?"error":"success"}p==null||p([...b]),L.err||w()};this.loopMultiTxStatus&&(B=setInterval(()=>y(this,null,function*(){var L;if(I){clearInterval(B);return}try{let O=yield this.connection.getTransaction(x,{commitment:"confirmed",maxSupportedTransactionVersion:0});O&&(I=!0,clearInterval(B),N({err:((L=O.meta)==null?void 0:L.err)||null}),console.log("tx status from getTransaction:",x))}catch(O){I=!0,clearInterval(B),console.error("getTransaction timeout:",O,x)}}),at)),C=this.connection.onSignature(x,L=>{if(I){this.connection.removeSignatureListener(C);return}I=!0,N(L)},"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(i){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:i,recentBlockhash:r}=f,a=z(f,["lookupTableCache","lookupTableAddress","forerunCreate","recentBlockhash"]),s=K(K({},this.cluster==="devnet"?{}:st),e),c=Array.from(new Set([...n,...this.lookupTableAddress])),u=[];for(let g of c)s[g]===void 0&&u.push(new ke(g));let m=yield Rt({connection:this.connection,address:u});for(let[g,k]of Object.entries(m))s[g]=k;let l=i?ke.default.toBase58():r!=null?r:yield we(this.connection,this.blockhashCommitment),p=new We({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 Ve(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(ye([d]),(A=this.owner)!=null&&A.isKeyPair){let T=yield this.connection.sendTransaction(d,{skipPreflight:k});return P&&(yield it(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:i}=yield this.buildV0(n),r=e.filter(m=>m.builder.instructions.length>0),a=[i,...r.map(m=>m.transaction)],s=[this.signers,...r.map(m=>m.signers)],c=[...this.instructionTypes,...r.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),ye(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 it(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(N=>N.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)}}),at)),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,i=z(l,["splitIns","computeBudgetConfig"]),r=n?rt(n):{instructions:[],instructionTypes:[]},a=this.signers.reduce((d,f)=>M(K({},d),{[f.publicKey.toBase58()]:f}),{}),s=[],c=[],u=[],m=0;if(this.allInstructions.forEach(d=>{let f=[...u,d],h=n?[...r.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 ke(P));if(d!==e[m]&&u.length<12&&(De({instructions:h,payer:this.feePayer,signers:k})||De({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,De({instructions:n?[...r.instructions,...u]:[...u],payer:this.feePayer,signers:k})?s.push(new ve().add(...r.instructions,...u)):s.push(new ve().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);De({instructions:n?[...r.instructions,...u]:[...u],payer:this.feePayer,signers:f.map(h=>h.publicKey)})?s.push(new ve().add(...r.instructions,...u)):s.push(new ve().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 we(this.connection,this.blockhashCommitment);if(s.forEach((b,w)=>y(this,null,function*(){b.recentBlockhash=A,c[w].length&&b.sign(...c[w])})),ye(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 Mt(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 N=!1,L=null,O=null,D=R=>{L!==null&&clearInterval(L),O!==null&&this.connection.removeSignatureListener(O);let E=I.findIndex(G=>G.txId===C);if(E>-1){if(I[E].status==="error"||I[E].status==="success")return;I[E].status=R.err?"error":"success"}h==null||h([...I]),R.err||B()};this.loopMultiTxStatus&&(L=setInterval(()=>y(this,null,function*(){var R;if(N){clearInterval(L);return}try{let E=yield this.connection.getTransaction(C,{commitment:"confirmed",maxSupportedTransactionVersion:0});E&&(N=!0,clearInterval(L),D({err:((R=E.meta)==null?void 0:R.err)||null}),console.log("tx status from getTransaction:",C))}catch(E){N=!0,clearInterval(L),console.error("getTransaction timeout:",E,C)}}),at)),O=this.connection.onSignature(C,R=>{if(N){this.connection.removeSignatureListener(O);return}N=!0,D(R)},"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:i||{}}})}sizeCheckBuildV0(t){return y(this,null,function*(){var A;let P=t||{},{computeBudgetConfig:e,splitIns:n=[],lookupTableCache:i={},lookupTableAddress:r=[]}=P,a=z(P,["computeBudgetConfig","splitIns","lookupTableCache","lookupTableAddress"]),s=K(K({},this.cluster==="devnet"?{}:st),i),c=Array.from(new Set([...this.lookupTableAddress,...r])),u=[];for(let T of c)s[T]===void 0&&u.push(new ke(T));let m=yield Rt({connection:this.connection,address:u});for(let[T,b]of Object.entries(m))s[T]=b;let l=e?rt(e):{instructions:[],instructionTypes:[]},p=yield we(this.connection,this.blockhashCommitment),d=this.signers.reduce((T,b)=>M(K({},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&&(Ee({instructions:w,payer:this.feePayer,lookupTableAddressAccount:s})||Ee({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&&Ee({instructions:[...l.instructions,...g],payer:this.feePayer,lookupTableAddressAccount:s,recentBlockhash:p})){let I=new We({payerKey:this.feePayer,recentBlockhash:p,instructions:[...l.instructions,...g]}).compileToV0Message(Object.values(s));f.push(new Ve(I))}else{let I=new We({payerKey:this.feePayer,recentBlockhash:p,instructions:[...g]}).compileToV0Message(Object.values(s));f.push(new Ve(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&&Ee({instructions:[...l.instructions,...g],payer:this.feePayer,lookupTableAddressAccount:s,recentBlockhash:p})){let w=new We({payerKey:this.feePayer,recentBlockhash:p,instructions:[...l.instructions,...g]}).compileToV0Message(Object.values(s));f.push(new Ve(w))}else{let w=new We({payerKey:this.feePayer,recentBlockhash:p,instructions:[...g]}).compileToV0Message(Object.values(s));f.push(new Ve(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((N,L)=>y(this,null,function*(){h[L].length&&N.sign(h[L]),I&&(N.message.recentBlockhash=I)})),ye(f),(C=this.owner)!=null&&C.isKeyPair){if(b){let N=0,L=[];for(let O of f){if(++N,N<=x){console.log("skip tx: ",N),L.push("tx skipped");continue}let D=yield this.connection.sendTransaction(O,{skipPreflight:B});yield it(this.connection,D),L.push(D)}return{txIds:L,signedTxs:f}}return{txIds:yield Promise.all(f.map(N=>y(this,null,function*(){return yield this.connection.sendTransaction(N,{skipPreflight:B})}))),signedTxs:f}}if(this.signAllTransactions){let N=yield this.signAllTransactions(f.slice(x,f.length)),L=[...f.slice(0,x),...N];if(b){let O=0,D=[],R=()=>y(this,null,function*(){if(!L[O])return;if(O<x){D.push({txId:"",status:"success",signedTx:L[O]}),w==null||w([...D]),O++,R();return}let E=yield this.connection.sendTransaction(L[O],{skipPreflight:B});D.push({txId:E,status:"sent",signedTx:L[O]}),w==null||w([...D]),O++;let G=!1,X=null,ge=null,en=be=>{X!==null&&clearInterval(X),ge!==null&&this.connection.removeSignatureListener(ge);let ae=D.findIndex(Xn=>Xn.txId===E);if(ae>-1){if(D[ae].status==="error"||D[ae].status==="success")return;D[ae].status=be.err?"error":"success"}w==null||w([...D]),be.err||R()};this.loopMultiTxStatus&&(X=setInterval(()=>y(this,null,function*(){var be;if(G){clearInterval(X);return}try{let ae=yield this.connection.getTransaction(E,{commitment:"confirmed",maxSupportedTransactionVersion:0});ae&&(G=!0,clearInterval(X),en({err:((be=ae.meta)==null?void 0:be.err)||null}),console.log("tx status from getTransaction:",E))}catch(ae){G=!0,clearInterval(X),console.error("getTransaction timeout:",ae,E)}}),at)),ge=this.connection.onSignature(E,be=>{if(G){this.connection.removeSignatureListener(ge);return}G=!0,en(be)},"confirmed"),this.connection.getSignatureStatus(E)});return R(),{txIds:[],signedTxs:L}}else{let O=[];for(let D=0;D<L.length;D+=1){let R=yield this.connection.sendTransaction(L[D],{skipPreflight:B});O.push(R)}return{txIds:O,signedTxs:L}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:a||{}}})}};import{Connection as Ma}from"@solana/web3.js";var oe={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"},nu=K({},oe);var Sn="ray_tab_hash",Dt="ray_req_hash",Eo=()=>{if(typeof window===void 0)return"";let o=sessionStorage.getItem(Sn);return o||(o=`ray-${Date.now()}`,sessionStorage.setItem(Sn,o)),o},ct=n=>y(void 0,null,function*(){var i=n,{logCount:o=1e3,removeLastLog:t}=i,e=z(i,["logCount","removeLastLog"]);if(typeof window===void 0)return new Promise(a=>a());let r=JSON.parse(localStorage.getItem(Dt)||"[]").slice(0,o-1);t&&r.pop(),new Blob([JSON.stringify(e.data)]).size>1024&&(e.data=JSON.stringify(e.data).substring(0,200)+"..."),r.unshift(M(K({},e),{time:Date.now(),session:Eo()}));try{localStorage.setItem(Dt,JSON.stringify(r))}catch(a){if(t){let s=!1,c=JSON.stringify(e.data).substring(0,100);for(r[0].data=c+(c.length>100?"...":"");!s;){r.pop();let u=JSON.stringify(e.data).substring(0,100);r[0].data=u+(u.length>100?"...":"");try{localStorage.setItem(Dt,JSON.stringify(r)),s=!0}catch(m){s=!1}}return new Promise(u=>u())}return ct(M(K({},e),{logCount:o,removeLastLog:!0}))}});var lt=V("Sega_Api"),Et=new Map;var mt=class{constructor({cluster:t,timeout:e,logRequests:n,logCount:i,urlConfigs:r}){this.cluster=t,this.urlConfigs=r||{},this.logCount=i||1e3,this.api=Bn.create({baseURL:this.urlConfigs.BASE_HOST||oe.BASE_HOST,timeout:e}),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&&ct({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&&ct({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 y(this,null,function*(){return(yield this.api.get(this.urlConfigs.CPMM_CONFIG||oe.CPMM_CONFIG)).data})}getBlockSlotCountForSecond(t){return y(this,null,function*(){if(!t)return 2;let n=(yield Bn.post(t,{id:"getRecentPerformanceSamples",jsonrpc:"2.0",method:"getRecentPerformanceSamples",params:[4]})).result.map(i=>i.numSlots);return n.reduce((i,r)=>i+r,0)/n.length/60})}getChainTimeOffset(){return y(this,null,function*(){return(yield this.api.get(this.urlConfigs.CHAIN_TIME||oe.CHAIN_TIME)).data})}fetchPoolKeysById(t){return y(this,null,function*(){let{idList:e}=t,n=[],i=e.filter(a=>Et.has(a)?(n.push(Et.get(a)),!1):!0),r=[];return i.length&&(r=(yield this.api.get((this.urlConfigs.POOL_KEY_BY_ID||oe.POOL_KEY_BY_ID)+`?ids=${i.join(",")}`)).data.filter(Boolean),r.forEach(s=>{Et.set(s.id,s)})),n.concat(r)})}getRpcs(){return y(this,null,function*(){return this.api.get(this.urlConfigs.RPCS||oe.RPCS)})}getTokenList(){return y(this,null,function*(){return(yield this.api.get(this.urlConfigs.TOKEN_LIST||oe.TOKEN_LIST)).data})}getJupTokenList(){return y(this,null,function*(){return this.api.get("",{baseURL:this.urlConfigs.JUP_TOKEN_LIST||oe.JUP_TOKEN_LIST})})}getTokenInfo(t){return y(this,null,function*(){return(yield this.api.get((this.urlConfigs.MINT_INFO_ID||oe.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||oe.CHECK_AVAILABILITY)).data})}};var pt="please provide owner in load() initialization or you can set by calling sega.setOwner(owner)",Cn="please provide connection in load() initialization or set it by sega.setConnection(connection)";import{PublicKey as gt,SystemProgram as ir}from"@solana/web3.js";import{AccountLayout as Ie,createAssociatedTokenAccountInstruction as Ht,TOKEN_PROGRAM_ID as fe,TOKEN_2022_PROGRAM_ID as sr}from"@solana/spl-token";var Ft=(...o)=>o.map(t=>{try{return typeof t=="object"?JSON.stringify(t):t}catch(e){return t}}).join(", "),re=class{constructor({scope:t,moduleName:e}){this.disabled=!1;this.scope=t,this.logger=V(e)}createTxBuilder(t){return this.scope.checkOwner(),new ut({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(Ft(t))}logInfo(...t){this.logger.info(Ft(t))}logAndCreateError(...t){let e=Ft(t);throw new Error(e)}checkDisabled(){(this.disabled||!this.scope)&&this.logAndCreateError("module not working")}};import{PublicKey as Qo,SystemProgram as er}from"@solana/web3.js";import tr from"bn.js";import{createCloseAccountInstruction as nr,createInitializeAccountInstruction as or,createTransferInstruction as rr,TOKEN_PROGRAM_ID as xe}from"@solana/spl-token";import{Keypair as Yo,PublicKey as Mn}from"@solana/web3.js";import Jo from"bn.js";import{TOKEN_PROGRAM_ID as $o}from"@solana/spl-token";import{sha256 as Zo}from"@noble/hashes/sha256";import{PublicKey as jo}from"@solana/web3.js";import Nn,{isBN as Rn}from"bn.js";import{bits as Cu,BitStructure as Ku,blob as Fo,Blob as Lu,cstr as _u,f32 as Ou,f32be as Nu,f64 as Ru,f64be as Mu,greedy as Du,Layout as vo,ns64 as Eu,ns64be as Fu,nu64 as vu,nu64be as Wu,offset as Vu,s16 as Uu,s16be as qu,s24 as Gu,s24be as ju,s32 as Hu,s32be as zu,s40 as Yu,s40be as Ju,s48 as $u,s48be as Zu,s8 as Xu,seq as Wo,struct as Qu,Structure as Vo,u16 as Uo,u16be as ec,u24 as tc,u24be as nc,u32 as oc,u32be as rc,u40 as ic,u40be as sc,u48 as ac,u48be as uc,u8 as qo,UInt as Go,union as cc,Union as lc,unionLayoutDiscriminator as mc,utf8 as pc}from"@solana/buffer-layout";var vt=vo,Kn=Vo;var Wt=Go;var Ln=qo,_n=Uo;var On=Wo;var ce=Fo;var Vt=class extends vt{constructor(t,e,n){super(t,n),this.blob=ce(t),this.signed=e}decode(t,e=0){let n=new Nn(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 Nn(t)),this.signed&&(t=t.toTwos(this.span*8)),this.blob.encode(t.toArrayLike(Buffer,"le",this.span),e,n)}};function H(o){return new Wt(1,o)}function Pe(o){return new Wt(4,o)}function _(o){return new Vt(8,!1,o)}var dt=class extends vt{constructor(t,e,n,i){super(t.span,i),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 F(o){return new dt(ce(32),t=>new jo(t),t=>t.toBuffer(),o)}function qt(o){return new dt(Ln(),Ho,zo,o)}function Ho(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 Ut=class extends Kn{decode(t,e){return super.decode(t,e)}};function j(o,t,e){return new Ut(o,t,e)}function de(o,t,e){let n,i=typeof t=="number"?t:Rn(t)?t.toNumber():new Proxy(t,{get(r,a){if(!n){let s=Reflect.get(r,"count");n=Rn(s)?s.toNumber():s,Reflect.set(r,"count",n)}return Reflect.get(r,a)},set(r,a,s){return a==="count"&&(n=s),Reflect.set(r,a,s)}});return On(o,i,e)}var Ue=j([F("mint"),F("owner"),_("amount"),Pe("delegateOption"),F("delegate"),H("state"),Pe("isNativeOption"),_("isNative"),_("delegatedAmount"),Pe("closeAuthorityOption"),F("closeAuthority")]);var Ec=V("Sega_Util");function Dn({owner:o,solAccountResp:t,tokenAccountResp:e}){let n=[],i=[];for(let{pubkey:r,account:a}of e.value){let s=Ue.decode(a.data),{mint:c,amount:u}=s;n.push({publicKey:r,mint:c,amount:u,isAssociated:he(o,c,a.owner).publicKey.equals(r),isNative:!1,programId:a.owner}),i.push({pubkey:r,accountInfo:s,programId:a.owner})}return t&&n.push({mint:Mn.default,amount:new Jo(String(t.lamports)),isNative:!0,programId:t.owner}),{tokenAccounts:n,tokenAccountRawInfos:i}}function ft({fromPublicKey:o,programId:t=$o,assignSeed:e}){let n=e?btoa(e).slice(0,32):Yo.generate().publicKey.toBase58().slice(0,32);return{publicKey:Xo(o,n,t),seed:n}}function Xo(o,t,e){let n=Buffer.concat([o.toBuffer(),Buffer.from(t),e.toBuffer()]),i=Zo(n);return new Mn(i)}function Gt(o){let{mint:t,tokenAccount:e,owner:n,programId:i=xe}=o;return or(e,t,n,i)}function qe(o){let{tokenAccount:t,payer:e,multiSigners:n=[],owner:i,programId:r=xe}=o;return nr(t,e,i,n,r)}function jt(o){return y(this,null,function*(){let{connection:t,amount:e,commitment:n,payer:i,owner:r,skipCloseAccount:a}=o,s=yield t.getMinimumBalanceForRentExemption(Ue.span,n),c=Q(e).add(new tr(s)),u=ft({fromPublicKey:i,programId:xe});return{addresses:{newAccount:u.publicKey},signers:[],instructions:[er.createAccountWithSeed({fromPubkey:i,basePubkey:i,seed:u.seed,newAccountPubkey:u.publicKey,lamports:c.toNumber(),space:Ue.span,programId:xe}),Gt({mint:new Qo(se.address),tokenAccount:u.publicKey,owner:r,programId:xe})],instructionTypes:[v.CreateAccount,v.InitAccount],endInstructionTypes:a?[]:[v.CloseAccount],endInstructions:a?[]:[qe({tokenAccount:u.publicKey,payer:i,owner:r})]}})}function En({source:o,destination:t,owner:e,amount:n,multiSigners:i=[],tokenProgram:r=xe}){return rr(o,t,e,BigInt(String(n)),i,r)}var Ge=class extends re{constructor(e){super(e);this._tokenAccounts=[];this._tokenAccountRawInfos=[];this._accountListener=[];this._clientOwnedToken=!1;this._notSubscribeAccountChange=!1;this._accountFetchTime=0;let{tokenAccounts:n,tokenAccountRawInfos:i,notSubscribeAccountChange:r}=e;this._tokenAccounts=n||[],this._tokenAccountRawInfos=i||[],this._notSubscribeAccountChange=r!=null?r:!0,this._clientOwnedToken=!!(n||i)}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 he(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 i=K(K({},{}),e),[r,a,s]=yield Promise.all([this.scope.connection.getAccountInfo(this.scope.ownerPubKey,i.commitment),this.scope.connection.getTokenAccountsByOwner(this.scope.ownerPubKey,{programId:fe},i.commitment),this.scope.connection.getTokenAccountsByOwner(this.scope.ownerPubKey,{programId:sr},i.commitment)]),{tokenAccounts:c,tokenAccountRawInfos:u}=Dn({owner:this.scope.ownerPubKey,solAccountResp:r,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._accountChangeListenerId),this._accountChangeListenerId=this.scope.connection.onAccountChange(this.scope.ownerPubKey,()=>{this.fetchWalletTokenAccounts({forceUpdate:!0}),this._accountListener.forEach(m=>m({tokenAccounts:this._tokenAccounts,tokenAccountRawInfos:this._tokenAccountRawInfos}))},{commitment:e==null?void 0:e.commitment})),{tokenAccounts:c,tokenAccountRawInfos:u}})}clearAccountChangeCkb(){this._accountChangeListenerId!==void 0&&this.scope.connection.removeAccountChangeListener(this._accountChangeListenerId)}getCreatedTokenAccount(r){return y(this,arguments,function*({mint:e,programId:n=fe,associatedOnly:i=!0}){yield this.fetchWalletTokenAccounts();let a=this._tokenAccounts.filter(({mint:c})=>c==null?void 0:c.equals(e)).sort((c,u)=>c.amount.lt(u.amount)?1:-1),s=this.getAssociatedTokenAccount(e,n);for(let c of a){let{publicKey:u}=c;if(u&&(!i||i&&s.equals(u)))return u}})}getOrCreateTokenAccount(e){return y(this,null,function*(){var h,g,k,P;yield this.fetchWalletTokenAccounts