Skip to content

Commit

Permalink
feat: optimized chain registry as record object (#57)
Browse files Browse the repository at this point in the history
  • Loading branch information
Griko Nibras authored Oct 19, 2023
2 parents 65a5bbe + 09be28c commit 55cf6af
Show file tree
Hide file tree
Showing 4 changed files with 75 additions and 26 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

src/chains/
tests/downloads/

# dependencies
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"scripts": {
"dev": "next dev",
"build": "next build",
"postinstall": "node ./scripts/generate.js",
"start": "next start",
"lint": "next lint",
"test": "jest",
Expand Down
54 changes: 54 additions & 0 deletions scripts/generate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/* eslint-disable @typescript-eslint/no-var-requires */

const { chains } = require("chain-registry");
const fs = require("fs/promises");

async function generate() {
/** @type {string[]} */
const chainIds = [];

/** @type {Record<string, any>} */
const chainRecord = {};

for (const chain of chains) {
if (!chain.chain_id) continue;
chainIds.push(chain.chain_id);
chainRecord[chain.chain_id] = chain;
}

await fs.mkdir("src/chains/", { recursive: true }).catch(() => {});

await fs.writeFile(
"src/chains/chainIds.js",
"module.exports=" + JSON.stringify(chainIds),
"utf-8",
);

const chainIdLiteralType = chainIds
.map((id) => `"${id}"`)
.concat("(string & {})")
.join("|");

const chainIdsDts = `/* eslint-disable */
export type ChainId = ${chainIdLiteralType};
declare const chainIds: ChainId[];
export default chainIds;
`;
await fs.writeFile("src/chains/chainIds.d.ts", chainIdsDts, "utf-8");

await fs.writeFile(
"src/chains/chainRecord.js",
"module.exports=" + JSON.stringify(chainRecord),
"utf-8",
);

const chainRecordDts = `/* eslint-disable */
import { Chain } from "@chain-registry/types";
import { ChainId } from "./chainIds";
declare const chainRecord: Record<ChainId, Chain>;
export default chainRecord;
`;
await fs.writeFile("src/chains/chainRecord.d.ts", chainRecordDts, "utf-8");
}

void generate();
45 changes: 19 additions & 26 deletions src/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,33 +29,30 @@ import { LeapClient } from "@cosmos-kit/leap-extension/dist/extension/client";
import { OfflineAminoSigner } from "@keplr-wallet/types";
import { SkipRouter } from "@skip-router/core";
import { useQuery } from "@tanstack/react-query";
import * as chainRegistry from "chain-registry";
import { SignMode } from "cosmjs-types/cosmos/tx/signing/v1beta1/signing";
import { TxRaw } from "cosmjs-types/cosmos/tx/v1beta1/tx";
import { erc20ABI, PublicClient, usePublicClient } from "wagmi";

import { ChainId } from "@/chains/chainIds";
import chainRecord from "@/chains/chainRecord";
import { EVM_CHAINS } from "@/constants";
import { multicall3ABI } from "@/constants/abis";
import { Chain } from "@/context/chains";
import { useSkipClient } from "@/solve";

export function getChainByID(chainID: string) {
return chainRegistry.chains.find(
(chain) => chain.chain_id === chainID,
) as (typeof chainRegistry.chains)[0];
export function getChainByID(chainID: ChainId) {
return chainRecord[chainID];
}

// cache clients to reuse later
const STARGATE_CLIENTS: Record<string, StargateClient> = {};

export async function getStargateClientForChainID(chainID: string) {
export async function getStargateClientForChainID(chainID: ChainId) {
if (STARGATE_CLIENTS[chainID]) {
return STARGATE_CLIENTS[chainID];
}

const chain = chainRegistry.chains.find(
(chain) => chain.chain_id === chainID,
);
const chain = getChainByID(chainID);

if (!chain) {
throw new Error(`Chain with ID ${chainID} not found`);
Expand Down Expand Up @@ -88,13 +85,11 @@ export async function getStargateClientForChainID(chainID: string) {
}

export async function getSigningStargateClientForChainID(
chainID: string,
chainID: ChainId,
signer: OfflineSigner,
options?: SigningStargateClientOptions,
) {
const chain = chainRegistry.chains.find(
(chain) => chain.chain_id === chainID,
);
const chain = getChainByID(chainID);

if (!chain) {
throw new Error(`Chain with ID ${chainID} not found`);
Expand Down Expand Up @@ -136,7 +131,7 @@ export async function getSigningStargateClientForChainID(

export async function getAddressForCosmosChain(
walletClient: WalletClient,
chainId: string,
chainId: ChainId,
) {
if (walletClient.getOfflineSigner) {
const signer = await walletClient.getOfflineSigner(chainId);
Expand All @@ -149,13 +144,11 @@ export async function getAddressForCosmosChain(
}

export async function getSigningCosmWasmClientForChainID(
chainID: string,
chainID: ChainId,
signer: OfflineSigner,
options?: SigningCosmWasmClientOptions,
) {
const chain = chainRegistry.chains.find(
(chain) => chain.chain_id === chainID,
);
const chain = getChainByID(chainID);

if (!chain) {
throw new Error(`Chain with ID ${chainID} not found`);
Expand Down Expand Up @@ -214,7 +207,7 @@ export async function enableChains(
throw new Error("Unsupported wallet");
}

export async function getAccount(walletClient: WalletClient, chainId: string) {
export async function getAccount(walletClient: WalletClient, chainId: ChainId) {
if (walletClient.getAccount) {
return walletClient.getAccount(chainId);
}
Expand All @@ -224,7 +217,7 @@ export async function getAccount(walletClient: WalletClient, chainId: string) {

export async function getOfflineSigner(
walletClient: WalletClient,
chainId: string,
chainId: ChainId,
) {
if (walletClient.getOfflineSignerDirect) {
return walletClient.getOfflineSignerDirect(chainId);
Expand All @@ -235,7 +228,7 @@ export async function getOfflineSigner(

export async function getOfflineSignerOnlyAmino(
walletClient: WalletClient,
chainId: string,
chainId: ChainId,
) {
if (walletClient.getOfflineSignerAmino) {
const signer = walletClient.getOfflineSignerAmino(chainId);
Expand All @@ -245,7 +238,7 @@ export async function getOfflineSignerOnlyAmino(
throw new Error("unsupported wallet");
}

export function getFee(chainID: string) {
export function getFee(chainID: ChainId) {
const chain = getChainByID(chainID);

const feeInfo = chain.fees?.fee_tokens[0];
Expand All @@ -264,7 +257,7 @@ export function getFee(chainID: string) {
return amountNeeded;
}

export async function isLedger(walletClient: WalletClient, chainID: string) {
export async function isLedger(walletClient: WalletClient, chainID: ChainId) {
if (walletClient instanceof KeplrClient && window.keplr) {
const key = await window.keplr.getKey(chainID);
return key.isNanoLedger;
Expand All @@ -289,7 +282,7 @@ export async function isLedger(walletClient: WalletClient, chainID: string) {
return false;
}

export function getExplorerLinkForTx(chainID: string, txHash: string) {
export function getExplorerLinkForTx(chainID: ChainId, txHash: string) {
const evmChain = EVM_CHAINS.find((c) => c.id === parseInt(chainID));

if (evmChain) {
Expand Down Expand Up @@ -388,7 +381,7 @@ export async function signAmino(
});
}

export async function getBalancesByChain(address: string, chainID: string) {
export async function getBalancesByChain(address: string, chainID: ChainId) {
const client = await getStargateClientForChainID(chainID);

const balances = await client.getAllBalances(address);
Expand Down Expand Up @@ -446,7 +439,7 @@ async function getEvmChainBalances(
skipClient: SkipRouter,
publicClient: PublicClient,
address: string,
chainID: string,
chainID: ChainId,
) {
const assets = await skipClient.assets({
chainID,
Expand Down

0 comments on commit 55cf6af

Please sign in to comment.