UNPKG

@sega-so/sega-sdk

Version:

An SDK for building applications on top of SEGA.

2 lines 8.06 kB
var u=(t,e,r)=>new Promise((o,n)=>{var m=s=>{try{l(r.next(s))}catch(i){n(i)}},a=s=>{try{l(r.throw(s))}catch(i){n(i)}},l=s=>s.done?o(s.value):Promise.resolve(s.value).then(m,a);l((r=r.apply(t,e)).next())});import{ComputeBudgetProgram as V,Keypair as A,PublicKey as P,Transaction as d,TransactionMessage as k,VersionedTransaction as L}from"@solana/web3.js";import{get as w,set as v}from"lodash";var h=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 r=e.map(o=>typeof o=="object"?JSON.stringify(o):o).join(", ");throw new Error(r)}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}},y={},R={};function S(t){let e=w(y,t);if(!e){let r=w(R,t);e=new h({name:t,logLevel:r}),v(y,t,e)}return e}var C={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 E}from"@solana/spl-token";var c=S("Sega_txUtil"),b=1644;function J(t){let e=[],r=[];return t.microLamports&&(e.push(V.setComputeUnitPrice({microLamports:t.microLamports})),r.push(C.SetComputeUnitPrice)),t.units&&(e.push(V.setComputeUnitLimit({units:t.units})),r.push(C.SetComputeUnitLimit)),{instructions:e,instructionTypes:r}}function X(t,e){return u(this,null,function*(){var o,n;let r=e!=null?e:"confirmed";return(n=yield(o=t.getLatestBlockhash)==null?void 0:o.call(t,{commitment:r}))==null?void 0:n.blockhash})}function Y(t,e){return u(this,null,function*(){return t.getSignatureStatuses([e]),new Promise((r,o)=>{let n=setTimeout(o,6e4);t.onSignature(e,m=>{if(clearTimeout(n),!m.err){r("");return}o(Object.assign(m.err,{txId:e}))},"confirmed")})})}function T(t,e){t.length<1&&c.logWithError(`no instructions provided: ${t.toString()}`),e.length<1&&c.logWithError(`no signers provided:, ${e.toString()}`);let r=new d;r.recentBlockhash="11111111111111111111111111111111",r.feePayer=e[0],r.add(...t);try{return Buffer.from(r.serialize({verifySignatures:!1})).toString("base64").length<b}catch(o){return!1}}function Z(t,e,r,o=!0){return u(this,null,function*(){let n=new P("SegaSimuLateTransaction11111111111111111"),m=[],a=new d;a.feePayer=n;for(let i of e)T([...a.instructions,i],[n])||(m.push(a),a=new d,a.feePayer=n),a.add(i);a.instructions.length>0&&m.push(a);let l=[];try{if(l=yield F(t,m,o),l.find(i=>i.err!==null))throw Error("rpc simulateTransaction error")}catch(i){i instanceof Error&&c.logWithError("failed to simulate for instructions","RPC_ERROR",{message:i.message})}let s=[];for(let i of l)if(c.debug("simulate result:",i),i.logs){let g=i.logs.filter(f=>f&&f.includes(r));c.debug("filteredLog:",s),g.length||c.logWithError("simulate log not match keyword","keyword",r),s.push(...g)}return s})}function Q(t,e){let r=t.match(/{["\w:,]+}/g);return!r||r.length!==1?c.logWithError(`simulate log fail to match json, keyword: ${e}`):r[0]}function ee(t,e){let o=new RegExp(`"${e}":(\\d+)`,"g").exec(t);return!o||o.length!==2?c.logWithError(`simulate log fail to match key", key: ${e}`):o[1]}function te(t,e){let[r,o]=P.findProgramAddressSync(t,e);return{publicKey:r,nonce:o}}function F(t,e,r){return u(this,null,function*(){let o=[];if(r){let n=yield t.getLatestBlockhash(),m=[];for(let i of e){i.recentBlockhash=n.blockhash,i.lastValidBlockHeight=n.lastValidBlockHeight;let f=i._compile().serialize(),I=i._serialize(f).toString("base64");m.push(I)}let a=m.map(i=>({methodName:"simulateTransaction",args:t._buildArgs([i],void 0,"base64")})),l=[],s=20;for(let i=0;i<Math.ceil(a.length/s);i++)l.push(a.slice(i*s,(i+1)*s));o=yield(yield Promise.all(l.map(i=>u(this,null,function*(){return(yield t._rpcBatchRequest(i)).map(g=>g.result.value)})))).flat()}else try{o=yield Promise.all(e.map(n=>u(this,null,function*(){return yield(yield t.simulateTransaction(n)).value})))}catch(n){n instanceof Error&&c.logWithError("failed to get info for multiple accounts","RPC_ERROR",{message:n.message})}return o})}function re({instructions:t,payer:e,signers:r}){return T(t,[e,...r])}function ie({instructions:t,payer:e,lookupTableAddressAccount:r,recentBlockhash:o=A.generate().publicKey.toString()}){let m=new k({payerKey:e,recentBlockhash:o,instructions:t}).compileToV0Message(Object.values(r!=null?r:{}));try{return Buffer.from(new L(m).serialize()).toString("base64").length<b}catch(a){return!1}}var p={time:0,data:void 0};function oe(t){return u(this,null,function*(){if(!p.data||(Date.now()-p.time)/1e3>30){let e=yield t.getEpochInfo();return p={time:Date.now(),data:e},e}else return p.data})}var B=t=>Buffer.isBuffer(t)?t:t instanceof Uint8Array?Buffer.from(t.buffer,t.byteOffset,t.byteLength):Buffer.from(t),x=t=>{let e=t.serialize({requireAllSignatures:!1,verifySignatures:!1});t instanceof L&&(e=B(e));try{return e instanceof Buffer?e.toString("base64"):Buffer.from(e).toString("base64")}catch(r){return e.toString("base64")}};function ne(t){let e=[];return t.forEach(r=>{r instanceof d&&(r.recentBlockhash||(r.recentBlockhash=E.toBase58()),r.feePayer||(r.feePayer=A.generate().publicKey)),e.push(x(r))}),console.log("simulate tx string:",e),e}function ae(t){let e=t.serialize({requireAllSignatures:!1,verifySignatures:!1});return t instanceof L&&(e=B(e)),e.toString("base64")}export{b as MAX_BASE64_SIZE,J as addComputeBudget,re as checkLegacyTxSize,ie as checkV0TxSize,Y as confirmTransaction,te as findProgramAddress,T as forecastTransactionSize,oe as getEpochInfo,X as getRecentBlockHash,Q as parseSimulateLogToJson,ee as parseSimulateValue,ne as printSimulate,Z as simulateMultipleInstruction,F as simulateTransaction,B as toBuffer,ae as transformTxToBase64,x as txToBase64}; //# sourceMappingURL=txUtils.mjs.map