@sega-so/sega-sdk
Version:
An SDK for building applications on top of SEGA.
1 lines • 51.7 kB
JavaScript
var Kt=Object.defineProperty,vt=Object.defineProperties;var qt=Object.getOwnPropertyDescriptors;var xe=Object.getOwnPropertySymbols;var it=Object.prototype.hasOwnProperty,ot=Object.prototype.propertyIsEnumerable;var st=Math.pow,rt=(t,e,n)=>e in t?Kt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,_=(t,e)=>{for(var n in e||(e={}))it.call(e,n)&&rt(t,n,e[n]);if(xe)for(var n of xe(e))ot.call(e,n)&&rt(t,n,e[n]);return t},q=(t,e)=>vt(t,qt(e));var we=(t,e)=>{var n={};for(var r in t)it.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&xe)for(var r of xe(t))e.indexOf(r)<0&&ot.call(t,r)&&(n[r]=t[r]);return n};var g=(t,e,n)=>new Promise((r,i)=>{var s=u=>{try{o(n.next(u))}catch(a){i(a)}},c=u=>{try{o(n.throw(u))}catch(a){i(a)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,c);o((n=n.apply(t,e)).next())});import{PublicKey as ut}from"@solana/web3.js";import{get as Fe,set as at}from"lodash";var Ut=(i=>(i[i.Error=0]="Error",i[i.Warning=1]="Warning",i[i.Info=2]="Info",i[i.Debug=3]="Debug",i))(Ut||{}),_e=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 n=e.map(r=>typeof r=="object"?JSON.stringify(r):r).join(", ");throw new Error(n)}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}},Ve={},ct={};function K(t){let e=Fe(Ve,t);if(!e){let n=Fe(ct,t);e=new _e({name:t,logLevel:n}),at(Ve,t,e)}return e}function qn(t,e){at(ct,t,e);let n=Fe(Ve,t);n&&(n.level=e)}import{MINT_SIZE as Gt,TOKEN_PROGRAM_ID as jt,getTransferFeeConfig as Ht,unpackMint as Yt}from"@solana/spl-token";var We=K("Sega_accountInfo_util");function ve(t,e,n){return g(this,null,function*(){let{batchRequest:r,commitment:i="confirmed",chunkCount:s=100}=_({batchRequest:!1},n),c=Ke(e,s),o=new Array(c.length).fill([]);if(r){let u=c.map(h=>({methodName:"getMultipleAccounts",args:t._buildArgs([h.map(w=>w.toBase58())],i,"base64")})),a=Ke(u,10);o=(yield(yield Promise.all(a.map(h=>g(this,null,function*(){return yield t._rpcBatchRequest(h)})))).flat()).map(h=>(h.error&&We.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${h.error.message}`),h.result.value.map(S=>{if(S){let{data:w,executable:T,lamports:x,owner:m,rentEpoch:A}=S;return w.length!==2&&w[1]!=="base64"&&We.logWithError("info must be base64 encoded, RPC_ERROR"),{data:Buffer.from(w[0],"base64"),executable:T,lamports:x,owner:new ut(m),rentEpoch:A}}return null})))}else try{o=yield Promise.all(c.map(u=>t.getMultipleAccountsInfo(u,i)))}catch(u){u instanceof Error&&We.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${u.message}`)}return o.flat()})}function zt(t,e,n){return g(this,null,function*(){let r=yield ve(t,e.map(i=>i.pubkey),n);return e.map((i,s)=>q(_({},i),{accountInfo:r[s]}))})}var Zt=(r=>(r[r.Uninitialized=0]="Uninitialized",r[r.Mint=1]="Mint",r[r.Account=2]="Account",r))(Zt||{}),Xn=1;function $n(r){return g(this,arguments,function*({connection:t,mints:e,config:n}){var c,o,u;if(e.length===0)return{};let i=yield zt(t,e.map(a=>({pubkey:lt(a)})),n),s={};for(let a of i){if(!a.accountInfo||a.accountInfo.data.length<Gt){console.log("invalid mint account",a.pubkey.toBase58());continue}let l=Yt(a.pubkey,a.accountInfo,(c=a.accountInfo)==null?void 0:c.owner);s[a.pubkey.toString()]=q(_({},l),{programId:((o=a.accountInfo)==null?void 0:o.owner)||jt,feeConfig:(u=Ht(l))!=null?u:void 0})}return s[ut.default.toBase58()]=s[Pe.toBase58()],s})}import E from"bn.js";import fn from"decimal.js";import nn from"big.js";import J from"bn.js";import Jt from"toformat";var Xt=Jt,ue=Xt;import Ae from"big.js";import $t from"bn.js";import Qt from"decimal.js-light";import le from"bn.js";var qe=(r=>(r[r.ROUND_DOWN=0]="ROUND_DOWN",r[r.ROUND_HALF_UP=1]="ROUND_HALF_UP",r[r.ROUND_UP=2]="ROUND_UP",r))(qe||{}),mt=9007199254740991;function W(t){let e=K("Sega_parseBigNumberish");if(t instanceof le)return t;if(typeof t=="string"){if(t.match(/^-?[0-9]+$/))return new le(t);e.logWithError(`invalid BigNumberish string: ${t}`)}return typeof t=="number"?(t%1&&e.logWithError(`BigNumberish number underflow: ${t}`),(t>=mt||t<=-mt)&&e.logWithError(`BigNumberish number overflow: ${t}`),new le(String(t))):typeof t=="bigint"?new le(t.toString()):(e.error(`invalid BigNumberish value: ${t}`),new le(0))}var Se=K("module/fraction"),Ue=ue(Ae),me=ue(Qt),en={0:me.ROUND_DOWN,1:me.ROUND_HALF_UP,2:me.ROUND_UP},tn={0:Ae.roundDown,1:Ae.roundHalfUp,2:Ae.roundUp},I=class t{constructor(e,n=new $t(1)){this.numerator=W(e),this.denominator=W(n)}get quotient(){return this.numerator.div(this.denominator)}invert(){return new t(this.denominator,this.numerator)}add(e){let n=e instanceof t?e:new t(W(e));return this.denominator.eq(n.denominator)?new t(this.numerator.add(n.numerator),this.denominator):new t(this.numerator.mul(n.denominator).add(n.numerator.mul(this.denominator)),this.denominator.mul(n.denominator))}sub(e){let n=e instanceof t?e:new t(W(e));return this.denominator.eq(n.denominator)?new t(this.numerator.sub(n.numerator),this.denominator):new t(this.numerator.mul(n.denominator).sub(n.numerator.mul(this.denominator)),this.denominator.mul(n.denominator))}mul(e){let n=e instanceof t?e:new t(W(e));return new t(this.numerator.mul(n.numerator),this.denominator.mul(n.denominator))}div(e){let n=e instanceof t?e:new t(W(e));return new t(this.numerator.mul(n.denominator),this.denominator.mul(n.numerator))}toSignificant(e,n={groupSeparator:""},r=1){Number.isInteger(e)||Se.logWithError(`${e} is not an integer.`),e<=0&&Se.logWithError(`${e} is not positive.`),me.set({precision:e+1,rounding:en[r]});let i=new me(this.numerator.toString()).div(this.denominator.toString()).toSignificantDigits(e);return i.toFormat(i.decimalPlaces(),n)}toFixed(e,n={groupSeparator:""},r=1){return Number.isInteger(e)||Se.logWithError(`${e} is not an integer.`),e<0&&Se.logWithError(`${e} is negative.`),Ue.DP=e,Ue.RM=tn[r]||1,new Ue(this.numerator.toString()).div(this.denominator.toString()).toFormat(e,n)}isZero(){return this.numerator.isZero()}};var rn=K("Sega_amount"),ke=ue(nn);function pt(t,e){let n="0",r="0";if(t.includes(".")){let i=t.split(".");i.length===2?([n,r]=i,r=r.padEnd(e,"0")):rn.logWithError(`invalid number string, num: ${t}`)}else n=t;return[n,r.slice(0,e)||r]}var z=class t extends I{constructor(e,n,r=!0,i){let s=new J(0),c=te.pow(new J(e.decimals));if(r)s=W(n);else{let o=new J(0),u=new J(0);if(typeof n=="string"||typeof n=="number"||typeof n=="bigint"){let[a,l]=pt(n.toString(),e.decimals);o=W(a),u=W(l)}o=o.mul(c),s=o.add(u)}super(s,c),this.logger=K(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 t(this.token,this.raw.add(e.raw))}subtract(e){return this.token.equals(e.token)||this.logger.logWithError("sub token not equals"),new t(this.token,this.raw.sub(e.raw))}toSignificant(e=this.token.decimals,n,r=0){return super.toSignificant(e,n,r)}toFixed(e=this.token.decimals,n,r=0){return e>this.token.decimals&&this.logger.logWithError("decimals overflow"),super.toFixed(e,n,r)}toExact(e={groupSeparator:""}){return ke.DP=this.token.decimals,new ke(this.numerator.toString()).div(this.denominator.toString()).toFormat(e)}},Ce=class t extends I{constructor(e,n,r=!0,i){let s=new J(0),c=te.pow(new J(e.decimals));if(r)s=W(n);else{let o=new J(0),u=new J(0);if(typeof n=="string"||typeof n=="number"||typeof n=="bigint"){let[a,l]=pt(n.toString(),e.decimals);o=W(a),u=W(l)}o=o.mul(c),s=o.add(u)}super(s,c),this.logger=K(i||"TokenAmount"),this.currency=e}get raw(){return this.numerator}isZero(){return this.raw.isZero()}gt(e){return this.currency.equals(e.currency)||this.logger.logWithError("gt currency not equals"),this.raw.gt(e.raw)}lt(e){return this.currency.equals(e.currency)||this.logger.logWithError("lt currency not equals"),this.raw.lt(e.raw)}add(e){return this.currency.equals(e.currency)||this.logger.logWithError("add currency not equals"),new t(this.currency,this.raw.add(e.raw))}sub(e){return this.currency.equals(e.currency)||this.logger.logWithError("sub currency not equals"),new t(this.currency,this.raw.sub(e.raw))}toSignificant(e=this.currency.decimals,n,r=0){return super.toSignificant(e,n,r)}toFixed(e=this.currency.decimals,n,r=0){return e>this.currency.decimals&&this.logger.logWithError("decimals overflow"),super.toFixed(e,n,r)}toExact(e={groupSeparator:""}){return ke.DP=this.currency.decimals,new ke(this.numerator.toString()).div(this.denominator.toString()).toFormat(e)}};import{PublicKey as on}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as dt}from"@solana/spl-token";var ft={chainId:101,address:on.default.toBase58(),programId:dt.toBase58(),decimals:9,symbol:"SOL",name:"solana",logoURI:"https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"sega",extensions:{coingeckoId:"solana"}},ne={chainId:101,address:"So11111111111111111111111111111111111111112",programId:dt.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 ze}from"@solana/web3.js";import{PublicKey as N,SystemProgram as gt,SYSVAR_RENT_PUBKEY as sn}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as an}from"@solana/spl-token";function Ge({pubkey:t,isSigner:e=!1,isWritable:n=!0}){return{pubkey:t,isWritable:n,isSigner:e}}var Nr=[Ge({pubkey:an,isWritable:!1}),Ge({pubkey:gt.programId,isWritable:!1}),Ge({pubkey:sn,isWritable:!1})];function je({publicKey:t,transformSol:e}){let n=He(t.toString());if(n instanceof N)return e&&n.equals(pe)?Pe:n;if(e&&n.toString()===pe.toBase58())return Pe;if(typeof n=="string"){if(n===N.default.toBase58())return N.default;try{return new N(n)}catch(r){throw new Error("invalid public key")}}throw new Error("invalid public key")}function He(t){try{return new N(t)}catch(e){return t}}var Dr=new N("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),Lr=new N("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),Or=new N("SysvarRent111111111111111111111111111111111"),Er=new N("SysvarC1ock11111111111111111111111111111111"),Ye=new N("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),Fr=new N("Sysvar1nstructions1111111111111111111111111"),_r=gt.programId,Vr=new N("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),Wr=new N("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),Kr=new N("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),vr=new N("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),qr=new N("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),Ur=new N("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),Gr=new N("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),jr=new N("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),Hr=new N("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),Yr=new N("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),zr=new N("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),Pe=new N("So11111111111111111111111111111111111111112"),pe=N.default;function lt(t){return je({publicKey:t,transformSol:!0})}var Be=class Be{constructor({mint:e,decimals:n,symbol:r,name:i,skipMint:s=!1,isToken2022:c=!1}){if(e===pe.toBase58()||e instanceof ze&&pe.equals(e)){this.decimals=ne.decimals,this.symbol=ne.symbol,this.name=ne.name,this.mint=new ze(ne.address),this.isToken2022=!1;return}this.decimals=n,this.symbol=r||e.toString().substring(0,6),this.name=i||e.toString().substring(0,6),this.mint=s?ze.default:je({publicKey:e}),this.isToken2022=c}equals(e){return this===e?!0:this.mint.equals(e.mint)}};Be.WSOL=new Be(q(_({},ne),{mint:ne.address}));var X=Be;var Re=class Re{constructor({decimals:e,symbol:n="UNKNOWN",name:r="UNKNOWN"}){this.decimals=e,this.symbol=n,this.name=r}equals(e){return this===e}};Re.SOL=new Re(ft);var Ie=Re;import cn from"bn.js";var ht=new I(new cn(100)),G=class extends I{toSignificant(e=5,n,r){return this.mul(ht).toSignificant(e,n,r)}toFixed(e=2,n,r){return this.mul(ht).toFixed(e,n,r)}};var un=K("Sega_price"),j=class t extends I{constructor(e){let{baseToken:n,quoteToken:r,numerator:i,denominator:s}=e;super(i,s),this.baseToken=n,this.quoteToken=r,this.scalar=new I(Ze(n.decimals),Ze(r.decimals))}get raw(){return new I(this.numerator,this.denominator)}get adjusted(){return super.mul(this.scalar)}invert(){return new t({baseToken:this.quoteToken,quoteToken:this.baseToken,denominator:this.numerator,numerator:this.denominator})}mul(e){this.quoteToken!==e.baseToken&&un.logWithError("mul token not equals");let n=super.mul(e);return new t({baseToken:this.baseToken,quoteToken:e.quoteToken,denominator:n.denominator,numerator:n.numerator})}toSignificant(e=this.quoteToken.decimals,n,r){return this.adjusted.toSignificant(e,n,r)}toFixed(e=this.quoteToken.decimals,n,r){return this.adjusted.toFixed(e,n,r)}};function O(t){if(t instanceof G)return new I(t.numerator,t.denominator);if(t instanceof j)return t.adjusted;if(t instanceof z)try{return O(t.toExact())}catch(r){return new I($)}if(t instanceof I)return t;let e=String(t),n=re(e);return new I(n.numerator,n.denominator)}function Ai(t){var r;if(t instanceof G)return{fr:new I(t.numerator,t.denominator)};if(t instanceof j)return{fr:t.adjusted};if(t instanceof z)return{fr:O(t.toExact()),decimals:t.token.decimals};if(t instanceof I)return{fr:t};let e=String(t),n=re(e);return{fr:new I(n.numerator,n.denominator),decimals:(r=n.dec)==null?void 0:r.length}}function ki(t,e){if(t==null||e==null)return!1;let n=O(t),r=O(e);return n.sub(r).numerator,n.sub(r).numerator.lt($)}function ln(t,e){if(t==null||e==null)return!1;let n=O(t),r=O(e);return n.sub(r).numerator.gt($)}function Ci(t,e){if(t==null||e==null)return!1;let n=O(t),r=O(e);return n.sub(r).numerator.lte($)}function Bi(t,e){if(t==null||e==null)return!1;let n=O(t),r=O(e);return n.sub(r).numerator.gte($)}function mn(t,e){if(t==null||e==null)return!1;let n=O(t),r=O(e);return n.sub(r).numerator.eq($)}function Ii(t,e){if(t==null||e==null)return;let n=O(t),r=O(e);try{return n.div(r)}catch(i){return n}}function Ri(t,e){if(t==null||e==null)return;let n=O(t),r=O(e);return n.sub(r)}function Mi(t){return t==null?!1:!mn(t,0)}function Ni(t,e){return ln(e,t)?e:t}function Je(t,e){if(t==null||e==null)return;let n=O(t),r=O(e);return n.mul(r)}function Di(t,e){if(t==null||e==null)return;let n=O(t),r=O(e);return n.add(r)}import{PublicKey as pn}from"@solana/web3.js";import dn from"bn.js";function Vi(t){return g(this,null,function*(){new Promise(e=>setTimeout(e,t))})}function Wi(){return new Date().getTime()}function Xe(t){return typeof t=="object"&&t!==null&&![X,z,pn,I,dn,j,G].some(e=>typeof e=="object"&&t instanceof e)}function Tt(t){return typeof t=="string"?He(t):Array.isArray(t)?t.map(e=>Tt(e)):Xe(t)?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,Tt(n)])):t}var $=new E(0),Qi=new E(1),eo=new E(2),to=new E(3),no=new E(5),te=new E(10),ro=new E(100),io=new E(1e3),oo=new E(1e4);function Ze(t){return te.pow(W(t))}function re(t){var o;if(t===void 0)return{denominator:"1",numerator:"0"};if(t instanceof E)return{numerator:t.toString(),denominator:"1"};if(t instanceof I)return{denominator:t.denominator.toString(),numerator:t.numerator.toString()};let e=String(t),[,n="",r="",i=""]=(o=e.replace(",","").match(/(-?)(\d*)\.?(\d*)/))!=null?o:[],s="1"+"0".repeat(i.length),c=n+(r==="0"?"":r)+i||"0";return{denominator:s,numerator:c,sign:n,int:r,dec:i}}function so(t,e){let n=t.divmod(e);return n.mod.isZero()?n.div:n.div.isNeg()?n.div.isubn(1):n.div.iaddn(1)}function gn(t){var r;let[,e="",n=""]=(r=t.toFixed(2).match(/(-?)(\d*)\.?(\d*)/))!=null?r:[];return`${e}${n}`}function hn(t,e=0){return t instanceof E?t:new E(gn(xt(t).mul(te.pow(new E(String(e))))))}function xt(t){if(t instanceof G)return new I(t.numerator,t.denominator);if(t instanceof j)return t.adjusted;if(t instanceof z)try{return xt(t.toExact())}catch(r){return new I($)}if(t instanceof I)return t;let e=String(t),n=re(e);return new I(n.numerator,n.denominator)}function ao(t,e){let{numerator:n,denominator:r}=re(t);return new G(new E(n),new E(r).mul(e!=null&&e.alreadyDecimaled?new E(100):new E(1)))}function co(t){let{token:e,numberPrice:n,decimalDone:r}=t,i=new X({mint:"",decimals:6,symbol:"usd",name:"usd",skipMint:!0}),{numerator:s,denominator:c}=re(n),o=r?new E(s).mul(te.pow(new E(e.decimals))):s,u=new E(c).mul(te.pow(new E(i.decimals)));return new j({baseToken:i,denominator:u.toString(),quoteToken:new X(q(_({},e),{skipMint:!0,mint:""})),numerator:o.toString()})}function bt(t){let e=new Ie({decimals:6,symbol:"usd",name:"usd"}),n=hn(Je(t,st(10,e.decimals)));return new Ce(e,n)}function uo(t,e){return bt(!e||!t?0:Je(t,e))}function Tn(t){if(t==null)return;let{numerator:e,denominator:n}=re(t.toString());return new I(e,n)}function bn(t){return t instanceof fn}function yt(t){return bn(t)?Tn(t):Array.isArray(t)?t.map(e=>yt(e)):Xe(t)?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,yt(n)])):t}var wt=t=>typeof t=="number",Pt=t=>t?new Date(t):new Date,yn=t=>Pt(t).getTime();function po(t,e,n){let r=wt(e)?e*((n==null?void 0:n.unit)==="s"?1e3:1):e;return new Date(t).getTime()<=+r}function fo(t,e,n){let r=wt(e)?e*((n==null?void 0:n.unit)==="s"?1e3:1):e;return new Date(t).getTime()>+r}function go(t,e){let r=yn(t)+(e.days?e.days*24*60*60*1e3:0)+(e.hours?e.hours*60*60*1e3:0)+(e.minutes?e.minutes*60*1e3:0)+(e.seconds?e.seconds*1e3:0)+(e.milliseconds?e.milliseconds:0);return Pt(r)}function Ke(t,e=1,n=[]){let r=[...t];if(e<=0)return n;for(;r.length;)n.push(r.splice(0,e));return n}function To(t,...e){return t.filter(n=>e.every(r=>r.includes(n)))}function bo(t,...e){return t.filter(n=>e.every(r=>!r.includes(n)))}function yo(t){return[...new Set(t)]}var St=class t{constructor(e){this._owner=e}get publicKey(){return t.isKeyPair(this._owner)?this._owner.publicKey:this._owner}get signer(){return t.isKeyPair(this._owner)?this._owner:void 0}get isKeyPair(){return t.isKeyPair(this._owner)}get isPublicKey(){return t.isPublicKey(this._owner)}static isKeyPair(e){return e.secretKey!==void 0}static isPublicKey(e){return!t.isKeyPair(e)}};import{PublicKey as An}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as kn}from"@solana/spl-token";import{ComputeBudgetProgram as kt,Keypair as Ct,PublicKey as Bt,Transaction as Ne,TransactionMessage as xn,VersionedTransaction as $e}from"@solana/web3.js";var At=(n=>(n[n.V0=0]="V0",n[n.LEGACY=1]="LEGACY",n))(At||{}),de={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 wn}from"@solana/spl-token";var Z=K("Sega_txUtil"),It=1644;function De(t){let e=[],n=[];return t.microLamports&&(e.push(kt.setComputeUnitPrice({microLamports:t.microLamports})),n.push(de.SetComputeUnitPrice)),t.units&&(e.push(kt.setComputeUnitLimit({units:t.units})),n.push(de.SetComputeUnitLimit)),{instructions:e,instructionTypes:n}}function se(t,e){return g(this,null,function*(){var r,i;let n=e!=null?e:"confirmed";return(i=yield(r=t.getLatestBlockhash)==null?void 0:r.call(t,{commitment:n}))==null?void 0:i.blockhash})}function Le(t,e){return g(this,null,function*(){return t.getSignatureStatuses([e]),new Promise((n,r)=>{let i=setTimeout(r,6e4);t.onSignature(e,s=>{if(clearTimeout(i),!s.err){n("");return}r(Object.assign(s.err,{txId:e}))},"confirmed")})})}function Rt(t,e){t.length<1&&Z.logWithError(`no instructions provided: ${t.toString()}`),e.length<1&&Z.logWithError(`no signers provided:, ${e.toString()}`);let n=new Ne;n.recentBlockhash="11111111111111111111111111111111",n.feePayer=e[0],n.add(...t);try{return Buffer.from(n.serialize({verifySignatures:!1})).toString("base64").length<It}catch(r){return!1}}function Do(t,e,n,r=!0){return g(this,null,function*(){let i=new Bt("SegaSimuLateTransaction11111111111111111"),s=[],c=new Ne;c.feePayer=i;for(let a of e)Rt([...c.instructions,a],[i])||(s.push(c),c=new Ne,c.feePayer=i),c.add(a);c.instructions.length>0&&s.push(c);let o=[];try{if(o=yield Pn(t,s,r),o.find(a=>a.err!==null))throw Error("rpc simulateTransaction error")}catch(a){a instanceof Error&&Z.logWithError("failed to simulate for instructions","RPC_ERROR",{message:a.message})}let u=[];for(let a of o)if(Z.debug("simulate result:",a),a.logs){let l=a.logs.filter(h=>h&&h.includes(n));Z.debug("filteredLog:",u),l.length||Z.logWithError("simulate log not match keyword","keyword",n),u.push(...l)}return u})}function Lo(t,e){let n=t.match(/{["\w:,]+}/g);return!n||n.length!==1?Z.logWithError(`simulate log fail to match json, keyword: ${e}`):n[0]}function Oo(t,e){let r=new RegExp(`"${e}":(\\d+)`,"g").exec(t);return!r||r.length!==2?Z.logWithError(`simulate log fail to match key", key: ${e}`):r[1]}function Qe(t,e){let[n,r]=Bt.findProgramAddressSync(t,e);return{publicKey:n,nonce:r}}function Pn(t,e,n){return g(this,null,function*(){let r=[];if(n){let i=yield t.getLatestBlockhash(),s=[];for(let a of e){a.recentBlockhash=i.blockhash,a.lastValidBlockHeight=i.lastValidBlockHeight;let h=a._compile().serialize(),w=a._serialize(h).toString("base64");s.push(w)}let c=s.map(a=>({methodName:"simulateTransaction",args:t._buildArgs([a],void 0,"base64")})),o=[],u=20;for(let a=0;a<Math.ceil(c.length/u);a++)o.push(c.slice(a*u,(a+1)*u));r=yield(yield Promise.all(o.map(a=>g(this,null,function*(){return(yield t._rpcBatchRequest(a)).map(l=>l.result.value)})))).flat()}else try{r=yield Promise.all(e.map(i=>g(this,null,function*(){return yield(yield t.simulateTransaction(i)).value})))}catch(i){i instanceof Error&&Z.logWithError("failed to get info for multiple accounts","RPC_ERROR",{message:i.message})}return r})}function fe({instructions:t,payer:e,signers:n}){return Rt(t,[e,...n])}function ge({instructions:t,payer:e,lookupTableAddressAccount:n,recentBlockhash:r=Ct.generate().publicKey.toString()}){let s=new xn({payerKey:e,recentBlockhash:r,instructions:t}).compileToV0Message(Object.values(n!=null?n:{}));try{return Buffer.from(new $e(s).serialize()).toString("base64").length<It}catch(c){return!1}}var Me={time:0,data:void 0};function Eo(t){return g(this,null,function*(){if(!Me.data||(Date.now()-Me.time)/1e3>30){let e=yield t.getEpochInfo();return Me={time:Date.now(),data:e},e}else return Me.data})}var Mt=t=>Buffer.isBuffer(t)?t:t instanceof Uint8Array?Buffer.from(t.buffer,t.byteOffset,t.byteLength):Buffer.from(t),Sn=t=>{let e=t.serialize({requireAllSignatures:!1,verifySignatures:!1});t instanceof $e&&(e=Mt(e));try{return e instanceof Buffer?e.toString("base64"):Buffer.from(e).toString("base64")}catch(n){return e.toString("base64")}};function ie(t){let e=[];return t.forEach(n=>{n instanceof Ne&&(n.recentBlockhash||(n.recentBlockhash=wn.toBase58()),n.feePayer||(n.feePayer=Ct.generate().publicKey)),e.push(Sn(n))}),console.log("simulate tx string:",e),e}function Fo(t){let e=t.serialize({requireAllSignatures:!1,verifySignatures:!1});return t instanceof $e&&(e=Mt(e)),e.toString("base64")}function Uo(t,e,n){return Qe([t.toBuffer(),(n!=null?n:kn).toBuffer(),e.toBuffer()],new An("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"))}function Go(t){return Qe([Buffer.from("metadata","utf8"),Ye.toBuffer(),t.toBuffer()],Ye)}import{PublicKey as U}from"@solana/web3.js";var Nt=new U("SegazTQwbYWknDZkJ6j2Kgvm5gw3MrHGKtWstZdoNKZ"),Dt=new U("Ajk8d9bERSaFdeoT1d8JUVfaDayrYLnAdgeB47TFMUaG"),Lt=new U("2HbjxVVKJ7Ct72Rcd8WK4VTqmwTXL5aAggkH1CHGFGmh"),Cn=new U("TegaRdjn9Qeh9DfUU28X19aPPpJtj9gs8ntSYrR5H4K "),Bn=new U("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y"),In=new U("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y"),Rn=new U("SegaXNnoXYTZiqUt9Xn2XqGcL56b25yzXLuJSpadcMu"),Mn=new U("2t1hV2YqnDCPuJZqr7Fy8oAygGwZE5Q9uaQzpLC1QryJ"),Nn=new U("BLxynZeHE123MmQgNJZiV1pwW4VYh46oZYyC66xwmtTY"),Yo={CREATE_CPMM_POOL_PROGRAM:Nt,CREATE_CPMM_POOL_AUTH:Dt,CREATE_CPMM_POOL_FEE_ACC:Lt},Ot={CREATE_CPMM_POOL_PROGRAM:Nt,CREATE_CPMM_POOL_AUTH:Dt,CREATE_CPMM_POOL_FEE_ACC:Lt},Et={CREATE_CPMM_POOL_PROGRAM:Rn,CREATE_CPMM_POOL_AUTH:Mn,CREATE_CPMM_POOL_FEE_ACC:Nn},Ft={SERUM_MARKET:U.default,UTIL1216:U.default,CREATE_CPMM_POOL_PROGRAM:Cn,CREATE_CPMM_POOL_AUTH:Bn,CREATE_CPMM_POOL_FEE_ACC:In};import F from"bn.js";var H=1e4;function Jo(t,e,n,r){if(e===void 0)return{amount:t,fee:void 0,expirationTime:void 0};let i=n.epoch<e.newerTransferFee.epoch?e.olderTransferFee:e.newerTransferFee,s=new F(i.maximumFee.toString()),c=n.epoch<e.newerTransferFee.epoch?(Number(e.newerTransferFee.epoch)*n.slotsInEpoch-n.absoluteSlot)*400/1e3:void 0;if(r)if(i.transferFeeBasisPoints===H){let o=new F(i.maximumFee.toString());return{amount:t.add(o),fee:o,expirationTime:c}}else{let o=ae(t.mul(new F(H)),new F(H-i.transferFeeBasisPoints)),u=new F(i.maximumFee.toString()),a=o.sub(t).gt(u)?t.add(u):o,l=ae(a.mul(new F(i.transferFeeBasisPoints)),new F(H)),h=l.gt(s)?s:l;return{amount:a,fee:h,expirationTime:c}}else{let o=ae(t.mul(new F(i.transferFeeBasisPoints)),new F(H)),u=o.gt(s)?s:o;return{amount:t,fee:u,expirationTime:c}}}function Xo(t,e,n,r){if(e===void 0)return{amount:t,fee:void 0,expirationTime:void 0};let i=q(_({},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}}),s=n.epoch<i.newerTransferFee.epoch?i.olderTransferFee:i.newerTransferFee,c=new F(s.maximumFee.toString()),o=n.epoch<i.newerTransferFee.epoch?(Number(i.newerTransferFee.epoch)*n.slotsInEpoch-n.absoluteSlot)*400/1e3:void 0;if(r)if(s.transferFeeBasisPoints===H){let u=new F(s.maximumFee.toString());return{amount:t.add(u),fee:u,expirationTime:o}}else{let u=ae(t.mul(new F(H)),new F(H-s.transferFeeBasisPoints)),a=new F(s.maximumFee.toString()),l=u.sub(t).gt(a)?t.add(a):u,h=ae(l.mul(new F(s.transferFeeBasisPoints)),new F(H)),S=h.gt(c)?c:h;return{amount:l,fee:S,expirationTime:o}}else{let u=ae(t.mul(new F(s.transferFeeBasisPoints)),new F(H)),a=u.gt(c)?c:u;return{amount:t,fee:a,expirationTime:o}}}function $o(t,e){return t===void 0?e:e===void 0?t:Math.min(t,e)}function ae(t,e){let{div:n,mod:r}=t.divmod(e);return r.gt(new F(0))?n.add(new F(1)):n}import{PublicKey as Dn,AddressLookupTableAccount as _t}from"@solana/web3.js";function et(n){return g(this,arguments,function*({connection:t,address:e}){let r=yield ve(t,[...new Set(e.map(s=>s.toString()))].map(s=>new Dn(s))),i={};for(let s=0;s<e.length;s++){let c=r[s],o=e[s];if(!c)continue;let u=new _t({key:o,state:_t.deserialize(c.data)});i[o.toString()]=u,Oe[o.toString()]=u}return i})}var Oe={};import{PublicKey as ce,sendAndConfirmTransaction as tt,SystemProgram as Ln,Transaction as he,TransactionMessage as Te,VersionedTransaction as be}from"@solana/web3.js";import On from"axios";var Ee=2e3,Vt=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 g(this,null,function*(){var r;let e=(yield On.get("https://solanacompass.com/api/fees?cacheFreshTime=300000")).data,{avg:n}=(r=e==null?void 0:e[15])!=null?r:{};if(n)return{units:6e5,microLamports:Math.min(Math.ceil(n*1e6/6e5),25e3)}})}addCustomComputeBudget(e){if(e){let{instructions:n,instructionTypes:r}=De(e);return this.instructions.unshift(...n),this.instructionTypes.unshift(...r),!0}return!1}addTipInstruction(e){var n;return e?(this.endInstructions.push(Ln.transfer({fromPubkey:(n=e.feePayer)!=null?n:this.feePayer,toPubkey:new ce(e.address),lamports:BigInt(e.amount.toString())})),this.endInstructionTypes.push(de.TransferTip),!0):!1}calComputeBudget(r){return g(this,arguments,function*({config:e,defaultIns:n}){try{let i=e||(yield this.getComputeBudgetConfig());if(this.addCustomComputeBudget(i))return;n&&this.instructions.unshift(...n)}catch(i){n&&this.instructions.unshift(...n)}})}addInstruction({instructions:e=[],endInstructions:n=[],signers:r=[],instructionTypes:i=[],endInstructionTypes:s=[],lookupTableAddress:c=[]}){return this.instructions.push(...e),this.endInstructions.push(...n),this.signers.push(...r),this.instructionTypes.push(...i),this.endInstructionTypes.push(...s),this.lookupTableAddress.push(...c.filter(o=>o!==ce.default.toString())),this}versionBuild(r){return g(this,arguments,function*({txVersion:e,extInfo:n}){return e===0?yield this.buildV0(_({},n||{})):this.build(n)})}build(e){var r;let n=new he;return this.allInstructions.length&&n.add(...this.allInstructions),n.feePayer=this.feePayer,(r=this.owner)!=null&&r.signer&&!this.signers.some(i=>i.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer),{builder:this,transaction:n,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:i=>g(this,null,function*(){var a;let{recentBlockHash:s,skipPreflight:c=!0,sendAndConfirm:o}=i||{},u=s!=null?s:yield se(this.connection,this.blockhashCommitment);if(n.recentBlockhash=u,this.signers.length&&n.sign(...this.signers),ie([n]),(a=this.owner)!=null&&a.isKeyPair)return{txId:o?yield tt(this.connection,n,this.signers.find(h=>h.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:c}):yield this.connection.sendRawTransaction(n.serialize(),{skipPreflight:c}),signedTx:n};if(this.signAllTransactions){let l=yield this.signAllTransactions([n]);if(this.signers.length)for(let h of l)try{h.sign(...this.signers)}catch(S){}return{txId:yield this.connection.sendRawTransaction(l[0].serialize(),{skipPreflight:c}),signedTx:l[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:e||{}}}buildMultiTx(e){var a;let{extraPreBuildData:n=[],extInfo:r}=e,{transaction:i}=this.build(r),s=n.filter(l=>l.transaction.instructions.length>0),c=[i,...s.map(l=>l.transaction)],o=[this.signers,...s.map(l=>l.signers)],u=[...this.instructionTypes,...s.map(l=>l.instructionTypes).flat()];return(a=this.owner)!=null&&a.signer&&o.forEach(l=>{l.some(h=>h.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),{builder:this,transactions:c,signers:o,instructionTypes:u,execute:l=>g(this,null,function*(){var A;let{sequentially:h,onTxUpdate:S,skipTxCount:w=0,recentBlockHash:T,skipPreflight:x=!0}=l||{},m=T!=null?T:yield se(this.connection,this.blockhashCommitment);if((A=this.owner)!=null&&A.isKeyPair){if(h){let b=[],k=0;for(let f of c){if(++k,k<=w)continue;let d=yield tt(this.connection,f,this.signers.find(p=>p.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:x});b.push(d)}return{txIds:b,signedTxs:c}}return{txIds:yield yield Promise.all(c.map(b=>g(this,null,function*(){return b.recentBlockhash=m,yield this.connection.sendRawTransaction(b.serialize(),{skipPreflight:x})}))),signedTxs:c}}if(this.signAllTransactions){let b=c.map((f,d)=>(f.recentBlockhash=m,o[d].length&&f.sign(...o[d]),f));ie(b);let k=yield this.signAllTransactions(b);if(h){let f=0,d=[],p=()=>g(this,null,function*(){if(!k[f])return;let P=yield this.connection.sendRawTransaction(k[f].serialize(),{skipPreflight:x});d.push({txId:P,status:"sent",signedTx:k[f]}),S==null||S([...d]),f++;let y=!1,C=null,R=null,D=B=>{C!==null&&clearInterval(C),R!==null&&this.connection.removeSignatureListener(R);let M=d.findIndex(L=>L.txId===P);if(M>-1){if(d[M].status==="error"||d[M].status==="success")return;d[M].status=B.err?"error":"success"}S==null||S([...d]),B.err||p()};this.loopMultiTxStatus&&(C=setInterval(()=>g(this,null,function*(){var B;if(y){clearInterval(C);return}try{let M=yield this.connection.getTransaction(P,{commitment:"confirmed",maxSupportedTransactionVersion:0});M&&(y=!0,clearInterval(C),D({err:((B=M.meta)==null?void 0:B.err)||null}),console.log("tx status from getTransaction:",P))}catch(M){y=!0,clearInterval(C),console.error("getTransaction timeout:",M,P)}}),Ee)),R=this.connection.onSignature(P,B=>{if(y){this.connection.removeSignatureListener(R);return}y=!0,D(B)},"confirmed"),this.connection.getSignatureStatus(P)});return yield p(),{txIds:d.map(P=>P.txId),signedTxs:k}}else{let f=[];for(let d=0;d<k.length;d+=1){let p=yield this.connection.sendRawTransaction(k[d].serialize(),{skipPreflight:x});f.push(p)}return{txIds:f,signedTxs:k}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:r||{}}}versionMultiBuild(i){return g(this,arguments,function*({extraPreBuildData:e,txVersion:n,extInfo:r}){return n===0?yield this.buildV0MultiTx({extraPreBuildData:e,buildProps:r||{}}):this.buildMultiTx({extraPreBuildData:e,extInfo:r})})}buildV0(e){return g(this,null,function*(){var x;let T=e||{},{lookupTableCache:n={},lookupTableAddress:r=[],forerunCreate:i,recentBlockhash:s}=T,c=we(T,["lookupTableCache","lookupTableAddress","forerunCreate","recentBlockhash"]),o=_(_({},this.cluster==="devnet"?{}:Oe),n),u=Array.from(new Set([...r,...this.lookupTableAddress])),a=[];for(let m of u)o[m]===void 0&&a.push(new ce(m));let l=yield et({connection:this.connection,address:a});for(let[m,A]of Object.entries(l))o[m]=A;let h=i?ce.default.toBase58():s!=null?s:yield se(this.connection,this.blockhashCommitment),S=new Te({payerKey:this.feePayer,recentBlockhash:h,instructions:[...this.allInstructions]}).compileToV0Message(Object.values(o));(x=this.owner)!=null&&x.signer&&!this.signers.some(m=>m.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer);let w=new be(S);return w.sign(this.signers),{builder:this,transaction:w,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:m=>g(this,null,function*(){var k;let{skipPreflight:A=!0,sendAndConfirm:b}=m||{};if(ie([w]),(k=this.owner)!=null&&k.isKeyPair){let f=yield this.connection.sendTransaction(w,{skipPreflight:A});return b&&(yield Le(this.connection,f)),{txId:f,signedTx:w}}if(this.signAllTransactions){let f=yield this.signAllTransactions([w]);if(this.signers.length)for(let d of f)try{d.sign(this.signers)}catch(p){}return{txId:yield this.connection.sendTransaction(f[0],{skipPreflight:A}),signedTx:f[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:c||{}}})}buildV0MultiTx(e){return g(this,null,function*(){var a;let{extraPreBuildData:n=[],buildProps:r}=e,{transaction:i}=yield this.buildV0(r),s=n.filter(l=>l.builder.instructions.length>0),c=[i,...s.map(l=>l.transaction)],o=[this.signers,...s.map(l=>l.signers)],u=[...this.instructionTypes,...s.map(l=>l.instructionTypes).flat()];return(a=this.owner)!=null&&a.signer&&o.forEach(l=>{l.some(h=>h.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),c.forEach((l,h)=>g(this,null,function*(){l.sign(o[h])})),{builder:this,transactions:c,signers:o,instructionTypes:u,buildProps:r,execute:l=>g(this,null,function*(){var x;let{sequentially:h,onTxUpdate:S,recentBlockHash:w,skipPreflight:T=!0}=l||{};if(w&&c.forEach(m=>m.message.recentBlockhash=w),ie(c),(x=this.owner)!=null&&x.isKeyPair){if(h){let m=[];for(let A of c){let b=yield this.connection.sendTransaction(A,{skipPreflight:T});yield Le(this.connection,b),m.push(b)}return{txIds:m,signedTxs:c}}return{txIds:yield Promise.all(c.map(m=>g(this,null,function*(){return yield this.connection.sendTransaction(m,{skipPreflight:T})}))),signedTxs:c}}if(this.signAllTransactions){let m=yield this.signAllTransactions(c);if(h){let A=0,b=[],k=()=>g(this,null,function*(){if(!m[A])return;let f=yield this.connection.sendTransaction(m[A],{skipPreflight:T});b.push({txId:f,status:"sent",signedTx:m[A]}),S==null||S([...b]),A++;let d=!1,p=null,P=null,y=C=>{p!==null&&clearInterval(p),P!==null&&this.connection.removeSignatureListener(P);let R=b.findIndex(D=>D.txId===f);if(R>-1){if(b[R].status==="error"||b[R].status==="success")return;b[R].status=C.err?"error":"success"}S==null||S([...b]),C.err||k()};this.loopMultiTxStatus&&(p=setInterval(()=>g(this,null,function*(){var C;if(d){clearInterval(p);return}try{let R=yield this.connection.getTransaction(f,{commitment:"confirmed",maxSupportedTransactionVersion:0});R&&(d=!0,clearInterval(p),y({err:((C=R.meta)==null?void 0:C.err)||null}),console.log("tx status from getTransaction:",f))}catch(R){d=!0,clearInterval(p),console.error("getTransaction timeout:",R,f)}}),Ee)),P=this.connection.onSignature(f,C=>{if(d){this.connection.removeSignatureListener(P);return}d=!0,y(C)},"confirmed"),this.connection.getSignatureStatus(f)});return k(),{txIds:[],signedTxs:m}}else{let A=[];for(let b=0;b<m.length;b+=1){let k=yield this.connection.sendTransaction(m[b],{skipPreflight:T});A.push(k)}return{txIds:A,signedTxs:m}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:r||{}}})}sizeCheckBuild(e){return g(this,null,function*(){var S;let h=e||{},{splitIns:n=[],computeBudgetConfig:r}=h,i=we(h,["splitIns","computeBudgetConfig"]),s=r?De(r):{instructions:[],instructionTypes:[]},c=this.signers.reduce((w,T)=>q(_({},w),{[T.publicKey.toBase58()]:T}),{}),o=[],u=[],a=[],l=0;if(this.allInstructions.forEach(w=>{let T=[...a,w],x=r?[...s.instructions,...T]:T,A=[...new Set(T.map(b=>b.keys.filter(k=>k.isSigner).map(k=>k.pubkey.toString())).flat()).values()].map(b=>new ce(b));if(w!==n[l]&&a.length<12&&(fe({instructions:x,payer:this.feePayer,signers:A})||fe({instructions:T,payer:this.feePayer,signers:A})))a.push(w);else{if(a.length===0)throw Error("item ins too big");l+=w===n[l]?1:0,fe({instructions:r?[...s.instructions,...a]:[...a],payer:this.feePayer,signers:A})?o.push(new he().add(...s.instructions,...a)):o.push(new he().add(...a)),u.push(Array.from(new Set(a.map(b=>b.keys.filter(k=>k.isSigner).map(k=>k.pubkey.toString())).flat())).map(b=>c[b]).filter(b=>b!==void 0)),a=[w]}}),a.length>0){let T=[...new Set(a.map(x=>x.keys.filter(m=>m.isSigner).map(m=>m.pubkey.toString())).flat()).values()].map(x=>c[x]).filter(x=>x!==void 0);fe({instructions:r?[...s.instructions,...a]:[...a],payer:this.feePayer,signers:T.map(x=>x.publicKey)})?o.push(new he().add(...s.instructions,...a)):o.push(new he().add(...a)),u.push(T)}return o.forEach(w=>w.feePayer=this.feePayer),(S=this.owner)!=null&&S.signer&&u.forEach(w=>{w.some(T=>T.publicKey.equals(this.owner.publicKey))||w.push(this.owner.signer)}),{builder:this,transactions:o,signers:u,instructionTypes:this.instructionTypes,execute:w=>g(this,null,function*(){var f;let{sequentially:T,onTxUpdate:x,skipTxCount:m=0,recentBlockHash:A,skipPreflight:b=!0}=w||{},k=A!=null?A:yield se(this.connection,this.blockhashCommitment);if(o.forEach((d,p)=>g(this,null,function*(){d.recentBlockhash=k,u[p].length&&d.sign(...u[p])})),ie(o),(f=this.owner)!=null&&f.isKeyPair){if(T){let d=0,p=[];for(let P of o){if(++d,d<=m){p.push("tx skipped");continue}let y=yield tt(this.connection,P,this.signers.find(C=>C.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:b});p.push(y)}return{txIds:p,signedTxs:o}}return{txIds:yield Promise.all(o.map(d=>g(this,null,function*(){return yield this.connection.sendRawTransaction(d.serialize(),{skipPreflight:b})}))),signedTxs:o}}if(this.signAllTransactions){let d=yield this.signAllTransactions(o.slice(m,o.length)),p=[...o.slice(0,m),...d];if(T){let P=0,y=[],C=()=>g(this,null,function*(){if(!p[P])return;P<m&&(y.push({txId:"",status:"success",signedTx:p[P]}),x==null||x([...y]),P++,C());let R=yield this.connection.sendRawTransaction(p[P].serialize(),{skipPreflight:b});y.push({txId:R,status:"sent",signedTx:p[P]}),x==null||x([...y]),P++;let D=!1,B=null,M=null,L=v=>{B!==null&&clearInterval(B),M!==null&&this.connection.removeSignatureListener(M);let V=y.findIndex(Q=>Q.txId===R);if(V>-1){if(y[V].status==="error"||y[V].status==="success")return;y[V].status=v.err?"error":"success"}x==null||x([...y]),v.err||C()};this.loopMultiTxStatus&&(B=setInterval(()=>g(this,null,function*(){var v;if(D){clearInterval(B);return}try{let V=yield this.connection.getTransaction(R,{commitment:"confirmed",maxSupportedTransactionVersion:0});V&&(D=!0,clearInterval(B),L({err:((v=V.meta)==null?void 0:v.err)||null}),console.log("tx status from getTransaction:",R))}catch(V){D=!0,clearInterval(B),console.error("getTransaction timeout:",V,R)}}),Ee)),M=this.connection.onSignature(R,v=>{if(D){this.connection.removeSignatureListener(M);return}D=!0,L(v)},"confirmed"),this.connection.getSignatureStatus(R)});return yield C(),{txIds:y.map(R=>R.txId),signedTxs:p}}else{let P=[];for(let y=0;y<p.length;y+=1){let C=yield this.connection.sendRawTransaction(p[y].serialize(),{skipPreflight:b});P.push(C)}return{txIds:P,signedTxs:p}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:i||{}}})}sizeCheckBuildV0(e){return g(this,null,function*(){var k;let b=e||{},{computeBudgetConfig:n,splitIns:r=[],lookupTableCache:i={},lookupTableAddress:s=[]}=b,c=we(b,["computeBudgetConfig","splitIns","lookupTableCache","lookupTableAddress"]),o=_(_({},this.cluster==="devnet"?{}:Oe),i),u=Array.from(new Set([...this.lookupTableAddress,...s])),a=[];for(let f of u)o[f]===void 0&&a.push(new ce(f));let l=yield et({connection:this.connection,address:a});for(let[f,d]of Object.entries(l))o[f]=d;let h=n?De(n):{instructions:[],instructionTypes:[]},S=yield se(this.connection,this.blockhashCommitment),w=this.signers.reduce((f,d)=>q(_({},f),{[d.publicKey.toBase58()]:d}),{}),T=[],x=[],m=[],A=0;if(this.allInstructions.forEach(f=>{let d=[...m,f],p=n?[...h.instructions,...d]:d;if(f!==r[A]&&m.length<12&&(ge({instructions:p,payer:this.feePayer,lookupTableAddressAccount:o})||ge({instructions:d,payer:this.feePayer,lookupTableAddressAccount:o})))m.push(f);else{if(m.length===0)throw Error("item ins too big");A+=f===r[A]?1:0;let P={};for(let y of[...new Set(u)])o[y]!==void 0&&(P[y]=o[y]);if(n&&ge({instructions:[...h.instructions,...m],payer:this.feePayer,lookupTableAddressAccount:o,recentBlockhash:S})){let y=new Te({payerKey:this.feePayer,recentBlockhash:S,instructions:[...h.instructions,...m]}).compileToV0Message(Object.values(o));T.push(new be(y))}else{let y=new Te({payerKey:this.feePayer,recentBlockhash:S,instructions:[...m]}).compileToV0Message(Object.values(o));T.push(new be(y))}x.push(Array.from(new Set(m.map(y=>y.keys.filter(C=>C.isSigner).map(C=>C.pubkey.toString())).flat())).map(y=>w[y]).filter(y=>y!==void 0)),m=[f]}}),m.length>0){let d=[...new Set(m.map(p=>p.keys.filter(P=>P.isSigner).map(P=>P.pubkey.toString())).flat()).values()].map(p=>w[p]).filter(p=>p!==void 0);if(n&&ge({instructions:[...h.instructions,...m],payer:this.feePayer,lookupTableAddressAccount:o,recentBlockhash:S})){let p=new Te({payerKey:this.feePayer,recentBlockhash:S,instructions:[...h.instructions,...m]}).compileToV0Message(Object.values(o));T.push(new be(p))}else{let p=new Te({payerKey:this.feePayer,recentBlockhash:S,instructions:[...m]}).compileToV0Message(Object.values(o));T.push(new be(p))}x.push(d)}return(k=this.owner)!=null&&k.signer&&x.forEach(f=>{f.some(d=>d.publicKey.equals(this.owner.publicKey))||f.push(this.owner.signer)}),{builder:this,transactions:T,buildProps:e,signers:x,instructionTypes:this.instructionTypes,execute:f=>g(this,null,function*(){var R;let{sequentially:d,onTxUpdate:p,skipTxCount:P=0,recentBlockHash:y,skipPreflight:C=!0}=f||{};if(T.map((D,B)=>g(this,null,function*(){x[B].length&&D.sign(x[B]),y&&(D.message.recentBlockhash=y)})),ie(T),(R=this.owner)!=null&&R.isKeyPair){if(d){let D=0,B=[];for(let M of T){if(++D,D<=P){console.log("skip tx: ",D),B.push("tx skipped");continue}let L=yield this.connection.sendTransaction(M,{skipPreflight:C});yield Le(this.connection,L),B.push(L)}return{txIds:B,signedTxs:T}}return{txIds:yield Promise.all(T.map(D=>g(this,null,function*(){return yield this.connection.sendTransaction(D,{skipPreflight:C})}))),signedTxs:T}}if(this.signAllTransactions){let D=yield this.signAllTransactions(T.slice(P,T.length)),B=[...T.slice(0,P),...D];if(d){let M=0,L=[],v=()=>g(this,null,function*(){if(!B[M])return;if(M<P){L.push({txId:"",status:"success",signedTx:B[M]}),p==null||p([...L]),M++,v();return}let V=yield this.connection.sendTransaction(B[M],{skipPreflight:C});L.push({txId:V,status:"sent",signedTx:B[M]}),p==null||p([...L]),M++;let Q=!1,oe=null,ye=null,nt=ee=>{oe!==null&&clearInterval(oe),ye!==null&&this.connection.removeSignatureListener(ye);let Y=L.findIndex(Wt=>Wt.txId===V);if(Y>-1){if(L[Y].status==="error"||L[Y].status==="success")return;L[Y].status=ee.err?"error":"success"}p==null||p([...L]),ee.err||v()};this.loopMultiTxStatus&&(oe=setInterval(()=>g(this,null,function*(){var ee;if(Q){clearInterval(oe);return}try{let Y=yield this.connection.getTransaction(V,{commitment:"confirmed",maxSupportedTransactionVersion:0});Y&&(Q=!0,clearInterval(oe),nt({err:((ee=Y.meta)==null?void 0:ee.err)||null}),console.log("tx status from getTransaction:",V))}catch(Y){Q=!0,clearInterval(oe),console.error("getTransaction timeout:",Y,V)}}),Ee)),ye=this.connection.onSignature(V,ee=>{if(Q){this.connection.removeSignatureListener(ye);return}Q=!0,nt(ee)},"confirmed"),this.connection.getSignatureStatus(V)});return v(),{txIds:[],signedTxs:B}}else{let M=[];for(let L=0;L<B.length;L+=1){let v=yield this.connection.sendTransaction(B[L],{skipPreflight:C});M.push(v)}return{txIds:M,signedTxs:B}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:c||{}}})}};import{Connection as En}from"@solana/web3.js";var Fn=(r=>(r.SonicMainnet="SonicMainnet",r.SonicTestnetV1="SonicTestnetV1",r.SolanaMainnet="SolanaMainnet",r))(Fn||{});function Ps(t,e=!0){return new En(e?Vn[t]:_n[t])}function Ss(t){return Wn[t]}var _n={SonicMainnet:"https://api.mainnet-alpha.sonic.game",SonicTestnetV1:"https://api.testnet.v1.sonic.game",SolanaMainnet:"https://api.mainnet-beta.solana.com"},Vn={SonicMainnet:"https://archival-mainnet.sonic.game",SonicTestnetV1:"https://archival-testnet.sonic.game",SolanaMainnet:"https://api.mainnet-beta.solana.com"},Wn={SonicMainnet:Ot,SonicTestnetV1:Ft,SolanaMainnet:Et};export{Xn as ACCOUNT_TYPE_SIZE,Yo as ALL_PROGRAM_ID,Yr as ANAMint,Zt as AccountType,ae as BNDivCeil,ro as BN_100,io as BN_1000,oo as BN_10000,no as BN_FIVE,Qi as BN_ONE,te as BN_TEN,to as BN_THREE,eo as BN_TWO,$ as BN_ZERO,Er as CLOCK_PROGRAM_ID,Dt as CREATE_CPMM_POOL_AUTH,Lt as CREATE_CPMM_POOL_FEE_ACC,Nt as CREATE_CPMM_POOL_PROGRAM,Ft as DEVNET_PROGRAM_ID,Bn as DEV_CREATE_CPMM_POOL_AUTH,In as DEV_CREATE_CPMM_POOL_FEE_ACC,Cn as DEV_CREATE_CPMM_POOL_PROGRAM,zr as ETHMint,Fr as INSTRUCTION_PROGRAM_ID,de as InstructionType,Oe as LOOKUP_TABLE_CACHE,Ut as LogLevel,_e as Logger,It as MAX_BASE64_SIZE,Dr as MEMO_PROGRAM_ID,Lr as MEMO_PROGRAM_ID2,Ye as METADATA_PROGRAM_ID,Hr as NRVMint,Fn as Network,St as Owner,Wr as PAIMint,Vr as RAYMint,Or as RENT_PROGRAM_ID,qe as Rounding,Mn as SOLANA_CPMM_POOL_AUTH,Nn as SOLANA_CPMM_POOL_FEE_ACC,Rn as SOLANA_CPMM_POOL_PROGRAM,Et as SOLANA_PROGRAM_ID,pe as SOLMint,Ot as SONIC_PROGRAM_ID,Kr as SRMMint,_r as SYSTEM_PROGRAM_ID,Vt as TxBuilder,At as TxVersion,vr as USD