@sega-so/sega-sdk
Version:
An SDK for building applications on top of SEGA.
2 lines • 35.7 kB
JavaScript
"use strict";var at=Object.create;var Q=Object.defineProperty,ct=Object.defineProperties,ut=Object.getOwnPropertyDescriptor,lt=Object.getOwnPropertyDescriptors,mt=Object.getOwnPropertyNames,me=Object.getOwnPropertySymbols,pt=Object.getPrototypeOf,ke=Object.prototype.hasOwnProperty,Ve=Object.prototype.propertyIsEnumerable;var Oe=(n,e,t)=>e in n?Q(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,O=(n,e)=>{for(var t in e||(e={}))ke.call(e,t)&&Oe(n,t,e[t]);if(me)for(var t of me(e))Ve.call(e,t)&&Oe(n,t,e[t]);return n},j=(n,e)=>ct(n,lt(e));var pe=(n,e)=>{var t={};for(var r in n)ke.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&me)for(var r of me(n))e.indexOf(r)<0&&Ve.call(n,r)&&(t[r]=n[r]);return t};var dt=(n,e)=>{for(var t in e)Q(n,t,{get:e[t],enumerable:!0})},We=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let l of mt(e))!ke.call(n,l)&&l!==t&&Q(n,l,{get:()=>e[l],enumerable:!(r=ut(e,l))||r.enumerable});return n};var K=(n,e,t)=>(t=n!=null?at(pt(n)):{},We(e||!n||!n.__esModule?Q(t,"default",{value:n,enumerable:!0}):t,n)),ft=n=>We(Q({},"__esModule",{value:!0}),n);var b=(n,e,t)=>new Promise((r,l)=>{var u=w=>{try{i(t.next(w))}catch(y){l(y)}},d=w=>{try{i(t.throw(w))}catch(y){l(y)}},i=w=>w.done?r(w.value):Promise.resolve(w.value).then(u,d);i((t=t.apply(n,e)).next())});var Vt={};dt(Vt,{default:()=>Se});module.exports=ft(Vt);var ee=require("lodash");var Ae=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(r=>typeof r=="object"?JSON.stringify(r):r).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}},Ke={},gt={};function V(n){let e=(0,ee.get)(Ke,n);if(!e){let t=(0,ee.get)(gt,n);e=new Ae({name:n,logLevel:t}),(0,ee.set)(Ke,n,e)}return e}var B=require("@solana/web3.js"),ot=K(require("axios"));var ue=require("@solana/web3.js");var rt=require("@solana/web3.js");var v=K(require("bn.js")),Bt=K(require("decimal.js"));var Ge=K(require("big.js")),xt=K(require("bn.js"));var ve=K(require("toformat")),ht=ve.default,te=ht;var ne=K(require("big.js")),qe=K(require("bn.js")),Ue=K(require("decimal.js-light"));var X=K(require("bn.js"));var _e=9007199254740991;function q(n){let e=V("Sega_parseBigNumberish");if(n instanceof X.default)return n;if(typeof n=="string"){if(n.match(/^-?[0-9]+$/))return new X.default(n);e.logWithError(`invalid BigNumberish string: ${n}`)}return typeof n=="number"?(n%1&&e.logWithError(`BigNumberish number underflow: ${n}`),(n>=_e||n<=-_e)&&e.logWithError(`BigNumberish number overflow: ${n}`),new X.default(String(n))):typeof n=="bigint"?new X.default(n.toString()):(e.error(`invalid BigNumberish value: ${n}`),new X.default(0))}var de=V("module/fraction"),Be=te(ne.default),re=te(Ue.default),Tt={0:re.ROUND_DOWN,1:re.ROUND_HALF_UP,2:re.ROUND_UP},yt={0:ne.default.roundDown,1:ne.default.roundHalfUp,2:ne.default.roundUp},U=class n{constructor(e,t=new qe.default(1)){this.numerator=q(e),this.denominator=q(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(q(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(q(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(q(e));return new n(this.numerator.mul(t.numerator),this.denominator.mul(t.denominator))}div(e){let t=e instanceof n?e:new n(q(e));return new n(this.numerator.mul(t.denominator),this.denominator.mul(t.numerator))}toSignificant(e,t={groupSeparator:""},r=1){Number.isInteger(e)||de.logWithError(`${e} is not an integer.`),e<=0&&de.logWithError(`${e} is not positive.`),re.set({precision:e+1,rounding:Tt[r]});let l=new re(this.numerator.toString()).div(this.denominator.toString()).toSignificantDigits(e);return l.toFormat(l.decimalPlaces(),t)}toFixed(e,t={groupSeparator:""},r=1){return Number.isInteger(e)||de.logWithError(`${e} is not an integer.`),e<0&&de.logWithError(`${e} is negative.`),Be.DP=e,Be.RM=yt[r]||1,new Be(this.numerator.toString()).div(this.denominator.toString()).toFormat(e,t)}isZero(){return this.numerator.isZero()}};var nn=V("Sega_amount"),rn=te(Ge.default);var je=require("@solana/web3.js"),Ce=require("@solana/spl-token"),He={chainId:101,address:je.PublicKey.default.toBase58(),programId:Ce.TOKEN_PROGRAM_ID.toBase58(),decimals:9,symbol:"SOL",name:"solana",logoURI:"https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png",tags:[],priority:2,type:"sega",extensions:{coingeckoId:"solana"}},Y={chainId:101,address:"So11111111111111111111111111111111111111112",programId:Ce.TOKEN_PROGRAM_ID.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"}};var fe=require("@solana/web3.js");var N=require("@solana/web3.js"),ze=require("@solana/spl-token");function Ie({pubkey:n,isSigner:e=!1,isWritable:t=!0}){return{pubkey:n,isWritable:t,isSigner:e}}var cn=[Ie({pubkey:ze.TOKEN_PROGRAM_ID,isWritable:!1}),Ie({pubkey:N.SystemProgram.programId,isWritable:!1}),Ie({pubkey:N.SYSVAR_RENT_PUBKEY,isWritable:!1})];function Ye({publicKey:n,transformSol:e}){let t=Je(n.toString());if(t instanceof N.PublicKey)return e&&t.equals(ie)?Ne:t;if(e&&t.toString()===ie.toBase58())return Ne;if(typeof t=="string"){if(t===N.PublicKey.default.toBase58())return N.PublicKey.default;try{return new N.PublicKey(t)}catch(r){throw new Error("invalid public key")}}throw new Error("invalid public key")}function Je(n){try{return new N.PublicKey(n)}catch(e){return n}}var un=new N.PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),ln=new N.PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),mn=new N.PublicKey("SysvarRent111111111111111111111111111111111"),pn=new N.PublicKey("SysvarC1ock11111111111111111111111111111111"),Pt=new N.PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),dn=new N.PublicKey("Sysvar1nstructions1111111111111111111111111"),fn=N.SystemProgram.programId,gn=new N.PublicKey("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),hn=new N.PublicKey("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),bn=new N.PublicKey("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),Tn=new N.PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),yn=new N.PublicKey("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),xn=new N.PublicKey("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),wn=new N.PublicKey("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),Pn=new N.PublicKey("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),Sn=new N.PublicKey("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),kn=new N.PublicKey("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),An=new N.PublicKey("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),Ne=new N.PublicKey("So11111111111111111111111111111111111111112"),ie=N.PublicKey.default;var ge=class ge{constructor({mint:e,decimals:t,symbol:r,name:l,skipMint:u=!1,isToken2022:d=!1}){if(e===ie.toBase58()||e instanceof fe.PublicKey&&ie.equals(e)){this.decimals=Y.decimals,this.symbol=Y.symbol,this.name=Y.name,this.mint=new fe.PublicKey(Y.address),this.isToken2022=!1;return}this.decimals=t,this.symbol=r||e.toString().substring(0,6),this.name=l||e.toString().substring(0,6),this.mint=u?fe.PublicKey.default:Ye({publicKey:e}),this.isToken2022=d}equals(e){return this===e?!0:this.mint.equals(e.mint)}};ge.WSOL=new ge(j(O({},Y),{mint:Y.address}));var oe=ge;var he=class he{constructor({decimals:e,symbol:t="UNKNOWN",name:r="UNKNOWN"}){this.decimals=e,this.symbol=t,this.name=r}equals(e){return this===e}};he.SOL=new he(He);var Re=he;var Ze=K(require("bn.js"));var On=new U(new Ze.default(100));var qn=V("Sega_price");var kt=require("@solana/web3.js"),At=K(require("bn.js"));var St=new v.default(0),wr=new v.default(1),Pr=new v.default(2),Sr=new v.default(3),kr=new v.default(5),wt=new v.default(10),Ar=new v.default(100),Br=new v.default(1e3),Cr=new v.default(1e4);function Me(n,e=1,t=[]){let r=[...n];if(e<=0)return t;for(;r.length;)t.push(r.splice(0,e));return t}var Rt=require("@solana/web3.js"),Mt=require("@solana/spl-token");var E=require("@solana/web3.js");var se={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"};var tt=require("@solana/spl-token");var et=V("Sega_txUtil"),nt=1644;function be(n){let e=[],t=[];return n.microLamports&&(e.push(E.ComputeBudgetProgram.setComputeUnitPrice({microLamports:n.microLamports})),t.push(se.SetComputeUnitPrice)),n.units&&(e.push(E.ComputeBudgetProgram.setComputeUnitLimit({units:n.units})),t.push(se.SetComputeUnitLimit)),{instructions:e,instructionTypes:t}}function $(n,e){return b(this,null,function*(){var r,l;let t=e!=null?e:"confirmed";return(l=yield(r=n.getLatestBlockhash)==null?void 0:r.call(n,{commitment:t}))==null?void 0:l.blockhash})}function Te(n,e){return b(this,null,function*(){return n.getSignatureStatuses([e]),new Promise((t,r)=>{let l=setTimeout(r,6e4);n.onSignature(e,u=>{if(clearTimeout(l),!u.err){t("");return}r(Object.assign(u.err,{txId:e}))},"confirmed")})})}function Ct(n,e){n.length<1&&et.logWithError(`no instructions provided: ${n.toString()}`),e.length<1&&et.logWithError(`no signers provided:, ${e.toString()}`);let t=new E.Transaction;t.recentBlockhash="11111111111111111111111111111111",t.feePayer=e[0],t.add(...n);try{return Buffer.from(t.serialize({verifySignatures:!1})).toString("base64").length<nt}catch(r){return!1}}function ae({instructions:n,payer:e,signers:t}){return Ct(n,[e,...t])}function ce({instructions:n,payer:e,lookupTableAddressAccount:t,recentBlockhash:r=E.Keypair.generate().publicKey.toString()}){let u=new E.TransactionMessage({payerKey:e,recentBlockhash:r,instructions:n}).compileToV0Message(Object.values(t!=null?t:{}));try{return Buffer.from(new E.VersionedTransaction(u).serialize()).toString("base64").length<nt}catch(d){return!1}}var It=n=>Buffer.isBuffer(n)?n:n instanceof Uint8Array?Buffer.from(n.buffer,n.byteOffset,n.byteLength):Buffer.from(n),Nt=n=>{let e=n.serialize({requireAllSignatures:!1,verifySignatures:!1});n instanceof E.VersionedTransaction&&(e=It(e));try{return e instanceof Buffer?e.toString("base64"):Buffer.from(e).toString("base64")}catch(t){return e.toString("base64")}};function J(n){let e=[];return n.forEach(t=>{t instanceof E.Transaction&&(t.recentBlockhash||(t.recentBlockhash=tt.TOKEN_PROGRAM_ID.toBase58()),t.feePayer||(t.feePayer=E.Keypair.generate().publicKey)),e.push(Nt(t))}),console.log("simulate tx string:",e),e}var G=require("@solana/web3.js"),zr=new G.PublicKey("SegazTQwbYWknDZkJ6j2Kgvm5gw3MrHGKtWstZdoNKZ"),Yr=new G.PublicKey("Ajk8d9bERSaFdeoT1d8JUVfaDayrYLnAdgeB47TFMUaG"),Jr=new G.PublicKey("2HbjxVVKJ7Ct72Rcd8WK4VTqmwTXL5aAggkH1CHGFGmh"),Dt=new G.PublicKey("auetiVUVJkRxvNPLYEvVnz8UJSqQ1VgoA83PcicHVD1"),Lt=new G.PublicKey("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y"),Ft=new G.PublicKey("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y");var Zr={SERUM_MARKET:G.PublicKey.default,UTIL1216:G.PublicKey.default,CREATE_CPMM_POOL_PROGRAM:Dt,CREATE_CPMM_POOL_AUTH:Lt,CREATE_CPMM_POOL_FEE_ACC:Ft};var Et=K(require("bn.js"));var Ot=require("@solana/web3.js");var ye=require("@solana/spl-token");var De=V("Sega_accountInfo_util");function it(n,e,t){return b(this,null,function*(){let{batchRequest:r,commitment:l="confirmed",chunkCount:u=100}=O({batchRequest:!1},t),d=Me(e,u),i=new Array(d.length).fill([]);if(r){let w=d.map(P=>({methodName:"getMultipleAccounts",args:n._buildArgs([P.map(x=>x.toBase58())],l,"base64")})),y=Me(w,10);i=(yield(yield Promise.all(y.map(P=>b(this,null,function*(){return yield n._rpcBatchRequest(P)})))).flat()).map(P=>(P.error&&De.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${P.error.message}`),P.result.value.map(C=>{if(C){let{data:x,executable:m,lamports:h,owner:o,rentEpoch:S}=C;return x.length!==2&&x[1]!=="base64"&&De.logWithError("info must be base64 encoded, RPC_ERROR"),{data:Buffer.from(x[0],"base64"),executable:m,lamports:h,owner:new rt.PublicKey(o),rentEpoch:S}}return null})))}else try{i=yield Promise.all(d.map(w=>n.getMultipleAccountsInfo(w,l)))}catch(w){w instanceof Error&&De.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${w.message}`)}return i.flat()})}function Le(t){return b(this,arguments,function*({connection:n,address:e}){let r=yield it(n,[...new Set(e.map(u=>u.toString()))].map(u=>new ue.PublicKey(u))),l={};for(let u=0;u<e.length;u++){let d=r[u],i=e[u];if(!d)continue;let w=new ue.AddressLookupTableAccount({key:i,state:ue.AddressLookupTableAccount.deserialize(d.data)});l[i.toString()]=w,xe[i.toString()]=w}return l})}var xe={};var we=2e3,Pe=class{constructor(e){this.instructions=[];this.endInstructions=[];this.lookupTableAddress=[];this.signers=[];this.instructionTypes=[];this.endInstructionTypes=[];this.connection=e.connection,this.feePayer=e.feePayer,this.signAllTransactions=e.signAllTransactions,this.owner=e.owner,this.cluster=e.cluster,this.blockhashCommitment=e.blockhashCommitment,this.loopMultiTxStatus=!!e.loopMultiTxStatus}get AllTxData(){return{instructions:this.instructions,endInstructions:this.endInstructions,signers:this.signers,instructionTypes:this.instructionTypes,endInstructionTypes:this.endInstructionTypes,lookupTableAddress:this.lookupTableAddress}}get allInstructions(){return[...this.instructions,...this.endInstructions]}getComputeBudgetConfig(){return b(this,null,function*(){var r;let e=(yield ot.default.get("https://solanacompass.com/api/fees?cacheFreshTime=300000")).data,{avg:t}=(r=e==null?void 0:e[15])!=null?r:{};if(t)return{units:6e5,microLamports:Math.min(Math.ceil(t*1e6/6e5),25e3)}})}addCustomComputeBudget(e){if(e){let{instructions:t,instructionTypes:r}=be(e);return this.instructions.unshift(...t),this.instructionTypes.unshift(...r),!0}return!1}addTipInstruction(e){var t;return e?(this.endInstructions.push(B.SystemProgram.transfer({fromPubkey:(t=e.feePayer)!=null?t:this.feePayer,toPubkey:new B.PublicKey(e.address),lamports:BigInt(e.amount.toString())})),this.endInstructionTypes.push(se.TransferTip),!0):!1}calComputeBudget(r){return b(this,arguments,function*({config:e,defaultIns:t}){try{let l=e||(yield this.getComputeBudgetConfig());if(this.addCustomComputeBudget(l))return;t&&this.instructions.unshift(...t)}catch(l){t&&this.instructions.unshift(...t)}})}addInstruction({instructions:e=[],endInstructions:t=[],signers:r=[],instructionTypes:l=[],endInstructionTypes:u=[],lookupTableAddress:d=[]}){return this.instructions.push(...e),this.endInstructions.push(...t),this.signers.push(...r),this.instructionTypes.push(...l),this.endInstructionTypes.push(...u),this.lookupTableAddress.push(...d.filter(i=>i!==B.PublicKey.default.toString())),this}versionBuild(r){return b(this,arguments,function*({txVersion:e,extInfo:t}){return e===0?yield this.buildV0(O({},t||{})):this.build(t)})}build(e){var r;let t=new B.Transaction;return this.allInstructions.length&&t.add(...this.allInstructions),t.feePayer=this.feePayer,(r=this.owner)!=null&&r.signer&&!this.signers.some(l=>l.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer),{builder:this,transaction:t,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:l=>b(this,null,function*(){var y;let{recentBlockHash:u,skipPreflight:d=!0,sendAndConfirm:i}=l||{},w=u!=null?u:yield $(this.connection,this.blockhashCommitment);if(t.recentBlockhash=w,this.signers.length&&t.sign(...this.signers),J([t]),(y=this.owner)!=null&&y.isKeyPair)return{txId:i?yield(0,B.sendAndConfirmTransaction)(this.connection,t,this.signers.find(P=>P.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:d}):yield this.connection.sendRawTransaction(t.serialize(),{skipPreflight:d}),signedTx:t};if(this.signAllTransactions){let g=yield this.signAllTransactions([t]);if(this.signers.length)for(let P of g)try{P.sign(...this.signers)}catch(C){}return{txId:yield this.connection.sendRawTransaction(g[0].serialize(),{skipPreflight:d}),signedTx:g[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:e||{}}}buildMultiTx(e){var y;let{extraPreBuildData:t=[],extInfo:r}=e,{transaction:l}=this.build(r),u=t.filter(g=>g.transaction.instructions.length>0),d=[l,...u.map(g=>g.transaction)],i=[this.signers,...u.map(g=>g.signers)],w=[...this.instructionTypes,...u.map(g=>g.instructionTypes).flat()];return(y=this.owner)!=null&&y.signer&&i.forEach(g=>{g.some(P=>P.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),{builder:this,transactions:d,signers:i,instructionTypes:w,execute:g=>b(this,null,function*(){var S;let{sequentially:P,onTxUpdate:C,skipTxCount:x=0,recentBlockHash:m,skipPreflight:h=!0}=g||{},o=m!=null?m:yield $(this.connection,this.blockhashCommitment);if((S=this.owner)!=null&&S.isKeyPair){if(P){let p=[],k=0;for(let c of d){if(++k,k<=x)continue;let a=yield(0,B.sendAndConfirmTransaction)(this.connection,c,this.signers.find(s=>s.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:h});p.push(a)}return{txIds:p,signedTxs:d}}return{txIds:yield yield Promise.all(d.map(p=>b(this,null,function*(){return p.recentBlockhash=o,yield this.connection.sendRawTransaction(p.serialize(),{skipPreflight:h})}))),signedTxs:d}}if(this.signAllTransactions){let p=d.map((c,a)=>(c.recentBlockhash=o,i[a].length&&c.sign(...i[a]),c));J(p);let k=yield this.signAllTransactions(p);if(P){let c=0,a=[],s=()=>b(this,null,function*(){if(!k[c])return;let T=yield this.connection.sendRawTransaction(k[c].serialize(),{skipPreflight:h});a.push({txId:T,status:"sent",signedTx:k[c]}),C==null||C([...a]),c++;let f=!1,A=null,R=null,D=I=>{A!==null&&clearInterval(A),R!==null&&this.connection.removeSignatureListener(R);let M=a.findIndex(L=>L.txId===T);if(M>-1){if(a[M].status==="error"||a[M].status==="success")return;a[M].status=I.err?"error":"success"}C==null||C([...a]),I.err||s()};this.loopMultiTxStatus&&(A=setInterval(()=>b(this,null,function*(){var I;if(f){clearInterval(A);return}try{let M=yield this.connection.getTransaction(T,{commitment:"confirmed",maxSupportedTransactionVersion:0});M&&(f=!0,clearInterval(A),D({err:((I=M.meta)==null?void 0:I.err)||null}),console.log("tx status from getTransaction:",T))}catch(M){f=!0,clearInterval(A),console.error("getTransaction timeout:",M,T)}}),we)),R=this.connection.onSignature(T,I=>{if(f){this.connection.removeSignatureListener(R);return}f=!0,D(I)},"confirmed"),this.connection.getSignatureStatus(T)});return yield s(),{txIds:a.map(T=>T.txId),signedTxs:k}}else{let c=[];for(let a=0;a<k.length;a+=1){let s=yield this.connection.sendRawTransaction(k[a].serialize(),{skipPreflight:h});c.push(s)}return{txIds:c,signedTxs:k}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:r||{}}}versionMultiBuild(l){return b(this,arguments,function*({extraPreBuildData:e,txVersion:t,extInfo:r}){return t===0?yield this.buildV0MultiTx({extraPreBuildData:e,buildProps:r||{}}):this.buildMultiTx({extraPreBuildData:e,extInfo:r})})}buildV0(e){return b(this,null,function*(){var h;let m=e||{},{lookupTableCache:t={},lookupTableAddress:r=[],forerunCreate:l,recentBlockhash:u}=m,d=pe(m,["lookupTableCache","lookupTableAddress","forerunCreate","recentBlockhash"]),i=O(O({},this.cluster==="devnet"?{}:xe),t),w=Array.from(new Set([...r,...this.lookupTableAddress])),y=[];for(let o of w)i[o]===void 0&&y.push(new B.PublicKey(o));let g=yield Le({connection:this.connection,address:y});for(let[o,S]of Object.entries(g))i[o]=S;let P=l?B.PublicKey.default.toBase58():u!=null?u:yield $(this.connection,this.blockhashCommitment),C=new B.TransactionMessage({payerKey:this.feePayer,recentBlockhash:P,instructions:[...this.allInstructions]}).compileToV0Message(Object.values(i));(h=this.owner)!=null&&h.signer&&!this.signers.some(o=>o.publicKey.equals(this.owner.publicKey))&&this.signers.push(this.owner.signer);let x=new B.VersionedTransaction(C);return x.sign(this.signers),{builder:this,transaction:x,signers:this.signers,instructionTypes:[...this.instructionTypes,...this.endInstructionTypes],execute:o=>b(this,null,function*(){var k;let{skipPreflight:S=!0,sendAndConfirm:p}=o||{};if(J([x]),(k=this.owner)!=null&&k.isKeyPair){let c=yield this.connection.sendTransaction(x,{skipPreflight:S});return p&&(yield Te(this.connection,c)),{txId:c,signedTx:x}}if(this.signAllTransactions){let c=yield this.signAllTransactions([x]);if(this.signers.length)for(let a of c)try{a.sign(this.signers)}catch(s){}return{txId:yield this.connection.sendTransaction(c[0],{skipPreflight:S}),signedTx:c[0]}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:d||{}}})}buildV0MultiTx(e){return b(this,null,function*(){var y;let{extraPreBuildData:t=[],buildProps:r}=e,{transaction:l}=yield this.buildV0(r),u=t.filter(g=>g.builder.instructions.length>0),d=[l,...u.map(g=>g.transaction)],i=[this.signers,...u.map(g=>g.signers)],w=[...this.instructionTypes,...u.map(g=>g.instructionTypes).flat()];return(y=this.owner)!=null&&y.signer&&i.forEach(g=>{g.some(P=>P.publicKey.equals(this.owner.publicKey))||this.signers.push(this.owner.signer)}),d.forEach((g,P)=>b(this,null,function*(){g.sign(i[P])})),{builder:this,transactions:d,signers:i,instructionTypes:w,buildProps:r,execute:g=>b(this,null,function*(){var h;let{sequentially:P,onTxUpdate:C,recentBlockHash:x,skipPreflight:m=!0}=g||{};if(x&&d.forEach(o=>o.message.recentBlockhash=x),J(d),(h=this.owner)!=null&&h.isKeyPair){if(P){let o=[];for(let S of d){let p=yield this.connection.sendTransaction(S,{skipPreflight:m});yield Te(this.connection,p),o.push(p)}return{txIds:o,signedTxs:d}}return{txIds:yield Promise.all(d.map(o=>b(this,null,function*(){return yield this.connection.sendTransaction(o,{skipPreflight:m})}))),signedTxs:d}}if(this.signAllTransactions){let o=yield this.signAllTransactions(d);if(P){let S=0,p=[],k=()=>b(this,null,function*(){if(!o[S])return;let c=yield this.connection.sendTransaction(o[S],{skipPreflight:m});p.push({txId:c,status:"sent",signedTx:o[S]}),C==null||C([...p]),S++;let a=!1,s=null,T=null,f=A=>{s!==null&&clearInterval(s),T!==null&&this.connection.removeSignatureListener(T);let R=p.findIndex(D=>D.txId===c);if(R>-1){if(p[R].status==="error"||p[R].status==="success")return;p[R].status=A.err?"error":"success"}C==null||C([...p]),A.err||k()};this.loopMultiTxStatus&&(s=setInterval(()=>b(this,null,function*(){var A;if(a){clearInterval(s);return}try{let R=yield this.connection.getTransaction(c,{commitment:"confirmed",maxSupportedTransactionVersion:0});R&&(a=!0,clearInterval(s),f({err:((A=R.meta)==null?void 0:A.err)||null}),console.log("tx status from getTransaction:",c))}catch(R){a=!0,clearInterval(s),console.error("getTransaction timeout:",R,c)}}),we)),T=this.connection.onSignature(c,A=>{if(a){this.connection.removeSignatureListener(T);return}a=!0,f(A)},"confirmed"),this.connection.getSignatureStatus(c)});return k(),{txIds:[],signedTxs:o}}else{let S=[];for(let p=0;p<o.length;p+=1){let k=yield this.connection.sendTransaction(o[p],{skipPreflight:m});S.push(k)}return{txIds:S,signedTxs:o}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:r||{}}})}sizeCheckBuild(e){return b(this,null,function*(){var C;let P=e||{},{splitIns:t=[],computeBudgetConfig:r}=P,l=pe(P,["splitIns","computeBudgetConfig"]),u=r?be(r):{instructions:[],instructionTypes:[]},d=this.signers.reduce((x,m)=>j(O({},x),{[m.publicKey.toBase58()]:m}),{}),i=[],w=[],y=[],g=0;if(this.allInstructions.forEach(x=>{let m=[...y,x],h=r?[...u.instructions,...m]:m,S=[...new Set(m.map(p=>p.keys.filter(k=>k.isSigner).map(k=>k.pubkey.toString())).flat()).values()].map(p=>new B.PublicKey(p));if(x!==t[g]&&y.length<12&&(ae({instructions:h,payer:this.feePayer,signers:S})||ae({instructions:m,payer:this.feePayer,signers:S})))y.push(x);else{if(y.length===0)throw Error("item ins too big");g+=x===t[g]?1:0,ae({instructions:r?[...u.instructions,...y]:[...y],payer:this.feePayer,signers:S})?i.push(new B.Transaction().add(...u.instructions,...y)):i.push(new B.Transaction().add(...y)),w.push(Array.from(new Set(y.map(p=>p.keys.filter(k=>k.isSigner).map(k=>k.pubkey.toString())).flat())).map(p=>d[p]).filter(p=>p!==void 0)),y=[x]}}),y.length>0){let m=[...new Set(y.map(h=>h.keys.filter(o=>o.isSigner).map(o=>o.pubkey.toString())).flat()).values()].map(h=>d[h]).filter(h=>h!==void 0);ae({instructions:r?[...u.instructions,...y]:[...y],payer:this.feePayer,signers:m.map(h=>h.publicKey)})?i.push(new B.Transaction().add(...u.instructions,...y)):i.push(new B.Transaction().add(...y)),w.push(m)}return i.forEach(x=>x.feePayer=this.feePayer),(C=this.owner)!=null&&C.signer&&w.forEach(x=>{x.some(m=>m.publicKey.equals(this.owner.publicKey))||x.push(this.owner.signer)}),{builder:this,transactions:i,signers:w,instructionTypes:this.instructionTypes,execute:x=>b(this,null,function*(){var c;let{sequentially:m,onTxUpdate:h,skipTxCount:o=0,recentBlockHash:S,skipPreflight:p=!0}=x||{},k=S!=null?S:yield $(this.connection,this.blockhashCommitment);if(i.forEach((a,s)=>b(this,null,function*(){a.recentBlockhash=k,w[s].length&&a.sign(...w[s])})),J(i),(c=this.owner)!=null&&c.isKeyPair){if(m){let a=0,s=[];for(let T of i){if(++a,a<=o){s.push("tx skipped");continue}let f=yield(0,B.sendAndConfirmTransaction)(this.connection,T,this.signers.find(A=>A.publicKey.equals(this.owner.publicKey))?this.signers:[...this.signers,this.owner.signer],{skipPreflight:p});s.push(f)}return{txIds:s,signedTxs:i}}return{txIds:yield Promise.all(i.map(a=>b(this,null,function*(){return yield this.connection.sendRawTransaction(a.serialize(),{skipPreflight:p})}))),signedTxs:i}}if(this.signAllTransactions){let a=yield this.signAllTransactions(i.slice(o,i.length)),s=[...i.slice(0,o),...a];if(m){let T=0,f=[],A=()=>b(this,null,function*(){if(!s[T])return;T<o&&(f.push({txId:"",status:"success",signedTx:s[T]}),h==null||h([...f]),T++,A());let R=yield this.connection.sendRawTransaction(s[T].serialize(),{skipPreflight:p});f.push({txId:R,status:"sent",signedTx:s[T]}),h==null||h([...f]),T++;let D=!1,I=null,M=null,L=W=>{I!==null&&clearInterval(I),M!==null&&this.connection.removeSignatureListener(M);let F=f.findIndex(H=>H.txId===R);if(F>-1){if(f[F].status==="error"||f[F].status==="success")return;f[F].status=W.err?"error":"success"}h==null||h([...f]),W.err||A()};this.loopMultiTxStatus&&(I=setInterval(()=>b(this,null,function*(){var W;if(D){clearInterval(I);return}try{let F=yield this.connection.getTransaction(R,{commitment:"confirmed",maxSupportedTransactionVersion:0});F&&(D=!0,clearInterval(I),L({err:((W=F.meta)==null?void 0:W.err)||null}),console.log("tx status from getTransaction:",R))}catch(F){D=!0,clearInterval(I),console.error("getTransaction timeout:",F,R)}}),we)),M=this.connection.onSignature(R,W=>{if(D){this.connection.removeSignatureListener(M);return}D=!0,L(W)},"confirmed"),this.connection.getSignatureStatus(R)});return yield A(),{txIds:f.map(R=>R.txId),signedTxs:s}}else{let T=[];for(let f=0;f<s.length;f+=1){let A=yield this.connection.sendRawTransaction(s[f].serialize(),{skipPreflight:p});T.push(A)}return{txIds:T,signedTxs:s}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:l||{}}})}sizeCheckBuildV0(e){return b(this,null,function*(){var k;let p=e||{},{computeBudgetConfig:t,splitIns:r=[],lookupTableCache:l={},lookupTableAddress:u=[]}=p,d=pe(p,["computeBudgetConfig","splitIns","lookupTableCache","lookupTableAddress"]),i=O(O({},this.cluster==="devnet"?{}:xe),l),w=Array.from(new Set([...this.lookupTableAddress,...u])),y=[];for(let c of w)i[c]===void 0&&y.push(new B.PublicKey(c));let g=yield Le({connection:this.connection,address:y});for(let[c,a]of Object.entries(g))i[c]=a;let P=t?be(t):{instructions:[],instructionTypes:[]},C=yield $(this.connection,this.blockhashCommitment),x=this.signers.reduce((c,a)=>j(O({},c),{[a.publicKey.toBase58()]:a}),{}),m=[],h=[],o=[],S=0;if(this.allInstructions.forEach(c=>{let a=[...o,c],s=t?[...P.instructions,...a]:a;if(c!==r[S]&&o.length<12&&(ce({instructions:s,payer:this.feePayer,lookupTableAddressAccount:i})||ce({instructions:a,payer:this.feePayer,lookupTableAddressAccount:i})))o.push(c);else{if(o.length===0)throw Error("item ins too big");S+=c===r[S]?1:0;let T={};for(let f of[...new Set(w)])i[f]!==void 0&&(T[f]=i[f]);if(t&&ce({instructions:[...P.instructions,...o],payer:this.feePayer,lookupTableAddressAccount:i,recentBlockhash:C})){let f=new B.TransactionMessage({payerKey:this.feePayer,recentBlockhash:C,instructions:[...P.instructions,...o]}).compileToV0Message(Object.values(i));m.push(new B.VersionedTransaction(f))}else{let f=new B.TransactionMessage({payerKey:this.feePayer,recentBlockhash:C,instructions:[...o]}).compileToV0Message(Object.values(i));m.push(new B.VersionedTransaction(f))}h.push(Array.from(new Set(o.map(f=>f.keys.filter(A=>A.isSigner).map(A=>A.pubkey.toString())).flat())).map(f=>x[f]).filter(f=>f!==void 0)),o=[c]}}),o.length>0){let a=[...new Set(o.map(s=>s.keys.filter(T=>T.isSigner).map(T=>T.pubkey.toString())).flat()).values()].map(s=>x[s]).filter(s=>s!==void 0);if(t&&ce({instructions:[...P.instructions,...o],payer:this.feePayer,lookupTableAddressAccount:i,recentBlockhash:C})){let s=new B.TransactionMessage({payerKey:this.feePayer,recentBlockhash:C,instructions:[...P.instructions,...o]}).compileToV0Message(Object.values(i));m.push(new B.VersionedTransaction(s))}else{let s=new B.TransactionMessage({payerKey:this.feePayer,recentBlockhash:C,instructions:[...o]}).compileToV0Message(Object.values(i));m.push(new B.VersionedTransaction(s))}h.push(a)}return(k=this.owner)!=null&&k.signer&&h.forEach(c=>{c.some(a=>a.publicKey.equals(this.owner.publicKey))||c.push(this.owner.signer)}),{builder:this,transactions:m,buildProps:e,signers:h,instructionTypes:this.instructionTypes,execute:c=>b(this,null,function*(){var R;let{sequentially:a,onTxUpdate:s,skipTxCount:T=0,recentBlockHash:f,skipPreflight:A=!0}=c||{};if(m.map((D,I)=>b(this,null,function*(){h[I].length&&D.sign(h[I]),f&&(D.message.recentBlockhash=f)})),J(m),(R=this.owner)!=null&&R.isKeyPair){if(a){let D=0,I=[];for(let M of m){if(++D,D<=T){console.log("skip tx: ",D),I.push("tx skipped");continue}let L=yield this.connection.sendTransaction(M,{skipPreflight:A});yield Te(this.connection,L),I.push(L)}return{txIds:I,signedTxs:m}}return{txIds:yield Promise.all(m.map(D=>b(this,null,function*(){return yield this.connection.sendTransaction(D,{skipPreflight:A})}))),signedTxs:m}}if(this.signAllTransactions){let D=yield this.signAllTransactions(m.slice(T,m.length)),I=[...m.slice(0,T),...D];if(a){let M=0,L=[],W=()=>b(this,null,function*(){if(!I[M])return;if(M<T){L.push({txId:"",status:"success",signedTx:I[M]}),s==null||s([...L]),M++,W();return}let F=yield this.connection.sendTransaction(I[M],{skipPreflight:A});L.push({txId:F,status:"sent",signedTx:I[M]}),s==null||s([...L]),M++;let H=!1,Z=null,le=null,Ee=z=>{Z!==null&&clearInterval(Z),le!==null&&this.connection.removeSignatureListener(le);let _=L.findIndex(st=>st.txId===F);if(_>-1){if(L[_].status==="error"||L[_].status==="success")return;L[_].status=z.err?"error":"success"}s==null||s([...L]),z.err||W()};this.loopMultiTxStatus&&(Z=setInterval(()=>b(this,null,function*(){var z;if(H){clearInterval(Z);return}try{let _=yield this.connection.getTransaction(F,{commitment:"confirmed",maxSupportedTransactionVersion:0});_&&(H=!0,clearInterval(Z),Ee({err:((z=_.meta)==null?void 0:z.err)||null}),console.log("tx status from getTransaction:",F))}catch(_){H=!0,clearInterval(Z),console.error("getTransaction timeout:",_,F)}}),we)),le=this.connection.onSignature(F,z=>{if(H){this.connection.removeSignatureListener(le);return}H=!0,Ee(z)},"confirmed"),this.connection.getSignatureStatus(F)});return W(),{txIds:[],signedTxs:I}}else{let M=[];for(let L=0;L<I.length;L+=1){let W=yield this.connection.sendTransaction(I[L],{skipPreflight:A});M.push(W)}return{txIds:M,signedTxs:I}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:d||{}}})}};var Fe=(...n)=>n.map(e=>{try{return typeof e=="object"?JSON.stringify(e):e}catch(t){return e}}).join(", "),Se=class{constructor({scope:e,moduleName:t}){this.disabled=!1;this.scope=e,this.logger=V(t)}createTxBuilder(e){return this.scope.checkOwner(),new Pe({connection:this.scope.connection,feePayer:e||this.scope.ownerPubKey,cluster:this.scope.cluster,owner:this.scope.owner,blockhashCommitment:this.scope.blockhashCommitment,loopMultiTxStatus:this.scope.loopMultiTxStatus,api:this.scope.api,signAllTransactions:this.scope.signAllTransactions})}logDebug(...e){this.logger.debug(Fe(e))}logInfo(...e){this.logger.info(Fe(e))}logAndCreateError(...e){let t=Fe(e);throw new Error(t)}checkDisabled(){(this.disabled||!this.scope)&&this.logAndCreateError("module not working")}};
//# sourceMappingURL=moduleBase.js.map