@sega-so/sega-sdk
Version:
An SDK for building applications on top of SEGA.
1 lines • 92.7 kB
JavaScript
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,L=(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},R=(o,t)=>eo(o,to(t));var Y=(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 Ir}from"lodash";import Cn 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 Le(o,t,e){return y(this,null,function*(){let{batchRequest:n,commitment:i="confirmed",chunkCount:r=100}=L({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 Ke(o,t,e){return y(this,null,function*(){let n=yield Le(o,t.map(i=>i.pubkey),e);return t.map((i,r)=>R(L({},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 Ke(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()]=R(L({},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[z.toBase58()],r})}import ce from"bn.js";import xs from"decimal.js";import bo from"big.js";import Qr 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 ee(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),Re=_e(po),fo={0:Re.ROUND_DOWN,1:Re.ROUND_HALF_UP,2:Re.ROUND_UP},go={0:tt.roundDown,1:tt.roundHalfUp,2:tt.roundUp},se=class o{constructor(t,e=new mo(1)){this.numerator=ee(t),this.denominator=ee(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(ee(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(ee(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(ee(t));return new o(this.numerator.mul(e.numerator),this.denominator.mul(e.denominator))}div(t){let e=t instanceof o?t:new o(ee(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.`),Re.set({precision:t+1,rounding:fo[n]});let i=new Re(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 ui=V("Sega_amount"),ci=_e(bo);import{PublicKey as ho}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as ln}from"@solana/spl-token";var pe={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"}},ae={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 Lt}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 Ct({pubkey:o,isSigner:t=!1,isWritable:e=!0}){return{pubkey:o,isWritable:e,isSigner:t}}var yi=[Ct({pubkey:Po,isWritable:!1}),Ct({pubkey:mn.programId,isWritable:!1}),Ct({pubkey:To,isWritable:!1})];function Bt({publicKey:o,transformSol:t}){let e=pn(o.toString());if(e instanceof W)return t&&e.equals(Ne)?z:e;if(t&&e.toString()===Ne.toBase58())return z;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 hi=new W("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),dn=new W("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),fn=new W("SysvarRent111111111111111111111111111111111"),Ti=new W("SysvarC1ock11111111111111111111111111111111"),gn=new W("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),Pi=new W("Sysvar1nstructions1111111111111111111111111"),bn=mn.programId,Ai=new W("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),wi=new W("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),ki=new W("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),xi=new W("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),Ii=new W("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),Si=new W("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),Ci=new W("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),Bi=new W("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),Li=new W("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),Ki=new W("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),_i=new W("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),z=new W("So11111111111111111111111111111111111111112"),Ne=W.default;function Qe(o){return Bt({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===Ne.toBase58()||t instanceof Lt&&Ne.equals(t)){this.decimals=ae.decimals,this.symbol=ae.symbol,this.name=ae.name,this.mint=new Lt(ae.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?Lt.default:Bt({publicKey:t}),this.isToken2022=a}equals(t){return this===t?!0:this.mint.equals(t.mint)}};nt.WSOL=new nt(R(L({},ae),{mint:ae.address}));var Z=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(pe);var Kt=ot;import Ao from"bn.js";var yn=new se(new Ao(100)),te=class extends se{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 Ji=V("Sega_price");import{PublicKey as ps}from"@solana/web3.js";import fs from"bn.js";var Ot=new ce(0),Ns=new ce(1),Ms=new ce(2),Es=new ce(3),Ds=new ce(5),yo=new ce(10),Fs=new ce(100),vs=new ce(1e3),Ws=new ce(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 Co}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as Bo}from"@solana/spl-token";import{ComputeBudgetProgram as Tn,Keypair as An,PublicKey as wo,Transaction as wn,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 Ae(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 Rt(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 wn;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 ne(o,t){let[e,n]=wo.findProgramAddressSync(o,t);return{publicKey:e,nonce:n}}function Ee({instructions:o,payer:t,signers:e}){return Rt(o,[t,...e])}function De({instructions:o,payer:t,lookupTableAddressAccount:e,recentBlockhash:n=An.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 wn&&(e.recentBlockhash||(e.recentBlockhash=xo.toBase58()),e.feePayer||(e.feePayer=An.generate().publicKey)),t.push(So(e))}),console.log("simulate tx string:",t),t}function he(o,t,e){return ne([o.toBuffer(),(e!=null?e:Bo).toBuffer(),t.toBuffer()],new Co("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"))}import{PublicKey as oe}from"@solana/web3.js";var Lo=new oe("SegazTQwbYWknDZkJ6j2Kgvm5gw3MrHGKtWstZdoNKZ"),Ko=new oe("Ajk8d9bERSaFdeoT1d8JUVfaDayrYLnAdgeB47TFMUaG"),la=new oe("2HbjxVVKJ7Ct72Rcd8WK4VTqmwTXL5aAggkH1CHGFGmh"),_o=new oe("TegaRdjn9Qeh9DfUU28X19aPPpJtj9gs8ntSYrR5H4K "),Oo=new oe("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y"),Ro=new oe("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y"),ma=new oe("SegaXNnoXYTZiqUt9Xn2XqGcL56b25yzXLuJSpadcMu"),pa=new oe("2t1hV2YqnDCPuJZqr7Fy8oAygGwZE5Q9uaQzpLC1QryJ"),da=new oe("BLxynZeHE123MmQgNJZiV1pwW4VYh46oZYyC66xwmtTY");var No={SERUM_MARKET:oe.default,UTIL1216:oe.default,CREATE_CPMM_POOL_PROGRAM:_o,CREATE_CPMM_POOL_AUTH:Oo,CREATE_CPMM_POOL_FEE_ACC:Ro};import re 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=R(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}}),r=e.epoch<i.newerTransferFee.epoch?i.olderTransferFee:i.newerTransferFee,a=new re(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 re(r.maximumFee.toString());return{amount:o.add(c),fee:c,expirationTime:s}}else{let c=we(o.mul(new re(Fe)),new re(Fe-r.transferFeeBasisPoints)),u=new re(r.maximumFee.toString()),m=c.sub(o).gt(u)?o.add(u):c,l=we(m.mul(new re(r.transferFeeBasisPoints)),new re(Fe)),p=l.gt(a)?a:l;return{amount:m,fee:p,expirationTime:s}}else{let c=we(o.mul(new re(r.transferFeeBasisPoints)),new re(Fe)),u=c.gt(a)?a:c;return{amount:o,fee:u,expirationTime:s}}}function we(o,t){let{div:e,mod:n}=o.divmod(t);return n.gt(new re(0))?e.add(new re(1)):e}import{PublicKey as Mo,AddressLookupTableAccount as In}from"@solana/web3.js";function Nt(e){return y(this,arguments,function*({connection:o,address:t}){let n=yield Le(o,[...new Set(t.map(r=>r.toString()))].map(r=>new Mo(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 Eo,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(Eo.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(L({},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 Ae(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 Ae(this.connection,this.blockhashCommitment);if((k=this.owner)!=null&&k.isKeyPair){if(l){let P=[],w=0;for(let T of a){if(++w,w<=d)continue;let b=yield Mt(this.connection,T,this.signers.find(A=>A.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 w=yield this.signAllTransactions(P);if(l){let T=0,b=[],A=()=>y(this,null,function*(){if(!w[T])return;let x=yield this.connection.sendRawTransaction(w[T].serialize(),{skipPreflight:h});b.push({txId:x,status:"sent",signedTx:w[T]}),p==null||p([...b]),T++;let I=!1,C=null,B=null,N=K=>{C!==null&&clearInterval(C),B!==null&&this.connection.removeSignatureListener(B);let O=b.findIndex(E=>E.txId===x);if(O>-1){if(b[O].status==="error"||b[O].status==="success")return;b[O].status=K.err?"error":"success"}p==null||p([...b]),K.err||A()};this.loopMultiTxStatus&&(C=setInterval(()=>y(this,null,function*(){var K;if(I){clearInterval(C);return}try{let O=yield this.connection.getTransaction(x,{commitment:"confirmed",maxSupportedTransactionVersion:0});O&&(I=!0,clearInterval(C),N({err:((K=O.meta)==null?void 0:K.err)||null}),console.log("tx status from getTransaction:",x))}catch(O){I=!0,clearInterval(C),console.error("getTransaction timeout:",O,x)}}),at)),B=this.connection.onSignature(x,K=>{if(I){this.connection.removeSignatureListener(B);return}I=!0,N(K)},"confirmed"),this.connection.getSignatureStatus(x)});return yield A(),{txIds:b.map(x=>x.txId),signedTxs:w}}else{let T=[];for(let b=0;b<w.length;b+=1){let A=yield this.connection.sendRawTransaction(w[b].serialize(),{skipPreflight:h});T.push(A)}return{txIds:T,signedTxs:w}}}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=Y(f,["lookupTableCache","lookupTableAddress","forerunCreate","recentBlockhash"]),s=L(L({},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 Nt({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 Ae(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 w;let{skipPreflight:k=!0,sendAndConfirm:P}=g||{};if(ye([d]),(w=this.owner)!=null&&w.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(A){}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=[],w=()=>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,A=null,x=null,I=C=>{A!==null&&clearInterval(A),x!==null&&this.connection.removeSignatureListener(x);let B=P.findIndex(N=>N.txId===T);if(B>-1){if(P[B].status==="error"||P[B].status==="success")return;P[B].status=C.err?"error":"success"}p==null||p([...P]),C.err||w()};this.loopMultiTxStatus&&(A=setInterval(()=>y(this,null,function*(){var C;if(b){clearInterval(A);return}try{let B=yield this.connection.getTransaction(T,{commitment:"confirmed",maxSupportedTransactionVersion:0});B&&(b=!0,clearInterval(A),I({err:((C=B.meta)==null?void 0:C.err)||null}),console.log("tx status from getTransaction:",T))}catch(B){b=!0,clearInterval(A),console.error("getTransaction timeout:",B,T)}}),at)),x=this.connection.onSignature(T,C=>{if(b){this.connection.removeSignatureListener(x);return}b=!0,I(C)},"confirmed"),this.connection.getSignatureStatus(T)});return w(),{txIds:[],signedTxs:g}}else{let k=[];for(let P=0;P<g.length;P+=1){let w=yield this.connection.sendTransaction(g[P],{skipPreflight:f});k.push(w)}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=Y(l,["splitIns","computeBudgetConfig"]),r=n?rt(n):{instructions:[],instructionTypes:[]},a=this.signers.reduce((d,f)=>R(L({},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(w=>w.isSigner).map(w=>w.pubkey.toString())).flat()).values()].map(P=>new ke(P));if(d!==e[m]&&u.length<12&&(Ee({instructions:h,payer:this.feePayer,signers:k})||Ee({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,Ee({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(w=>w.isSigner).map(w=>w.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);Ee({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||{},w=k!=null?k:yield Ae(this.connection,this.blockhashCommitment);if(s.forEach((b,A)=>y(this,null,function*(){b.recentBlockhash=w,c[A].length&&b.sign(...c[A])})),ye(s),(T=this.owner)!=null&&T.isKeyPair){if(f){let b=0,A=[];for(let x of s){if(++b,b<=g){A.push("tx skipped");continue}let I=yield Mt(this.connection,x,this.signers.find(C=>C.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:P});A.push(I)}return{txIds:A,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)),A=[...s.slice(0,g),...b];if(f){let x=0,I=[],C=()=>y(this,null,function*(){if(!A[x])return;x<g&&(I.push({txId:"",status:"success",signedTx:A[x]}),h==null||h([...I]),x++,C());let B=yield this.connection.sendRawTransaction(A[x].serialize(),{skipPreflight:P});I.push({txId:B,status:"sent",signedTx:A[x]}),h==null||h([...I]),x++;let N=!1,K=null,O=null,E=M=>{K!==null&&clearInterval(K),O!==null&&this.connection.removeSignatureListener(O);let D=I.findIndex(G=>G.txId===B);if(D>-1){if(I[D].status==="error"||I[D].status==="success")return;I[D].status=M.err?"error":"success"}h==null||h([...I]),M.err||C()};this.loopMultiTxStatus&&(K=setInterval(()=>y(this,null,function*(){var M;if(N){clearInterval(K);return}try{let D=yield this.connection.getTransaction(B,{commitment:"confirmed",maxSupportedTransactionVersion:0});D&&(N=!0,clearInterval(K),E({err:((M=D.meta)==null?void 0:M.err)||null}),console.log("tx status from getTransaction:",B))}catch(D){N=!0,clearInterval(K),console.error("getTransaction timeout:",D,B)}}),at)),O=this.connection.onSignature(B,M=>{if(N){this.connection.removeSignatureListener(O);return}N=!0,E(M)},"confirmed"),this.connection.getSignatureStatus(B)});return yield C(),{txIds:I.map(B=>B.txId),signedTxs:A}}else{let x=[];for(let I=0;I<A.length;I+=1){let C=yield this.connection.sendRawTransaction(A[I].serialize(),{skipPreflight:P});x.push(C)}return{txIds:x,signedTxs:A}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:i||{}}})}sizeCheckBuildV0(t){return y(this,null,function*(){var w;let P=t||{},{computeBudgetConfig:e,splitIns:n=[],lookupTableCache:i={},lookupTableAddress:r=[]}=P,a=Y(P,["computeBudgetConfig","splitIns","lookupTableCache","lookupTableAddress"]),s=L(L({},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 Nt({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 Ae(this.connection,this.blockhashCommitment),d=this.signers.reduce((T,b)=>R(L({},T),{[b.publicKey.toBase58()]:b}),{}),f=[],h=[],g=[],k=0;if(this.allInstructions.forEach(T=>{let b=[...g,T],A=e?[...l.instructions,...b]:b;if(T!==n[k]&&g.length<12&&(De({instructions:A,payer:this.feePayer,lookupTableAddressAccount:s})||De({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&&De({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(C=>C.isSigner).map(C=>C.pubkey.toString())).flat())).map(I=>d[I]).filter(I=>I!==void 0)),g=[T]}}),g.length>0){let b=[...new Set(g.map(A=>A.keys.filter(x=>x.isSigner).map(x=>x.pubkey.toString())).flat()).values()].map(A=>d[A]).filter(A=>A!==void 0);if(e&&De({instructions:[...l.instructions,...g],payer:this.feePayer,lookupTableAddressAccount:s,recentBlockhash:p})){let A=new We({payerKey:this.feePayer,recentBlockhash:p,instructions:[...l.instructions,...g]}).compileToV0Message(Object.values(s));f.push(new Ve(A))}else{let A=new We({payerKey:this.feePayer,recentBlockhash:p,instructions:[...g]}).compileToV0Message(Object.values(s));f.push(new Ve(A))}h.push(b)}return(w=this.owner)!=null&&w.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 B;let{sequentially:b,onTxUpdate:A,skipTxCount:x=0,recentBlockHash:I,skipPreflight:C=!0}=T||{};if(f.map((N,K)=>y(this,null,function*(){h[K].length&&N.sign(h[K]),I&&(N.message.recentBlockhash=I)})),ye(f),(B=this.owner)!=null&&B.isKeyPair){if(b){let N=0,K=[];for(let O of f){if(++N,N<=x){console.log("skip tx: ",N),K.push("tx skipped");continue}let E=yield this.connection.sendTransaction(O,{skipPreflight:C});yield it(this.connection,E),K.push(E)}return{txIds:K,signedTxs:f}}return{txIds:yield Promise.all(f.map(N=>y(this,null,function*(){return yield this.connection.sendTransaction(N,{skipPreflight:C})}))),signedTxs:f}}if(this.signAllTransactions){let N=yield this.signAllTransactions(f.slice(x,f.length)),K=[...f.slice(0,x),...N];if(b){let O=0,E=[],M=()=>y(this,null,function*(){if(!K[O])return;if(O<x){E.push({txId:"",status:"success",signedTx:K[O]}),A==null||A([...E]),O++,M();return}let D=yield this.connection.sendTransaction(K[O],{skipPreflight:C});E.push({txId:D,status:"sent",signedTx:K[O]}),A==null||A([...E]),O++;let G=!1,Q=null,ge=null,en=be=>{Q!==null&&clearInterval(Q),ge!==null&&this.connection.removeSignatureListener(ge);let ue=E.findIndex(Xn=>Xn.txId===D);if(ue>-1){if(E[ue].status==="error"||E[ue].status==="success")return;E[ue].status=be.err?"error":"success"}A==null||A([...E]),be.err||M()};this.loopMultiTxStatus&&(Q=setInterval(()=>y(this,null,function*(){var be;if(G){clearInterval(Q);return}try{let ue=yield this.connection.getTransaction(D,{commitment:"confirmed",maxSupportedTransactionVersion:0});ue&&(G=!0,clearInterval(Q),en({err:((be=ue.meta)==null?void 0:be.err)||null}),console.log("tx status from getTransaction:",D))}catch(ue){G=!0,clearInterval(Q),console.error("getTransaction timeout:",ue,D)}}),at)),ge=this.connection.onSignature(D,be=>{if(G){this.connection.removeSignatureListener(ge);return}G=!0,en(be)},"confirmed"),this.connection.getSignatureStatus(D)});return M(),{txIds:[],signedTxs:K}}else{let O=[];for(let E=0;E<K.length;E+=1){let M=yield this.connection.sendTransaction(K[E],{skipPreflight:C});O.push(M)}return{txIds:O,signedTxs:K}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:a||{}}})}};import{Connection as Wa}from"@solana/web3.js";var $={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"},cu=R(L({},$),{BASE_HOST:"https://dev-api.sega.so/api"}),lu=R(L({},$),{BASE_HOST:"https://api-sol.sega.so/api"});var Sn="ray_tab_hash",Et="ray_req_hash",Fo=()=>{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=Y(i,["logCount","removeLastLog"]);if(typeof window===void 0)return new Promise(a=>a());let r=JSON.parse(localStorage.getItem(Et)||"[]").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(R(L({},e),{time:Date.now(),session:Fo()}));try{localStorage.setItem(Et,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(Et,JSON.stringify(r)),s=!0}catch(m){s=!1}}return new Promise(u=>u())}return ct(R(L({},e),{logCount:o,removeLastLog:!0}))}});var lt=V("Sega_Api"),Dt=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=Cn.create({baseURL:this.urlConfigs.BASE_HOST||$.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||$.CPMM_CONFIG)).data})}getBlockSlotCountForSecond(t){return y(this,null,function*(){if(!t)return 2;let n=(yield Cn.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||$.CHAIN_TIME)).data})}fetchPoolKeysById(t){return y(this,null,function*(){let{idList:e}=t,n=[],i=e.filter(a=>Dt.has(a)?(n.push(Dt.get(a)),!1):!0),r=[];return i.length&&(r=(yield this.api.get((this.urlConfigs.POOL_KEY_BY_ID||$.POOL_KEY_BY_ID)+`?ids=${i.join(",")}`)).data.filter(Boolean),r.forEach(s=>{Dt.set(s.id,s)})),n.concat(r)})}getRpcs(){return y(this,null,function*(){return this.api.get(this.urlConfigs.RPCS||$.RPCS)})}getTokenList(){return y(this,null,function*(){return(yield this.api.get(this.urlConfigs.TOKEN_LIST||$.TOKEN_LIST)).data})}getJupTokenList(){return y(this,null,function*(){return this.api.get("",{baseURL:this.urlConfigs.JUP_TOKEN_LIST||$.JUP_TOKEN_LIST})})}getTokenInfo(t){return y(this,null,function*(){return(yield this.api.get((this.urlConfigs.MINT_INFO_ID||$.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||$.CHECK_AVAILABILITY)).data})}};var pt="please provide owner in load() initialization or you can set by calling sega.setOwner(owner)",Bn="please provide connection in load() initialization or set it by sega.setConnection(connection)";import{PublicKey as gt,SystemProgram as sr}from"@solana/web3.js";import{AccountLayout as Ie,createAssociatedTokenAccountInstruction as Ht,TOKEN_PROGRAM_ID as fe,TOKEN_2022_PROGRAM_ID as ar}from"@solana/spl-token";var Ft=(...o)=>o.map(t=>{try{return typeof t=="object"?JSON.stringify(t):t}catch(e){return t}}).join(", "),ie=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 er,SystemProgram as tr}from"@solana/web3.js";import nr from"bn.js";import{createCloseAccountInstruction as or,createInitializeAccountInstruction as rr,createTransferInstruction as ir,TOKEN_PROGRAM_ID as xe}from"@solana/spl-token";import{Keypair as Jo,PublicKey as Mn}from"@solana/web3.js";import Zo from"bn.js";import{TOKEN_PROGRAM_ID as $o}from"@solana/spl-token";import{sha256 as Xo}from"@noble/hashes/sha256";import{PublicKey as Ho}from"@solana/web3.js";import Rn,{isBN as Nn}from"bn.js";import{bits as Eu,BitStructure as Du,blob as vo,Blob as Fu,cstr as vu,f32 as Wu,f32be as Vu,f64 as Uu,f64be as qu,greedy as Gu,Layout as Wo,ns64 as ju,ns64be as Hu,nu64 as Yu,nu64be as zu,offset as Ju,s16 as Zu,s16be as $u,s24 as Xu,s24be as Qu,s32 as ec,s32be as tc,s40 as nc,s40be as oc,s48 as rc,s48be as ic,s8 as sc,seq as Vo,struct as ac,Structure as Uo,u16 as qo,u16be as uc,u24 as cc,u24be as lc,u32 as mc,u32be as pc,u40 as dc,u40be as fc,u48 as gc,u48be as bc,u8 as Go,UInt as jo,union as yc,Union as hc,unionLayoutDiscriminator as Tc,utf8 as Pc}from"@solana/buffer-layout";var vt=Wo,Ln=Uo;var Wt=jo;var Kn=Go,_n=qo;var On=Vo;var le=vo;var Vt=class extends vt{constructor(t,e,n){super(t,n),this.blob=le(t),this.signed=e}decode(t,e=0){let n=new Rn(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 Rn(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(le(32),t=>new Ho(t),t=>t.toBuffer(),o)}function qt(o){return new dt(Kn(),Yo,zo,o)}function Yo(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 Ln{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:Nn(t)?t.toNumber():new Proxy(t,{get(r,a){if(!n){let s=Reflect.get(r,"count");n=Nn(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 jc=V("Sega_Util");function En({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 Zo(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):Jo.generate().publicKey.toBase58().slice(0,32);return{publicKey:Qo(o,n,t),seed:n}}function Qo(o,t,e){let n=Buffer.concat([o.toBuffer(),Buffer.from(t),e.toBuffer()]),i=Xo(n);return new Mn(i)}function Gt(o){let{mint:t,tokenAccount:e,owner:n,programId:i=xe}=o;return rr(e,t,n,i)}function qe(o){let{tokenAccount:t,payer:e,multiSigners:n=[],owner:i,programId:r=xe}=o;return or(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=ee(e).add(new nr(s)),u=ft({fromPublicKey:i,programId:xe});return{addresses:{newAccount:u.publicKey},signers:[],instructions:[tr.createAccountWithSeed({fromPubkey:i,basePubkey:i,seed:u.seed,newAccountPubkey:u.publicKey,lamports:c.toNumber(),space:Ue.span,programId:xe}),Gt({mint:new er(ae.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 Dn({source:o,destination:t,owner:e,amount:n,multiSigners:i=[],tokenProgram:r=xe}){return ir(o,t,e,BigInt(String(n)),i,r)}var Ge=class extends ie{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=L(L({},{}),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:ar},i.commitment)]),{tokenAccounts:c,tokenAccountRawInfos:u}=En({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