UNPKG

@sega-so/sega-sdk

Version:

An SDK for building applications on top of SEGA.

1 lines 99.5 kB
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},R=(o,e)=>mo(o,po(e));var Y=(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 Ur}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)=>R(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()]=R(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 me from"bn.js";import Fs from"decimal.js";import Co 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 De from"bn.js";var gn=9007199254740991;function Z(o){let e=V("Sega_parseBigNumberish");if(o instanceof De)return o;if(typeof o=="string"){if(o.match(/^-?[0-9]+$/))return new De(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 De(String(o))):typeof o=="bigint"?new De(o.toString()):(e.error(`invalid BigNumberish value: ${o}`),new De(0))}var rt=V("module/fraction"),Ot=Ee(it),Fe=Ee(ko),Io={0:Fe.ROUND_DOWN,1:Fe.ROUND_HALF_UP,2:Fe.ROUND_UP},So={0:it.roundDown,1:it.roundHalfUp,2:it.roundUp},oe=class o{constructor(e,t=new xo(1)){this.numerator=Z(e),this.denominator=Z(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(Z(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(Z(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(Z(e));return new o(this.numerator.mul(t.numerator),this.denominator.mul(t.denominator))}div(e){let t=e instanceof o?e:new o(Z(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.`),Fe.set({precision:e+1,rounding:Io[n]});let i=new Fe(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 Bo=V("Sega_amount"),yn=Ee(Co);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")):Bo.logWithError(`invalid number string, num: ${o}`)}else t=o;return[t,n.slice(0,e)||n]}var Te=class o extends oe{constructor(e,t,n=!0,i){let r=new st(0),a=bn.pow(new st(e.decimals));if(n)r=Z(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=Z(u),c=Z(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 ue={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 Dt}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 _i=[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 Oi=new W("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),Mt=new W("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),Et=new W("SysvarRent111111111111111111111111111111111"),Ri=new W("SysvarC1ock11111111111111111111111111111111"),We=new W("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),Ni=new W("Sysvar1nstructions1111111111111111111111111"),An=Tn.programId,Mi=new W("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),Ei=new W("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),Di=new W("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),Fi=new W("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),vi=new W("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),Wi=new W("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),Vi=new W("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),Ui=new W("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),qi=new W("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),Gi=new W("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),ji=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 Dt&&ve.equals(e)){this.decimals=Q.decimals,this.symbol=Q.symbol,this.name=Q.name,this.mint=new Dt(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?Dt.default:Nt({publicKey:e}),this.isToken2022=a}equals(e){return this===e?!0:this.mint.equals(e.mint)}};at.WSOL=new at(R(K({},Q),{mint:Q.address}));var z=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(ue);var Ft=ut;import Ro from"bn.js";var wn=new oe(new Ro(100)),re=class extends oe{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 cs=V("Sega_price");import{PublicKey as Ss}from"@solana/web3.js";import Bs from"bn.js";var vt=new me(0),zs=new me(1),Js=new me(2),Zs=new me(3),$s=new me(5),bn=new me(10),Xs=new me(100),Qs=new me(1e3),ea=new me(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 Cn,TransactionMessage as Mo,VersionedTransaction as Bn}from"@solana/web3.js";var F={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(F.SetComputeUnitPrice)),o.units&&(e.push(kn.setComputeUnitLimit({units:o.units})),t.push(F.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 Cn;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 $(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 Bn(r).serialize()).toString("base64").length<Kn}catch(a){return!1}}var Do=o=>Buffer.isBuffer(o)?o:o instanceof Uint8Array?Buffer.from(o.buffer,o.byteOffset,o.byteLength):Buffer.from(o),Fo=o=>{let e=o.serialize({requireAllSignatures:!1,verifySignatures:!1});o instanceof Bn&&(e=Do(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 Cn&&(t.recentBlockhash||(t.recentBlockhash=Eo.toBase58()),t.feePayer||(t.feePayer=Sn.generate().publicKey)),e.push(Fo(t))}),console.log("simulate tx string:",e),e}function ce(o,e,t){return $([o.toBuffer(),(t!=null?t:Wo).toBuffer(),e.toBuffer()],new vo("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"))}function Ln(o){return $([Buffer.from("metadata","utf8"),We.toBuffer(),o.toBuffer()],We)}import{PublicKey as ie}from"@solana/web3.js";var _n=new ie("SegazTQwbYWknDZkJ6j2Kgvm5gw3MrHGKtWstZdoNKZ"),On=new ie("Ajk8d9bERSaFdeoT1d8JUVfaDayrYLnAdgeB47TFMUaG"),ka=new ie("2HbjxVVKJ7Ct72Rcd8WK4VTqmwTXL5aAggkH1CHGFGmh"),Vo=new ie("TegaRdjn9Qeh9DfUU28X19aPPpJtj9gs8ntSYrR5H4K "),Uo=new ie("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y"),qo=new ie("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y"),Ia=new ie("SegaXNnoXYTZiqUt9Xn2XqGcL56b25yzXLuJSpadcMu"),Sa=new ie("2t1hV2YqnDCPuJZqr7Fy8oAygGwZE5Q9uaQzpLC1QryJ"),Ca=new ie("BLxynZeHE123MmQgNJZiV1pwW4VYh46oZYyC66xwmtTY");var Go={SERUM_MARKET:ie.default,UTIL1216:ie.default,CREATE_CPMM_POOL_PROGRAM:Vo,CREATE_CPMM_POOL_AUTH:Uo,CREATE_CPMM_POOL_FEE_ACC:qo};import se 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=R(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 se(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 se(r.maximumFee.toString());return{amount:o.add(c),fee:c,expirationTime:s}}else{let c=Se(o.mul(new se(Ge)),new se(Ge-r.transferFeeBasisPoints)),u=new se(r.maximumFee.toString()),m=c.sub(o).gt(u)?o.add(u):c,l=Se(m.mul(new se(r.transferFeeBasisPoints)),new se(Ge)),p=l.gt(a)?a:l;return{amount:m,fee:p,expirationTime:s}}else{let c=Se(o.mul(new se(r.transferFeeBasisPoints)),new se(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 se(0))?t.add(new se(1)):t}import{PublicKey as jo,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 jo(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 Ce,sendAndConfirmTransaction as Ut,SystemProgram as Ho,Transaction as je,TransactionMessage as He,VersionedTransaction as Ye}from"@solana/web3.js";import Yo 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 Yo.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(Ho.transfer({fromPubkey:(t=e.feePayer)!=null?t:this.feePayer,toPubkey:new Ce(e.address),lamports:BigInt(e.amount.toString())})),this.endInstructionTypes.push(F.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!==Ce.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,C=null,B=null,N=_=>{C!==null&&clearInterval(C),B!==null&&this.connection.removeSignatureListener(B);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&&(C=setInterval(()=>b(this,null,function*(){var _;if(I){clearInterval(C);return}try{let O=yield this.connection.getTransaction(k,{commitment:"confirmed",maxSupportedTransactionVersion:0});O&&(I=!0,clearInterval(C),N({err:((_=O.meta)==null?void 0:_.err)||null}),console.log("tx status from getTransaction:",k))}catch(O){I=!0,clearInterval(C),console.error("getTransaction timeout:",O,k)}}),pt)),B=this.connection.onSignature(k,_=>{if(I){this.connection.removeSignatureListener(B);return}I=!0,N(_)},"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=Y(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 Ce(g));let m=yield Vt({connection:this.connection,address:u});for(let[g,x]of Object.entries(m))s[g]=x;let l=i?Ce.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 Ye(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=C=>{w!==null&&clearInterval(w),k!==null&&this.connection.removeSignatureListener(k);let B=h.findIndex(N=>N.txId===T);if(B>-1){if(h[B].status==="error"||h[B].status==="success")return;h[B].status=C.err?"error":"success"}p==null||p([...h]),C.err||A()};this.loopMultiTxStatus&&(w=setInterval(()=>b(this,null,function*(){var C;if(P){clearInterval(w);return}try{let B=yield this.connection.getTransaction(T,{commitment:"confirmed",maxSupportedTransactionVersion:0});B&&(P=!0,clearInterval(w),I({err:((C=B.meta)==null?void 0:C.err)||null}),console.log("tx status from getTransaction:",T))}catch(B){P=!0,clearInterval(w),console.error("getTransaction timeout:",B,T)}}),pt)),k=this.connection.onSignature(T,C=>{if(P){this.connection.removeSignatureListener(k);return}P=!0,I(C)},"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=Y(l,["splitIns","computeBudgetConfig"]),r=n?ct(n):{instructions:[],instructionTypes:[]},a=this.signers.reduce((d,f)=>R(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 Ce(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(C=>C.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=[],C=()=>b(this,null,function*(){if(!w[k])return;k<g&&(I.push({txId:"",status:"success",signedTx:w[k]}),y==null||y([...I]),k++,C());let B=yield this.connection.sendRawTransaction(w[k].serialize(),{skipPreflight:h});I.push({txId:B,status:"sent",signedTx:w[k]}),y==null||y([...I]),k++;let N=!1,_=null,O=null,E=M=>{_!==null&&clearInterval(_),O!==null&&this.connection.removeSignatureListener(O);let D=I.findIndex(j=>j.txId===B);if(D>-1){if(I[D].status==="error"||I[D].status==="success")return;I[D].status=M.err?"error":"success"}y==null||y([...I]),M.err||C()};this.loopMultiTxStatus&&(_=setInterval(()=>b(this,null,function*(){var M;if(N){clearInterval(_);return}try{let D=yield this.connection.getTransaction(B,{commitment:"confirmed",maxSupportedTransactionVersion:0});D&&(N=!0,clearInterval(_),E({err:((M=D.meta)==null?void 0:M.err)||null}),console.log("tx status from getTransaction:",B))}catch(D){N=!0,clearInterval(_),console.error("getTransaction timeout:",D,B)}}),pt)),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:w}}else{let k=[];for(let I=0;I<w.length;I+=1){let C=yield this.connection.sendRawTransaction(w[I].serialize(),{skipPreflight:h});k.push(C)}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=Y(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 Ce(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)=>R(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 Ye(I))}else{let I=new He({payerKey:this.feePayer,recentBlockhash:p,instructions:[...g]}).compileToV0Message(Object.values(s));f.push(new Ye(I))}y.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 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 Ye(w))}else{let w=new He({payerKey:this.feePayer,recentBlockhash:p,instructions:[...g]}).compileToV0Message(Object.values(s));f.push(new Ye(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 B;let{sequentially:P,onTxUpdate:w,skipTxCount:k=0,recentBlockHash:I,skipPreflight:C=!0}=T||{};if(f.map((N,_)=>b(this,null,function*(){y[_].length&&N.sign(y[_]),I&&(N.message.recentBlockhash=I)})),Pe(f),(B=this.owner)!=null&&B.isKeyPair){if(P){let N=0,_=[];for(let O of f){if(++N,N<=k){console.log("skip tx: ",N),_.push("tx skipped");continue}let E=yield this.connection.sendTransaction(O,{skipPreflight:C});yield lt(this.connection,E),_.push(E)}return{txIds:_,signedTxs:f}}return{txIds:yield Promise.all(f.map(N=>b(this,null,function*(){return yield this.connection.sendTransaction(N,{skipPreflight:C})}))),signedTxs:f}}if(this.signAllTransactions){let N=yield this.signAllTransactions(f.slice(k,f.length)),_=[...f.slice(0,k),...N];if(P){let O=0,E=[],M=()=>b(this,null,function*(){if(!_[O])return;if(O<k){E.push({txId:"",status:"success",signedTx:_[O]}),w==null||w([...E]),O++,M();return}let D=yield this.connection.sendTransaction(_[O],{skipPreflight:C});E.push({txId:D,status:"sent",signedTx:_[O]}),w==null||w([...E]),O++;let j=!1,ne=null,be=null,an=he=>{ne!==null&&clearInterval(ne),be!==null&&this.connection.removeSignatureListener(be);let le=E.findIndex(co=>co.txId===D);if(le>-1){if(E[le].status==="error"||E[le].status==="success")return;E[le].status=he.err?"error":"success"}w==null||w([...E]),he.err||M()};this.loopMultiTxStatus&&(ne=setInterval(()=>b(this,null,function*(){var he;if(j){clearInterval(ne);return}try{let le=yield this.connection.getTransaction(D,{commitment:"confirmed",maxSupportedTransactionVersion:0});le&&(j=!0,clearInterval(ne),an({err:((he=le.meta)==null?void 0:he.err)||null}),console.log("tx status from getTransaction:",D))}catch(le){j=!0,clearInterval(ne),console.error("getTransaction timeout:",le,D)}}),pt)),be=this.connection.onSignature(D,he=>{if(j){this.connection.removeSignatureListener(be);return}j=!0,an(he)},"confirmed"),this.connection.getSignatureStatus(D)});return M(),{txIds:[],signedTxs:_}}else{let O=[];for(let E=0;E<_.length;E+=1){let M=yield this.connection.sendTransaction(_[E],{skipPreflight:C});O.push(M)}return{txIds:O,signedTxs:_}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:a||{}}})}};import{Connection as eu}from"@solana/web3.js";var ee={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"},xu=R(K({},ee),{BASE_HOST:"https://dev-api.sega.so/api"}),ku=R(K({},ee),{BASE_HOST:"https://api-sol.sega.so/api"});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=Y(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(R(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(R(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||ee.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||ee.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||ee.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||ee.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||ee.RPCS)})}getTokenList(){return b(this,null,function*(){return(yield this.api.get(this.urlConfigs.TOKEN_LIST||ee.TOKEN_LIST)).data})}getJupTokenList(){return b(this,null,function*(){return this.api.get("",{baseURL:this.urlConfigs.JUP_TOKEN_LIST||ee.JUP_TOKEN_LIST})})}getTokenInfo(e){return b(this,null,function*(){return(yield this.api.get((this.urlConfigs.MINT_INFO_ID||ee.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||ee.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 yr}from"@solana/web3.js";import{AccountLayout as Ke,createAssociatedTokenAccountInstruction as Xt,TOKEN_PROGRAM_ID as ge,TOKEN_2022_PROGRAM_ID as br}from"@solana/spl-token";var jt=(...o)=>o.map(e=>{try{return typeof e=="object"?JSON.stringify(e):e}catch(t){return e}}).join(", "),ae=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 lr,SystemProgram as mr}from"@solana/web3.js";import pr from"bn.js";import{createCloseAccountInstruction as dr,createInitializeAccountInstruction as fr,createTransferInstruction as gr,TOKEN_PROGRAM_ID as Be}from"@solana/spl-token";import{Keypair as ir,PublicKey as qn}from"@solana/web3.js";import sr from"bn.js";import{TOKEN_PROGRAM_ID as ar}from"@solana/spl-token";import{sha256 as ur}from"@noble/hashes/sha256";import{PublicKey as nr}from"@solana/web3.js";import Vn,{isBN as Un}from"bn.js";import{bits as Zu,BitStructure as $u,blob as Jo,Blob as Xu,cstr as Qu,f32 as ec,f32be as tc,f64 as nc,f64be as oc,greedy as rc,Layout as Zo,ns64 as ic,ns64be as sc,nu64 as ac,nu64be as uc,offset as cc,s16 as lc,s16be as mc,s24 as pc,s24be as dc,s32 as fc,s32be as gc,s40 as yc,s40be as bc,s48 as hc,s48be as Tc,s8 as Pc,seq as $o,struct as Ac,Structure as Xo,u16 as Qo,u16be as wc,u24 as xc,u24be as kc,u32 as Ic,u32be as Sc,u40 as Cc,u40be as Bc,u48 as Kc,u48be as Lc,u8 as er,UInt as tr,union as _c,Union as Oc,unionLayoutDiscriminator as Rc,utf8 as Nc}from"@solana/buffer-layout";var Ht=Zo,Dn=Xo;var Yt=tr;var Fn=er,vn=Qo;var Wn=$o;var pe=Jo;var zt=class extends Ht{constructor(e,t,n){super(e,n),this.blob=pe(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 Yt(1,o)}function we(o){return new Yt(4,o)}function L(o){return new zt(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(pe(32),e=>new nr(e),e=>e.toBuffer(),o)}function Tt(o){return new ht(Fn(),or,rr,o)}function or(o){if(o===0)return!1;if(o===1)return!0;throw new Error("Invalid bool: "+o)}function rr(o){return o?1:0}var Jt=class extends Dn{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 ze=G([v("mint"),v("owner"),L("amount"),we("delegateOption"),v("delegate"),H("state"),we("isNativeOption"),L("isNative"),L("delegatedAmount"),we("closeAuthorityOption"),v("closeAuthority")]);var il=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=ze.decode(a.data),{mint:c,amount:u}=s;n.push({publicKey:r,mint:c,amount:u,isAssociated:ce(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 sr(String(e.lamports)),isNative:!0,programId:e.owner}),{tokenAccounts:n,tokenAccountRawInfos:i}}function Pt({fromPublicKey:o,programId:e=ar,assignSeed:t}){let n=t?btoa(t).slice(0,32):ir.generate().publicKey.toBase58().slice(0,32);return{publicKey:cr(o,n,e),seed:n}}function cr(o,e,t){let n=Buffer.concat([o.toBuffer(),Buffer.from(e),t.toBuffer()]),i=ur(n);return new qn(i)}function Zt(o){let{mint:e,tokenAccount:t,owner:n,programId:i=Be}=o;return fr(t,e,n,i)}function Je(o){let{tokenAccount:e,payer:t,multiSigners:n=[],owner:i,programId:r=Be}=o;return dr(e,t,i,n,r)}function $t(o){return b(this,null,function*(){let{connection:e,amount:t,commitment:n,payer:i,owner:r,skipCloseAccount:a}=o,s=yield e.getMinimumBalanceForRentExemption(ze.span,n),c=Z(t).add(new pr(s)),u=Pt({fromPublicKey:i,programId:Be});return{addresses:{newAccount:u.publicKey},signers:[],instructions:[mr.createAccountWithSeed({fromPubkey:i,basePubkey:i,seed:u.seed,newAccountPubkey:u.publicKey,lamports:c.toNumber(),space:ze.span,programId:Be}),Zt({mint:new lr(Q.address),tokenAccount:u.publicKey,owner:r,programId:Be})],instructionTypes:[F.CreateAccount,F.InitAccount],endInstructionTypes:a?[]:[F.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=Be}){return gr(o,e,t,BigInt(String(n)),i,r)}var Ze=class extends ae{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 ce(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{