diff --git a/example-03-subPrice/README.md b/example-03-subPrice/README.md new file mode 100644 index 0000000..0b19aec --- /dev/null +++ b/example-03-subPrice/README.md @@ -0,0 +1,31 @@ +# 监听raydium clmm代币的实时价格 + +此例子结合 `onSlotUpdate` 和 解析buffer的方法来实时订阅raydium clmm WSOL/USDC流动池中WSOL的价格。 + +通过 `npx esrun example-03-subPrice/index.ts` 运行 + +``` +sqrtPriceX64Value at offset 253: 8617564287599812924 +WSOL价格: 218.23762107593976 +--- + +sqrtPriceX64Value at offset 253: 8618158284616202734 +WSOL价格: 218.2677077591724 +--- + +sqrtPriceX64Value at offset 253: 8617802344396074973 +WSOL价格: 218.24967869796686 +--- + +sqrtPriceX64Value at offset 253: 8616982572722284816 +WSOL价格: 218.2081585081117 +--- + +sqrtPriceX64Value at offset 253: 8617078429812061202 +WSOL价格: 218.21301332015403 +--- + +sqrtPriceX64Value at offset 253: 8616930983791568854 +WSOL价格: 218.2055457392501 +--- +``` \ No newline at end of file diff --git a/example-03-subPrice/index.ts b/example-03-subPrice/index.ts new file mode 100644 index 0000000..6023c20 --- /dev/null +++ b/example-03-subPrice/index.ts @@ -0,0 +1,31 @@ +import { + Connection, + PublicKey +} from '@solana/web3.js'; +import BN from 'bn.js'; + +const connection = new Connection("https://api.mainnet-beta.solana.com", "confirmed"); +// const connection = new Connection("https://mainnet-ams.chainbuff.com", "confirmed"); + +connection.onAccountChange( + new PublicKey('8sLbNZoA1cfnvMJLPfp98ZLAnFSYCFApfJKMbiXNLwxj'), + async (accountInfo) => { + const dataBuffer = accountInfo?.data; + if (!dataBuffer) { + throw new Error("Account data not found"); + } + + const offset = 253 + const sqrtPriceX64Buffer = dataBuffer.slice(offset, offset + 16); // 读取16个字节 + const sqrtPriceX64Value = new BN(sqrtPriceX64Buffer, 'le'); // 使用小端字节序创建BN实例 + console.log(`sqrtPriceX64Value at offset ${offset}:`, sqrtPriceX64Value.toString()); + + // 计算价格 + const sqrtPriceX64BigInt = BigInt(sqrtPriceX64Value.toString()); + const sqrtPriceX64Float = Number(sqrtPriceX64BigInt) / (2 ** 64); + const price = sqrtPriceX64Float ** 2 * 1e9 / 1e6; + console.log(`WSOL价格:`, price.toString()) + console.log('---\n') + }, + 'confirmed' +); \ No newline at end of file