UNPKG

@sega-so/sega-sdk

Version:

An SDK for building applications on top of SEGA.

1 lines 117 kB
var Yo=Object.defineProperty,zo=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?Yo(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},R=(n,e)=>zo(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&&gt)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 fo from"axios";import{PublicKey as vn}from"@solana/web3.js";import{get as Yt,set as Dn}from"lodash";var Zo=(r=>(r[r.Error=0]="Error",r[r.Warning=1]="Warning",r[r.Info=2]="Info",r[r.Debug=3]="Debug",r))(Zo||{}),zt=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}},Jt={},Fn={};function U(n){let e=Yt(Jt,n);if(!e){let t=Yt(Fn,n);e=new zt({name:n,logLevel:t}),Dn(Jt,n,e)}return e}function Cs(n,e){Dn(Fn,n,e);let t=Yt(Jt,n);t&&(t.level=e)}import{MINT_SIZE as $o,TOKEN_PROGRAM_ID as Xo,getTransferFeeConfig as Qo,unpackMint as er}from"@solana/spl-token";var Zt=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=$t(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=$t(c,10);s=(yield(yield Promise.all(u.map(l=>y(this,null,function*(){return yield n._rpcBatchRequest(l)})))).flat()).map(l=>(l.error&&Zt.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"&&Zt.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&&Zt.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)=>R(K({},r),{accountInfo:o[i]}))})}var tr=(o=>(o[o.Uninitialized=0]="Uninitialized",o[o.Mint=1]="Mint",o[o.Account=2]="Account",o))(tr||{}),Es=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<$o){console.log("invalid mint account",u.pubkey.toBase58());continue}let m=er(u.pubkey,u.accountInfo,(a=u.accountInfo)==null?void 0:a.owner);i[u.pubkey.toString()]=R(K({},m),{programId:((s=u.accountInfo)==null?void 0:s.owner)||Xo,feeConfig:(c=Qo(m))!=null?c:void 0})}return i[vn.default.toBase58()]=i[ne.toBase58()],i})}import z from"bn.js";import Tr from"decimal.js";import ur from"big.js";import xe from"bn.js";import nr from"toformat";var or=nr,Ye=or;import bt from"big.js";import rr from"bn.js";import ir from"decimal.js-light";import ze from"bn.js";var Xt=(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))(Xt||{}),Vn=9007199254740991;function $(n){let e=U("Sega_parseBigNumberish");if(n instanceof ze)return n;if(typeof n=="string"){if(n.match(/^-?[0-9]+$/))return new ze(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 ze(String(n))):typeof n=="bigint"?new ze(n.toString()):(e.error(`invalid BigNumberish value: ${n}`),new ze(0))}var yt=U("module/fraction"),Qt=Ye(bt),Je=Ye(ir),sr={0:Je.ROUND_DOWN,1:Je.ROUND_HALF_UP,2:Je.ROUND_UP},ar={0:bt.roundDown,1:bt.roundHalfUp,2:bt.roundUp},D=class n{constructor(e,t=new rr(1)){this.numerator=$(e),this.denominator=$(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($(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($(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($(e));return new n(this.numerator.mul(t.numerator),this.denominator.mul(t.denominator))}div(e){let t=e instanceof n?e:new n($(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:sr[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.`),Qt.DP=e,Qt.RM=ar[o]||1,new Qt(this.numerator.toString()).div(this.denominator.toString()).toFormat(e,t)}isZero(){return this.numerator.isZero()}};var cr=U("Sega_amount"),ht=Ye(ur);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")):cr.logWithError(`invalid number string, num: ${n}`)}else t=n;return[t,o.slice(0,e)||o]}var ue=class n extends D{constructor(e,t,o=!0,r){let i=new xe(0),a=Be.pow(new xe(e.decimals));if(o)i=$(t);else{let s=new xe(0),c=new xe(0);if(typeof t=="string"||typeof t=="number"||typeof t=="bigint"){let[u,m]=Un(t.toString(),e.decimals);s=$(u),c=$(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 D{constructor(e,t,o=!0,r){let i=new xe(0),a=Be.pow(new xe(e.decimals));if(o)i=$(t);else{let s=new xe(0),c=new xe(0);if(typeof t=="string"||typeof t=="number"||typeof t=="bigint"){let[u,m]=Un(t.toString(),e.decimals);s=$(u),c=$(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 lr}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as qn}from"@solana/spl-token";var me={chainId:101,address:lr.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 sn}from"@solana/web3.js";import{PublicKey as q,SystemProgram as Gn,SYSVAR_RENT_PUBKEY as mr}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as pr}from"@solana/spl-token";function en({pubkey:n,isSigner:e=!1,isWritable:t=!0}){return{pubkey:n,isWritable:t,isSigner:e}}var ga=[en({pubkey:pr,isWritable:!1}),en({pubkey:Gn.programId,isWritable:!1}),en({pubkey:mr,isWritable:!1})];function tn({publicKey:n,transformSol:e}){let t=nn(n.toString());if(t instanceof q)return e&&t.equals(Ze)?ne:t;if(e&&t.toString()===Ze.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 nn(n){try{return new q(n)}catch(e){return n}}var ya=new q("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),on=new q("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),rn=new q("SysvarRent111111111111111111111111111111111"),ba=new q("SysvarC1ock11111111111111111111111111111111"),$e=new q("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),ha=new q("Sysvar1nstructions1111111111111111111111111"),jn=Gn.programId,Ta=new q("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),Pa=new q("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),Aa=new q("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),wa=new q("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),xa=new q("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),ka=new q("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),Ia=new q("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),Sa=new q("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),Ca=new q("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),Ba=new q("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),Ka=new q("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),ne=new q("So11111111111111111111111111111111111111112"),Ze=q.default;function He(n){return tn({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===Ze.toBase58()||e instanceof sn&&Ze.equals(e)){this.decimals=re.decimals,this.symbol=re.symbol,this.name=re.name,this.mint=new sn(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?sn.default:tn({publicKey:e}),this.isToken2022=a}equals(e){return this===e?!0:this.mint.equals(e.mint)}};Pt.WSOL=new Pt(R(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(me);var At=wt;function va(n,e){return n instanceof G&&e instanceof G?n.equals(e):n instanceof G||e instanceof G?!1:n===e}import dr from"bn.js";var Hn=new D(new dr(100)),Q=class extends D{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 fr=U("Sega_price"),pe=class n extends D{constructor(e){let{baseToken:t,quoteToken:o,numerator:r,denominator:i}=e;super(r,i),this.baseToken=t,this.quoteToken=o,this.scalar=new D(an(t.decimals),an(o.decimals))}get raw(){return new D(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&&fr.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 Y(n){if(n instanceof Q)return new D(n.numerator,n.denominator);if(n instanceof pe)return n.adjusted;if(n instanceof ue)try{return Y(n.toExact())}catch(o){return new D(de)}if(n instanceof D)return n;let e=String(n),t=Ke(e);return new D(t.numerator,t.denominator)}function su(n){var o;if(n instanceof Q)return{fr:new D(n.numerator,n.denominator)};if(n instanceof pe)return{fr:n.adjusted};if(n instanceof ue)return{fr:Y(n.toExact()),decimals:n.token.decimals};if(n instanceof D)return{fr:n};let e=String(n),t=Ke(e);return{fr:new D(t.numerator,t.denominator),decimals:(o=t.dec)==null?void 0:o.length}}function au(n,e){if(n==null||e==null)return!1;let t=Y(n),o=Y(e);return t.sub(o).numerator,t.sub(o).numerator.lt(de)}function gr(n,e){if(n==null||e==null)return!1;let t=Y(n),o=Y(e);return t.sub(o).numerator.gt(de)}function uu(n,e){if(n==null||e==null)return!1;let t=Y(n),o=Y(e);return t.sub(o).numerator.lte(de)}function cu(n,e){if(n==null||e==null)return!1;let t=Y(n),o=Y(e);return t.sub(o).numerator.gte(de)}function yr(n,e){if(n==null||e==null)return!1;let t=Y(n),o=Y(e);return t.sub(o).numerator.eq(de)}function lu(n,e){if(n==null||e==null)return;let t=Y(n),o=Y(e);try{return t.div(o)}catch(r){return t}}function mu(n,e){if(n==null||e==null)return;let t=Y(n),o=Y(e);return t.sub(o)}function pu(n){return n==null?!1:!yr(n,0)}function du(n,e){return gr(e,n)?e:n}function un(n,e){if(n==null||e==null)return;let t=Y(n),o=Y(e);return t.mul(o)}function fu(n,e){if(n==null||e==null)return;let t=Y(n),o=Y(e);return t.add(o)}import{PublicKey as br}from"@solana/web3.js";import hr from"bn.js";function zn(n){return y(this,null,function*(){new Promise(e=>setTimeout(e,n))})}function Pu(){return new Date().getTime()}function cn(n){return typeof n=="object"&&n!==null&&![G,ue,br,D,hr,pe,Q].some(e=>typeof e=="object"&&n instanceof e)}function Yn(n){return typeof n=="string"?nn(n):Array.isArray(n)?n.map(e=>Yn(e)):cn(n)?Object.fromEntries(Object.entries(n).map(([e,t])=>[e,Yn(t)])):n}var de=new z(0),Nu=new z(1),Mu=new z(2),Eu=new z(3),Du=new z(5),Be=new z(10),Fu=new z(100),vu=new z(1e3),Wu=new z(1e4);function an(n){return Be.pow($(n))}function Ke(n){var s;if(n===void 0)return{denominator:"1",numerator:"0"};if(n instanceof z)return{numerator:n.toString(),denominator:"1"};if(n instanceof D)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 Vu(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 Pr(n){var o;let[,e="",t=""]=(o=n.toFixed(2).match(/(-?)(\d*)\.?(\d*)/))!=null?o:[];return`${e}${t}`}function Ar(n,e=0){return n instanceof z?n:new z(Pr($n(n).mul(Be.pow(new z(String(e))))))}function $n(n){if(n instanceof Q)return new D(n.numerator,n.denominator);if(n instanceof pe)return n.adjusted;if(n instanceof ue)try{return $n(n.toExact())}catch(o){return new D(de)}if(n instanceof D)return n;let e=String(n),t=Ke(e);return new D(t.numerator,t.denominator)}function Uu(n,e){let{numerator:t,denominator:o}=Ke(n);return new Q(new z(t),new z(o).mul(e!=null&&e.alreadyDecimaled?new z(100):new z(1)))}function qu(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 z(i).mul(Be.pow(new z(e.decimals))):i,c=new z(a).mul(Be.pow(new z(r.decimals)));return new pe({baseToken:r,denominator:c.toString(),quoteToken:new G(R(K({},e),{skipMint:!0,mint:""})),numerator:s.toString()})}function Jn(n){let e=new At({decimals:6,symbol:"usd",name:"usd"}),t=Ar(un(n,te(10,e.decimals)));return new Tt(e,t)}function Gu(n,e){return Jn(!e||!n?0:un(n,e))}function wr(n){if(n==null)return;let{numerator:e,denominator:t}=Ke(n.toString());return new D(e,t)}function xr(n){return n instanceof Tr}function Zn(n){return xr(n)?wr(n):Array.isArray(n)?n.map(e=>Zn(e)):cn(n)?Object.fromEntries(Object.entries(n).map(([e,t])=>[e,Zn(t)])):n}var Xn=n=>typeof n=="number",Qn=n=>n?new Date(n):new Date,kr=n=>Qn(n).getTime();function Yu(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 zu(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 Ju(n,e){let o=kr(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 $t(n,e=1,t=[]){let o=[...n];if(e<=0)return t;for(;o.length;)t.push(o.splice(0,e));return t}function $u(n,...e){return n.filter(t=>e.every(o=>o.includes(t)))}function Xu(n,...e){return n.filter(t=>e.every(o=>!o.includes(t)))}function Qu(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 Kr}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as Lr}from"@solana/spl-token";import{ComputeBudgetProgram as to,Keypair as no,PublicKey as oo,Transaction as kt,TransactionMessage as Ir,VersionedTransaction as ln}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 Sr}from"@solana/spl-token";var Te=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 Ct(n,e){n.length<1&&Te.logWithError(`no instructions provided: ${n.toString()}`),e.length<1&&Te.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 pc(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)Ct([...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 Cr(n,i,o),s.find(u=>u.err!==null))throw Error("rpc simulateTransaction error")}catch(u){u instanceof Error&&Te.logWithError("failed to simulate for instructions","RPC_ERROR",{message:u.message})}let c=[];for(let u of s)if(Te.debug("simulate result:",u),u.logs){let m=u.logs.filter(l=>l&&l.includes(t));Te.debug("filteredLog:",c),m.length||Te.logWithError("simulate log not match keyword","keyword",t),c.push(...m)}return c})}function dc(n,e){let t=n.match(/{["\w:,]+}/g);return!t||t.length!==1?Te.logWithError(`simulate log fail to match json, keyword: ${e}`):t[0]}function fc(n,e){let o=new RegExp(`"${e}":(\\d+)`,"g").exec(n);return!o||o.length!==2?Te.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 Cr(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&&Te.logWithError("failed to get info for multiple accounts","RPC_ERROR",{message:r.message})}return o})}function Qe({instructions:n,payer:e,signers:t}){return Ct(n,[e,...t])}function et({instructions:n,payer:e,lookupTableAddressAccount:t,recentBlockhash:o=no.generate().publicKey.toString()}){let i=new Ir({payerKey:e,recentBlockhash:o,instructions:n}).compileToV0Message(Object.values(t!=null?t:{}));try{return Buffer.from(new ln(i).serialize()).toString("base64").length<ro}catch(a){return!1}}var xt={time:0,data:void 0};function gc(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),Br=n=>{let e=n.serialize({requireAllSignatures:!1,verifySignatures:!1});n instanceof ln&&(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=Sr.toBase58()),t.feePayer||(t.feePayer=no.generate().publicKey)),e.push(Br(t))}),console.log("simulate tx string:",e),e}function yc(n){let e=n.serialize({requireAllSignatures:!1,verifySignatures:!1});return n instanceof ln&&(e=io(e)),e.toString("base64")}function fe(n,e,t){return oe([n.toBuffer(),(t!=null?t:Lr).toBuffer(),e.toBuffer()],new Kr("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"))}function so(n){return oe([Buffer.from("metadata","utf8"),$e.toBuffer(),n.toBuffer()],$e)}import{PublicKey as ce}from"@solana/web3.js";var Bt=new ce("SegazTQwbYWknDZkJ6j2Kgvm5gw3MrHGKtWstZdoNKZ"),Kt=new ce("Ajk8d9bERSaFdeoT1d8JUVfaDayrYLnAdgeB47TFMUaG"),ao=new ce("2HbjxVVKJ7Ct72Rcd8WK4VTqmwTXL5aAggkH1CHGFGmh"),_r=new ce("TegaRdjn9Qeh9DfUU28X19aPPpJtj9gs8ntSYrR5H4K "),Or=new ce("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y"),Rr=new ce("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y"),Nr=new ce("SegaXNnoXYTZiqUt9Xn2XqGcL56b25yzXLuJSpadcMu"),Mr=new ce("2t1hV2YqnDCPuJZqr7Fy8oAygGwZE5Q9uaQzpLC1QryJ"),Er=new ce("BLxynZeHE123MmQgNJZiV1pwW4VYh46oZYyC66xwmtTY"),Ic={CREATE_CPMM_POOL_PROGRAM:Bt,CREATE_CPMM_POOL_AUTH:Kt,CREATE_CPMM_POOL_FEE_ACC:ao},uo={CREATE_CPMM_POOL_PROGRAM:Bt,CREATE_CPMM_POOL_AUTH:Kt,CREATE_CPMM_POOL_FEE_ACC:ao},co={CREATE_CPMM_POOL_PROGRAM:Nr,CREATE_CPMM_POOL_AUTH:Mr,CREATE_CPMM_POOL_FEE_ACC:Er},lo={SERUM_MARKET:ce.default,UTIL1216:ce.default,CREATE_CPMM_POOL_PROGRAM:_r,CREATE_CPMM_POOL_AUTH:Or,CREATE_CPMM_POOL_FEE_ACC:Rr};import J from"bn.js";var ge=1e4;function Bc(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===ge){let s=new J(r.maximumFee.toString());return{amount:n.add(s),fee:s,expirationTime:a}}else{let s=Pe(n.mul(new J(ge)),new J(ge-r.transferFeeBasisPoints)),c=new J(r.maximumFee.toString()),u=s.sub(n).gt(c)?n.add(c):s,m=Pe(u.mul(new J(r.transferFeeBasisPoints)),new J(ge)),l=m.gt(i)?i:m;return{amount:u,fee:l,expirationTime:a}}else{let s=Pe(n.mul(new J(r.transferFeeBasisPoints)),new J(ge)),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=R(K({},e),{olderTransferFee:{epoch:BigInt(e.olderTransferFee.epoch),maximumFee:BigInt(e.olderTransferFee.maximumFee),transferFeeBasisPoints:e.olderTransferFee.transferFeeBasisPoints},newerTransferFee:{epoch:BigInt(e.newerTransferFee.epoch),maximumFee:BigInt(e.newerTransferFee.maximumFee),transferFeeBasisPoints:e.newerTransferFee.transferFeeBasisPoints}}),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===ge){let c=new J(i.maximumFee.toString());return{amount:n.add(c),fee:c,expirationTime:s}}else{let c=Pe(n.mul(new J(ge)),new J(ge-i.transferFeeBasisPoints)),u=new J(i.maximumFee.toString()),m=c.sub(n).gt(u)?n.add(u):c,l=Pe(m.mul(new J(i.transferFeeBasisPoints)),new J(ge)),d=l.gt(a)?a:l;return{amount:m,fee:d,expirationTime:s}}else{let c=Pe(n.mul(new J(i.transferFeeBasisPoints)),new J(ge)),u=c.gt(a)?a:c;return{amount:n,fee:u,expirationTime:s}}}function Kc(n,e){return n===void 0?e:e===void 0?n:Math.min(n,e)}function Pe(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 Dr,AddressLookupTableAccount as mo}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 Dr(i))),r={};for(let i=0;i<e.length;i++){let a=o[i],s=e[i];if(!a)continue;let c=new mo({key:s,state:mo.deserialize(a.data)});r[s.toString()]=c,Lt[s.toString()]=c}return r})}var Lt={};import{PublicKey as De,sendAndConfirmTransaction as pn,SystemProgram as Fr,Transaction as tt,TransactionMessage as nt,VersionedTransaction as ot}from"@solana/web3.js";import vr from"axios";var _t=2e3,Ot=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 vr.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(Fr.transfer({fromPubkey:(t=e.feePayer)!=null?t:this.feePayer,toPubkey:new De(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!==De.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,C=null,B=null,N=_=>{C!==null&&clearInterval(C),B!==null&&this.connection.removeSignatureListener(B);let O=P.findIndex(E=>E.txId===k);if(O>-1){if(P[O].status==="error"||P[O].status==="success")return;P[O].status=_.err?"error":"success"}d==null||d([...P]),_.err||w()};this.loopMultiTxStatus&&(C=setInterval(()=>y(this,null,function*(){var _;if(I){clearInterval(C);return}try{let O=yield this.connection.getTransaction(k,{commitment:"confirmed",maxSupportedTransactionVersion:0});O&&(I=!0,clearInterval(C),N({err:((_=O.meta)==null?void 0:_.err)||null}),console.log("tx status from getTransaction:",k))}catch(O){I=!0,clearInterval(C),console.error("getTransaction timeout:",O,k)}}),_t)),B=this.connection.onSignature(k,_=>{if(I){this.connection.removeSignatureListener(B);return}I=!0,N(_)},"confirmed"),this.connection.getSignatureStatus(k)});return yield w(),{txIds:P.map(k=>k.txId),signedTxs:A}}else{let T=[];for(let P=0;P<A.length;P+=1){let w=yield this.connection.sendRawTransaction(A[P].serialize(),{skipPreflight: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"?{}:Lt),t),c=Array.from(new Set([...o,...this.lookupTableAddress])),u=[];for(let g of c)s[g]===void 0&&u.push(new De(g));let m=yield mn({connection:this.connection,address:u});for(let[g,x]of Object.entries(m))s[g]=x;let l=r?De.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=C=>{w!==null&&clearInterval(w),k!==null&&this.connection.removeSignatureListener(k);let B=h.findIndex(N=>N.txId===T);if(B>-1){if(h[B].status==="error"||h[B].status==="success")return;h[B].status=C.err?"error":"success"}d==null||d([...h]),C.err||A()};this.loopMultiTxStatus&&(w=setInterval(()=>y(this,null,function*(){var C;if(P){clearInterval(w);return}try{let B=yield this.connection.getTransaction(T,{commitment:"confirmed",maxSupportedTransactionVersion:0});B&&(P=!0,clearInterval(w),I({err:((C=B.meta)==null?void 0:C.err)||null}),console.log("tx status from getTransaction:",T))}catch(B){P=!0,clearInterval(w),console.error("getTransaction timeout:",B,T)}}),_t)),k=this.connection.onSignature(T,C=>{if(P){this.connection.removeSignatureListener(k);return}P=!0,I(C)},"confirmed"),this.connection.getSignatureStatus(T)});return A(),{txIds:[],signedTxs:g}}else{let x=[];for(let h=0;h<g.length;h+=1){let A=yield this.connection.sendTransaction(g[h],{skipPreflight:f});x.push(A)}return{txIds:x,signedTxs:g}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo: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)=>R(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 De(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(C=>C.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:h});w.push(I)}return{txIds:w,signedTxs:s}}return{txIds:yield Promise.all(s.map(P=>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=[],C=()=>y(this,null,function*(){if(!w[k])return;k<g&&(I.push({txId:"",status:"success",signedTx:w[k]}),b==null||b([...I]),k++,C());let B=yield this.connection.sendRawTransaction(w[k].serialize(),{skipPreflight:h});I.push({txId:B,status:"sent",signedTx:w[k]}),b==null||b([...I]),k++;let N=!1,_=null,O=null,E=M=>{_!==null&&clearInterval(_),O!==null&&this.connection.removeSignatureListener(O);let F=I.findIndex(Z=>Z.txId===B);if(F>-1){if(I[F].status==="error"||I[F].status==="success")return;I[F].status=M.err?"error":"success"}b==null||b([...I]),M.err||C()};this.loopMultiTxStatus&&(_=setInterval(()=>y(this,null,function*(){var M;if(N){clearInterval(_);return}try{let F=yield this.connection.getTransaction(B,{commitment:"confirmed",maxSupportedTransactionVersion:0});F&&(N=!0,clearInterval(_),E({err:((M=F.meta)==null?void 0:M.err)||null}),console.log("tx status from getTransaction:",B))}catch(F){N=!0,clearInterval(_),console.error("getTransaction timeout:",F,B)}}),_t)),O=this.connection.onSignature(B,M=>{if(N){this.connection.removeSignatureListener(O);return}N=!0,E(M)},"confirmed"),this.connection.getSignatureStatus(B)});return yield C(),{txIds:I.map(B=>B.txId),signedTxs:w}}else{let k=[];for(let I=0;I<w.length;I+=1){let C=yield this.connection.sendRawTransaction(w[I].serialize(),{skipPreflight:h});k.push(C)}return{txIds:k,signedTxs:w}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo: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"?{}:Lt),r),c=Array.from(new Set([...this.lookupTableAddress,...i])),u=[];for(let T of c)s[T]===void 0&&u.push(new De(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)=>R(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(C=>C.isSigner).map(C=>C.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 B;let{sequentially:P,onTxUpdate:w,skipTxCount:k=0,recentBlockHash:I,skipPreflight:C=!0}=T||{};if(f.map((N,_)=>y(this,null,function*(){b[_].length&&N.sign(b[_]),I&&(N.message.recentBlockhash=I)})),Le(f),(B=this.owner)!=null&&B.isKeyPair){if(P){let N=0,_=[];for(let O of f){if(++N,N<=k){console.log("skip tx: ",N),_.push("tx skipped");continue}let E=yield this.connection.sendTransaction(O,{skipPreflight:C});yield St(this.connection,E),_.push(E)}return{txIds:_,signedTxs:f}}return{txIds:yield Promise.all(f.map(N=>y(this,null,function*(){return yield this.connection.sendTransaction(N,{skipPreflight:C})}))),signedTxs:f}}if(this.signAllTransactions){let N=yield this.signAllTransactions(f.slice(k,f.length)),_=[...f.slice(0,k),...N];if(P){let O=0,E=[],M=()=>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 F=yield this.connection.sendTransaction(_[O],{skipPreflight:C});E.push({txId:F,status:"sent",signedTx:_[O]}),w==null||w([...E]),O++;let Z=!1,ae=null,Se=null,Rn=Ce=>{ae!==null&&clearInterval(ae),Se!==null&&this.connection.removeSignatureListener(Se);let he=E.findIndex(Ho=>Ho.txId===F);if(he>-1){if(E[he].status==="error"||E[he].status==="success")return;E[he].status=Ce.err?"error":"success"}w==null||w([...E]),Ce.err||M()};this.loopMultiTxStatus&&(ae=setInterval(()=>y(this,null,function*(){var Ce;if(Z){clearInterval(ae);return}try{let he=yield this.connection.getTransaction(F,{commitment:"confirmed",maxSupportedTransactionVersion:0});he&&(Z=!0,clearInterval(ae),Rn({err:((Ce=he.meta)==null?void 0:Ce.err)||null}),console.log("tx status from getTransaction:",F))}catch(he){Z=!0,clearInterval(ae),console.error("getTransaction timeout:",he,F)}}),_t)),Se=this.connection.onSignature(F,Ce=>{if(Z){this.connection.removeSignatureListener(Se);return}Z=!0,Rn(Ce)},"confirmed"),this.connection.getSignatureStatus(F)});return M(),{txIds:[],signedTxs:_}}else{let O=[];for(let E=0;E<_.length;E+=1){let M=yield this.connection.sendTransaction(_[E],{skipPreflight:C});O.push(M)}return{txIds:O,signedTxs:_}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:a||{}}})}};import{Connection as Wr}from"@solana/web3.js";var Vr=(o=>(o.SonicMainnet="SonicMainnet",o.SonicTestnetV1="SonicTestnetV1",o.SolanaMainnet="SolanaMainnet",o))(Vr||{});function Qc(n,e=!0){return new Wr(e?qr[n]:Ur[n])}function el(n){return Gr[n]}var Ur={SonicMainnet:"https://api.mainnet-alpha.sonic.game",SonicTestnetV1:"https://api.testnet.v1.sonic.game",SolanaMainnet:"https://api.mainnet-beta.solana.com"},qr={SonicMainnet:"https://archival-mainnet.sonic.game",SonicTestnetV1:"https://archival-testnet.sonic.game",SolanaMainnet:"https://api.mainnet-beta.solana.com"},Gr={SonicMainnet:uo,SonicTestnetV1:lo,SolanaMainnet:co};var ie={BASE_HOST:"https://api.sega.so/api",SEND_TRANSACTION:"/send-transaction",FARM_ARP:"/main/farm/info",FARM_ARP_LINE:"/main/farm-apr-tv",CLMM_CONFIG:"/main/clmm-config",CPMM_CONFIG:"/main/cpmm-config",VERSION:"/main/version",CHECK_AVAILABILITY:"/v3/main/AvailabilityCheckAPI",RPCS:"/main/rpcs",INFO:"/main/info",STAKE_POOLS:"/main/stake-pools",CHAIN_TIME:"/main/chain-time",TOKEN_LIST:"/mint/list",MINT_INFO_ID:"/mint/ids",JUP_TOKEN_LIST:"https://tokens.jup.ag/tokens?tags=lst,community",POOL_LIST:"/pools/info/list",POOL_SEARCH_BY_ID:"/pools/info/ids",POOL_SEARCH_MINT:"/pools/info/mint",POOL_SEARCH_LP:"/pools/info/lps",POOL_KEY_BY_ID:"/pools/key/ids",POOL_LIQUIDITY_LINE:"/pools/line/liquidity",POOL_POSITION_LINE:"/pools/line/position",FARM_INFO:"/farms/info/ids",FARM_LP_INFO:"/farms/info/lp",FARM_KEYS