Skip to content

Instantly share code, notes, and snippets.

@larry0x
Last active September 15, 2022 22:56
Show Gist options
  • Save larry0x/4231625c1898ce2e79f813192c99130e to your computer and use it in GitHub Desktop.
Save larry0x/4231625c1898ce2e79f813192c99130e to your computer and use it in GitHub Desktop.
import { Tendermint34Client } from "@cosmjs/tendermint-rpc";
import { createProtobufRpcClient, QueryClient } from "@cosmjs/stargate";
import { osmosis } from "osmojs";
import { Long } from "@osmonauts/helpers";
const rpcEndpoint = "https://rpc.osmosis.zone:443";
async function querySpotPrice(
poolId: number,
token1Denom: string,
token2Denom: string,
) {
// 4 steps just to create a query service!
const tmClient = await Tendermint34Client.connect(rpcEndpoint);
const queryClient = new QueryClient(tmClient);
const protobufRpcClient = createProtobufRpcClient(queryClient);
const queryService = new osmosis.gamm.v1beta1.QueryClientImpl(protobufRpcClient);
// do the actual query
const queryRes = await queryService.pool({
// poolId needs to be in `Long` type
poolId: Long.fromInt(poolId),
});
// `pool` has protobuf `Any` type, so neesd to be decoded
const pool = osmosis.gamm.v1beta1.Pool.decode(queryRes.pool.value);
const token1InPool = pool
.poolAssets
.find((asset) => asset.token.denom === token1Denom)!
.token
.amount;
const token2InPool = pool
.poolAssets
.find((asset) => asset.token.denom === token2Denom)!
.token
.amount;
return {
token1PerToken2: token1InPool / token2InPool,
token2PerToken1: token2InPool / token1InPool,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment