@sega-so/sega-sdk
Version:
An SDK for building applications on top of SEGA.
1 lines • 116 kB
JavaScript
var qo=Object.defineProperty,Go=Object.defineProperties;var jo=Object.getOwnPropertyDescriptors;var gt=Object.getOwnPropertySymbols;var Mn=Object.prototype.hasOwnProperty,En=Object.prototype.propertyIsEnumerable;var te=Math.pow,Nn=(n,e,t)=>e in n?qo(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,K=(n,e)=>{for(var t in e||(e={}))Mn.call(e,t)&&Nn(n,t,e[t]);if(gt)for(var t of gt(e))En.call(e,t)&&Nn(n,t,e[t]);return n},N=(n,e)=>Go(n,jo(e));var ee=(n,e)=>{var t={};for(var o in n)Mn.call(n,o)&&e.indexOf(o)<0&&(t[o]=n[o]);if(n!=null&>)for(var o of gt(n))e.indexOf(o)<0&&En.call(n,o)&&(t[o]=n[o]);return t};var y=(n,e,t)=>new Promise((o,r)=>{var i=c=>{try{s(t.next(c))}catch(u){r(u)}},a=c=>{try{s(t.throw(c))}catch(u){r(u)}},s=c=>c.done?o(c.value):Promise.resolve(c.value).then(i,a);s((t=t.apply(n,e)).next())});import co from"axios";import{PublicKey as vn}from"@solana/web3.js";import{get as jt,set as Fn}from"lodash";var Ho=(r=>(r[r.Error=0]="Error",r[r.Warning=1]="Warning",r[r.Info=2]="Info",r[r.Debug=3]="Debug",r))(Ho||{}),Ht=class{constructor(e){this.logLevel=e.logLevel!==void 0?e.logLevel:0,this.name=e.name}set level(e){this.logLevel=e}get time(){return Date.now().toString()}get moduleName(){return this.name}isLogLevel(e){return e<=this.logLevel}error(...e){return this.isLogLevel(0)?(console.error(this.time,this.name,"sdk logger error",...e),this):this}logWithError(...e){let t=e.map(o=>typeof o=="object"?JSON.stringify(o):o).join(", ");throw new Error(t)}warning(...e){return this.isLogLevel(1)?(console.warn(this.time,this.name,"sdk logger warning",...e),this):this}info(...e){return this.isLogLevel(2)?(console.info(this.time,this.name,"sdk logger info",...e),this):this}debug(...e){return this.isLogLevel(3)?(console.debug(this.time,this.name,"sdk logger debug",...e),this):this}},zt={},Dn={};function U(n){let e=jt(zt,n);if(!e){let t=jt(Dn,n);e=new Ht({name:n,logLevel:t}),Fn(zt,n,e)}return e}function Ps(n,e){Fn(Dn,n,e);let t=jt(zt,n);t&&(t.level=e)}import{MINT_SIZE as zo,TOKEN_PROGRAM_ID as Yo,getTransferFeeConfig as Jo,unpackMint as $o}from"@solana/spl-token";var Yt=U("Sega_accountInfo_util");function Ge(n,e,t){return y(this,null,function*(){let{batchRequest:o,commitment:r="confirmed",chunkCount:i=100}=K({batchRequest:!1},t),a=Jt(e,i),s=new Array(a.length).fill([]);if(o){let c=a.map(l=>({methodName:"getMultipleAccounts",args:n._buildArgs([l.map(p=>p.toBase58())],r,"base64")})),u=Jt(c,10);s=(yield(yield Promise.all(u.map(l=>y(this,null,function*(){return yield n._rpcBatchRequest(l)})))).flat()).map(l=>(l.error&&Yt.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${l.error.message}`),l.result.value.map(d=>{if(d){let{data:p,executable:f,lamports:b,owner:g,rentEpoch:x}=d;return p.length!==2&&p[1]!=="base64"&&Yt.logWithError("info must be base64 encoded, RPC_ERROR"),{data:Buffer.from(p[0],"base64"),executable:f,lamports:b,owner:new vn(g),rentEpoch:x}}return null})))}else try{s=yield Promise.all(a.map(c=>n.getMultipleAccountsInfo(c,r)))}catch(c){c instanceof Error&&Yt.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${c.message}`)}return s.flat()})}function je(n,e,t){return y(this,null,function*(){let o=yield Ge(n,e.map(r=>r.pubkey),t);return e.map((r,i)=>N(K({},r),{accountInfo:o[i]}))})}var Zo=(o=>(o[o.Uninitialized=0]="Uninitialized",o[o.Mint=1]="Mint",o[o.Account=2]="Account",o))(Zo||{}),Ks=1;function Wn(o){return y(this,arguments,function*({connection:n,mints:e,config:t}){var a,s,c;if(e.length===0)return{};let r=yield je(n,e.map(u=>({pubkey:He(u)})),t),i={};for(let u of r){if(!u.accountInfo||u.accountInfo.data.length<zo){console.log("invalid mint account",u.pubkey.toBase58());continue}let m=$o(u.pubkey,u.accountInfo,(a=u.accountInfo)==null?void 0:a.owner);i[u.pubkey.toString()]=N(K({},m),{programId:((s=u.accountInfo)==null?void 0:s.owner)||Yo,feeConfig:(c=Jo(m))!=null?c:void 0})}return i[vn.default.toBase58()]=i[ne.toBase58()],i})}import Y from"bn.js";import gr from"decimal.js";import rr from"big.js";import we from"bn.js";import Xo from"toformat";var Qo=Xo,ze=Qo;import bt from"big.js";import er from"bn.js";import tr from"decimal.js-light";import Ye from"bn.js";var $t=(o=>(o[o.ROUND_DOWN=0]="ROUND_DOWN",o[o.ROUND_HALF_UP=1]="ROUND_HALF_UP",o[o.ROUND_UP=2]="ROUND_UP",o))($t||{}),Vn=9007199254740991;function Z(n){let e=U("Sega_parseBigNumberish");if(n instanceof Ye)return n;if(typeof n=="string"){if(n.match(/^-?[0-9]+$/))return new Ye(n);e.logWithError(`invalid BigNumberish string: ${n}`)}return typeof n=="number"?(n%1&&e.logWithError(`BigNumberish number underflow: ${n}`),(n>=Vn||n<=-Vn)&&e.logWithError(`BigNumberish number overflow: ${n}`),new Ye(String(n))):typeof n=="bigint"?new Ye(n.toString()):(e.error(`invalid BigNumberish value: ${n}`),new Ye(0))}var yt=U("module/fraction"),Zt=ze(bt),Je=ze(tr),nr={0:Je.ROUND_DOWN,1:Je.ROUND_HALF_UP,2:Je.ROUND_UP},or={0:bt.roundDown,1:bt.roundHalfUp,2:bt.roundUp},F=class n{constructor(e,t=new er(1)){this.numerator=Z(e),this.denominator=Z(t)}get quotient(){return this.numerator.div(this.denominator)}invert(){return new n(this.denominator,this.numerator)}add(e){let t=e instanceof n?e:new n(Z(e));return this.denominator.eq(t.denominator)?new n(this.numerator.add(t.numerator),this.denominator):new n(this.numerator.mul(t.denominator).add(t.numerator.mul(this.denominator)),this.denominator.mul(t.denominator))}sub(e){let t=e instanceof n?e:new n(Z(e));return this.denominator.eq(t.denominator)?new n(this.numerator.sub(t.numerator),this.denominator):new n(this.numerator.mul(t.denominator).sub(t.numerator.mul(this.denominator)),this.denominator.mul(t.denominator))}mul(e){let t=e instanceof n?e:new n(Z(e));return new n(this.numerator.mul(t.numerator),this.denominator.mul(t.denominator))}div(e){let t=e instanceof n?e:new n(Z(e));return new n(this.numerator.mul(t.denominator),this.denominator.mul(t.numerator))}toSignificant(e,t={groupSeparator:""},o=1){Number.isInteger(e)||yt.logWithError(`${e} is not an integer.`),e<=0&&yt.logWithError(`${e} is not positive.`),Je.set({precision:e+1,rounding:nr[o]});let r=new Je(this.numerator.toString()).div(this.denominator.toString()).toSignificantDigits(e);return r.toFormat(r.decimalPlaces(),t)}toFixed(e,t={groupSeparator:""},o=1){return Number.isInteger(e)||yt.logWithError(`${e} is not an integer.`),e<0&&yt.logWithError(`${e} is negative.`),Zt.DP=e,Zt.RM=or[o]||1,new Zt(this.numerator.toString()).div(this.denominator.toString()).toFormat(e,t)}isZero(){return this.numerator.isZero()}};var ir=U("Sega_amount"),ht=ze(rr);function Un(n,e){let t="0",o="0";if(n.includes(".")){let r=n.split(".");r.length===2?([t,o]=r,o=o.padEnd(e,"0")):ir.logWithError(`invalid number string, num: ${n}`)}else t=n;return[t,o.slice(0,e)||o]}var ae=class n extends F{constructor(e,t,o=!0,r){let i=new we(0),a=Ce.pow(new we(e.decimals));if(o)i=Z(t);else{let s=new we(0),c=new we(0);if(typeof t=="string"||typeof t=="number"||typeof t=="bigint"){let[u,m]=Un(t.toString(),e.decimals);s=Z(u),c=Z(m)}s=s.mul(a),i=s.add(c)}super(i,a),this.logger=U(r||"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 n(this.token,this.raw.add(e.raw))}subtract(e){return this.token.equals(e.token)||this.logger.logWithError("sub token not equals"),new n(this.token,this.raw.sub(e.raw))}toSignificant(e=this.token.decimals,t,o=0){return super.toSignificant(e,t,o)}toFixed(e=this.token.decimals,t,o=0){return e>this.token.decimals&&this.logger.logWithError("decimals overflow"),super.toFixed(e,t,o)}toExact(e={groupSeparator:""}){return ht.DP=this.token.decimals,new ht(this.numerator.toString()).div(this.denominator.toString()).toFormat(e)}},Tt=class n extends F{constructor(e,t,o=!0,r){let i=new we(0),a=Ce.pow(new we(e.decimals));if(o)i=Z(t);else{let s=new we(0),c=new we(0);if(typeof t=="string"||typeof t=="number"||typeof t=="bigint"){let[u,m]=Un(t.toString(),e.decimals);s=Z(u),c=Z(m)}s=s.mul(a),i=s.add(c)}super(i,a),this.logger=U(r||"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 n(this.currency,this.raw.add(e.raw))}sub(e){return this.currency.equals(e.currency)||this.logger.logWithError("sub currency not equals"),new n(this.currency,this.raw.sub(e.raw))}toSignificant(e=this.currency.decimals,t,o=0){return super.toSignificant(e,t,o)}toFixed(e=this.currency.decimals,t,o=0){return e>this.currency.decimals&&this.logger.logWithError("decimals overflow"),super.toFixed(e,t,o)}toExact(e={groupSeparator:""}){return ht.DP=this.currency.decimals,new ht(this.numerator.toString()).div(this.denominator.toString()).toFormat(e)}};import{PublicKey as sr}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as qn}from"@solana/spl-token";var le={chainId:101,address:sr.default.toBase58(),programId:qn.toBase58(),decimals:9,symbol:"SOL",name:"solana",logoURI:"https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"sega",extensions:{coingeckoId:"solana"}},re={chainId:101,address:"So11111111111111111111111111111111111111112",programId:qn.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 on}from"@solana/web3.js";import{PublicKey as q,SystemProgram as Gn,SYSVAR_RENT_PUBKEY as ar}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as ur}from"@solana/spl-token";function Xt({pubkey:n,isSigner:e=!1,isWritable:t=!0}){return{pubkey:n,isWritable:t,isSigner:e}}var ua=[Xt({pubkey:ur,isWritable:!1}),Xt({pubkey:Gn.programId,isWritable:!1}),Xt({pubkey:ar,isWritable:!1})];function Qt({publicKey:n,transformSol:e}){let t=en(n.toString());if(t instanceof q)return e&&t.equals($e)?ne:t;if(e&&t.toString()===$e.toBase58())return ne;if(typeof t=="string"){if(t===q.default.toBase58())return q.default;try{return new q(t)}catch(o){throw new Error("invalid public key")}}throw new Error("invalid public key")}function en(n){try{return new q(n)}catch(e){return n}}var ca=new q("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),tn=new q("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),nn=new q("SysvarRent111111111111111111111111111111111"),la=new q("SysvarC1ock11111111111111111111111111111111"),Ze=new q("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),ma=new q("Sysvar1nstructions1111111111111111111111111"),jn=Gn.programId,pa=new q("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),da=new q("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),fa=new q("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),ga=new q("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),ya=new q("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),ba=new q("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),ha=new q("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),Ta=new q("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),Pa=new q("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),Aa=new q("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),wa=new q("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),ne=new q("So11111111111111111111111111111111111111112"),$e=q.default;function He(n){return Qt({publicKey:n,transformSol:!0})}var Pt=class Pt{constructor({mint:e,decimals:t,symbol:o,name:r,skipMint:i=!1,isToken2022:a=!1}){if(e===$e.toBase58()||e instanceof on&&$e.equals(e)){this.decimals=re.decimals,this.symbol=re.symbol,this.name=re.name,this.mint=new on(re.address),this.isToken2022=!1;return}this.decimals=t,this.symbol=o||e.toString().substring(0,6),this.name=r||e.toString().substring(0,6),this.mint=i?on.default:Qt({publicKey:e}),this.isToken2022=a}equals(e){return this===e?!0:this.mint.equals(e.mint)}};Pt.WSOL=new Pt(N(K({},re),{mint:re.address}));var G=Pt;var wt=class wt{constructor({decimals:e,symbol:t="UNKNOWN",name:o="UNKNOWN"}){this.decimals=e,this.symbol=t,this.name=o}equals(e){return this===e}};wt.SOL=new wt(le);var At=wt;function Oa(n,e){return n instanceof G&&e instanceof G?n.equals(e):n instanceof G||e instanceof G?!1:n===e}import cr from"bn.js";var Hn=new F(new cr(100)),Q=class extends F{toSignificant(e=5,t,o){return this.mul(Hn).toSignificant(e,t,o)}toFixed(e=2,t,o){return this.mul(Hn).toFixed(e,t,o)}};var lr=U("Sega_price"),me=class n extends F{constructor(e){let{baseToken:t,quoteToken:o,numerator:r,denominator:i}=e;super(r,i),this.baseToken=t,this.quoteToken=o,this.scalar=new F(rn(t.decimals),rn(o.decimals))}get raw(){return new F(this.numerator,this.denominator)}get adjusted(){return super.mul(this.scalar)}invert(){return new n({baseToken:this.quoteToken,quoteToken:this.baseToken,denominator:this.numerator,numerator:this.denominator})}mul(e){this.quoteToken!==e.baseToken&&lr.logWithError("mul token not equals");let t=super.mul(e);return new n({baseToken:this.baseToken,quoteToken:e.quoteToken,denominator:t.denominator,numerator:t.numerator})}toSignificant(e=this.quoteToken.decimals,t,o){return this.adjusted.toSignificant(e,t,o)}toFixed(e=this.quoteToken.decimals,t,o){return this.adjusted.toFixed(e,t,o)}};function z(n){if(n instanceof Q)return new F(n.numerator,n.denominator);if(n instanceof me)return n.adjusted;if(n instanceof ae)try{return z(n.toExact())}catch(o){return new F(pe)}if(n instanceof F)return n;let e=String(n),t=Ke(e);return new F(t.numerator,t.denominator)}function Qa(n){var o;if(n instanceof Q)return{fr:new F(n.numerator,n.denominator)};if(n instanceof me)return{fr:n.adjusted};if(n instanceof ae)return{fr:z(n.toExact()),decimals:n.token.decimals};if(n instanceof F)return{fr:n};let e=String(n),t=Ke(e);return{fr:new F(t.numerator,t.denominator),decimals:(o=t.dec)==null?void 0:o.length}}function eu(n,e){if(n==null||e==null)return!1;let t=z(n),o=z(e);return t.sub(o).numerator,t.sub(o).numerator.lt(pe)}function mr(n,e){if(n==null||e==null)return!1;let t=z(n),o=z(e);return t.sub(o).numerator.gt(pe)}function tu(n,e){if(n==null||e==null)return!1;let t=z(n),o=z(e);return t.sub(o).numerator.lte(pe)}function nu(n,e){if(n==null||e==null)return!1;let t=z(n),o=z(e);return t.sub(o).numerator.gte(pe)}function pr(n,e){if(n==null||e==null)return!1;let t=z(n),o=z(e);return t.sub(o).numerator.eq(pe)}function ou(n,e){if(n==null||e==null)return;let t=z(n),o=z(e);try{return t.div(o)}catch(r){return t}}function ru(n,e){if(n==null||e==null)return;let t=z(n),o=z(e);return t.sub(o)}function iu(n){return n==null?!1:!pr(n,0)}function su(n,e){return mr(e,n)?e:n}function sn(n,e){if(n==null||e==null)return;let t=z(n),o=z(e);return t.mul(o)}function au(n,e){if(n==null||e==null)return;let t=z(n),o=z(e);return t.add(o)}import{PublicKey as dr}from"@solana/web3.js";import fr from"bn.js";function Yn(n){return y(this,null,function*(){new Promise(e=>setTimeout(e,n))})}function du(){return new Date().getTime()}function an(n){return typeof n=="object"&&n!==null&&![G,ae,dr,F,fr,me,Q].some(e=>typeof e=="object"&&n instanceof e)}function zn(n){return typeof n=="string"?en(n):Array.isArray(n)?n.map(e=>zn(e)):an(n)?Object.fromEntries(Object.entries(n).map(([e,t])=>[e,zn(t)])):n}var pe=new Y(0),Bu=new Y(1),Cu=new Y(2),Ku=new Y(3),Lu=new Y(5),Ce=new Y(10),_u=new Y(100),Ou=new Y(1e3),Ru=new Y(1e4);function rn(n){return Ce.pow(Z(n))}function Ke(n){var s;if(n===void 0)return{denominator:"1",numerator:"0"};if(n instanceof Y)return{numerator:n.toString(),denominator:"1"};if(n instanceof F)return{denominator:n.denominator.toString(),numerator:n.numerator.toString()};let e=String(n),[,t="",o="",r=""]=(s=e.replace(",","").match(/(-?)(\d*)\.?(\d*)/))!=null?s:[],i="1"+"0".repeat(r.length),a=t+(o==="0"?"":o)+r||"0";return{denominator:i,numerator:a,sign:t,int:o,dec:r}}function Nu(n,e){let t=n.divmod(e);return t.mod.isZero()?t.div:t.div.isNeg()?t.div.isubn(1):t.div.iaddn(1)}function yr(n){var o;let[,e="",t=""]=(o=n.toFixed(2).match(/(-?)(\d*)\.?(\d*)/))!=null?o:[];return`${e}${t}`}function br(n,e=0){return n instanceof Y?n:new Y(yr(Zn(n).mul(Ce.pow(new Y(String(e))))))}function Zn(n){if(n instanceof Q)return new F(n.numerator,n.denominator);if(n instanceof me)return n.adjusted;if(n instanceof ae)try{return Zn(n.toExact())}catch(o){return new F(pe)}if(n instanceof F)return n;let e=String(n),t=Ke(e);return new F(t.numerator,t.denominator)}function Mu(n,e){let{numerator:t,denominator:o}=Ke(n);return new Q(new Y(t),new Y(o).mul(e!=null&&e.alreadyDecimaled?new Y(100):new Y(1)))}function Eu(n){let{token:e,numberPrice:t,decimalDone:o}=n,r=new G({mint:"",decimals:6,symbol:"usd",name:"usd",skipMint:!0}),{numerator:i,denominator:a}=Ke(t),s=o?new Y(i).mul(Ce.pow(new Y(e.decimals))):i,c=new Y(a).mul(Ce.pow(new Y(r.decimals)));return new me({baseToken:r,denominator:c.toString(),quoteToken:new G(N(K({},e),{skipMint:!0,mint:""})),numerator:s.toString()})}function Jn(n){let e=new At({decimals:6,symbol:"usd",name:"usd"}),t=br(sn(n,te(10,e.decimals)));return new Tt(e,t)}function Fu(n,e){return Jn(!e||!n?0:sn(n,e))}function hr(n){if(n==null)return;let{numerator:e,denominator:t}=Ke(n.toString());return new F(e,t)}function Tr(n){return n instanceof gr}function $n(n){return Tr(n)?hr(n):Array.isArray(n)?n.map(e=>$n(e)):an(n)?Object.fromEntries(Object.entries(n).map(([e,t])=>[e,$n(t)])):n}var Xn=n=>typeof n=="number",Qn=n=>n?new Date(n):new Date,Pr=n=>Qn(n).getTime();function Wu(n,e,t){let o=Xn(e)?e*((t==null?void 0:t.unit)==="s"?1e3:1):e;return new Date(n).getTime()<=+o}function Vu(n,e,t){let o=Xn(e)?e*((t==null?void 0:t.unit)==="s"?1e3:1):e;return new Date(n).getTime()>+o}function Uu(n,e){let o=Pr(n)+(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 Qn(o)}function Jt(n,e=1,t=[]){let o=[...n];if(e<=0)return t;for(;o.length;)t.push(o.splice(0,e));return t}function Gu(n,...e){return n.filter(t=>e.every(o=>o.includes(t)))}function ju(n,...e){return n.filter(t=>e.every(o=>!o.includes(t)))}function Hu(n){return[...new Set(n)]}var Xe=class n{constructor(e){this._owner=e}get publicKey(){return n.isKeyPair(this._owner)?this._owner.publicKey:this._owner}get signer(){return n.isKeyPair(this._owner)?this._owner:void 0}get isKeyPair(){return n.isKeyPair(this._owner)}get isPublicKey(){return n.isPublicKey(this._owner)}static isKeyPair(e){return e.secretKey!==void 0}static isPublicKey(e){return!n.isKeyPair(e)}};import{PublicKey as Ir}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as Sr}from"@solana/spl-token";import{ComputeBudgetProgram as to,Keypair as no,PublicKey as oo,Transaction as kt,TransactionMessage as Ar,VersionedTransaction as un}from"@solana/web3.js";var eo=(t=>(t[t.V0=0]="V0",t[t.LEGACY=1]="LEGACY",t))(eo||{}),v={CreateAccount:"CreateAccount",InitAccount:"InitAccount",CreateATA:"CreateATA",CloseAccount:"CloseAccount",TransferAmount:"TransferAmount",InitMint:"InitMint",MintTo:"MintTo",InitMarket:"InitMarket",Util1216OwnerClaim:"Util1216OwnerClaim",SetComputeUnitPrice:"SetComputeUnitPrice",SetComputeUnitLimit:"SetComputeUnitLimit",ClmmCreatePool:"ClmmCreatePool",ClmmOpenPosition:"ClmmOpenPosition",ClmmIncreasePosition:"ClmmIncreasePosition",ClmmDecreasePosition:"ClmmDecreasePosition",ClmmClosePosition:"ClmmClosePosition",ClmmSwapBaseIn:"ClmmSwapBaseIn",ClmmSwapBaseOut:"ClmmSwapBaseOut",ClmmInitReward:"ClmmInitReward",ClmmSetReward:"ClmmSetReward",ClmmCollectReward:"ClmmCollectReward",ClmmLockPosition:"ClmmLockPosition",ClmmHarvestLockPosition:"ClmmHarvestLockPosition",AmmV4Swap:"AmmV4Swap",AmmV4AddLiquidity:"AmmV4AddLiquidity",AmmV4RemoveLiquidity:"AmmV4RemoveLiquidity",AmmV4SimulatePoolInfo:"AmmV4SimulatePoolInfo",AmmV4SwapBaseIn:"AmmV4SwapBaseIn",AmmV4SwapBaseOut:"AmmV4SwapBaseOut",AmmV4CreatePool:"AmmV4CreatePool",AmmV4InitPool:"AmmV4InitPool",AmmV5AddLiquidity:"AmmV5AddLiquidity",AmmV5RemoveLiquidity:"AmmV5RemoveLiquidity",AmmV5SimulatePoolInfo:"AmmV5SimulatePoolInfo",AmmV5SwapBaseIn:"AmmV5SwapBaseIn",AmmV5SwapBaseOut:"AmmV5SwapBaseOut",RouteSwap:"RouteSwap",RouteSwap1:"RouteSwap1",RouteSwap2:"RouteSwap2",FarmV3Deposit:"FarmV3Deposit",FarmV3Withdraw:"FarmV3Withdraw",FarmV3CreateLedger:"FarmV3CreateLedger",FarmV4Withdraw:"FarmV4Withdraw",FarmV5Deposit:"FarmV5Deposit",FarmV5Withdraw:"FarmV5Withdraw",FarmV5CreateLedger:"FarmV5CreateLedger",FarmV6Deposit:"FarmV6Deposit",FarmV6Withdraw:"FarmV6Withdraw",FarmV6Create:"FarmV6Create",FarmV6Restart:"FarmV6Restart",FarmV6CreatorAddReward:"FarmV6CreatorAddReward",FarmV6CreatorWithdraw:"FarmV6CreatorWithdraw",CpmmCreatePool:"CpmmCreatePool",CpmmAddLiquidity:"CpmmAddLiquidity",CpmmWithdrawLiquidity:"CpmmWithdrawLiquidity",CpmmSwapBaseIn:"CpmmSwapBaseIn",CpmmSwapBaseOut:"CpmmSwapBaseOut",CpmmLockLp:"CpmmLockLp",CpmmCollectLockFee:"CpmmCollectLockFee",TransferTip:"TransferTip"};import{TOKEN_PROGRAM_ID as wr}from"@solana/spl-token";var he=U("Sega_txUtil"),ro=1644;function It(n){let e=[],t=[];return n.microLamports&&(e.push(to.setComputeUnitPrice({microLamports:n.microLamports})),t.push(v.SetComputeUnitPrice)),n.units&&(e.push(to.setComputeUnitLimit({units:n.units})),t.push(v.SetComputeUnitLimit)),{instructions:e,instructionTypes:t}}function Ee(n,e){return y(this,null,function*(){var o,r;let t=e!=null?e:"confirmed";return(r=yield(o=n.getLatestBlockhash)==null?void 0:o.call(n,{commitment:t}))==null?void 0:r.blockhash})}function St(n,e){return y(this,null,function*(){return n.getSignatureStatuses([e]),new Promise((t,o)=>{let r=setTimeout(o,6e4);n.onSignature(e,i=>{if(clearTimeout(r),!i.err){t("");return}o(Object.assign(i.err,{txId:e}))},"confirmed")})})}function Bt(n,e){n.length<1&&he.logWithError(`no instructions provided: ${n.toString()}`),e.length<1&&he.logWithError(`no signers provided:, ${e.toString()}`);let t=new kt;t.recentBlockhash="11111111111111111111111111111111",t.feePayer=e[0],t.add(...n);try{return Buffer.from(t.serialize({verifySignatures:!1})).toString("base64").length<ro}catch(o){return!1}}function ic(n,e,t,o=!0){return y(this,null,function*(){let r=new oo("SegaSimuLateTransaction11111111111111111"),i=[],a=new kt;a.feePayer=r;for(let u of e)Bt([...a.instructions,u],[r])||(i.push(a),a=new kt,a.feePayer=r),a.add(u);a.instructions.length>0&&i.push(a);let s=[];try{if(s=yield xr(n,i,o),s.find(u=>u.err!==null))throw Error("rpc simulateTransaction error")}catch(u){u instanceof Error&&he.logWithError("failed to simulate for instructions","RPC_ERROR",{message:u.message})}let c=[];for(let u of s)if(he.debug("simulate result:",u),u.logs){let m=u.logs.filter(l=>l&&l.includes(t));he.debug("filteredLog:",c),m.length||he.logWithError("simulate log not match keyword","keyword",t),c.push(...m)}return c})}function sc(n,e){let t=n.match(/{["\w:,]+}/g);return!t||t.length!==1?he.logWithError(`simulate log fail to match json, keyword: ${e}`):t[0]}function ac(n,e){let o=new RegExp(`"${e}":(\\d+)`,"g").exec(n);return!o||o.length!==2?he.logWithError(`simulate log fail to match key", key: ${e}`):o[1]}function oe(n,e){let[t,o]=oo.findProgramAddressSync(n,e);return{publicKey:t,nonce:o}}function xr(n,e,t){return y(this,null,function*(){let o=[];if(t){let r=yield n.getLatestBlockhash(),i=[];for(let u of e){u.recentBlockhash=r.blockhash,u.lastValidBlockHeight=r.lastValidBlockHeight;let l=u._compile().serialize(),p=u._serialize(l).toString("base64");i.push(p)}let a=i.map(u=>({methodName:"simulateTransaction",args:n._buildArgs([u],void 0,"base64")})),s=[],c=20;for(let u=0;u<Math.ceil(a.length/c);u++)s.push(a.slice(u*c,(u+1)*c));o=yield(yield Promise.all(s.map(u=>y(this,null,function*(){return(yield n._rpcBatchRequest(u)).map(m=>m.result.value)})))).flat()}else try{o=yield Promise.all(e.map(r=>y(this,null,function*(){return yield(yield n.simulateTransaction(r)).value})))}catch(r){r instanceof Error&&he.logWithError("failed to get info for multiple accounts","RPC_ERROR",{message:r.message})}return o})}function Qe({instructions:n,payer:e,signers:t}){return Bt(n,[e,...t])}function et({instructions:n,payer:e,lookupTableAddressAccount:t,recentBlockhash:o=no.generate().publicKey.toString()}){let i=new Ar({payerKey:e,recentBlockhash:o,instructions:n}).compileToV0Message(Object.values(t!=null?t:{}));try{return Buffer.from(new un(i).serialize()).toString("base64").length<ro}catch(a){return!1}}var xt={time:0,data:void 0};function uc(n){return y(this,null,function*(){if(!xt.data||(Date.now()-xt.time)/1e3>30){let e=yield n.getEpochInfo();return xt={time:Date.now(),data:e},e}else return xt.data})}var io=n=>Buffer.isBuffer(n)?n:n instanceof Uint8Array?Buffer.from(n.buffer,n.byteOffset,n.byteLength):Buffer.from(n),kr=n=>{let e=n.serialize({requireAllSignatures:!1,verifySignatures:!1});n instanceof un&&(e=io(e));try{return e instanceof Buffer?e.toString("base64"):Buffer.from(e).toString("base64")}catch(t){return e.toString("base64")}};function Le(n){let e=[];return n.forEach(t=>{t instanceof kt&&(t.recentBlockhash||(t.recentBlockhash=wr.toBase58()),t.feePayer||(t.feePayer=no.generate().publicKey)),e.push(kr(t))}),console.log("simulate tx string:",e),e}function cc(n){let e=n.serialize({requireAllSignatures:!1,verifySignatures:!1});return n instanceof un&&(e=io(e)),e.toString("base64")}function de(n,e,t){return oe([n.toBuffer(),(t!=null?t:Sr).toBuffer(),e.toBuffer()],new Ir("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"))}function so(n){return oe([Buffer.from("metadata","utf8"),Ze.toBuffer(),n.toBuffer()],Ze)}import{PublicKey as xe}from"@solana/web3.js";var cn=new xe("SegazTQwbYWknDZkJ6j2Kgvm5gw3MrHGKtWstZdoNKZ"),ln=new xe("Ajk8d9bERSaFdeoT1d8JUVfaDayrYLnAdgeB47TFMUaG"),Br=new xe("2HbjxVVKJ7Ct72Rcd8WK4VTqmwTXL5aAggkH1CHGFGmh"),Cr=new xe("auetiVUVJkRxvNPLYEvVnz8UJSqQ1VgoA83PcicHVD1"),Kr=new xe("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y"),Lr=new xe("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y"),hc={CREATE_CPMM_POOL_PROGRAM:cn,CREATE_CPMM_POOL_AUTH:ln,CREATE_CPMM_POOL_FEE_ACC:Br},Tc={SERUM_MARKET:xe.default,UTIL1216:xe.default,CREATE_CPMM_POOL_PROGRAM:Cr,CREATE_CPMM_POOL_AUTH:Kr,CREATE_CPMM_POOL_FEE_ACC:Lr};import J from"bn.js";var fe=1e4;function wc(n,e,t,o){if(e===void 0)return{amount:n,fee:void 0,expirationTime:void 0};let r=t.epoch<e.newerTransferFee.epoch?e.olderTransferFee:e.newerTransferFee,i=new J(r.maximumFee.toString()),a=t.epoch<e.newerTransferFee.epoch?(Number(e.newerTransferFee.epoch)*t.slotsInEpoch-t.absoluteSlot)*400/1e3:void 0;if(o)if(r.transferFeeBasisPoints===fe){let s=new J(r.maximumFee.toString());return{amount:n.add(s),fee:s,expirationTime:a}}else{let s=Te(n.mul(new J(fe)),new J(fe-r.transferFeeBasisPoints)),c=new J(r.maximumFee.toString()),u=s.sub(n).gt(c)?n.add(c):s,m=Te(u.mul(new J(r.transferFeeBasisPoints)),new J(fe)),l=m.gt(i)?i:m;return{amount:u,fee:l,expirationTime:a}}else{let s=Te(n.mul(new J(r.transferFeeBasisPoints)),new J(fe)),c=s.gt(i)?i:s;return{amount:n,fee:c,expirationTime:a}}}function _e(n,e,t,o){if(e===void 0)return{amount:n,fee:void 0,expirationTime:void 0};let r=N(K({},e),{olderTransferFee:{epoch:BigInt(e.olderTransferFee.epoch),maximumFee:BigInt(e.olderTransferFee.maximumFee),transferFeeBasisPoints:e.olderTransferFee.transferFeeBasisPoints},newerTransferFee:{epoch:BigInt(e.newerTransferFee.epoch),maximumFee:BigInt(e.newerTransferFee.maximumFee),transferFeeBasisPoints:e.newerTransferFee.transferFeeBasisPoints}}),i=t.epoch<r.newerTransferFee.epoch?r.olderTransferFee:r.newerTransferFee,a=new J(i.maximumFee.toString()),s=t.epoch<r.newerTransferFee.epoch?(Number(r.newerTransferFee.epoch)*t.slotsInEpoch-t.absoluteSlot)*400/1e3:void 0;if(o)if(i.transferFeeBasisPoints===fe){let c=new J(i.maximumFee.toString());return{amount:n.add(c),fee:c,expirationTime:s}}else{let c=Te(n.mul(new J(fe)),new J(fe-i.transferFeeBasisPoints)),u=new J(i.maximumFee.toString()),m=c.sub(n).gt(u)?n.add(u):c,l=Te(m.mul(new J(i.transferFeeBasisPoints)),new J(fe)),d=l.gt(a)?a:l;return{amount:m,fee:d,expirationTime:s}}else{let c=Te(n.mul(new J(i.transferFeeBasisPoints)),new J(fe)),u=c.gt(a)?a:c;return{amount:n,fee:u,expirationTime:s}}}function xc(n,e){return n===void 0?e:e===void 0?n:Math.min(n,e)}function Te(n,e){let{div:t,mod:o}=n.divmod(e);return o.gt(new J(0))?t.add(new J(1)):t}import{PublicKey as _r,AddressLookupTableAccount as ao}from"@solana/web3.js";function mn(t){return y(this,arguments,function*({connection:n,address:e}){let o=yield Ge(n,[...new Set(e.map(i=>i.toString()))].map(i=>new _r(i))),r={};for(let i=0;i<e.length;i++){let a=o[i],s=e[i];if(!a)continue;let c=new ao({key:s,state:ao.deserialize(a.data)});r[s.toString()]=c,Ct[s.toString()]=c}return r})}var Ct={};import{PublicKey as Fe,sendAndConfirmTransaction as pn,SystemProgram as Or,Transaction as tt,TransactionMessage as nt,VersionedTransaction as ot}from"@solana/web3.js";import Rr from"axios";var Kt=2e3,Lt=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 y(this,null,function*(){var o;let e=(yield Rr.get("https://solanacompass.com/api/fees?cacheFreshTime=300000")).data,{avg:t}=(o=e==null?void 0:e[15])!=null?o:{};if(t)return{units:6e5,microLamports:Math.min(Math.ceil(t*1e6/6e5),25e3)}})}addCustomComputeBudget(e){if(e){let{instructions:t,instructionTypes:o}=It(e);return this.instructions.unshift(...t),this.instructionTypes.unshift(...o),!0}return!1}addTipInstruction(e){var t;return e?(this.endInstructions.push(Or.transfer({fromPubkey:(t=e.feePayer)!=null?t:this.feePayer,toPubkey:new Fe(e.address),lamports:BigInt(e.amount.toString())})),this.endInstructionTypes.push(v.TransferTip),!0):!1}calComputeBudget(o){return y(this,arguments,function*({config:e,defaultIns:t}){try{let r=e||(yield this.getComputeBudgetConfig());if(this.addCustomComputeBudget(r))return;t&&this.instructions.unshift(...t)}catch(r){t&&this.instructions.unshift(...t)}})}addInstruction({instructions:e=[],endInstructions:t=[],signers:o=[],instructionTypes:r=[],endInstructionTypes:i=[],lookupTableAddress:a=[]}){return this.instructions.push(...e),this.endInstructions.push(...t),this.signers.push(...o),this.instructionTypes.push(...r),this.endInstructionTypes.push(...i),this.lookupTableAddress.push(...a.filter(s=>s!==Fe.default.toString())),this}versionBuild(o){return y(this,arguments,function*({txVersion:e,extInfo:t}){return e===0?yield this.buildV0(K({},t||{})):this.build(t)})}build(e){var o;let t=new tt;return this.allInstructions.length&&t.add(...this.allInstructions),t.feePayer=this.feePayer,(o=this.owner)!=null&&o.signer&&!this.signers.some(r=>r.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer),{builder:this,transaction:t,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:r=>y(this,null,function*(){var u;let{recentBlockHash:i,skipPreflight:a=!0,sendAndConfirm:s}=r||{},c=i!=null?i:yield Ee(this.connection,this.blockhashCommitment);if(t.recentBlockhash=c,this.signers.length&&t.sign(...this.signers),Le([t]),(u=this.owner)!=null&&u.isKeyPair)return{txId:s?yield pn(this.connection,t,this.signers.find(l=>l.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:a}):yield this.connection.sendRawTransaction(t.serialize(),{skipPreflight:a}),signedTx:t};if(this.signAllTransactions){let m=yield this.signAllTransactions([t]);if(this.signers.length)for(let l of m)try{l.sign(...this.signers)}catch(d){}return{txId:yield this.connection.sendRawTransaction(m[0].serialize(),{skipPreflight:a}),signedTx:m[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:e||{}}}buildMultiTx(e){var u;let{extraPreBuildData:t=[],extInfo:o}=e,{transaction:r}=this.build(o),i=t.filter(m=>m.transaction.instructions.length>0),a=[r,...i.map(m=>m.transaction)],s=[this.signers,...i.map(m=>m.signers)],c=[...this.instructionTypes,...i.map(m=>m.instructionTypes).flat()];return(u=this.owner)!=null&&u.signer&&s.forEach(m=>{m.some(l=>l.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),{builder:this,transactions:a,signers:s,instructionTypes:c,execute:m=>y(this,null,function*(){var x;let{sequentially:l,onTxUpdate:d,skipTxCount:p=0,recentBlockHash:f,skipPreflight:b=!0}=m||{},g=f!=null?f:yield Ee(this.connection,this.blockhashCommitment);if((x=this.owner)!=null&&x.isKeyPair){if(l){let h=[],A=0;for(let T of a){if(++A,A<=p)continue;let P=yield pn(this.connection,T,this.signers.find(w=>w.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:b});h.push(P)}return{txIds:h,signedTxs:a}}return{txIds:yield yield Promise.all(a.map(h=>y(this,null,function*(){return h.recentBlockhash=g,yield this.connection.sendRawTransaction(h.serialize(),{skipPreflight:b})}))),signedTxs:a}}if(this.signAllTransactions){let h=a.map((T,P)=>(T.recentBlockhash=g,s[P].length&&T.sign(...s[P]),T));Le(h);let A=yield this.signAllTransactions(h);if(l){let T=0,P=[],w=()=>y(this,null,function*(){if(!A[T])return;let k=yield this.connection.sendRawTransaction(A[T].serialize(),{skipPreflight:b});P.push({txId:k,status:"sent",signedTx:A[T]}),d==null||d([...P]),T++;let I=!1,B=null,C=null,R=_=>{B!==null&&clearInterval(B),C!==null&&this.connection.removeSignatureListener(C);let O=P.findIndex(E=>E.txId===k);if(O>-1){if(P[O].status==="error"||P[O].status==="success")return;P[O].status=_.err?"error":"success"}d==null||d([...P]),_.err||w()};this.loopMultiTxStatus&&(B=setInterval(()=>y(this,null,function*(){var _;if(I){clearInterval(B);return}try{let O=yield this.connection.getTransaction(k,{commitment:"confirmed",maxSupportedTransactionVersion:0});O&&(I=!0,clearInterval(B),R({err:((_=O.meta)==null?void 0:_.err)||null}),console.log("tx status from getTransaction:",k))}catch(O){I=!0,clearInterval(B),console.error("getTransaction timeout:",O,k)}}),Kt)),C=this.connection.onSignature(k,_=>{if(I){this.connection.removeSignatureListener(C);return}I=!0,R(_)},"confirmed"),this.connection.getSignatureStatus(k)});return yield w(),{txIds:P.map(k=>k.txId),signedTxs:A}}else{let T=[];for(let P=0;P<A.length;P+=1){let w=yield this.connection.sendRawTransaction(A[P].serialize(),{skipPreflight:b});T.push(w)}return{txIds:T,signedTxs:A}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:o||{}}}versionMultiBuild(r){return y(this,arguments,function*({extraPreBuildData:e,txVersion:t,extInfo:o}){return t===0?yield this.buildV0MultiTx({extraPreBuildData:e,buildProps:o||{}}):this.buildMultiTx({extraPreBuildData:e,extInfo:o})})}buildV0(e){return y(this,null,function*(){var b;let f=e||{},{lookupTableCache:t={},lookupTableAddress:o=[],forerunCreate:r,recentBlockhash:i}=f,a=ee(f,["lookupTableCache","lookupTableAddress","forerunCreate","recentBlockhash"]),s=K(K({},this.cluster==="devnet"?{}:Ct),t),c=Array.from(new Set([...o,...this.lookupTableAddress])),u=[];for(let g of c)s[g]===void 0&&u.push(new Fe(g));let m=yield mn({connection:this.connection,address:u});for(let[g,x]of Object.entries(m))s[g]=x;let l=r?Fe.default.toBase58():i!=null?i:yield Ee(this.connection,this.blockhashCommitment),d=new nt({payerKey:this.feePayer,recentBlockhash:l,instructions:[...this.allInstructions]}).compileToV0Message(Object.values(s));(b=this.owner)!=null&&b.signer&&!this.signers.some(g=>g.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer);let p=new ot(d);return p.sign(this.signers),{builder:this,transaction:p,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:g=>y(this,null,function*(){var A;let{skipPreflight:x=!0,sendAndConfirm:h}=g||{};if(Le([p]),(A=this.owner)!=null&&A.isKeyPair){let T=yield this.connection.sendTransaction(p,{skipPreflight:x});return h&&(yield St(this.connection,T)),{txId:T,signedTx:p}}if(this.signAllTransactions){let T=yield this.signAllTransactions([p]);if(this.signers.length)for(let P of T)try{P.sign(this.signers)}catch(w){}return{txId:yield this.connection.sendTransaction(T[0],{skipPreflight:x}),signedTx:T[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:a||{}}})}buildV0MultiTx(e){return y(this,null,function*(){var u;let{extraPreBuildData:t=[],buildProps:o}=e,{transaction:r}=yield this.buildV0(o),i=t.filter(m=>m.builder.instructions.length>0),a=[r,...i.map(m=>m.transaction)],s=[this.signers,...i.map(m=>m.signers)],c=[...this.instructionTypes,...i.map(m=>m.instructionTypes).flat()];return(u=this.owner)!=null&&u.signer&&s.forEach(m=>{m.some(l=>l.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),a.forEach((m,l)=>y(this,null,function*(){m.sign(s[l])})),{builder:this,transactions:a,signers:s,instructionTypes:c,buildProps:o,execute:m=>y(this,null,function*(){var b;let{sequentially:l,onTxUpdate:d,recentBlockHash:p,skipPreflight:f=!0}=m||{};if(p&&a.forEach(g=>g.message.recentBlockhash=p),Le(a),(b=this.owner)!=null&&b.isKeyPair){if(l){let g=[];for(let x of a){let h=yield this.connection.sendTransaction(x,{skipPreflight:f});yield St(this.connection,h),g.push(h)}return{txIds:g,signedTxs:a}}return{txIds:yield Promise.all(a.map(g=>y(this,null,function*(){return yield this.connection.sendTransaction(g,{skipPreflight:f})}))),signedTxs:a}}if(this.signAllTransactions){let g=yield this.signAllTransactions(a);if(l){let x=0,h=[],A=()=>y(this,null,function*(){if(!g[x])return;let T=yield this.connection.sendTransaction(g[x],{skipPreflight:f});h.push({txId:T,status:"sent",signedTx:g[x]}),d==null||d([...h]),x++;let P=!1,w=null,k=null,I=B=>{w!==null&&clearInterval(w),k!==null&&this.connection.removeSignatureListener(k);let C=h.findIndex(R=>R.txId===T);if(C>-1){if(h[C].status==="error"||h[C].status==="success")return;h[C].status=B.err?"error":"success"}d==null||d([...h]),B.err||A()};this.loopMultiTxStatus&&(w=setInterval(()=>y(this,null,function*(){var B;if(P){clearInterval(w);return}try{let C=yield this.connection.getTransaction(T,{commitment:"confirmed",maxSupportedTransactionVersion:0});C&&(P=!0,clearInterval(w),I({err:((B=C.meta)==null?void 0:B.err)||null}),console.log("tx status from getTransaction:",T))}catch(C){P=!0,clearInterval(w),console.error("getTransaction timeout:",C,T)}}),Kt)),k=this.connection.onSignature(T,B=>{if(P){this.connection.removeSignatureListener(k);return}P=!0,I(B)},"confirmed"),this.connection.getSignatureStatus(T)});return A(),{txIds:[],signedTxs:g}}else{let x=[];for(let h=0;h<g.length;h+=1){let A=yield this.connection.sendTransaction(g[h],{skipPreflight:f});x.push(A)}return{txIds:x,signedTxs:g}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:o||{}}})}sizeCheckBuild(e){return y(this,null,function*(){var d;let l=e||{},{splitIns:t=[],computeBudgetConfig:o}=l,r=ee(l,["splitIns","computeBudgetConfig"]),i=o?It(o):{instructions:[],instructionTypes:[]},a=this.signers.reduce((p,f)=>N(K({},p),{[f.publicKey.toBase58()]:f}),{}),s=[],c=[],u=[],m=0;if(this.allInstructions.forEach(p=>{let f=[...u,p],b=o?[...i.instructions,...f]:f,x=[...new Set(f.map(h=>h.keys.filter(A=>A.isSigner).map(A=>A.pubkey.toString())).flat()).values()].map(h=>new Fe(h));if(p!==t[m]&&u.length<12&&(Qe({instructions:b,payer:this.feePayer,signers:x})||Qe({instructions:f,payer:this.feePayer,signers:x})))u.push(p);else{if(u.length===0)throw Error("item ins too big");m+=p===t[m]?1:0,Qe({instructions:o?[...i.instructions,...u]:[...u],payer:this.feePayer,signers:x})?s.push(new tt().add(...i.instructions,...u)):s.push(new tt().add(...u)),c.push(Array.from(new Set(u.map(h=>h.keys.filter(A=>A.isSigner).map(A=>A.pubkey.toString())).flat())).map(h=>a[h]).filter(h=>h!==void 0)),u=[p]}}),u.length>0){let f=[...new Set(u.map(b=>b.keys.filter(g=>g.isSigner).map(g=>g.pubkey.toString())).flat()).values()].map(b=>a[b]).filter(b=>b!==void 0);Qe({instructions:o?[...i.instructions,...u]:[...u],payer:this.feePayer,signers:f.map(b=>b.publicKey)})?s.push(new tt().add(...i.instructions,...u)):s.push(new tt().add(...u)),c.push(f)}return s.forEach(p=>p.feePayer=this.feePayer),(d=this.owner)!=null&&d.signer&&c.forEach(p=>{p.some(f=>f.publicKey.equals(this.owner.publicKey))||p.push(this.owner.signer)}),{builder:this,transactions:s,signers:c,instructionTypes:this.instructionTypes,execute:p=>y(this,null,function*(){var T;let{sequentially:f,onTxUpdate:b,skipTxCount:g=0,recentBlockHash:x,skipPreflight:h=!0}=p||{},A=x!=null?x:yield Ee(this.connection,this.blockhashCommitment);if(s.forEach((P,w)=>y(this,null,function*(){P.recentBlockhash=A,c[w].length&&P.sign(...c[w])})),Le(s),(T=this.owner)!=null&&T.isKeyPair){if(f){let P=0,w=[];for(let k of s){if(++P,P<=g){w.push("tx skipped");continue}let I=yield pn(this.connection,k,this.signers.find(B=>B.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:h});w.push(I)}return{txIds:w,signedTxs:s}}return{txIds:yield Promise.all(s.map(P=>y(this,null,function*(){return yield this.connection.sendRawTransaction(P.serialize(),{skipPreflight:h})}))),signedTxs:s}}if(this.signAllTransactions){let P=yield this.signAllTransactions(s.slice(g,s.length)),w=[...s.slice(0,g),...P];if(f){let k=0,I=[],B=()=>y(this,null,function*(){if(!w[k])return;k<g&&(I.push({txId:"",status:"success",signedTx:w[k]}),b==null||b([...I]),k++,B());let C=yield this.connection.sendRawTransaction(w[k].serialize(),{skipPreflight:h});I.push({txId:C,status:"sent",signedTx:w[k]}),b==null||b([...I]),k++;let R=!1,_=null,O=null,E=M=>{_!==null&&clearInterval(_),O!==null&&this.connection.removeSignatureListener(O);let D=I.findIndex($=>$.txId===C);if(D>-1){if(I[D].status==="error"||I[D].status==="success")return;I[D].status=M.err?"error":"success"}b==null||b([...I]),M.err||B()};this.loopMultiTxStatus&&(_=setInterval(()=>y(this,null,function*(){var M;if(R){clearInterval(_);return}try{let D=yield this.connection.getTransaction(C,{commitment:"confirmed",maxSupportedTransactionVersion:0});D&&(R=!0,clearInterval(_),E({err:((M=D.meta)==null?void 0:M.err)||null}),console.log("tx status from getTransaction:",C))}catch(D){R=!0,clearInterval(_),console.error("getTransaction timeout:",D,C)}}),Kt)),O=this.connection.onSignature(C,M=>{if(R){this.connection.removeSignatureListener(O);return}R=!0,E(M)},"confirmed"),this.connection.getSignatureStatus(C)});return yield B(),{txIds:I.map(C=>C.txId),signedTxs:w}}else{let k=[];for(let I=0;I<w.length;I+=1){let B=yield this.connection.sendRawTransaction(w[I].serialize(),{skipPreflight:h});k.push(B)}return{txIds:k,signedTxs:w}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:r||{}}})}sizeCheckBuildV0(e){return y(this,null,function*(){var A;let h=e||{},{computeBudgetConfig:t,splitIns:o=[],lookupTableCache:r={},lookupTableAddress:i=[]}=h,a=ee(h,["computeBudgetConfig","splitIns","lookupTableCache","lookupTableAddress"]),s=K(K({},this.cluster==="devnet"?{}:Ct),r),c=Array.from(new Set([...this.lookupTableAddress,...i])),u=[];for(let T of c)s[T]===void 0&&u.push(new Fe(T));let m=yield mn({connection:this.connection,address:u});for(let[T,P]of Object.entries(m))s[T]=P;let l=t?It(t):{instructions:[],instructionTypes:[]},d=yield Ee(this.connection,this.blockhashCommitment),p=this.signers.reduce((T,P)=>N(K({},T),{[P.publicKey.toBase58()]:P}),{}),f=[],b=[],g=[],x=0;if(this.allInstructions.forEach(T=>{let P=[...g,T],w=t?[...l.instructions,...P]:P;if(T!==o[x]&&g.length<12&&(et({instructions:w,payer:this.feePayer,lookupTableAddressAccount:s})||et({instructions:P,payer:this.feePayer,lookupTableAddressAccount:s})))g.push(T);else{if(g.length===0)throw Error("item ins too big");x+=T===o[x]?1:0;let k={};for(let I of[...new Set(c)])s[I]!==void 0&&(k[I]=s[I]);if(t&&et({instructions:[...l.instructions,...g],payer:this.feePayer,lookupTableAddressAccount:s,recentBlockhash:d})){let I=new nt({payerKey:this.feePayer,recentBlockhash:d,instructions:[...l.instructions,...g]}).compileToV0Message(Object.values(s));f.push(new ot(I))}else{let I=new nt({payerKey:this.feePayer,recentBlockhash:d,instructions:[...g]}).compileToV0Message(Object.values(s));f.push(new ot(I))}b.push(Array.from(new Set(g.map(I=>I.keys.filter(B=>B.isSigner).map(B=>B.pubkey.toString())).flat())).map(I=>p[I]).filter(I=>I!==void 0)),g=[T]}}),g.length>0){let P=[...new Set(g.map(w=>w.keys.filter(k=>k.isSigner).map(k=>k.pubkey.toString())).flat()).values()].map(w=>p[w]).filter(w=>w!==void 0);if(t&&et({instructions:[...l.instructions,...g],payer:this.feePayer,lookupTableAddressAccount:s,recentBlockhash:d})){let w=new nt({payerKey:this.feePayer,recentBlockhash:d,instructions:[...l.instructions,...g]}).compileToV0Message(Object.values(s));f.push(new ot(w))}else{let w=new nt({payerKey:this.feePayer,recentBlockhash:d,instructions:[...g]}).compileToV0Message(Object.values(s));f.push(new ot(w))}b.push(P)}return(A=this.owner)!=null&&A.signer&&b.forEach(T=>{T.some(P=>P.publicKey.equals(this.owner.publicKey))||T.push(this.owner.signer)}),{builder:this,transactions:f,buildProps:e,signers:b,instructionTypes:this.instructionTypes,execute:T=>y(this,null,function*(){var C;let{sequentially:P,onTxUpdate:w,skipTxCount:k=0,recentBlockHash:I,skipPreflight:B=!0}=T||{};if(f.map((R,_)=>y(this,null,function*(){b[_].length&&R.sign(b[_]),I&&(R.message.recentBlockhash=I)})),Le(f),(C=this.owner)!=null&&C.isKeyPair){if(P){let R=0,_=[];for(let O of f){if(++R,R<=k){console.log("skip tx: ",R),_.push("tx skipped");continue}let E=yield this.connection.sendTransaction(O,{skipPreflight:B});yield St(this.connection,E),_.push(E)}return{txIds:_,signedTxs:f}}return{txIds:yield Promise.all(f.map(R=>y(this,null,function*(){return yield this.connection.sendTransaction(R,{skipPreflight:B})}))),signedTxs:f}}if(this.signAllTransactions){let R=yield this.signAllTransactions(f.slice(k,f.length)),_=[...f.slice(0,k),...R];if(P){let O=0,E=[],M=()=>y(this,null,function*(){if(!_[O])return;if(O<k){E.push({txId:"",status:"success",signedTx:_[O]}),w==null||w([...E]),O++,M();return}let D=yield this.connection.sendTransaction(_[O],{skipPreflight:B});E.push({txId:D,status:"sent",signedTx:_[O]}),w==null||w([...E]),O++;let $=!1,se=null,Se=null,Rn=Be=>{se!==null&&clearInterval(se),Se!==null&&this.connection.removeSignatureListener(Se);let be=E.findIndex(Uo=>Uo.txId===D);if(be>-1){if(E[be].status==="error"||E[be].status==="success")return;E[be].status=Be.err?"error":"success"}w==null||w([...E]),Be.err||M()};this.loopMultiTxStatus&&(se=setInterval(()=>y(this,null,function*(){var Be;if($){clearInterval(se);return}try{let be=yield this.connection.getTransaction(D,{commitment:"confirmed",maxSupportedTransactionVersion:0});be&&($=!0,clearInterval(se),Rn({err:((Be=be.meta)==null?void 0:Be.err)||null}),console.log("tx status from getTransaction:",D))}catch(be){$=!0,clearInterval(se),console.error("getTransaction timeout:",be,D)}}),Kt)),Se=this.connection.onSignature(D,Be=>{if($){this.connection.removeSignatureListener(Se);return}$=!0,Rn(Be)},"confirmed"),this.connection.getSignatureStatus(D)});return M(),{txIds:[],signedTxs:_}}else{let O=[];for(let E=0;E<_.length;E+=1){let M=yield this.connection.sendTransaction(_[E],{skipPreflight:B});O.push(M)}return{txIds:O,signedTxs:_}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:a||{}}})}};import{Connection as Nr}from"@solana/web3.js";var Mr=(t=>(t.SonicMainnet="SonicMainnet",t.SonicTestnetV1="SonicTestnetV1",t))(Mr||{});function jc(n,e=!0){let o=n==="SonicMainnet"?"SonicMainnet":"SonicTestnetV1";return new Nr(e?Fr[o]:Er[o])}var Er={SonicMainnet:"https://api.mainnet-alpha.sonic.game",SonicTestnetV1:"https://api.testnet.v1.sonic.game"},Fr={SonicMainnet:"https://archival-mainnet.sonic.game",SonicTestnetV1:"https://archival-testnet.sonic.game"};var ue={BASE_HOST:"https://api.sega.so/api",SEND_TRANSACTION:"/send-transaction",FARM_ARP:"/main/farm/info",FARM_ARP_LINE:"/main/farm-apr-tv",CLMM_CONFIG:"/main/clmm-config",CPMM_CONFIG:"/main/cpmm-config",VERSION:"/main/version",CHECK_AVAILABILITY:"/v3/main/AvailabilityCheckAPI",RPCS:"/main/rpcs",INFO:"/main/info",STAKE_POOLS:"/main/stake-pools",CHAIN_TIME:"/main/chain-time",TOKEN_LIST:"/mint/list",MINT_INFO_ID:"/mint/ids",JUP_TOKEN_LIST:"https://tokens.jup.ag/tokens?tags=lst,community",POOL_LIST:"/pools/info/list",POOL_SEARCH_BY_ID:"/pools/info/ids",POOL_SEARCH_MINT:"/pools/info/mint",POOL_SEARCH_LP:"/pools/info/lps",POOL_KEY_BY_ID:"/pools/key/ids",POOL_LIQUIDITY_LINE:"/pools/line/liquidity",POOL_POSITION_LINE:"/pools/line/position",FARM_INFO:"/farms/info/ids",FARM_LP_INFO:"/farms/info/lp",FARM_KEYS:"/farms/key/ids",OWNER_CREATED_FARM:"/create-pool/{owner}",OWNER_IDO:"/main/ido/{owner}",OWNER_STAKE_FARMS:"/position/stake/{owner}",OWNER_LOCK_POSITION:"/position/clmm-lock/{owner}",IDO_KEYS:"/ido/key/ids",SWAP_COMPUTE:"/compute/",SWAP_TX:"/transaction/",MINT_PRICE:"/mint/price",MIGRATE_CONFIG:"/main/migrate-lp",PRIORITY_FEE:"/main/auto-fee"},pl=K({},ue);var uo="ray_tab_hash",dn="ray_req_hash",Dr=()=>{if(typeof window===void 0)return"";let n=sessionStorage.getItem(uo);return n||(n=`ray-${Date.now()}`,s