@sega-so/sega-sdk
Version:
An SDK for building applications on top of SEGA.
1 lines • 51 kB
JavaScript
var Lt=Object.defineProperty,Et=Object.defineProperties;var Ot=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?Lt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,V=(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)=>Et(t,Ot(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 Oe,set as at}from"lodash";var Vt=(i=>(i[i.Error=0]="Error",i[i.Warning=1]="Warning",i[i.Info=2]="Info",i[i.Debug=3]="Debug",i))(Vt||{}),Ve=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}},We={},ct={};function v(t){let e=Oe(We,t);if(!e){let n=Oe(ct,t);e=new Ve({name:t,logLevel:n}),at(We,t,e)}return e}function En(t,e){at(ct,t,e);let n=Oe(We,t);n&&(n.level=e)}import{MINT_SIZE as Wt,TOKEN_PROGRAM_ID as Kt,getTransferFeeConfig as vt,unpackMint as _t}from"@solana/spl-token";var Ke=v("Sega_accountInfo_util");function _e(t,e,n){return g(this,null,function*(){let{batchRequest:r,commitment:i="confirmed",chunkCount:s=100}=V({batchRequest:!1},n),c=ve(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=ve(u,10);o=(yield(yield Promise.all(a.map(h=>g(this,null,function*(){return yield t._rpcBatchRequest(h)})))).flat()).map(h=>(h.error&&Ke.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:k}=S;return w.length!==2&&w[1]!=="base64"&&Ke.logWithError("info must be base64 encoded, RPC_ERROR"),{data:Buffer.from(w[0],"base64"),executable:T,lamports:x,owner:new ut(m),rentEpoch:k}}return null})))}else try{o=yield Promise.all(c.map(u=>t.getMultipleAccountsInfo(u,i)))}catch(u){u instanceof Error&&Ke.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${u.message}`)}return o.flat()})}function qt(t,e,n){return g(this,null,function*(){let r=yield _e(t,e.map(i=>i.pubkey),n);return e.map((i,s)=>q(V({},i),{accountInfo:r[s]}))})}var Ut=(r=>(r[r.Uninitialized=0]="Uninitialized",r[r.Mint=1]="Mint",r[r.Account=2]="Account",r))(Ut||{}),Gn=1;function jn(r){return g(this,arguments,function*({connection:t,mints:e,config:n}){var c,o,u;if(e.length===0)return{};let i=yield qt(t,e.map(a=>({pubkey:lt(a)})),n),s={};for(let a of i){if(!a.accountInfo||a.accountInfo.data.length<Wt){console.log("invalid mint account",a.pubkey.toBase58());continue}let l=_t(a.pubkey,a.accountInfo,(c=a.accountInfo)==null?void 0:c.owner);s[a.pubkey.toString()]=q(V({},l),{programId:((o=a.accountInfo)==null?void 0:o.owner)||Kt,feeConfig:(u=vt(l))!=null?u:void 0})}return s[ut.default.toBase58()]=s[Pe.toBase58()],s})}import E from"bn.js";import cn from"decimal.js";import Zt from"big.js";import J from"bn.js";import Gt from"toformat";var jt=Gt,ue=jt;import ke from"big.js";import Ht from"bn.js";import zt 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 K(t){let e=v("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=v("module/fraction"),Ue=ue(ke),me=ue(zt),Yt={0:me.ROUND_DOWN,1:me.ROUND_HALF_UP,2:me.ROUND_UP},Jt={0:ke.roundDown,1:ke.roundHalfUp,2:ke.roundUp},I=class t{constructor(e,n=new Ht(1)){this.numerator=K(e),this.denominator=K(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(K(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(K(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(K(e));return new t(this.numerator.mul(n.numerator),this.denominator.mul(n.denominator))}div(e){let n=e instanceof t?e:new t(K(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:Yt[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=Jt[r]||1,new Ue(this.numerator.toString()).div(this.denominator.toString()).toFormat(e,n)}isZero(){return this.numerator.isZero()}};var Xt=v("Sega_amount"),Ae=ue(Zt);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")):Xt.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=K(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=K(a),u=K(l)}o=o.mul(c),s=o.add(u)}super(s,c),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 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 Ae.DP=this.token.decimals,new Ae(this.numerator.toString()).div(this.denominator.toString()).toFormat(e)}},Be=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=K(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=K(a),u=K(l)}o=o.mul(c),s=o.add(u)}super(s,c),this.logger=v(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 Ae.DP=this.currency.decimals,new Ae(this.numerator.toString()).div(this.denominator.toString()).toFormat(e)}};import{PublicKey as $t}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as dt}from"@solana/spl-token";var ft={chainId:101,address:$t.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 Ye}from"@solana/web3.js";import{PublicKey as D,SystemProgram as gt,SYSVAR_RENT_PUBKEY as Qt}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as en}from"@solana/spl-token";function Ge({pubkey:t,isSigner:e=!1,isWritable:n=!0}){return{pubkey:t,isWritable:n,isSigner:e}}var kr=[Ge({pubkey:en,isWritable:!1}),Ge({pubkey:gt.programId,isWritable:!1}),Ge({pubkey:Qt,isWritable:!1})];function je({publicKey:t,transformSol:e}){let n=He(t.toString());if(n instanceof D)return e&&n.equals(pe)?Pe:n;if(e&&n.toString()===pe.toBase58())return Pe;if(typeof n=="string"){if(n===D.default.toBase58())return D.default;try{return new D(n)}catch(r){throw new Error("invalid public key")}}throw new Error("invalid public key")}function He(t){try{return new D(t)}catch(e){return t}}var Ar=new D("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),Br=new D("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),Cr=new D("SysvarRent111111111111111111111111111111111"),Ir=new D("SysvarC1ock11111111111111111111111111111111"),ze=new D("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),Nr=new D("Sysvar1nstructions1111111111111111111111111"),Rr=gt.programId,Dr=new D("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),Mr=new D("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),Fr=new D("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),Lr=new D("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),Er=new D("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),Or=new D("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),Vr=new D("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),Wr=new D("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),Kr=new D("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),vr=new D("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),_r=new D("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),Pe=new D("So11111111111111111111111111111111111111112"),pe=D.default;function lt(t){return je({publicKey:t,transformSol:!0})}var Ce=class Ce{constructor({mint:e,decimals:n,symbol:r,name:i,skipMint:s=!1,isToken2022:c=!1}){if(e===pe.toBase58()||e instanceof Ye&&pe.equals(e)){this.decimals=ne.decimals,this.symbol=ne.symbol,this.name=ne.name,this.mint=new Ye(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?Ye.default:je({publicKey:e}),this.isToken2022=c}equals(e){return this===e?!0:this.mint.equals(e.mint)}};Ce.WSOL=new Ce(q(V({},ne),{mint:ne.address}));var Z=Ce;var Ne=class Ne{constructor({decimals:e,symbol:n="UNKNOWN",name:r="UNKNOWN"}){this.decimals=e,this.symbol=n,this.name=r}equals(e){return this===e}};Ne.SOL=new Ne(ft);var Ie=Ne;import tn from"bn.js";var ht=new I(new tn(100)),U=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 nn=v("Sega_price"),G=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(Je(n.decimals),Je(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&&nn.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 L(t){if(t instanceof U)return new I(t.numerator,t.denominator);if(t instanceof G)return t.adjusted;if(t instanceof z)try{return L(t.toExact())}catch(r){return new I(X)}if(t instanceof I)return t;let e=String(t),n=re(e);return new I(n.numerator,n.denominator)}function Ti(t){var r;if(t instanceof U)return{fr:new I(t.numerator,t.denominator)};if(t instanceof G)return{fr:t.adjusted};if(t instanceof z)return{fr:L(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 bi(t,e){if(t==null||e==null)return!1;let n=L(t),r=L(e);return n.sub(r).numerator,n.sub(r).numerator.lt(X)}function rn(t,e){if(t==null||e==null)return!1;let n=L(t),r=L(e);return n.sub(r).numerator.gt(X)}function yi(t,e){if(t==null||e==null)return!1;let n=L(t),r=L(e);return n.sub(r).numerator.lte(X)}function xi(t,e){if(t==null||e==null)return!1;let n=L(t),r=L(e);return n.sub(r).numerator.gte(X)}function on(t,e){if(t==null||e==null)return!1;let n=L(t),r=L(e);return n.sub(r).numerator.eq(X)}function wi(t,e){if(t==null||e==null)return;let n=L(t),r=L(e);try{return n.div(r)}catch(i){return n}}function Pi(t,e){if(t==null||e==null)return;let n=L(t),r=L(e);return n.sub(r)}function Si(t){return t==null?!1:!on(t,0)}function ki(t,e){return rn(e,t)?e:t}function Ze(t,e){if(t==null||e==null)return;let n=L(t),r=L(e);return n.mul(r)}function Ai(t,e){if(t==null||e==null)return;let n=L(t),r=L(e);return n.add(r)}import{PublicKey as sn}from"@solana/web3.js";import an from"bn.js";function Di(t){return g(this,null,function*(){new Promise(e=>setTimeout(e,t))})}function Mi(){return new Date().getTime()}function Xe(t){return typeof t=="object"&&t!==null&&![Z,z,sn,I,an,G,U].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 X=new E(0),Hi=new E(1),zi=new E(2),Yi=new E(3),Ji=new E(5),te=new E(10),Zi=new E(100),Xi=new E(1e3),$i=new E(1e4);function Je(t){return te.pow(K(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 Qi(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 un(t){var r;let[,e="",n=""]=(r=t.toFixed(2).match(/(-?)(\d*)\.?(\d*)/))!=null?r:[];return`${e}${n}`}function ln(t,e=0){return t instanceof E?t:new E(un(xt(t).mul(te.pow(new E(String(e))))))}function xt(t){if(t instanceof U)return new I(t.numerator,t.denominator);if(t instanceof G)return t.adjusted;if(t instanceof z)try{return xt(t.toExact())}catch(r){return new I(X)}if(t instanceof I)return t;let e=String(t),n=re(e);return new I(n.numerator,n.denominator)}function eo(t,e){let{numerator:n,denominator:r}=re(t);return new U(new E(n),new E(r).mul(e!=null&&e.alreadyDecimaled?new E(100):new E(1)))}function to(t){let{token:e,numberPrice:n,decimalDone:r}=t,i=new Z({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 G({baseToken:i,denominator:u.toString(),quoteToken:new Z(q(V({},e),{skipMint:!0,mint:""})),numerator:o.toString()})}function bt(t){let e=new Ie({decimals:6,symbol:"usd",name:"usd"}),n=ln(Ze(t,st(10,e.decimals)));return new Be(e,n)}function no(t,e){return bt(!e||!t?0:Ze(t,e))}function mn(t){if(t==null)return;let{numerator:e,denominator:n}=re(t.toString());return new I(e,n)}function pn(t){return t instanceof cn}function yt(t){return pn(t)?mn(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,dn=t=>Pt(t).getTime();function oo(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 so(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 ao(t,e){let r=dn(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 ve(t,e=1,n=[]){let r=[...t];if(e<=0)return n;for(;r.length;)n.push(r.splice(0,e));return n}function uo(t,...e){return t.filter(n=>e.every(r=>r.includes(n)))}function lo(t,...e){return t.filter(n=>e.every(r=>!r.includes(n)))}function mo(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 bn}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as yn}from"@solana/spl-token";import{ComputeBudgetProgram as At,Keypair as Bt,PublicKey as Ct,Transaction as De,TransactionMessage as fn,VersionedTransaction as $e}from"@solana/web3.js";var kt=(n=>(n[n.V0=0]="V0",n[n.LEGACY=1]="LEGACY",n))(kt||{}),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 gn}from"@solana/spl-token";var Y=v("Sega_txUtil"),It=1644;function Me(t){let e=[],n=[];return t.microLamports&&(e.push(At.setComputeUnitPrice({microLamports:t.microLamports})),n.push(de.SetComputeUnitPrice)),t.units&&(e.push(At.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 Fe(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 Nt(t,e){t.length<1&&Y.logWithError(`no instructions provided: ${t.toString()}`),e.length<1&&Y.logWithError(`no signers provided:, ${e.toString()}`);let n=new De;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 Ao(t,e,n,r=!0){return g(this,null,function*(){let i=new Ct("SegaSimuLateTransaction11111111111111111"),s=[],c=new De;c.feePayer=i;for(let a of e)Nt([...c.instructions,a],[i])||(s.push(c),c=new De,c.feePayer=i),c.add(a);c.instructions.length>0&&s.push(c);let o=[];try{if(o=yield hn(t,s,r),o.find(a=>a.err!==null))throw Error("rpc simulateTransaction error")}catch(a){a instanceof Error&&Y.logWithError("failed to simulate for instructions","RPC_ERROR",{message:a.message})}let u=[];for(let a of o)if(Y.debug("simulate result:",a),a.logs){let l=a.logs.filter(h=>h&&h.includes(n));Y.debug("filteredLog:",u),l.length||Y.logWithError("simulate log not match keyword","keyword",n),u.push(...l)}return u})}function Bo(t,e){let n=t.match(/{["\w:,]+}/g);return!n||n.length!==1?Y.logWithError(`simulate log fail to match json, keyword: ${e}`):n[0]}function Co(t,e){let r=new RegExp(`"${e}":(\\d+)`,"g").exec(t);return!r||r.length!==2?Y.logWithError(`simulate log fail to match key", key: ${e}`):r[1]}function Qe(t,e){let[n,r]=Ct.findProgramAddressSync(t,e);return{publicKey:n,nonce:r}}function hn(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&&Y.logWithError("failed to get info for multiple accounts","RPC_ERROR",{message:i.message})}return r})}function fe({instructions:t,payer:e,signers:n}){return Nt(t,[e,...n])}function ge({instructions:t,payer:e,lookupTableAddressAccount:n,recentBlockhash:r=Bt.generate().publicKey.toString()}){let s=new fn({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 Re={time:0,data:void 0};function Io(t){return g(this,null,function*(){if(!Re.data||(Date.now()-Re.time)/1e3>30){let e=yield t.getEpochInfo();return Re={time:Date.now(),data:e},e}else return Re.data})}var Rt=t=>Buffer.isBuffer(t)?t:t instanceof Uint8Array?Buffer.from(t.buffer,t.byteOffset,t.byteLength):Buffer.from(t),Tn=t=>{let e=t.serialize({requireAllSignatures:!1,verifySignatures:!1});t instanceof $e&&(e=Rt(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 De&&(n.recentBlockhash||(n.recentBlockhash=gn.toBase58()),n.feePayer||(n.feePayer=Bt.generate().publicKey)),e.push(Tn(n))}),console.log("simulate tx string:",e),e}function No(t){let e=t.serialize({requireAllSignatures:!1,verifySignatures:!1});return t instanceof $e&&(e=Rt(e)),e.toString("base64")}function Oo(t,e,n){return Qe([t.toBuffer(),(n!=null?n:yn).toBuffer(),e.toBuffer()],new bn("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"))}function Vo(t){return Qe([Buffer.from("metadata","utf8"),ze.toBuffer(),t.toBuffer()],ze)}import{PublicKey as $}from"@solana/web3.js";var xn=new $("SegazTQwbYWknDZkJ6j2Kgvm5gw3MrHGKtWstZdoNKZ"),wn=new $("Ajk8d9bERSaFdeoT1d8JUVfaDayrYLnAdgeB47TFMUaG"),Pn=new $("2HbjxVVKJ7Ct72Rcd8WK4VTqmwTXL5aAggkH1CHGFGmh"),Sn=new $("auetiVUVJkRxvNPLYEvVnz8UJSqQ1VgoA83PcicHVD1"),kn=new $("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y"),An=new $("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y"),vo={CREATE_CPMM_POOL_PROGRAM:xn,CREATE_CPMM_POOL_AUTH:wn,CREATE_CPMM_POOL_FEE_ACC:Pn},_o={SERUM_MARKET:$.default,UTIL1216:$.default,CREATE_CPMM_POOL_PROGRAM:Sn,CREATE_CPMM_POOL_AUTH:kn,CREATE_CPMM_POOL_FEE_ACC:An};import O from"bn.js";var j=1e4;function Go(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 O(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===j){let o=new O(i.maximumFee.toString());return{amount:t.add(o),fee:o,expirationTime:c}}else{let o=ae(t.mul(new O(j)),new O(j-i.transferFeeBasisPoints)),u=new O(i.maximumFee.toString()),a=o.sub(t).gt(u)?t.add(u):o,l=ae(a.mul(new O(i.transferFeeBasisPoints)),new O(j)),h=l.gt(s)?s:l;return{amount:a,fee:h,expirationTime:c}}else{let o=ae(t.mul(new O(i.transferFeeBasisPoints)),new O(j)),u=o.gt(s)?s:o;return{amount:t,fee:u,expirationTime:c}}}function jo(t,e,n,r){if(e===void 0)return{amount:t,fee:void 0,expirationTime:void 0};let i=q(V({},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 O(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===j){let u=new O(s.maximumFee.toString());return{amount:t.add(u),fee:u,expirationTime:o}}else{let u=ae(t.mul(new O(j)),new O(j-s.transferFeeBasisPoints)),a=new O(s.maximumFee.toString()),l=u.sub(t).gt(a)?t.add(a):u,h=ae(l.mul(new O(s.transferFeeBasisPoints)),new O(j)),S=h.gt(c)?c:h;return{amount:l,fee:S,expirationTime:o}}else{let u=ae(t.mul(new O(s.transferFeeBasisPoints)),new O(j)),a=u.gt(c)?c:u;return{amount:t,fee:a,expirationTime:o}}}function Ho(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 O(0))?n.add(new O(1)):n}import{PublicKey as Bn,AddressLookupTableAccount as Dt}from"@solana/web3.js";function et(n){return g(this,arguments,function*({connection:t,address:e}){let r=yield _e(t,[...new Set(e.map(s=>s.toString()))].map(s=>new Bn(s))),i={};for(let s=0;s<e.length;s++){let c=r[s],o=e[s];if(!c)continue;let u=new Dt({key:o,state:Dt.deserialize(c.data)});i[o.toString()]=u,Le[o.toString()]=u}return i})}var Le={};import{PublicKey as ce,sendAndConfirmTransaction as tt,SystemProgram as Cn,Transaction as he,TransactionMessage as Te,VersionedTransaction as be}from"@solana/web3.js";import In from"axios";var Ee=2e3,Mt=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 In.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}=Me(e);return this.instructions.unshift(...n),this.instructionTypes.unshift(...r),!0}return!1}addTipInstruction(e){var n;return e?(this.endInstructions.push(Cn.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(V({},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 k;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((k=this.owner)!=null&&k.isKeyPair){if(h){let b=[],A=0;for(let f of c){if(++A,A<=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 A=yield this.signAllTransactions(b);if(h){let f=0,d=[],p=()=>g(this,null,function*(){if(!A[f])return;let P=yield this.connection.sendRawTransaction(A[f].serialize(),{skipPreflight:x});d.push({txId:P,status:"sent",signedTx:A[f]}),S==null||S([...d]),f++;let y=!1,B=null,N=null,M=C=>{B!==null&&clearInterval(B),N!==null&&this.connection.removeSignatureListener(N);let R=d.findIndex(F=>F.txId===P);if(R>-1){if(d[R].status==="error"||d[R].status==="success")return;d[R].status=C.err?"error":"success"}S==null||S([...d]),C.err||p()};this.loopMultiTxStatus&&(B=setInterval(()=>g(this,null,function*(){var C;if(y){clearInterval(B);return}try{let R=yield this.connection.getTransaction(P,{commitment:"confirmed",maxSupportedTransactionVersion:0});R&&(y=!0,clearInterval(B),M({err:((C=R.meta)==null?void 0:C.err)||null}),console.log("tx status from getTransaction:",P))}catch(R){y=!0,clearInterval(B),console.error("getTransaction timeout:",R,P)}}),Ee)),N=this.connection.onSignature(P,C=>{if(y){this.connection.removeSignatureListener(N);return}y=!0,M(C)},"confirmed"),this.connection.getSignatureStatus(P)});return yield p(),{txIds:d.map(P=>P.txId),signedTxs:A}}else{let f=[];for(let d=0;d<A.length;d+=1){let p=yield this.connection.sendRawTransaction(A[d].serialize(),{skipPreflight:x});f.push(p)}return{txIds:f,signedTxs:A}}}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=V(V({},this.cluster==="devnet"?{}:Le),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,k]of Object.entries(l))o[m]=k;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 A;let{skipPreflight:k=!0,sendAndConfirm:b}=m||{};if(ie([w]),(A=this.owner)!=null&&A.isKeyPair){let f=yield this.connection.sendTransaction(w,{skipPreflight:k});return b&&(yield Fe(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:k}),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 k of c){let b=yield this.connection.sendTransaction(k,{skipPreflight:T});yield Fe(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 k=0,b=[],A=()=>g(this,null,function*(){if(!m[k])return;let f=yield this.connection.sendTransaction(m[k],{skipPreflight:T});b.push({txId:f,status:"sent",signedTx:m[k]}),S==null||S([...b]),k++;let d=!1,p=null,P=null,y=B=>{p!==null&&clearInterval(p),P!==null&&this.connection.removeSignatureListener(P);let N=b.findIndex(M=>M.txId===f);if(N>-1){if(b[N].status==="error"||b[N].status==="success")return;b[N].status=B.err?"error":"success"}S==null||S([...b]),B.err||A()};this.loopMultiTxStatus&&(p=setInterval(()=>g(this,null,function*(){var B;if(d){clearInterval(p);return}try{let N=yield this.connection.getTransaction(f,{commitment:"confirmed",maxSupportedTransactionVersion:0});N&&(d=!0,clearInterval(p),y({err:((B=N.meta)==null?void 0:B.err)||null}),console.log("tx status from getTransaction:",f))}catch(N){d=!0,clearInterval(p),console.error("getTransaction timeout:",N,f)}}),Ee)),P=this.connection.onSignature(f,B=>{if(d){this.connection.removeSignatureListener(P);return}d=!0,y(B)},"confirmed"),this.connection.getSignatureStatus(f)});return A(),{txIds:[],signedTxs:m}}else{let k=[];for(let b=0;b<m.length;b+=1){let A=yield this.connection.sendTransaction(m[b],{skipPreflight:T});k.push(A)}return{txIds:k,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?Me(r):{instructions:[],instructionTypes:[]},c=this.signers.reduce((w,T)=>q(V({},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,k=[...new Set(T.map(b=>b.keys.filter(A=>A.isSigner).map(A=>A.pubkey.toString())).flat()).values()].map(b=>new ce(b));if(w!==n[l]&&a.length<12&&(fe({instructions:x,payer:this.feePayer,signers:k})||fe({instructions:T,payer:this.feePayer,signers:k})))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:k})?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(A=>A.isSigner).map(A=>A.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:k,skipPreflight:b=!0}=w||{},A=k!=null?k:yield se(this.connection,this.blockhashCommitment);if(o.forEach((d,p)=>g(this,null,function*(){d.recentBlockhash=A,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(B=>B.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=[],B=()=>g(this,null,function*(){if(!p[P])return;P<m&&(y.push({txId:"",status:"success",signedTx:p[P]}),x==null||x([...y]),P++,B());let N=yield this.connection.sendRawTransaction(p[P].serialize(),{skipPreflight:b});y.push({txId:N,status:"sent",signedTx:p[P]}),x==null||x([...y]),P++;let M=!1,C=null,R=null,F=_=>{C!==null&&clearInterval(C),R!==null&&this.connection.removeSignatureListener(R);let W=y.findIndex(Q=>Q.txId===N);if(W>-1){if(y[W].status==="error"||y[W].status==="success")return;y[W].status=_.err?"error":"success"}x==null||x([...y]),_.err||B()};this.loopMultiTxStatus&&(C=setInterval(()=>g(this,null,function*(){var _;if(M){clearInterval(C);return}try{let W=yield this.connection.getTransaction(N,{commitment:"confirmed",maxSupportedTransactionVersion:0});W&&(M=!0,clearInterval(C),F({err:((_=W.meta)==null?void 0:_.err)||null}),console.log("tx status from getTransaction:",N))}catch(W){M=!0,clearInterval(C),console.error("getTransaction timeout:",W,N)}}),Ee)),R=this.connection.onSignature(N,_=>{if(M){this.connection.removeSignatureListener(R);return}M=!0,F(_)},"confirmed"),this.connection.getSignatureStatus(N)});return yield B(),{txIds:y.map(N=>N.txId),signedTxs:p}}else{let P=[];for(let y=0;y<p.length;y+=1){let B=yield this.connection.sendRawTransaction(p[y].serialize(),{skipPreflight:b});P.push(B)}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 A;let b=e||{},{computeBudgetConfig:n,splitIns:r=[],lookupTableCache:i={},lookupTableAddress:s=[]}=b,c=we(b,["computeBudgetConfig","splitIns","lookupTableCache","lookupTableAddress"]),o=V(V({},this.cluster==="devnet"?{}:Le),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?Me(n):{instructions:[],instructionTypes:[]},S=yield se(this.connection,this.blockhashCommitment),w=this.signers.reduce((f,d)=>q(V({},f),{[d.publicKey.toBase58()]:d}),{}),T=[],x=[],m=[],k=0;if(this.allInstructions.forEach(f=>{let d=[...m,f],p=n?[...h.instructions,...d]:d;if(f!==r[k]&&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");k+=f===r[k]?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(B=>B.isSigner).map(B=>B.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(A=this.owner)!=null&&A.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 N;let{sequentially:d,onTxUpdate:p,skipTxCount:P=0,recentBlockHash:y,skipPreflight:B=!0}=f||{};if(T.map((M,C)=>g(this,null,function*(){x[C].length&&M.sign(x[C]),y&&(M.message.recentBlockhash=y)})),ie(T),(N=this.owner)!=null&&N.isKeyPair){if(d){let M=0,C=[];for(let R of T){if(++M,M<=P){console.log("skip tx: ",M),C.push("tx skipped");continue}let F=yield this.connection.sendTransaction(R,{skipPreflight:B});yield Fe(this.connection,F),C.push(F)}return{txIds:C,signedTxs:T}}return{txIds:yield Promise.all(T.map(M=>g(this,null,function*(){return yield this.connection.sendTransaction(M,{skipPreflight:B})}))),signedTxs:T}}if(this.signAllTransactions){let M=yield this.signAllTransactions(T.slice(P,T.length)),C=[...T.slice(0,P),...M];if(d){let R=0,F=[],_=()=>g(this,null,function*(){if(!C[R])return;if(R<P){F.push({txId:"",status:"success",signedTx:C[R]}),p==null||p([...F]),R++,_();return}let W=yield this.connection.sendTransaction(C[R],{skipPreflight:B});F.push({txId:W,status:"sent",signedTx:C[R]}),p==null||p([...F]),R++;let Q=!1,oe=null,ye=null,nt=ee=>{oe!==null&&clearInterval(oe),ye!==null&&this.connection.removeSignatureListener(ye);let H=F.findIndex(Ft=>Ft.txId===W);if(H>-1){if(F[H].status==="error"||F[H].status==="success")return;F[H].status=ee.err?"error":"success"}p==null||p([...F]),ee.err||_()};this.loopMultiTxStatus&&(oe=setInterval(()=>g(this,null,function*(){var ee;if(Q){clearInterval(oe);return}try{let H=yield this.connection.getTransaction(W,{commitment:"confirmed",maxSupportedTransactionVersion:0});H&&(Q=!0,clearInterval(oe),nt({err:((ee=H.meta)==null?void 0:ee.err)||null}),console.log("tx status from getTransaction:",W))}catch(H){Q=!0,clearInterval(oe),console.error("getTransaction timeout:",H,W)}}),Ee)),ye=this.connection.onSignature(W,ee=>{if(Q){this.connection.removeSignatureListener(ye);return}Q=!0,nt(ee)},"confirmed"),this.connection.getSignatureStatus(W)});return _(),{txIds:[],signedTxs:C}}else{let R=[];for(let F=0;F<C.length;F+=1){let _=yield this.connection.sendTransaction(C[F],{skipPreflight:B});R.push(_)}return{txIds:R,signedTxs:C}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:c||{}}})}};import{Connection as Nn}from"@solana/web3.js";var Rn=(n=>(n.SonicMainnet="SonicMainnet",n.SonicTestnetV1="SonicTestnetV1",n))(Rn||{});function fs(t,e=!0){let r=t==="SonicMainnet"?"SonicMainnet":"SonicTestnetV1";return new Nn(e?Mn[r]:Dn[r])}var Dn={SonicMainnet:"https://api.mainnet-alpha.sonic.game",SonicTestnetV1:"https://api.testnet.v1.sonic.game"},Mn={SonicMainnet:"https://archival-mainnet.sonic.game",SonicTestnetV1:"https://archival-testnet.sonic.game"};export{Gn as ACCOUNT_TYPE_SIZE,vo as ALL_PROGRAM_ID,vr as ANAMint,Ut as AccountType,ae as BNDivCeil,Zi as BN_100,Xi as BN_1000,$i as BN_10000,Ji as BN_FIVE,Hi as BN_ONE,te as BN_TEN,Yi as BN_THREE,zi as BN_TWO,X as BN_ZERO,Ir as CLOCK_PROGRAM_ID,wn as CREATE_CPMM_POOL_AUTH,Pn as CREATE_CPMM_POOL_FEE_ACC,xn as CREATE_CPMM_POOL_PROGRAM,_o as DEVNET_PROGRAM_ID,kn as DEV_CREATE_CPMM_POOL_AUTH,An as DEV_CREATE_CPMM_POOL_FEE_ACC,Sn as DEV_CREATE_CPMM_POOL_PROGRAM,_r as ETHMint,Nr as INSTRUCTION_PROGRAM_ID,de as InstructionType,Le as LOOKUP_TABLE_CACHE,Vt as LogLevel,Ve as Logger,It as MAX_BASE64_SIZE,Ar as MEMO_PROGRAM_ID,Br as MEMO_PROGRAM_ID2,ze as METADATA_PROGRAM_ID,Kr as NRVMint,Rn as Network,St as Owner,Mr as PAIMint,Dr as RAYMint,Cr as RENT_PROGRAM_ID,qe as Rounding,pe as SOLMint,Fr as SRMMint,Rr as SYSTEM_PROGRAM_ID,Mt as TxBuilder,kt as TxVersion,Lr as USDCMint,Wr as USDHMint,Er as USDTMint,Pe as WSOLMint,Ge as accountMeta,Ai as add,Me as addComputeBudget,fe as checkLegacyTxSize,ge as checkV0TxSize,ve as chunkArray,kr as commonSystemAccountMeta,Fe as confirmTransaction,v as createLogger,mn as decimalToFraction,wi as div,Qi as divCeil,on as eq,jn as fetchMultipleMintInfos,Qe as findProgramAddress,Nt as forecastTransactionSize,Oo as getATAAddress,fs as getConnection,Pt as getDate,Io as getEpochInfo,ki as getMax,_e as getMultipleAccountsInfo,qt as getMultipleAccountsInfoWithCustomFlags,et as getMultipleLookupTableInfo,Vo as getPdaMetadataKey,se as getRecentBlockHash,dn as getTime,Mi as get