UNPKG

@sega-so/sega-sdk

Version:

An SDK for building applications on top of SEGA.

2 lines 34.9 kB
"use strict";var ot=Object.create;var Q=Object.defineProperty,st=Object.defineProperties,at=Object.getOwnPropertyDescriptor,ct=Object.getOwnPropertyDescriptors,ut=Object.getOwnPropertyNames,me=Object.getOwnPropertySymbols,lt=Object.getPrototypeOf,Pe=Object.prototype.hasOwnProperty,Ee=Object.prototype.propertyIsEnumerable;var Le=(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={}))Pe.call(e,t)&&Le(n,t,e[t]);if(me)for(var t of me(e))Ee.call(e,t)&&Le(n,t,e[t]);return n},j=(n,e)=>st(n,ct(e));var pe=(n,e)=>{var t={};for(var r in n)Pe.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&&Ee.call(n,r)&&(t[r]=n[r]);return t};var mt=(n,e)=>{for(var t in e)Q(n,t,{get:e[t],enumerable:!0})},Oe=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let l of ut(e))!Pe.call(n,l)&&l!==t&&Q(n,l,{get:()=>e[l],enumerable:!(r=at(e,l))||r.enumerable});return n};var W=(n,e,t)=>(t=n!=null?ot(lt(n)):{},Oe(e||!n||!n.__esModule?Q(t,"default",{value:n,enumerable:!0}):t,n)),pt=n=>Oe(Q({},"__esModule",{value:!0}),n);var T=(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 Et={};mt(Et,{TxBuilder:()=>Me});module.exports=pt(Et);var B=require("@solana/web3.js"),rt=W(require("axios"));var ue=require("@solana/web3.js");var tt=require("@solana/web3.js");var v=W(require("bn.js")),kt=W(require("decimal.js"));var qe=W(require("big.js")),bt=W(require("bn.js"));var ee=require("lodash");var Se=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}},Ve={},dt={};function K(n){let e=(0,ee.get)(Ve,n);if(!e){let t=(0,ee.get)(dt,n);e=new Se({name:n,logLevel:t}),(0,ee.set)(Ve,n,e)}return e}var We=W(require("toformat")),ft=We.default,te=ft;var ne=W(require("big.js")),ve=W(require("bn.js")),_e=W(require("decimal.js-light"));var X=W(require("bn.js"));var Ke=9007199254740991;function q(n){let e=K("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>=Ke||n<=-Ke)&&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=K("module/fraction"),ke=te(ne.default),re=te(_e.default),ht={0:re.ROUND_DOWN,1:re.ROUND_HALF_UP,2:re.ROUND_UP},Tt={0:ne.default.roundDown,1:ne.default.roundHalfUp,2:ne.default.roundUp},U=class n{constructor(e,t=new ve.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:ht[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.`),ke.DP=e,ke.RM=Tt[r]||1,new ke(this.numerator.toString()).div(this.denominator.toString()).toFormat(e,t)}isZero(){return this.numerator.isZero()}};var en=K("Sega_amount"),tn=te(qe.default);var Ue=require("@solana/web3.js"),Ae=require("@solana/spl-token"),Ge={chainId:101,address:Ue.PublicKey.default.toBase58(),programId:Ae.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:Ae.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"),je=require("@solana/spl-token");function Be({pubkey:n,isSigner:e=!1,isWritable:t=!0}){return{pubkey:n,isWritable:t,isSigner:e}}var sn=[Be({pubkey:je.TOKEN_PROGRAM_ID,isWritable:!1}),Be({pubkey:N.SystemProgram.programId,isWritable:!1}),Be({pubkey:N.SYSVAR_RENT_PUBKEY,isWritable:!1})];function He({publicKey:n,transformSol:e}){let t=ze(n.toString());if(t instanceof N.PublicKey)return e&&t.equals(ie)?Ce:t;if(e&&t.toString()===ie.toBase58())return Ce;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 ze(n){try{return new N.PublicKey(n)}catch(e){return n}}var an=new N.PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),cn=new N.PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),un=new N.PublicKey("SysvarRent111111111111111111111111111111111"),ln=new N.PublicKey("SysvarC1ock11111111111111111111111111111111"),xt=new N.PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"),mn=new N.PublicKey("Sysvar1nstructions1111111111111111111111111"),pn=N.SystemProgram.programId,dn=new N.PublicKey("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R"),fn=new N.PublicKey("Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS"),gn=new N.PublicKey("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt"),hn=new N.PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),Tn=new N.PublicKey("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),bn=new N.PublicKey("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),yn=new N.PublicKey("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),xn=new N.PublicKey("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),wn=new N.PublicKey("NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa"),Pn=new N.PublicKey("ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo"),Sn=new N.PublicKey("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),Ce=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:He({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(Ge);var Ie=he;var Ye=W(require("bn.js"));var Ln=new U(new Ye.default(100));var vn=K("Sega_price");var Pt=require("@solana/web3.js"),St=W(require("bn.js"));var wt=new v.default(0),yr=new v.default(1),xr=new v.default(2),wr=new v.default(3),Pr=new v.default(5),yt=new v.default(10),Sr=new v.default(100),kr=new v.default(1e3),Ar=new v.default(1e4);function Ne(n,e=1,t=[]){let r=[...n];if(e<=0)return t;for(;r.length;)t.push(r.splice(0,e));return t}var It=require("@solana/web3.js"),Nt=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 Qe=require("@solana/spl-token");var $e=K("Sega_txUtil"),et=1644;function Te(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 T(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 be(n,e){return T(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 At(n,e){n.length<1&&$e.logWithError(`no instructions provided: ${n.toString()}`),e.length<1&&$e.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<et}catch(r){return!1}}function ae({instructions:n,payer:e,signers:t}){return At(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<et}catch(d){return!1}}var Bt=n=>Buffer.isBuffer(n)?n:n instanceof Uint8Array?Buffer.from(n.buffer,n.byteOffset,n.byteLength):Buffer.from(n),Ct=n=>{let e=n.serialize({requireAllSignatures:!1,verifySignatures:!1});n instanceof E.VersionedTransaction&&(e=Bt(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=Qe.TOKEN_PROGRAM_ID.toBase58()),t.feePayer||(t.feePayer=E.Keypair.generate().publicKey)),e.push(Ct(t))}),console.log("simulate tx string:",e),e}var G=require("@solana/web3.js"),jr=new G.PublicKey("SegazTQwbYWknDZkJ6j2Kgvm5gw3MrHGKtWstZdoNKZ"),Hr=new G.PublicKey("Ajk8d9bERSaFdeoT1d8JUVfaDayrYLnAdgeB47TFMUaG"),zr=new G.PublicKey("2HbjxVVKJ7Ct72Rcd8WK4VTqmwTXL5aAggkH1CHGFGmh"),Rt=new G.PublicKey("auetiVUVJkRxvNPLYEvVnz8UJSqQ1VgoA83PcicHVD1"),Dt=new G.PublicKey("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y"),Mt=new G.PublicKey("GzqQwxPSmUZnTyCfX9YWqi32MJg43ujP786ZoacL559Y");var Yr={SERUM_MARKET:G.PublicKey.default,UTIL1216:G.PublicKey.default,CREATE_CPMM_POOL_PROGRAM:Rt,CREATE_CPMM_POOL_AUTH:Dt,CREATE_CPMM_POOL_FEE_ACC:Mt};var Ft=W(require("bn.js"));var Lt=require("@solana/web3.js");var ye=require("@solana/spl-token");var Re=K("Sega_accountInfo_util");function nt(n,e,t){return T(this,null,function*(){let{batchRequest:r,commitment:l="confirmed",chunkCount:u=100}=O({batchRequest:!1},t),d=Ne(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=Ne(w,10);i=(yield(yield Promise.all(y.map(P=>T(this,null,function*(){return yield n._rpcBatchRequest(P)})))).flat()).map(P=>(P.error&&Re.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"&&Re.logWithError("info must be base64 encoded, RPC_ERROR"),{data:Buffer.from(x[0],"base64"),executable:m,lamports:h,owner:new tt.PublicKey(o),rentEpoch:S}}return null})))}else try{i=yield Promise.all(d.map(w=>n.getMultipleAccountsInfo(w,l)))}catch(w){w instanceof Error&&Re.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${w.message}`)}return i.flat()})}function De(t){return T(this,arguments,function*({connection:n,address:e}){let r=yield nt(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,Me=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 T(this,null,function*(){var r;let e=(yield rt.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}=Te(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 T(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 T(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=>T(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=>T(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=>T(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=()=>T(this,null,function*(){if(!k[c])return;let b=yield this.connection.sendRawTransaction(k[c].serialize(),{skipPreflight:h});a.push({txId:b,status:"sent",signedTx:k[c]}),C==null||C([...a]),c++;let f=!1,A=null,R=null,M=I=>{A!==null&&clearInterval(A),R!==null&&this.connection.removeSignatureListener(R);let D=a.findIndex(F=>F.txId===b);if(D>-1){if(a[D].status==="error"||a[D].status==="success")return;a[D].status=I.err?"error":"success"}C==null||C([...a]),I.err||s()};this.loopMultiTxStatus&&(A=setInterval(()=>T(this,null,function*(){var I;if(f){clearInterval(A);return}try{let D=yield this.connection.getTransaction(b,{commitment:"confirmed",maxSupportedTransactionVersion:0});D&&(f=!0,clearInterval(A),M({err:((I=D.meta)==null?void 0:I.err)||null}),console.log("tx status from getTransaction:",b))}catch(D){f=!0,clearInterval(A),console.error("getTransaction timeout:",D,b)}}),we)),R=this.connection.onSignature(b,I=>{if(f){this.connection.removeSignatureListener(R);return}f=!0,M(I)},"confirmed"),this.connection.getSignatureStatus(b)});return yield s(),{txIds:a.map(b=>b.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 T(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 T(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 De({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=>T(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 be(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 T(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)=>T(this,null,function*(){g.sign(i[P])})),{builder:this,transactions:d,signers:i,instructionTypes:w,buildProps:r,execute:g=>T(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 be(this.connection,p),o.push(p)}return{txIds:o,signedTxs:d}}return{txIds:yield Promise.all(d.map(o=>T(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=()=>T(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,b=null,f=A=>{s!==null&&clearInterval(s),b!==null&&this.connection.removeSignatureListener(b);let R=p.findIndex(M=>M.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(()=>T(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)),b=this.connection.onSignature(c,A=>{if(a){this.connection.removeSignatureListener(b);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 T(this,null,function*(){var C;let P=e||{},{splitIns:t=[],computeBudgetConfig:r}=P,l=pe(P,["splitIns","computeBudgetConfig"]),u=r?Te(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=>T(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)=>T(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 b of i){if(++a,a<=o){s.push("tx skipped");continue}let f=yield(0,B.sendAndConfirmTransaction)(this.connection,b,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=>T(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 b=0,f=[],A=()=>T(this,null,function*(){if(!s[b])return;b<o&&(f.push({txId:"",status:"success",signedTx:s[b]}),h==null||h([...f]),b++,A());let R=yield this.connection.sendRawTransaction(s[b].serialize(),{skipPreflight:p});f.push({txId:R,status:"sent",signedTx:s[b]}),h==null||h([...f]),b++;let M=!1,I=null,D=null,F=V=>{I!==null&&clearInterval(I),D!==null&&this.connection.removeSignatureListener(D);let L=f.findIndex(H=>H.txId===R);if(L>-1){if(f[L].status==="error"||f[L].status==="success")return;f[L].status=V.err?"error":"success"}h==null||h([...f]),V.err||A()};this.loopMultiTxStatus&&(I=setInterval(()=>T(this,null,function*(){var V;if(M){clearInterval(I);return}try{let L=yield this.connection.getTransaction(R,{commitment:"confirmed",maxSupportedTransactionVersion:0});L&&(M=!0,clearInterval(I),F({err:((V=L.meta)==null?void 0:V.err)||null}),console.log("tx status from getTransaction:",R))}catch(L){M=!0,clearInterval(I),console.error("getTransaction timeout:",L,R)}}),we)),D=this.connection.onSignature(R,V=>{if(M){this.connection.removeSignatureListener(D);return}M=!0,F(V)},"confirmed"),this.connection.getSignatureStatus(R)});return yield A(),{txIds:f.map(R=>R.txId),signedTxs:s}}else{let b=[];for(let f=0;f<s.length;f+=1){let A=yield this.connection.sendRawTransaction(s[f].serialize(),{skipPreflight:p});b.push(A)}return{txIds:b,signedTxs:s}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:l||{}}})}sizeCheckBuildV0(e){return T(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 De({connection:this.connection,address:y});for(let[c,a]of Object.entries(g))i[c]=a;let P=t?Te(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 b={};for(let f of[...new Set(w)])i[f]!==void 0&&(b[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(b=>b.isSigner).map(b=>b.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=>T(this,null,function*(){var R;let{sequentially:a,onTxUpdate:s,skipTxCount:b=0,recentBlockHash:f,skipPreflight:A=!0}=c||{};if(m.map((M,I)=>T(this,null,function*(){h[I].length&&M.sign(h[I]),f&&(M.message.recentBlockhash=f)})),J(m),(R=this.owner)!=null&&R.isKeyPair){if(a){let M=0,I=[];for(let D of m){if(++M,M<=b){console.log("skip tx: ",M),I.push("tx skipped");continue}let F=yield this.connection.sendTransaction(D,{skipPreflight:A});yield be(this.connection,F),I.push(F)}return{txIds:I,signedTxs:m}}return{txIds:yield Promise.all(m.map(M=>T(this,null,function*(){return yield this.connection.sendTransaction(M,{skipPreflight:A})}))),signedTxs:m}}if(this.signAllTransactions){let M=yield this.signAllTransactions(m.slice(b,m.length)),I=[...m.slice(0,b),...M];if(a){let D=0,F=[],V=()=>T(this,null,function*(){if(!I[D])return;if(D<b){F.push({txId:"",status:"success",signedTx:I[D]}),s==null||s([...F]),D++,V();return}let L=yield this.connection.sendTransaction(I[D],{skipPreflight:A});F.push({txId:L,status:"sent",signedTx:I[D]}),s==null||s([...F]),D++;let H=!1,Z=null,le=null,Fe=z=>{Z!==null&&clearInterval(Z),le!==null&&this.connection.removeSignatureListener(le);let _=F.findIndex(it=>it.txId===L);if(_>-1){if(F[_].status==="error"||F[_].status==="success")return;F[_].status=z.err?"error":"success"}s==null||s([...F]),z.err||V()};this.loopMultiTxStatus&&(Z=setInterval(()=>T(this,null,function*(){var z;if(H){clearInterval(Z);return}try{let _=yield this.connection.getTransaction(L,{commitment:"confirmed",maxSupportedTransactionVersion:0});_&&(H=!0,clearInterval(Z),Fe({err:((z=_.meta)==null?void 0:z.err)||null}),console.log("tx status from getTransaction:",L))}catch(_){H=!0,clearInterval(Z),console.error("getTransaction timeout:",_,L)}}),we)),le=this.connection.onSignature(L,z=>{if(H){this.connection.removeSignatureListener(le);return}H=!0,Fe(z)},"confirmed"),this.connection.getSignatureStatus(L)});return V(),{txIds:[],signedTxs:I}}else{let D=[];for(let F=0;F<I.length;F+=1){let V=yield this.connection.sendTransaction(I[F],{skipPreflight:A});D.push(V)}return{txIds:D,signedTxs:I}}}throw new Error("please provide owner in keypair format or signAllTransactions function")}),extInfo:d||{}}})}};0&&(module.exports={TxBuilder}); //# sourceMappingURL=txTool.js.map