UNPKG

goosefx-amm-sdk

Version:

SDK for the GooseFx AMM

2 lines 6.74 kB
"use strict";var d=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var E=Object.prototype.hasOwnProperty;var A=(t,e)=>{for(var n in e)d(t,n,{get:e[n],enumerable:!0})},R=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of x(e))!E.call(t,o)&&o!==n&&d(t,o,{get:()=>e[o],enumerable:!(r=k(e,o))||r.enumerable});return t};var K=t=>R(d({},"__esModule",{value:!0}),t);var N={};A(N,{MAX_BASE64_SIZE:()=>b,addComputeBudget:()=>U,checkLegacyTxSize:()=>D,checkV0TxSize:()=>V,findProgramAddress:()=>_,forecastTransactionSize:()=>w,getEpochInfo:()=>$,getRecentBlockHash:()=>W,parseSimulateLogToJson:()=>z,parseSimulateValue:()=>O,printSimulate:()=>j,simulateMultipleInstruction:()=>q,simulateTransaction:()=>v,toBuffer:()=>C,transformTxToBase64:()=>G});module.exports=K(N);var s=require("@solana/web3.js"),P=require("@solana/spl-token");var f=require("lodash");var y=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 n=e.map(r=>typeof r=="object"?JSON.stringify(r):r).join(", ");throw new Error(n)}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}},T={},M={};function B(t){let e=(0,f.get)(T,t);if(!e){let n=(0,f.get)(M,t);e=new y({name:t,logLevel:n}),(0,f.set)(T,t,e)}return e}var L={CreateAccount:"CreateAccount",InitAccount:"InitAccount",CreateATA:"CreateATA",CloseAccount:"CloseAccount",TransferAmount:"TransferAmount",InitMint:"InitMint",MintTo:"MintTo",SetComputeUnitPrice:"SetComputeUnitPrice",SetComputeUnitLimit:"SetComputeUnitLimit",CpmmInitUserLiquidity:"CpmmInitUserLiquidity",CpmmCreatePool:"CpmmCreatePool",CpmmAddLiquidity:"CpmmAddLiquidity",CpmmWithdrawLiquidity:"CpmmWithdrawLiquidity",CpmmSwapBaseIn:"CpmmSwapBaseIn",CpmmSwapBaseOut:"CpmmSwapBaseOut",CpmmOracleSwapBaseIn:"CpmmOracleSwapBaseIn"};var c=B("Gfx_txUtil"),b=1644;function U(t){let e=[],n=[];return t.microLamports&&(e.push(s.ComputeBudgetProgram.setComputeUnitPrice({microLamports:t.microLamports})),n.push(L.SetComputeUnitPrice)),t.units&&(e.push(s.ComputeBudgetProgram.setComputeUnitLimit({units:t.units})),n.push(L.SetComputeUnitLimit)),{instructions:e,instructionTypes:n}}async function W(t,e){var r,o;let n=e!=null?e:"confirmed";try{return((o=await((r=t.getLatestBlockhash)==null?void 0:r.call(t,{commitment:n})))==null?void 0:o.blockhash)||(await t.getRecentBlockhash(n)).blockhash}catch{return(await t.getRecentBlockhash(n)).blockhash}}function w(t,e){t.length<1&&c.logWithError(`no instructions provided: ${t.toString()}`),e.length<1&&c.logWithError(`no signers provided:, ${e.toString()}`);let n=new s.Transaction;n.recentBlockhash="11111111111111111111111111111111",n.feePayer=e[0],n.add(...t);try{return n.serialize({verifySignatures:!1}).toString("base64").length<b}catch{return!1}}async function q(t,e,n,r=!0){let o=new s.PublicKey("GfxSimuLateTransaction11111111111111111"),u=[],a=new s.Transaction;a.feePayer=o;for(let i of e)w([...a.instructions,i],[o])||(u.push(a),a=new s.Transaction,a.feePayer=o),a.add(i);a.instructions.length>0&&u.push(a);let m=[];try{if(m=await v(t,u,r),m.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 l=[];for(let i of m)if(c.debug("simulate result:",i),i.logs){let g=i.logs.filter(h=>h&&h.includes(n));c.debug("filteredLog:",l),g.length||c.logWithError("simulate log not match keyword","keyword",n),l.push(...g)}return l}function z(t,e){let n=t.match(/{["\w:,]+}/g);return!n||n.length!==1?c.logWithError(`simulate log fail to match json, keyword: ${e}`):n[0]}function O(t,e){let r=new RegExp(`"${e}":(\\d+)`,"g").exec(t);return!r||r.length!==2?c.logWithError(`simulate log fail to match key", key: ${e}`):r[1]}function _(t,e){let[n,r]=s.PublicKey.findProgramAddressSync(t,e);return{publicKey:n,nonce:r}}async function v(t,e,n){let r=[];if(n){let o=await t.getLatestBlockhash(),u=[];for(let i of e){i.recentBlockhash=o.blockhash,i.lastValidBlockHeight=o.lastValidBlockHeight;let h=i._compile().serialize(),I=i._serialize(h).toString("base64");u.push(I)}let a=u.map(i=>{let g=t._buildArgs([i],void 0,"base64");return{methodName:"simulateTransaction",args:g}}),m=[],l=20;for(let i=0;i<Math.ceil(a.length/l);i++)m.push(a.slice(i*l,(i+1)*l));r=await(await Promise.all(m.map(async i=>(await t._rpcBatchRequest(i)).map(g=>g.result.value)))).flat()}else try{r=await Promise.all(e.map(async o=>await(await t.simulateTransaction(o)).value))}catch(o){o instanceof Error&&c.logWithError("failed to simulate transaction","RPC_ERROR",{message:o.message})}return r}function D({instructions:t,payer:e,signers:n}){return w(t,[e,...n])}function V({instructions:t,payer:e,lookupTableAddressAccount:n,recentBlockhash:r=s.Keypair.generate().publicKey.toString()}){let u=new s.TransactionMessage({payerKey:e,recentBlockhash:r,instructions:t}).compileToV0Message(Object.values(n!=null?n:{}));try{return Buffer.from(new s.VersionedTransaction(u).serialize()).toString("base64").length<b}catch{return!1}}var p={time:0,data:void 0};async function $(t){if(!p.data||(Date.now()-p.time)/1e3>30){let e=await t.getEpochInfo();return p={time:Date.now(),data:e},e}else return p.data}var C=t=>Buffer.isBuffer(t)?t:t instanceof Uint8Array?Buffer.from(t.buffer,t.byteOffset,t.byteLength):Buffer.from(t);function j(t){let e=[];return t.forEach(n=>{n instanceof s.Transaction&&(n.recentBlockhash||(n.recentBlockhash=P.TOKEN_PROGRAM_ID.toBase58()),n.feePayer||(n.feePayer=s.Keypair.generate().publicKey));let r=n.serialize({requireAllSignatures:!1,verifySignatures:!1});n instanceof s.VersionedTransaction&&(r=C(r));let o=r.toString("base64");e.push(o)}),console.log("simulate tx string:",e),e}function G(t){let e=t.serialize({requireAllSignatures:!1,verifySignatures:!1});return t instanceof s.VersionedTransaction&&(e=C(e)),e.toString("base64")}0&&(module.exports={MAX_BASE64_SIZE,addComputeBudget,checkLegacyTxSize,checkV0TxSize,findProgramAddress,forecastTransactionSize,getEpochInfo,getRecentBlockHash,parseSimulateLogToJson,parseSimulateValue,printSimulate,simulateMultipleInstruction,simulateTransaction,toBuffer,transformTxToBase64}); //# sourceMappingURL=txUtils.js.map