@sega-so/sega-sdk
Version:
An SDK for building applications on top of SEGA.
1 lines • 99.2 kB
JavaScript
var lo=Object.defineProperty,mo=Object.defineProperties;var po=Object.getOwnPropertyDescriptors;var ot=Object.getOwnPropertySymbols;var cn=Object.prototype.hasOwnProperty,ln=Object.prototype.propertyIsEnumerable;var X=Math.pow,un=(o,e,t)=>e in o?lo(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,K=(o,e)=>{for(var t in e||(e={}))cn.call(e,t)&&un(o,t,e[t]);if(ot)for(var t of ot(e))ln.call(e,t)&&un(o,t,e[t]);return o},M=(o,e)=>mo(o,po(e));var z=(o,e)=>{var t={};for(var n in o)cn.call(o,n)&&e.indexOf(n)<0&&(t[n]=o[n]);if(o!=null&&ot)for(var n of ot(o))e.indexOf(n)<0&&ln.call(o,n)&&(t[n]=o[n]);return t};var b=(o,e,t)=>new Promise((n,i)=>{var r=c=>{try{s(t.next(c))}catch(u){i(u)}},a=c=>{try{s(t.throw(c))}catch(u){i(u)}},s=c=>c.done?n(c.value):Promise.resolve(c.value).then(r,a);s((t=t.apply(o,e)).next())});import{merge as Vr}from"lodash";import Mn from"axios";import{PublicKey as dn}from"@solana/web3.js";import{get as mn,set as fo}from"lodash";var Kt=class{constructor(e){this.logLevel=e.logLevel!==void 0?e.logLevel:0,this.name=e.name}set level(e){this.logLevel=e}get time(){return Date.now().toString()}get moduleName(){return this.name}isLogLevel(e){return e<=this.logLevel}error(...e){return this.isLogLevel(0)?(console.error(this.time,this.name,"sdk logger error",...e),this):this}logWithError(...e){let t=e.map(n=>typeof n=="object"?JSON.stringify(n):n).join(", ");throw new Error(t)}warning(...e){return this.isLogLevel(1)?(console.warn(this.time,this.name,"sdk logger warning",...e),this):this}info(...e){return this.isLogLevel(2)?(console.info(this.time,this.name,"sdk logger info",...e),this):this}debug(...e){return this.isLogLevel(3)?(console.debug(this.time,this.name,"sdk logger debug",...e),this):this}},pn={},go={};function V(o){let e=mn(pn,o);if(!e){let t=mn(go,o);e=new Kt({name:o,logLevel:t}),fo(pn,o,e)}return e}import{MINT_SIZE as yo,TOKEN_PROGRAM_ID as bo,getTransferFeeConfig as ho,unpackMint as To}from"@solana/spl-token";var Lt=V("Sega_accountInfo_util");function Re(o,e,t){return b(this,null,function*(){let{batchRequest:n,commitment:i="confirmed",chunkCount:r=100}=K({batchRequest:!1},t),a=_t(e,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=_t(c,10);s=(yield(yield Promise.all(u.map(l=>b(this,null,function*(){return yield o._rpcBatchRequest(l)})))).flat()).map(l=>(l.error&&Lt.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${l.error.message}`),l.result.value.map(p=>{if(p){let{data:d,executable:f,lamports:y,owner:g,rentEpoch:x}=p;return d.length!==2&&d[1]!=="base64"&&Lt.logWithError("info must be base64 encoded, RPC_ERROR"),{data:Buffer.from(d[0],"base64"),executable:f,lamports:y,owner:new dn(g),rentEpoch:x}}return null})))}else try{s=yield Promise.all(a.map(c=>o.getMultipleAccountsInfo(c,i)))}catch(c){c instanceof Error&&Lt.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${c.message}`)}return s.flat()})}function Ne(o,e,t){return b(this,null,function*(){let n=yield Re(o,e.map(i=>i.pubkey),t);return e.map((i,r)=>M(K({},i),{accountInfo:n[r]}))})}function fn(n){return b(this,arguments,function*({connection:o,mints:e,config:t}){var a,s,c;if(e.length===0)return{};let i=yield Ne(o,e.map(u=>({pubkey:Me(u)})),t),r={};for(let u of i){if(!u.accountInfo||u.accountInfo.data.length<yo){console.log("invalid mint account",u.pubkey.toBase58());continue}let m=To(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)||bo,feeConfig:(c=ho(m))!=null?c:void 0})}return r[dn.default.toBase58()]=r[J.toBase58()],r})}import le from"bn.js";import Fs from"decimal.js";import Bo from"big.js";import st from"bn.js";import Po from"toformat";var Ao=Po,Ee=Ao;import it from"big.js";import xo from"bn.js";import ko from"decimal.js-light";import Fe from"bn.js";var gn=9007199254740991;function $(o){let e=V("Sega_parseBigNumberish");if(o instanceof Fe)return o;if(typeof o=="string"){if(o.match(/^-?[0-9]+$/))return new Fe(o);e.logWithError(`invalid BigNumberish string: ${o}`)}return typeof o=="number"?(o%1&&e.logWithError(`BigNumberish number underflow: ${o}`),(o>=gn||o<=-gn)&&e.logWithError(`BigNumberish number overflow: ${o}`),new Fe(String(o))):typeof o=="bigint"?new Fe(o.toString()):(e.error(`invalid BigNumberish value: ${o}`),new Fe(0))}var rt=V("module/fraction"),Ot=Ee(it),De=Ee(ko),Io={0:De.ROUND_DOWN,1:De.ROUND_HALF_UP,2:De.ROUND_UP},So={0:it.roundDown,1:it.roundHalfUp,2:it.roundUp},ne=class o{constructor(e,t=new xo(1)){this.numerator=$(e),this.denominator=$(t)}get quotient(){return this.numerator.div(this.denominator)}invert(){return new o(this.denominator,this.numerator)}add(e){let t=e instanceof o?e:new o($(e));return this.denominator.eq(t.denominator)?new o(this.numerator.add(t.numerator),this.denominator):new o(this.numerator.mul(t.denominator).add(t.numerator.mul(this.denominator)),this.denominator.mul(t.denominator))}sub(e){let t=e instanceof o?e:new o($(e));return this.denominator.eq(t.denominator)?new o(this.numerator.sub(t.numerator),this.denominator):new o(this.numerator.mul(t.denominator).sub(t.numerator.mul(this.denominator)),this.denominator.mul(t.denominator))}mul(e){let t=e instanceof o?e:new o($(e));return new o(this.numerator.mul(t.numerator),this.denominator.mul(t.denominator))}div(e){let t=e instanceof o?e:new o($(e));return new o(this.numerator.mul(t.denominator),this.denominator.mul(t.numerator))}toSignificant(e,t={groupSeparator:""},n=1){Number.isInteger(e)||rt.logWithError(`${e} is not an integer.`),e<=0&&rt.logWithError(`${e} is not positive.`),De.set({precision:e+1,rounding:Io[n]});let i=new De(this.numerator.toString()).div(this.denominator.toString()).toSignificantDigits(e);return i.toFormat(i.decimalPlaces(),t)}toFixed(e,t={groupSeparator:""},n=1){return Number.isInteger(e)||rt.logWithError(`${e} is not an integer.`),e<0&&rt.logWithError(`${e} is negative.`),Ot.DP=e,Ot.RM=So[n]||1,new Ot(this.numerator.toString()).div(this.denominator.toString()).toFormat(e,t)}isZero(){return this.numerator.isZero()}};var Co=V("Sega_amount"),yn=Ee(Bo);function Ko(o,e){let t="0",n="0";if(o.includes(".")){let i=o.split(".");i.length===2?([t,n]=i,n=n.padEnd(e,"0")):Co.logWithError(`invalid number string, num: ${o}`)}else t=o;return[t,n.slice(0,e)||n]}var Te=class o extends ne{constructor(e,t,n=!0,i){let r=new st(0),a=bn.pow(new st(e.decimals));if(n)r=$(t);else{let s=new st(0),c=new st(0);if(typeof t=="string"||typeof t=="number"||typeof t=="bigint"){let[u,m]=Ko(t.toString(),e.decimals);s=$(u),c=$(m)}s=s.mul(a),r=s.add(c)}super(r,a),this.logger=V(i||"TokenAmount"),this.token=e}get raw(){return this.numerator}isZero(){return this.raw.isZero()}gt(e){return this.token.equals(e.token)||this.logger.logWithError("gt token not equals"),this.raw.gt(e.raw)}lt(e){return this.token.equals(e.token)||this.logger.logWithError("lt token not equals"),this.raw.lt(e.raw)}add(e){return this.token.equals(e.token)||this.logger.logWithError("add token not equals"),new o(this.token,this.raw.add(e.raw))}subtract(e){return this.token.equals(e.token)||this.logger.logWithError("sub token not equals"),new o(this.token,this.raw.sub(e.raw))}toSignificant(e=this.token.decimals,t,n=0){return super.toSignificant(e,t,n)}toFixed(e=this.token.decimals,t,n=0){return e>this.token.decimals&&this.logger.logWithError("decimals overflow"),super.toFixed(e,t,n)}toExact(e={groupSeparator:""}){return yn.DP=this.token.decimals,new yn(this.numerator.toString()).div(this.denominator.toString()).toFormat(e)}};import{PublicKey as Lo}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as hn}from"@solana/spl-token";var ae={chainId:101,address:Lo.default.toBase58(),programId:hn.toBase58(),decimals:9,symbol:"SOL",name:"solana",logoURI:"https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"sega",extensions:{coingeckoId:"solana"}},Q={chainId:101,address:"So11111111111111111111111111111111111111112",programId:hn.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 Ft}from"@solana/web3.js";import{PublicKey as W,SystemProgram as Tn,SYSVAR_RENT_PUBKEY as _o}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as Oo}from"@solana/spl-token";function Rt({pubkey:o,isSigner:e=!1,isWritable:t=!0}){return{pubkey:o,isWritable:t,isSigner:e}}var Li=[Rt({pubkey:Oo,isWritable:!1}),Rt({pubkey:Tn.programId,isWritable:!1}),Rt({pubkey:_o,isWritable:!1})];function Nt({publicKey:o,transformSol:e}){let t=Pn(o.toString());if(t instanceof W)return e&&t.equals(ve)?J:t;if(e&&t.toString()===ve.toBase58())return J;if(typeof t=="string"){if(t===W.default.toBase58())return W.default;try{return new W(t)}catch(n){throw new Error("invalid public key")}}throw new Error("invalid public key")}function Pn(o){try{return new W(o)}catch(e){return o}}var _i=new W("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),Mt=new W("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),Et=new W("SysvarRent111111111111111111111111111111111"),Oi=new W("SysvarC1ock11111111111111111111111111111111"),We=new W("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),Ri=new W("Sysvar1nstructions1111111111111111111111111"),An=Tn.programId,Ni=new W("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),Mi=new W("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),Ei=new W("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),Fi=new W("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),Di=new W("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),vi=new W("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),Wi=new W("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),Vi=new W("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),Ui=new W("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),qi=new W("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),Gi=new W("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),J=new W("So11111111111111111111111111111111111111112"),ve=W.default;function Me(o){return Nt({publicKey:o,transformSol:!0})}var at=class at{constructor({mint:e,decimals:t,symbol:n,name:i,skipMint:r=!1,isToken2022:a=!1}){if(e===ve.toBase58()||e instanceof Ft&&ve.equals(e)){this.decimals=Q.decimals,this.symbol=Q.symbol,this.name=Q.name,this.mint=new Ft(Q.address),this.isToken2022=!1;return}this.decimals=t,this.symbol=n||e.toString().substring(0,6),this.name=i||e.toString().substring(0,6),this.mint=r?Ft.default:Nt({publicKey:e}),this.isToken2022=a}equals(e){return this===e?!0:this.mint.equals(e.mint)}};at.WSOL=new at(M(K({},Q),{mint:Q.address}));var Y=at;var ut=class ut{constructor({decimals:e,symbol:t="UNKNOWN",name:n="UNKNOWN"}){this.decimals=e,this.symbol=t,this.name=n}equals(e){return this===e}};ut.SOL=new ut(ae);var Dt=ut;import Ro from"bn.js";var wn=new ne(new Ro(100)),oe=class extends ne{toSignificant(e=5,t,n){return this.mul(wn).toSignificant(e,t,n)}toFixed(e=2,t,n){return this.mul(wn).toFixed(e,t,n)}};var us=V("Sega_price");import{PublicKey as Is}from"@solana/web3.js";import Bs from"bn.js";var vt=new le(0),zs=new le(1),Ys=new le(2),Js=new le(3),$s=new le(5),bn=new le(10),Zs=new le(100),Xs=new le(1e3),Qs=new le(1e4);function _t(o,e=1,t=[]){let n=[...o];if(e<=0)return t;for(;n.length;)t.push(n.splice(0,e));return t}var Ve=class o{constructor(e){this._owner=e}get publicKey(){return o.isKeyPair(this._owner)?this._owner.publicKey:this._owner}get signer(){return o.isKeyPair(this._owner)?this._owner:void 0}get isKeyPair(){return o.isKeyPair(this._owner)}get isPublicKey(){return o.isPublicKey(this._owner)}static isKeyPair(e){return e.secretKey!==void 0}static isPublicKey(e){return!o.isKeyPair(e)}};import{PublicKey as vo}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as Wo}from"@solana/spl-token";import{ComputeBudgetProgram as kn,Keypair as Sn,PublicKey as No,Transaction as Bn,TransactionMessage as Mo,VersionedTransaction as Cn}from"@solana/web3.js";var D={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 Eo}from"@solana/spl-token";var In=V("Sega_txUtil"),Kn=1644;function ct(o){let e=[],t=[];return o.microLamports&&(e.push(kn.setComputeUnitPrice({microLamports:o.microLamports})),t.push(D.SetComputeUnitPrice)),o.units&&(e.push(kn.setComputeUnitLimit({units:o.units})),t.push(D.SetComputeUnitLimit)),{instructions:e,instructionTypes:t}}function Ie(o,e){return b(this,null,function*(){var n,i;let t=e!=null?e:"confirmed";return(i=yield(n=o.getLatestBlockhash)==null?void 0:n.call(o,{commitment:t}))==null?void 0:i.blockhash})}function lt(o,e){return b(this,null,function*(){return o.getSignatureStatuses([e]),new Promise((t,n)=>{let i=setTimeout(n,6e4);o.onSignature(e,r=>{if(clearTimeout(i),!r.err){t("");return}n(Object.assign(r.err,{txId:e}))},"confirmed")})})}function Wt(o,e){o.length<1&&In.logWithError(`no instructions provided: ${o.toString()}`),e.length<1&&In.logWithError(`no signers provided:, ${e.toString()}`);let t=new Bn;t.recentBlockhash="11111111111111111111111111111111",t.feePayer=e[0],t.add(...o);try{return Buffer.from(t.serialize({verifySignatures:!1})).toString("base64").length<Kn}catch(n){return!1}}function Z(o,e){let[t,n]=No.findProgramAddressSync(o,e);return{publicKey:t,nonce:n}}function Ue({instructions:o,payer:e,signers:t}){return Wt(o,[e,...t])}function qe({instructions:o,payer:e,lookupTableAddressAccount:t,recentBlockhash:n=Sn.generate().publicKey.toString()}){let r=new Mo({payerKey:e,recentBlockhash:n,instructions:o}).compileToV0Message(Object.values(t!=null?t:{}));try{return Buffer.from(new Cn(r).serialize()).toString("base64").length<Kn}catch(a){return!1}}var Fo=o=>Buffer.isBuffer(o)?o:o instanceof Uint8Array?Buffer.from(o.buffer,o.byteOffset,o.byteLength):Buffer.from(o),Do=o=>{let e=o.serialize({requireAllSignatures:!1,verifySignatures:!1});o instanceof Cn&&(e=Fo(e));try{return e instanceof Buffer?e.toString("base64"):Buffer.from(e).toString("base64")}catch(t){return e.toString("base64")}};function Pe(o){let e=[];return o.forEach(t=>{t instanceof Bn&&(t.recentBlockhash||(t.recentBlockhash=Eo.toBase58()),t.feePayer||(t.feePayer=Sn.generate().publicKey)),e.push(Do(t))}),console.log("simulate tx string:",e),e}function ue(o,e,t){return Z([o.toBuffer(),(t!=null?t:Wo).toBuffer(),e.toBuffer()],new vo("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"))}function Ln(o){return Z([Buffer.from("metadata","utf8"),We.toBuffer(),o.toBuffer()],We)}import{PublicKey as de}from"@solana/web3.js";var _n=new de("SegazTQwbYWknDZkJ6j2Kgvm5gw3MrHGKtWstZdoNKZ"),On=new de("Ajk8d9bERSaFdeoT1d8JUVfaDayrYLnAdgeB47TFMUaG"),xa=new de("2HbjxVVKJ7Ct72Rcd8WK4VTqmwTXL5aAggkH1CHGFGmh"),Vo=new de("auetiVUVJkRxvNPLYEvVnz8UJSqQ1VgoA83PcicHVD1"),Uo=new de("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y"),qo=new de("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y");var ka={SERUM_MARKET:de.default,UTIL1216:de.default,CREATE_CPMM_POOL_PROGRAM:Vo,CREATE_CPMM_POOL_AUTH:Uo,CREATE_CPMM_POOL_FEE_ACC:qo};import re from"bn.js";var Ge=1e4;function Ae(o,e,t,n){if(e===void 0)return{amount:o,fee:void 0,expirationTime:void 0};let i=M(K({},e),{olderTransferFee:{epoch:BigInt(e.olderTransferFee.epoch),maximumFee:BigInt(e.olderTransferFee.maximumFee),transferFeeBasisPoints:e.olderTransferFee.transferFeeBasisPoints},newerTransferFee:{epoch:BigInt(e.newerTransferFee.epoch),maximumFee:BigInt(e.newerTransferFee.maximumFee),transferFeeBasisPoints:e.newerTransferFee.transferFeeBasisPoints}}),r=t.epoch<i.newerTransferFee.epoch?i.olderTransferFee:i.newerTransferFee,a=new re(r.maximumFee.toString()),s=t.epoch<i.newerTransferFee.epoch?(Number(i.newerTransferFee.epoch)*t.slotsInEpoch-t.absoluteSlot)*400/1e3:void 0;if(n)if(r.transferFeeBasisPoints===Ge){let c=new re(r.maximumFee.toString());return{amount:o.add(c),fee:c,expirationTime:s}}else{let c=Se(o.mul(new re(Ge)),new re(Ge-r.transferFeeBasisPoints)),u=new re(r.maximumFee.toString()),m=c.sub(o).gt(u)?o.add(u):c,l=Se(m.mul(new re(r.transferFeeBasisPoints)),new re(Ge)),p=l.gt(a)?a:l;return{amount:m,fee:p,expirationTime:s}}else{let c=Se(o.mul(new re(r.transferFeeBasisPoints)),new re(Ge)),u=c.gt(a)?a:c;return{amount:o,fee:u,expirationTime:s}}}function Se(o,e){let{div:t,mod:n}=o.divmod(e);return n.gt(new re(0))?t.add(new re(1)):t}import{PublicKey as Go,AddressLookupTableAccount as Rn}from"@solana/web3.js";function Vt(t){return b(this,arguments,function*({connection:o,address:e}){let n=yield Re(o,[...new Set(e.map(r=>r.toString()))].map(r=>new Go(r))),i={};for(let r=0;r<e.length;r++){let a=n[r],s=e[r];if(!a)continue;let c=new Rn({key:s,state:Rn.deserialize(a.data)});i[s.toString()]=c,mt[s.toString()]=c}return i})}var mt={};import{PublicKey as Be,sendAndConfirmTransaction as Ut,SystemProgram as jo,Transaction as je,TransactionMessage as He,VersionedTransaction as ze}from"@solana/web3.js";import Ho from"axios";var pt=2e3,dt=class{constructor(e){this.instructions=[];this.endInstructions=[];this.lookupTableAddress=[];this.signers=[];this.instructionTypes=[];this.endInstructionTypes=[];this.connection=e.connection,this.feePayer=e.feePayer,this.signAllTransactions=e.signAllTransactions,this.owner=e.owner,this.cluster=e.cluster,this.blockhashCommitment=e.blockhashCommitment,this.loopMultiTxStatus=!!e.loopMultiTxStatus}get AllTxData(){return{instructions:this.instructions,endInstructions:this.endInstructions,signers:this.signers,instructionTypes:this.instructionTypes,endInstructionTypes:this.endInstructionTypes,lookupTableAddress:this.lookupTableAddress}}get allInstructions(){return[...this.instructions,...this.endInstructions]}getComputeBudgetConfig(){return b(this,null,function*(){var n;let e=(yield Ho.get("https://solanacompass.com/api/fees?cacheFreshTime=300000")).data,{avg:t}=(n=e==null?void 0:e[15])!=null?n:{};if(t)return{units:6e5,microLamports:Math.min(Math.ceil(t*1e6/6e5),25e3)}})}addCustomComputeBudget(e){if(e){let{instructions:t,instructionTypes:n}=ct(e);return this.instructions.unshift(...t),this.instructionTypes.unshift(...n),!0}return!1}addTipInstruction(e){var t;return e?(this.endInstructions.push(jo.transfer({fromPubkey:(t=e.feePayer)!=null?t:this.feePayer,toPubkey:new Be(e.address),lamports:BigInt(e.amount.toString())})),this.endInstructionTypes.push(D.TransferTip),!0):!1}calComputeBudget(n){return b(this,arguments,function*({config:e,defaultIns:t}){try{let i=e||(yield this.getComputeBudgetConfig());if(this.addCustomComputeBudget(i))return;t&&this.instructions.unshift(...t)}catch(i){t&&this.instructions.unshift(...t)}})}addInstruction({instructions:e=[],endInstructions:t=[],signers:n=[],instructionTypes:i=[],endInstructionTypes:r=[],lookupTableAddress:a=[]}){return this.instructions.push(...e),this.endInstructions.push(...t),this.signers.push(...n),this.instructionTypes.push(...i),this.endInstructionTypes.push(...r),this.lookupTableAddress.push(...a.filter(s=>s!==Be.default.toString())),this}versionBuild(n){return b(this,arguments,function*({txVersion:e,extInfo:t}){return e===0?yield this.buildV0(K({},t||{})):this.build(t)})}build(e){var n;let t=new je;return this.allInstructions.length&&t.add(...this.allInstructions),t.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:t,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:i=>b(this,null,function*(){var u;let{recentBlockHash:r,skipPreflight:a=!0,sendAndConfirm:s}=i||{},c=r!=null?r:yield Ie(this.connection,this.blockhashCommitment);if(t.recentBlockhash=c,this.signers.length&&t.sign(...this.signers),Pe([t]),(u=this.owner)!=null&&u.isKeyPair)return{txId:s?yield Ut(this.connection,t,this.signers.find(l=>l.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:a}):yield this.connection.sendRawTransaction(t.serialize(),{skipPreflight:a}),signedTx:t};if(this.signAllTransactions){let m=yield this.signAllTransactions([t]);if(this.signers.length)for(let l of m)try{l.sign(...this.signers)}catch(p){}return{txId:yield this.connection.sendRawTransaction(m[0].serialize(),{skipPreflight:a}),signedTx:m[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:e||{}}}buildMultiTx(e){var u;let{extraPreBuildData:t=[],extInfo:n}=e,{transaction:i}=this.build(n),r=t.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=>b(this,null,function*(){var x;let{sequentially:l,onTxUpdate:p,skipTxCount:d=0,recentBlockHash:f,skipPreflight:y=!0}=m||{},g=f!=null?f:yield Ie(this.connection,this.blockhashCommitment);if((x=this.owner)!=null&&x.isKeyPair){if(l){let h=[],A=0;for(let T of a){if(++A,A<=d)continue;let P=yield Ut(this.connection,T,this.signers.find(w=>w.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:y});h.push(P)}return{txIds:h,signedTxs:a}}return{txIds:yield yield Promise.all(a.map(h=>b(this,null,function*(){return h.recentBlockhash=g,yield this.connection.sendRawTransaction(h.serialize(),{skipPreflight:y})}))),signedTxs:a}}if(this.signAllTransactions){let h=a.map((T,P)=>(T.recentBlockhash=g,s[P].length&&T.sign(...s[P]),T));Pe(h);let A=yield this.signAllTransactions(h);if(l){let T=0,P=[],w=()=>b(this,null,function*(){if(!A[T])return;let k=yield this.connection.sendRawTransaction(A[T].serialize(),{skipPreflight:y});P.push({txId:k,status:"sent",signedTx:A[T]}),p==null||p([...P]),T++;let I=!1,B=null,C=null,R=_=>{B!==null&&clearInterval(B),C!==null&&this.connection.removeSignatureListener(C);let O=P.findIndex(E=>E.txId===k);if(O>-1){if(P[O].status==="error"||P[O].status==="success")return;P[O].status=_.err?"error":"success"}p==null||p([...P]),_.err||w()};this.loopMultiTxStatus&&(B=setInterval(()=>b(this,null,function*(){var _;if(I){clearInterval(B);return}try{let O=yield this.connection.getTransaction(k,{commitment:"confirmed",maxSupportedTransactionVersion:0});O&&(I=!0,clearInterval(B),R({err:((_=O.meta)==null?void 0:_.err)||null}),console.log("tx status from getTransaction:",k))}catch(O){I=!0,clearInterval(B),console.error("getTransaction timeout:",O,k)}}),pt)),C=this.connection.onSignature(k,_=>{if(I){this.connection.removeSignatureListener(C);return}I=!0,R(_)},"confirmed"),this.connection.getSignatureStatus(k)});return yield w(),{txIds:P.map(k=>k.txId),signedTxs:A}}else{let T=[];for(let P=0;P<A.length;P+=1){let w=yield this.connection.sendRawTransaction(A[P].serialize(),{skipPreflight:y});T.push(w)}return{txIds:T,signedTxs:A}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:n||{}}}versionMultiBuild(i){return b(this,arguments,function*({extraPreBuildData:e,txVersion:t,extInfo:n}){return t===0?yield this.buildV0MultiTx({extraPreBuildData:e,buildProps:n||{}}):this.buildMultiTx({extraPreBuildData:e,extInfo:n})})}buildV0(e){return b(this,null,function*(){var y;let f=e||{},{lookupTableCache:t={},lookupTableAddress:n=[],forerunCreate:i,recentBlockhash:r}=f,a=z(f,["lookupTableCache","lookupTableAddress","forerunCreate","recentBlockhash"]),s=K(K({},this.cluster==="devnet"?{}:mt),t),c=Array.from(new Set([...n,...this.lookupTableAddress])),u=[];for(let g of c)s[g]===void 0&&u.push(new Be(g));let m=yield Vt({connection:this.connection,address:u});for(let[g,x]of Object.entries(m))s[g]=x;let l=i?Be.default.toBase58():r!=null?r:yield Ie(this.connection,this.blockhashCommitment),p=new He({payerKey:this.feePayer,recentBlockhash:l,instructions:[...this.allInstructions]}).compileToV0Message(Object.values(s));(y=this.owner)!=null&&y.signer&&!this.signers.some(g=>g.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer);let d=new ze(p);return d.sign(this.signers),{builder:this,transaction:d,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:g=>b(this,null,function*(){var A;let{skipPreflight:x=!0,sendAndConfirm:h}=g||{};if(Pe([d]),(A=this.owner)!=null&&A.isKeyPair){let T=yield this.connection.sendTransaction(d,{skipPreflight:x});return h&&(yield lt(this.connection,T)),{txId:T,signedTx:d}}if(this.signAllTransactions){let T=yield this.signAllTransactions([d]);if(this.signers.length)for(let P of T)try{P.sign(this.signers)}catch(w){}return{txId:yield this.connection.sendTransaction(T[0],{skipPreflight:x}),signedTx:T[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:a||{}}})}buildV0MultiTx(e){return b(this,null,function*(){var u;let{extraPreBuildData:t=[],buildProps:n}=e,{transaction:i}=yield this.buildV0(n),r=t.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)=>b(this,null,function*(){m.sign(s[l])})),{builder:this,transactions:a,signers:s,instructionTypes:c,buildProps:n,execute:m=>b(this,null,function*(){var y;let{sequentially:l,onTxUpdate:p,recentBlockHash:d,skipPreflight:f=!0}=m||{};if(d&&a.forEach(g=>g.message.recentBlockhash=d),Pe(a),(y=this.owner)!=null&&y.isKeyPair){if(l){let g=[];for(let x of a){let h=yield this.connection.sendTransaction(x,{skipPreflight:f});yield lt(this.connection,h),g.push(h)}return{txIds:g,signedTxs:a}}return{txIds:yield Promise.all(a.map(g=>b(this,null,function*(){return yield this.connection.sendTransaction(g,{skipPreflight:f})}))),signedTxs:a}}if(this.signAllTransactions){let g=yield this.signAllTransactions(a);if(l){let x=0,h=[],A=()=>b(this,null,function*(){if(!g[x])return;let T=yield this.connection.sendTransaction(g[x],{skipPreflight:f});h.push({txId:T,status:"sent",signedTx:g[x]}),p==null||p([...h]),x++;let P=!1,w=null,k=null,I=B=>{w!==null&&clearInterval(w),k!==null&&this.connection.removeSignatureListener(k);let C=h.findIndex(R=>R.txId===T);if(C>-1){if(h[C].status==="error"||h[C].status==="success")return;h[C].status=B.err?"error":"success"}p==null||p([...h]),B.err||A()};this.loopMultiTxStatus&&(w=setInterval(()=>b(this,null,function*(){var B;if(P){clearInterval(w);return}try{let C=yield this.connection.getTransaction(T,{commitment:"confirmed",maxSupportedTransactionVersion:0});C&&(P=!0,clearInterval(w),I({err:((B=C.meta)==null?void 0:B.err)||null}),console.log("tx status from getTransaction:",T))}catch(C){P=!0,clearInterval(w),console.error("getTransaction timeout:",C,T)}}),pt)),k=this.connection.onSignature(T,B=>{if(P){this.connection.removeSignatureListener(k);return}P=!0,I(B)},"confirmed"),this.connection.getSignatureStatus(T)});return A(),{txIds:[],signedTxs:g}}else{let x=[];for(let h=0;h<g.length;h+=1){let A=yield this.connection.sendTransaction(g[h],{skipPreflight:f});x.push(A)}return{txIds:x,signedTxs:g}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:n||{}}})}sizeCheckBuild(e){return b(this,null,function*(){var p;let l=e||{},{splitIns:t=[],computeBudgetConfig:n}=l,i=z(l,["splitIns","computeBudgetConfig"]),r=n?ct(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],y=n?[...r.instructions,...f]:f,x=[...new Set(f.map(h=>h.keys.filter(A=>A.isSigner).map(A=>A.pubkey.toString())).flat()).values()].map(h=>new Be(h));if(d!==t[m]&&u.length<12&&(Ue({instructions:y,payer:this.feePayer,signers:x})||Ue({instructions:f,payer:this.feePayer,signers:x})))u.push(d);else{if(u.length===0)throw Error("item ins too big");m+=d===t[m]?1:0,Ue({instructions:n?[...r.instructions,...u]:[...u],payer:this.feePayer,signers:x})?s.push(new je().add(...r.instructions,...u)):s.push(new je().add(...u)),c.push(Array.from(new Set(u.map(h=>h.keys.filter(A=>A.isSigner).map(A=>A.pubkey.toString())).flat())).map(h=>a[h]).filter(h=>h!==void 0)),u=[d]}}),u.length>0){let f=[...new Set(u.map(y=>y.keys.filter(g=>g.isSigner).map(g=>g.pubkey.toString())).flat()).values()].map(y=>a[y]).filter(y=>y!==void 0);Ue({instructions:n?[...r.instructions,...u]:[...u],payer:this.feePayer,signers:f.map(y=>y.publicKey)})?s.push(new je().add(...r.instructions,...u)):s.push(new je().add(...u)),c.push(f)}return s.forEach(d=>d.feePayer=this.feePayer),(p=this.owner)!=null&&p.signer&&c.forEach(d=>{d.some(f=>f.publicKey.equals(this.owner.publicKey))||d.push(this.owner.signer)}),{builder:this,transactions:s,signers:c,instructionTypes:this.instructionTypes,execute:d=>b(this,null,function*(){var T;let{sequentially:f,onTxUpdate:y,skipTxCount:g=0,recentBlockHash:x,skipPreflight:h=!0}=d||{},A=x!=null?x:yield Ie(this.connection,this.blockhashCommitment);if(s.forEach((P,w)=>b(this,null,function*(){P.recentBlockhash=A,c[w].length&&P.sign(...c[w])})),Pe(s),(T=this.owner)!=null&&T.isKeyPair){if(f){let P=0,w=[];for(let k of s){if(++P,P<=g){w.push("tx skipped");continue}let I=yield Ut(this.connection,k,this.signers.find(B=>B.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:h});w.push(I)}return{txIds:w,signedTxs:s}}return{txIds:yield Promise.all(s.map(P=>b(this,null,function*(){return yield this.connection.sendRawTransaction(P.serialize(),{skipPreflight:h})}))),signedTxs:s}}if(this.signAllTransactions){let P=yield this.signAllTransactions(s.slice(g,s.length)),w=[...s.slice(0,g),...P];if(f){let k=0,I=[],B=()=>b(this,null,function*(){if(!w[k])return;k<g&&(I.push({txId:"",status:"success",signedTx:w[k]}),y==null||y([...I]),k++,B());let C=yield this.connection.sendRawTransaction(w[k].serialize(),{skipPreflight:h});I.push({txId:C,status:"sent",signedTx:w[k]}),y==null||y([...I]),k++;let R=!1,_=null,O=null,E=N=>{_!==null&&clearInterval(_),O!==null&&this.connection.removeSignatureListener(O);let F=I.findIndex(j=>j.txId===C);if(F>-1){if(I[F].status==="error"||I[F].status==="success")return;I[F].status=N.err?"error":"success"}y==null||y([...I]),N.err||B()};this.loopMultiTxStatus&&(_=setInterval(()=>b(this,null,function*(){var N;if(R){clearInterval(_);return}try{let F=yield this.connection.getTransaction(C,{commitment:"confirmed",maxSupportedTransactionVersion:0});F&&(R=!0,clearInterval(_),E({err:((N=F.meta)==null?void 0:N.err)||null}),console.log("tx status from getTransaction:",C))}catch(F){R=!0,clearInterval(_),console.error("getTransaction timeout:",F,C)}}),pt)),O=this.connection.onSignature(C,N=>{if(R){this.connection.removeSignatureListener(O);return}R=!0,E(N)},"confirmed"),this.connection.getSignatureStatus(C)});return yield B(),{txIds:I.map(C=>C.txId),signedTxs:w}}else{let k=[];for(let I=0;I<w.length;I+=1){let B=yield this.connection.sendRawTransaction(w[I].serialize(),{skipPreflight:h});k.push(B)}return{txIds:k,signedTxs:w}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:i||{}}})}sizeCheckBuildV0(e){return b(this,null,function*(){var A;let h=e||{},{computeBudgetConfig:t,splitIns:n=[],lookupTableCache:i={},lookupTableAddress:r=[]}=h,a=z(h,["computeBudgetConfig","splitIns","lookupTableCache","lookupTableAddress"]),s=K(K({},this.cluster==="devnet"?{}:mt),i),c=Array.from(new Set([...this.lookupTableAddress,...r])),u=[];for(let T of c)s[T]===void 0&&u.push(new Be(T));let m=yield Vt({connection:this.connection,address:u});for(let[T,P]of Object.entries(m))s[T]=P;let l=t?ct(t):{instructions:[],instructionTypes:[]},p=yield Ie(this.connection,this.blockhashCommitment),d=this.signers.reduce((T,P)=>M(K({},T),{[P.publicKey.toBase58()]:P}),{}),f=[],y=[],g=[],x=0;if(this.allInstructions.forEach(T=>{let P=[...g,T],w=t?[...l.instructions,...P]:P;if(T!==n[x]&&g.length<12&&(qe({instructions:w,payer:this.feePayer,lookupTableAddressAccount:s})||qe({instructions:P,payer:this.feePayer,lookupTableAddressAccount:s})))g.push(T);else{if(g.length===0)throw Error("item ins too big");x+=T===n[x]?1:0;let k={};for(let I of[...new Set(c)])s[I]!==void 0&&(k[I]=s[I]);if(t&&qe({instructions:[...l.instructions,...g],payer:this.feePayer,lookupTableAddressAccount:s,recentBlockhash:p})){let I=new He({payerKey:this.feePayer,recentBlockhash:p,instructions:[...l.instructions,...g]}).compileToV0Message(Object.values(s));f.push(new ze(I))}else{let I=new He({payerKey:this.feePayer,recentBlockhash:p,instructions:[...g]}).compileToV0Message(Object.values(s));f.push(new ze(I))}y.push(Array.from(new Set(g.map(I=>I.keys.filter(B=>B.isSigner).map(B=>B.pubkey.toString())).flat())).map(I=>d[I]).filter(I=>I!==void 0)),g=[T]}}),g.length>0){let P=[...new Set(g.map(w=>w.keys.filter(k=>k.isSigner).map(k=>k.pubkey.toString())).flat()).values()].map(w=>d[w]).filter(w=>w!==void 0);if(t&&qe({instructions:[...l.instructions,...g],payer:this.feePayer,lookupTableAddressAccount:s,recentBlockhash:p})){let w=new He({payerKey:this.feePayer,recentBlockhash:p,instructions:[...l.instructions,...g]}).compileToV0Message(Object.values(s));f.push(new ze(w))}else{let w=new He({payerKey:this.feePayer,recentBlockhash:p,instructions:[...g]}).compileToV0Message(Object.values(s));f.push(new ze(w))}y.push(P)}return(A=this.owner)!=null&&A.signer&&y.forEach(T=>{T.some(P=>P.publicKey.equals(this.owner.publicKey))||T.push(this.owner.signer)}),{builder:this,transactions:f,buildProps:e,signers:y,instructionTypes:this.instructionTypes,execute:T=>b(this,null,function*(){var C;let{sequentially:P,onTxUpdate:w,skipTxCount:k=0,recentBlockHash:I,skipPreflight:B=!0}=T||{};if(f.map((R,_)=>b(this,null,function*(){y[_].length&&R.sign(y[_]),I&&(R.message.recentBlockhash=I)})),Pe(f),(C=this.owner)!=null&&C.isKeyPair){if(P){let R=0,_=[];for(let O of f){if(++R,R<=k){console.log("skip tx: ",R),_.push("tx skipped");continue}let E=yield this.connection.sendTransaction(O,{skipPreflight:B});yield lt(this.connection,E),_.push(E)}return{txIds:_,signedTxs:f}}return{txIds:yield Promise.all(f.map(R=>b(this,null,function*(){return yield this.connection.sendTransaction(R,{skipPreflight:B})}))),signedTxs:f}}if(this.signAllTransactions){let R=yield this.signAllTransactions(f.slice(k,f.length)),_=[...f.slice(0,k),...R];if(P){let O=0,E=[],N=()=>b(this,null,function*(){if(!_[O])return;if(O<k){E.push({txId:"",status:"success",signedTx:_[O]}),w==null||w([...E]),O++,N();return}let F=yield this.connection.sendTransaction(_[O],{skipPreflight:B});E.push({txId:F,status:"sent",signedTx:_[O]}),w==null||w([...E]),O++;let j=!1,te=null,be=null,an=he=>{te!==null&&clearInterval(te),be!==null&&this.connection.removeSignatureListener(be);let ce=E.findIndex(co=>co.txId===F);if(ce>-1){if(E[ce].status==="error"||E[ce].status==="success")return;E[ce].status=he.err?"error":"success"}w==null||w([...E]),he.err||N()};this.loopMultiTxStatus&&(te=setInterval(()=>b(this,null,function*(){var he;if(j){clearInterval(te);return}try{let ce=yield this.connection.getTransaction(F,{commitment:"confirmed",maxSupportedTransactionVersion:0});ce&&(j=!0,clearInterval(te),an({err:((he=ce.meta)==null?void 0:he.err)||null}),console.log("tx status from getTransaction:",F))}catch(ce){j=!0,clearInterval(te),console.error("getTransaction timeout:",ce,F)}}),pt)),be=this.connection.onSignature(F,he=>{if(j){this.connection.removeSignatureListener(be);return}j=!0,an(he)},"confirmed"),this.connection.getSignatureStatus(F)});return N(),{txIds:[],signedTxs:_}}else{let O=[];for(let E=0;E<_.length;E+=1){let N=yield this.connection.sendTransaction(_[E],{skipPreflight:B});O.push(N)}return{txIds:O,signedTxs:_}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:a||{}}})}};import{Connection as Ja}from"@solana/web3.js";var ie={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"},yu=K({},ie);var Nn="ray_tab_hash",qt="ray_req_hash",zo=()=>{if(typeof window===void 0)return"";let o=sessionStorage.getItem(Nn);return o||(o=`ray-${Date.now()}`,sessionStorage.setItem(Nn,o)),o},ft=n=>b(void 0,null,function*(){var i=n,{logCount:o=1e3,removeLastLog:e}=i,t=z(i,["logCount","removeLastLog"]);if(typeof window===void 0)return new Promise(a=>a());let r=JSON.parse(localStorage.getItem(qt)||"[]").slice(0,o-1);e&&r.pop(),new Blob([JSON.stringify(t.data)]).size>1024&&(t.data=JSON.stringify(t.data).substring(0,200)+"..."),r.unshift(M(K({},t),{time:Date.now(),session:zo()}));try{localStorage.setItem(qt,JSON.stringify(r))}catch(a){if(e){let s=!1,c=JSON.stringify(t.data).substring(0,100);for(r[0].data=c+(c.length>100?"...":"");!s;){r.pop();let u=JSON.stringify(t.data).substring(0,100);r[0].data=u+(u.length>100?"...":"");try{localStorage.setItem(qt,JSON.stringify(r)),s=!0}catch(m){s=!1}}return new Promise(u=>u())}return ft(M(K({},t),{logCount:o,removeLastLog:!0}))}});var gt=V("Sega_Api"),Gt=new Map;var yt=class{constructor({cluster:e,timeout:t,logRequests:n,logCount:i,urlConfigs:r}){this.cluster=e,this.urlConfigs=r||{},this.logCount=i||1e3,this.api=Mn.create({baseURL:this.urlConfigs.BASE_HOST||ie.BASE_HOST,timeout:t}),this.api.interceptors.request.use(a=>{let{method:s,baseURL:c,url:u}=a;return gt.debug(`${s==null?void 0:s.toUpperCase()} ${c}${u}`),a},a=>(gt.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&&ft({status:u,url:`${l}${p}`,params:s.params,data:c,logCount:this.logCount}),gt.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&&ft({status:u,url:`${l}${p}`,params:s.params,data:a.message,logCount:this.logCount}),gt.error(`${m.toUpperCase()} ${l}${p} ${u||a.message}`),Promise.reject(a)})}getCpmmConfigs(){return b(this,null,function*(){return(yield this.api.get(this.urlConfigs.CPMM_CONFIG||ie.CPMM_CONFIG)).data})}getBlockSlotCountForSecond(e){return b(this,null,function*(){if(!e)return 2;let n=(yield Mn.post(e,{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 b(this,null,function*(){return(yield this.api.get(this.urlConfigs.CHAIN_TIME||ie.CHAIN_TIME)).data})}fetchPoolKeysById(e){return b(this,null,function*(){let{idList:t}=e,n=[],i=t.filter(a=>Gt.has(a)?(n.push(Gt.get(a)),!1):!0),r=[];return i.length&&(r=(yield this.api.get((this.urlConfigs.POOL_KEY_BY_ID||ie.POOL_KEY_BY_ID)+`?ids=${i.join(",")}`)).data.filter(Boolean),r.forEach(s=>{Gt.set(s.id,s)})),n.concat(r)})}getRpcs(){return b(this,null,function*(){return this.api.get(this.urlConfigs.RPCS||ie.RPCS)})}getTokenList(){return b(this,null,function*(){return(yield this.api.get(this.urlConfigs.TOKEN_LIST||ie.TOKEN_LIST)).data})}getJupTokenList(){return b(this,null,function*(){return this.api.get("",{baseURL:this.urlConfigs.JUP_TOKEN_LIST||ie.JUP_TOKEN_LIST})})}getTokenInfo(e){return b(this,null,function*(){return(yield this.api.get((this.urlConfigs.MINT_INFO_ID||ie.MINT_INFO_ID)+`?mints=${e.map(n=>n.toString()).join(",")}`)).data})}fetchAvailabilityStatus(){return b(this,null,function*(){return(yield this.api.get(this.urlConfigs.CHECK_AVAILABILITY||ie.CHECK_AVAILABILITY)).data})}};var bt="please provide owner in load() initialization or you can set by calling sega.setOwner(owner)",En="please provide connection in load() initialization or set it by sega.setConnection(connection)";import{PublicKey as At,SystemProgram as gr}from"@solana/web3.js";import{AccountLayout as Ke,createAssociatedTokenAccountInstruction as Xt,TOKEN_PROGRAM_ID as ge,TOKEN_2022_PROGRAM_ID as yr}from"@solana/spl-token";var jt=(...o)=>o.map(e=>{try{return typeof e=="object"?JSON.stringify(e):e}catch(t){return e}}).join(", "),se=class{constructor({scope:e,moduleName:t}){this.disabled=!1;this.scope=e,this.logger=V(t)}createTxBuilder(e){return this.scope.checkOwner(),new dt({connection:this.scope.connection,feePayer:e||this.scope.ownerPubKey,cluster:this.scope.cluster,owner:this.scope.owner,blockhashCommitment:this.scope.blockhashCommitment,loopMultiTxStatus:this.scope.loopMultiTxStatus,api:this.scope.api,signAllTransactions:this.scope.signAllTransactions})}logDebug(...e){this.logger.debug(jt(e))}logInfo(...e){this.logger.info(jt(e))}logAndCreateError(...e){let t=jt(e);throw new Error(t)}checkDisabled(){(this.disabled||!this.scope)&&this.logAndCreateError("module not working")}};import{PublicKey as cr,SystemProgram as lr}from"@solana/web3.js";import mr from"bn.js";import{createCloseAccountInstruction as pr,createInitializeAccountInstruction as dr,createTransferInstruction as fr,TOKEN_PROGRAM_ID as Ce}from"@solana/spl-token";import{Keypair as rr,PublicKey as qn}from"@solana/web3.js";import ir from"bn.js";import{TOKEN_PROGRAM_ID as sr}from"@solana/spl-token";import{sha256 as ar}from"@noble/hashes/sha256";import{PublicKey as tr}from"@solana/web3.js";import Vn,{isBN as Un}from"bn.js";import{bits as Uu,BitStructure as qu,blob as Yo,Blob as Gu,cstr as ju,f32 as Hu,f32be as zu,f64 as Yu,f64be as Ju,greedy as $u,Layout as Jo,ns64 as Zu,ns64be as Xu,nu64 as Qu,nu64be as ec,offset as tc,s16 as nc,s16be as oc,s24 as rc,s24be as ic,s32 as sc,s32be as ac,s40 as uc,s40be as cc,s48 as lc,s48be as mc,s8 as pc,seq as $o,struct as dc,Structure as Zo,u16 as Xo,u16be as fc,u24 as gc,u24be as yc,u32 as bc,u32be as hc,u40 as Tc,u40be as Pc,u48 as Ac,u48be as wc,u8 as Qo,UInt as er,union as xc,Union as kc,unionLayoutDiscriminator as Ic,utf8 as Sc}from"@solana/buffer-layout";var Ht=Jo,Fn=Zo;var zt=er;var Dn=Qo,vn=Xo;var Wn=$o;var me=Yo;var Yt=class extends Ht{constructor(e,t,n){super(e,n),this.blob=me(e),this.signed=t}decode(e,t=0){let n=new Vn(this.blob.decode(e,t),10,"le");return this.signed?n.fromTwos(this.span*8).clone():n}encode(e,t,n=0){return typeof e=="number"&&(e=new Vn(e)),this.signed&&(e=e.toTwos(this.span*8)),this.blob.encode(e.toArrayLike(Buffer,"le",this.span),t,n)}};function H(o){return new zt(1,o)}function we(o){return new zt(4,o)}function L(o){return new Yt(8,!1,o)}var ht=class extends Ht{constructor(e,t,n,i){super(e.span,i),this.layout=e,this.decoder=t,this.encoder=n}decode(e,t){return this.decoder(this.layout.decode(e,t))}encode(e,t,n){return this.layout.encode(this.encoder(e),t,n)}getSpan(e,t){return this.layout.getSpan(e,t)}};function v(o){return new ht(me(32),e=>new tr(e),e=>e.toBuffer(),o)}function Tt(o){return new ht(Dn(),nr,or,o)}function nr(o){if(o===0)return!1;if(o===1)return!0;throw new Error("Invalid bool: "+o)}function or(o){return o?1:0}var Jt=class extends Fn{decode(e,t){return super.decode(e,t)}};function G(o,e,t){return new Jt(o,e,t)}function fe(o,e,t){let n,i=typeof e=="number"?e:Un(e)?e.toNumber():new Proxy(e,{get(r,a){if(!n){let s=Reflect.get(r,"count");n=Un(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 Wn(o,i,t)}var Ye=G([v("mint"),v("owner"),L("amount"),we("delegateOption"),v("delegate"),H("state"),we("isNativeOption"),L("isNative"),L("delegatedAmount"),we("closeAuthorityOption"),v("closeAuthority")]);var Zc=V("Sega_Util");function Gn({owner:o,solAccountResp:e,tokenAccountResp:t}){let n=[],i=[];for(let{pubkey:r,account:a}of t.value){let s=Ye.decode(a.data),{mint:c,amount:u}=s;n.push({publicKey:r,mint:c,amount:u,isAssociated:ue(o,c,a.owner).publicKey.equals(r),isNative:!1,programId:a.owner}),i.push({pubkey:r,accountInfo:s,programId:a.owner})}return e&&n.push({mint:qn.default,amount:new ir(String(e.lamports)),isNative:!0,programId:e.owner}),{tokenAccounts:n,tokenAccountRawInfos:i}}function Pt({fromPublicKey:o,programId:e=sr,assignSeed:t}){let n=t?btoa(t).slice(0,32):rr.generate().publicKey.toBase58().slice(0,32);return{publicKey:ur(o,n,e),seed:n}}function ur(o,e,t){let n=Buffer.concat([o.toBuffer(),Buffer.from(e),t.toBuffer()]),i=ar(n);return new qn(i)}function $t(o){let{mint:e,tokenAccount:t,owner:n,programId:i=Ce}=o;return dr(t,e,n,i)}function Je(o){let{tokenAccount:e,payer:t,multiSigners:n=[],owner:i,programId:r=Ce}=o;return pr(e,t,i,n,r)}function Zt(o){return b(this,null,function*(){let{connection:e,amount:t,commitment:n,payer:i,owner:r,skipCloseAccount:a}=o,s=yield e.getMinimumBalanceForRentExemption(Ye.span,n),c=$(t).add(new mr(s)),u=Pt({fromPublicKey:i,programId:Ce});return{addresses:{newAccount:u.publicKey},signers:[],instructions:[lr.createAccountWithSeed({fromPubkey:i,basePubkey:i,seed:u.seed,newAccountPubkey:u.publicKey,lamports:c.toNumber(),space:Ye.span,programId:Ce}),$t({mint:new cr(Q.address),tokenAccount:u.publicKey,owner:r,programId:Ce})],instructionTypes:[D.CreateAccount,D.InitAccount],endInstructionTypes:a?[]:[D.CloseAccount],endInstructions:a?[]:[Je({tokenAccount:u.publicKey,payer:i,owner:r})]}})}function jn({source:o,destination:e,owner:t,amount:n,multiSigners:i=[],tokenProgram:r=Ce}){return fr(o,e,t,BigInt(String(n)),i,r)}var $e=class extends se{constructor(t){super(t);this._tokenAccounts=[];this._tokenAccountRawInfos=[];this._accountListener=[];this._clientOwnedToken=!1;this._notSubscribeAccountChange=!1;this._accountFetchTime=0;let{tokenAccounts:n,tokenAccountRawInfos:i,notSubscribeAccountChange:r}=t;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(t){this._notSubscribeAccountChange=t}updateTokenAccount({tokenAccounts:t,tokenAccountRawInfos:n}){return t&&(this._tokenAccounts=t),n&&(this._tokenAccountRawInfos=n),this._accountChangeListenerId&&this.scope.connection.removeAccountChangeListener(this._accountChangeListenerId),this._accountChangeListenerId=void 0,this._clientOwnedToken=!0,this}addAccountChangeListener(t){return this._accountListener.push(t),this}removeAccountChangeListener(t){return this._accountListener=this._accountListener.filter(n=>n!==t),this}getAssociatedTokenAccount(t,n){return ue(this.scope.ownerPubKey,t,n).publicKey}resetTokenAccounts(){this._clientOwnedToken||(this._tokenAccounts=[],this._tokenAccountRawInfos=[])}fetchWalletTokenAccounts(t){return b(this,null,function*(){if(this._clientOwnedToken||!(t!=null&&t.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({},{}),t),[r,a,s]=yield Promise.all([this.scope.connection.getAccountInfo(this.scope.ownerPubKey,i.commitment),this.scope.connection.getTokenAccountsByOwner(th