test-raydium-sdk-v2
Version:
An SDK for building applications on top of Raydium.
2 lines • 6.9 kB
JavaScript
import{PublicKey as P,ComputeBudgetProgram as V,Transaction as p,TransactionMessage as k,Keypair as b,VersionedTransaction as x}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as F}from"@solana/spl-token";import{get as y,set as T}from"lodash";import A from"dayjs";import v from"dayjs/plugin/utc";A.extend(v);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 A().utc().format("YYYY/MM/DD HH:mm:ss UTC")}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(i=>typeof i=="object"?JSON.stringify(i):i).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}},C={},E={};function S(t){let e=y(C,t);if(!e){let r=y(E,t);e=new h({name:t,logLevel:r}),T(C,t,e)}return e}var d={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",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",FarmV5Deposit:"FarmV5Deposit",FarmV5Withdraw:"FarmV5Withdraw",FarmV5CreateLedger:"FarmV5CreateLedger",FarmV6Deposit:"FarmV6Deposit",FarmV6Withdraw:"FarmV6Withdraw",FarmV6Create:"FarmV6Create",FarmV6Restart:"FarmV6Restart",FarmV6CreatorAddReward:"FarmV6CreatorAddReward",FarmV6CreatorWithdraw:"FarmV6CreatorWithdraw"};var s=S("Raydium_txUtil"),B=1644;function X(t){let e=[],r=[];return t.microLamports&&(e.push(V.setComputeUnitPrice({microLamports:t.microLamports})),r.push(d.SetComputeUnitPrice)),t.units&&(e.push(V.setComputeUnitLimit({units:t.units})),r.push(d.SetComputeUnitLimit)),{instructions:e,instructionTypes:r}}async function Z(t){var e,r;try{return((r=await((e=t.getLatestBlockhash)==null?void 0:e.call(t)))==null?void 0:r.blockhash)||(await t.getRecentBlockhash()).blockhash}catch{return(await t.getRecentBlockhash()).blockhash}}function I(t,e){t.length<1&&s.logWithError(`no instructions provided: ${t.toString()}`),e.length<1&&s.logWithError(`no signers provided:, ${e.toString()}`);let r=new p;r.recentBlockhash="11111111111111111111111111111111",r.feePayer=e[0],r.add(...t);try{return Buffer.from(r.serialize({verifySignatures:!1})).toString("base64").length<B}catch{return!1}}async function Q(t,e,r,i=!0){let n=new P("RaydiumSimuLateTransaction11111111111111111"),m=[],a=new p;a.feePayer=n;for(let o of e)I([...a.instructions,o],[n])||(m.push(a),a=new p,a.feePayer=n),a.add(o);a.instructions.length>0&&m.push(a);let u=[];try{if(u=await M(t,m,i),u.find(o=>o.err!==null))throw Error("rpc simulateTransaction error")}catch(o){o instanceof Error&&s.logWithError("failed to simulate for instructions","RPC_ERROR",{message:o.message})}let l=[];for(let o of u)if(s.debug("simulate result:",o),o.logs){let c=o.logs.filter(g=>g&&g.includes(r));s.debug("filteredLog:",l),c.length||s.logWithError("simulate log not match keyword","keyword",r),l.push(...c)}return l}function ee(t,e){let r=t.match(/{["\w:,]+}/g);return!r||r.length!==1?s.logWithError(`simulate log fail to match json, keyword: ${e}`):r[0]}function te(t,e){let i=new RegExp(`"${e}":(\\d+)`,"g").exec(t);return!i||i.length!==2?s.logWithError(`simulate log fail to match key", key: ${e}`):i[1]}function re(t,e){let[r,i]=P.findProgramAddressSync(t,e);return{publicKey:r,nonce:i}}async function M(t,e,r){let i=[];if(r){let n=await t.getLatestBlockhash(),m=[];for(let o of e){o.recentBlockhash=n.blockhash,o.lastValidBlockHeight=n.lastValidBlockHeight;let g=o._compile().serialize(),R=o._serialize(g).toString("base64");m.push(R)}let a=m.map(o=>{let c=t._buildArgs([o],void 0,"base64");return{methodName:"simulateTransaction",args:c}}),u=[],l=20;for(let o=0;o<Math.ceil(a.length/l);o++)u.push(a.slice(o*l,(o+1)*l));i=await(await Promise.all(u.map(async o=>(await t._rpcBatchRequest(o)).map(c=>c.result.value)))).flat()}else try{i=await Promise.all(e.map(async n=>await(await t.simulateTransaction(n)).value))}catch(n){n instanceof Error&&s.logWithError("failed to get info for multiple accounts","RPC_ERROR",{message:n.message})}return i}function oe({instructions:t,payer:e,signers:r}){return I(t,[e,...r])}function ie({instructions:t,payer:e,lookupTableAddressAccount:r}){let n=new k({payerKey:e,recentBlockhash:b.generate().publicKey.toString(),instructions:t}).compileToV0Message(Object.values(r!=null?r:{}));try{return Buffer.from(n.serialize()).toString("base64").length<B}catch{return!1}}var f={time:0,data:void 0};async function ne(t){if(!f.data||(Date.now()-f.time)/1e3>30){let e=await t.getEpochInfo();return f={time:Date.now(),data:e},e}else return f.data}var W=t=>Buffer.isBuffer(t)?t:t instanceof Uint8Array?Buffer.from(t.buffer,t.byteOffset,t.byteLength):Buffer.from(t);function ae(t){let e=[];return t.forEach(r=>{r instanceof p&&(r.recentBlockhash||(r.recentBlockhash=F.toBase58()),r.feePayer||(r.feePayer=b.generate().publicKey));let i=r.serialize({requireAllSignatures:!1,verifySignatures:!1});r instanceof x&&(i=W(i));let n=i.toString("base64");e.push(n)}),console.log("simulate tx string:",e),e}export{B as MAX_BASE64_SIZE,X as addComputeBudget,oe as checkLegacyTxSize,ie as checkV0TxSize,re as findProgramAddress,I as forecastTransactionSize,ne as getEpochInfo,Z as getRecentBlockHash,ee as parseSimulateLogToJson,te as parseSimulateValue,ae as printSimulate,Q as simulateMultipleInstruction,M as simulateTransaction,W as toBuffer};
//# sourceMappingURL=txUtils.mjs.map