goosefx-amm-sdk
Version:
SDK for the GooseFx AMM
2 lines • 5.89 kB
JavaScript
import{PublicKey as B,ComputeBudgetProgram as S,Transaction as h,TransactionMessage as R,Keypair as P,VersionedTransaction as y}from"@solana/web3.js";import{TOKEN_PROGRAM_ID as K}from"@solana/spl-token";import{get as L,set as E}from"lodash";var p=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}},b={},A={};function T(t){let e=L(b,t);if(!e){let n=L(A,t);e=new p({name:t,logLevel:n}),E(b,t,e)}return e}var d={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 a=T("Gfx_txUtil"),v=1644;function J(t){let e=[],n=[];return t.microLamports&&(e.push(S.setComputeUnitPrice({microLamports:t.microLamports})),n.push(d.SetComputeUnitPrice)),t.units&&(e.push(S.setComputeUnitLimit({units:t.units})),n.push(d.SetComputeUnitLimit)),{instructions:e,instructionTypes:n}}async function X(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 I(t,e){t.length<1&&a.logWithError(`no instructions provided: ${t.toString()}`),e.length<1&&a.logWithError(`no signers provided:, ${e.toString()}`);let n=new h;n.recentBlockhash="11111111111111111111111111111111",n.feePayer=e[0],n.add(...t);try{return n.serialize({verifySignatures:!1}).toString("base64").length<v}catch{return!1}}async function Y(t,e,n,r=!0){let o=new B("GfxSimuLateTransaction11111111111111111"),c=[],s=new h;s.feePayer=o;for(let i of e)I([...s.instructions,i],[o])||(c.push(s),s=new h,s.feePayer=o),s.add(i);s.instructions.length>0&&c.push(s);let g=[];try{if(g=await M(t,c,r),g.find(i=>i.err!==null))throw Error("rpc simulateTransaction error")}catch(i){i instanceof Error&&a.logWithError("failed to simulate for instructions","RPC_ERROR",{message:i.message})}let u=[];for(let i of g)if(a.debug("simulate result:",i),i.logs){let l=i.logs.filter(m=>m&&m.includes(n));a.debug("filteredLog:",u),l.length||a.logWithError("simulate log not match keyword","keyword",n),u.push(...l)}return u}function Z(t,e){let n=t.match(/{["\w:,]+}/g);return!n||n.length!==1?a.logWithError(`simulate log fail to match json, keyword: ${e}`):n[0]}function F(t,e){let r=new RegExp(`"${e}":(\\d+)`,"g").exec(t);return!r||r.length!==2?a.logWithError(`simulate log fail to match key", key: ${e}`):r[1]}function Q(t,e){let[n,r]=B.findProgramAddressSync(t,e);return{publicKey:n,nonce:r}}async function M(t,e,n){let r=[];if(n){let o=await t.getLatestBlockhash(),c=[];for(let i of e){i.recentBlockhash=o.blockhash,i.lastValidBlockHeight=o.lastValidBlockHeight;let m=i._compile().serialize(),x=i._serialize(m).toString("base64");c.push(x)}let s=c.map(i=>{let l=t._buildArgs([i],void 0,"base64");return{methodName:"simulateTransaction",args:l}}),g=[],u=20;for(let i=0;i<Math.ceil(s.length/u);i++)g.push(s.slice(i*u,(i+1)*u));r=await(await Promise.all(g.map(async i=>(await t._rpcBatchRequest(i)).map(l=>l.result.value)))).flat()}else try{r=await Promise.all(e.map(async o=>await(await t.simulateTransaction(o)).value))}catch(o){o instanceof Error&&a.logWithError("failed to simulate transaction","RPC_ERROR",{message:o.message})}return r}function ee({instructions:t,payer:e,signers:n}){return I(t,[e,...n])}function te({instructions:t,payer:e,lookupTableAddressAccount:n,recentBlockhash:r=P.generate().publicKey.toString()}){let c=new R({payerKey:e,recentBlockhash:r,instructions:t}).compileToV0Message(Object.values(n!=null?n:{}));try{return Buffer.from(new y(c).serialize()).toString("base64").length<v}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 k=t=>Buffer.isBuffer(t)?t:t instanceof Uint8Array?Buffer.from(t.buffer,t.byteOffset,t.byteLength):Buffer.from(t);function re(t){let e=[];return t.forEach(n=>{n instanceof h&&(n.recentBlockhash||(n.recentBlockhash=K.toBase58()),n.feePayer||(n.feePayer=P.generate().publicKey));let r=n.serialize({requireAllSignatures:!1,verifySignatures:!1});n instanceof y&&(r=k(r));let o=r.toString("base64");e.push(o)}),console.log("simulate tx string:",e),e}function ie(t){let e=t.serialize({requireAllSignatures:!1,verifySignatures:!1});return t instanceof y&&(e=k(e)),e.toString("base64")}export{v as MAX_BASE64_SIZE,J as addComputeBudget,ee as checkLegacyTxSize,te as checkV0TxSize,Q as findProgramAddress,I as forecastTransactionSize,ne as getEpochInfo,X as getRecentBlockHash,Z as parseSimulateLogToJson,F as parseSimulateValue,re as printSimulate,Y as simulateMultipleInstruction,M as simulateTransaction,k as toBuffer,ie as transformTxToBase64};
//# sourceMappingURL=txUtils.mjs.map