Skip to content

Commit

Permalink
update example-03-subPrice
Browse files Browse the repository at this point in the history
  • Loading branch information
XingqiWang committed Nov 16, 2024
1 parent 5088258 commit c8e5c88
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
31 changes: 31 additions & 0 deletions example-03-subPrice/README.md
Original file line number Diff line number Diff line change
@@ -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
---
```
31 changes: 31 additions & 0 deletions example-03-subPrice/index.ts
Original file line number Diff line number Diff line change
@@ -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'
);

0 comments on commit c8e5c88

Please sign in to comment.