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