Skip to content

Instantly share code, notes, and snippets.

@tubackkhoa
Last active December 21, 2023 04:50
Show Gist options
  • Save tubackkhoa/318479a4b210491dad8b58be279d705b to your computer and use it in GitHub Desktop.
Save tubackkhoa/318479a4b210491dad8b58be279d705b to your computer and use it in GitHub Desktop.
Query pending txs
import { decodeTxRaw } from "@cosmjs/proto-signing";
import * as injProto from "@injectivelabs/core-proto-ts";
import { GasFee } from "@injectivelabs/sdk-ts";
import { MsgType } from "@injectivelabs/ts-types";
const typeMap = Object.fromEntries(Object.entries(MsgType).map(([k, v]) => ["/" + v, k]));
type TxType = keyof typeof MsgType;
const findType = (obj: any, type: string) => {
if (typeof obj !== "object") return;
const msg = obj[type];
if (msg && msg.decode) return msg;
for (const subObj of Object.values(obj)) {
const find = findType(subObj, type);
if (find) return find;
}
};
const decodeProto = (msg: { typeUrl: string; value: Uint8Array }) => {
const type = typeMap[msg.typeUrl];
if (type) {
const obj = findType(injProto, type);
if (obj) {
const res = obj.decode(msg.value);
res.type = type;
if (res.msgs) {
res.msgs = res.msgs.map(decodeProto);
}
return res;
}
}
};
export type FrontRunInfo = {
fee: GasFee;
msgs: object[];
};
class FrontRunClient {
public readonly rpc: string;
constructor(rpc: string) {
this.rpc = rpc.replace(/\/+$/, "");
}
async queryPendingTxs(types: TxType[] = [], limit = 30): Promise<FrontRunInfo[]> {
const { result } = await fetch(`${this.rpc}/unconfirmed_txs?limit=${limit}`).then((res) => res.json());
return result.txs.map((txRaw: string) => {
const tx = decodeTxRaw(Buffer.from(txRaw, "base64"));
const { amount, gasLimit, ...rest } = tx.authInfo.fee;
const info: FrontRunInfo = {
fee: {
amounts: amount,
gasLimit: gasLimit.toNumber(),
...rest
},
msgs: tx.body.messages
.filter((msg) => {
if (!types || types.length == 0) return true;
const type = typeMap[msg.typeUrl] as TxType;
return types.includes(type);
})
.map(decodeProto)
};
return info;
});
}
}
(async () => {
const frontRunClient = new FrontRunClient("https://rpc-injective.keplr.app");
const pendingTxs = await frontRunClient.queryPendingTxs(["MsgBatchUpdateOrders"]);
const maxGasLimit = Math.max(...pendingTxs.map((tx) => tx.fee.gasLimit));
console.log(maxGasLimit);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment