From a50369e43e716a8925e4c5e7751babc5a1e7325d Mon Sep 17 00:00:00 2001 From: Simon Warta Date: Wed, 11 Mar 2020 10:39:37 +0100 Subject: [PATCH] Cache chain ID --- packages/sdk/src/cosmwasmclient.spec.ts | 12 ++++++++++++ packages/sdk/src/cosmwasmclient.ts | 11 +++++++++-- packages/sdk/types/cosmwasmclient.d.ts | 1 + 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/packages/sdk/src/cosmwasmclient.spec.ts b/packages/sdk/src/cosmwasmclient.spec.ts index 521335df..6f9ff4c4 100644 --- a/packages/sdk/src/cosmwasmclient.spec.ts +++ b/packages/sdk/src/cosmwasmclient.spec.ts @@ -54,6 +54,18 @@ describe("CosmWasmClient", () => { const client = new CosmWasmClient(wasmdEndpoint); expect(await client.getChainId()).toEqual("testing"); }); + + it("caches chain ID", async () => { + pendingWithoutWasmd(); + const client = new CosmWasmClient(wasmdEndpoint); + const openedClient = (client as unknown) as PrivateCosmWasmClient; + const getCodeSpy = spyOn(openedClient.restClient, "nodeInfo").and.callThrough(); + + expect(await client.getChainId()).toEqual("testing"); // from network + expect(await client.getChainId()).toEqual("testing"); // from cache + + expect(getCodeSpy).toHaveBeenCalledTimes(1); + }); }); describe("getHeight", () => { diff --git a/packages/sdk/src/cosmwasmclient.ts b/packages/sdk/src/cosmwasmclient.ts index 50d8aefa..1413b11c 100644 --- a/packages/sdk/src/cosmwasmclient.ts +++ b/packages/sdk/src/cosmwasmclient.ts @@ -148,14 +148,21 @@ export class CosmWasmClient { protected anyValidAddress: string | undefined; private readonly codesCache = new Map(); + private chainId: string | undefined; public constructor(url: string, broadcastMode = BroadcastMode.Block) { this.restClient = new RestClient(url, broadcastMode); } public async getChainId(): Promise { - const response = await this.restClient.nodeInfo(); - return response.node_info.network; + if (!this.chainId) { + const response = await this.restClient.nodeInfo(); + const chainId = response.node_info.network; + if (!chainId) throw new Error("Chain ID must not be empty"); + this.chainId = chainId; + } + + return this.chainId; } public async getHeight(): Promise { diff --git a/packages/sdk/types/cosmwasmclient.d.ts b/packages/sdk/types/cosmwasmclient.d.ts index f3ed5ac2..b83ff2f5 100644 --- a/packages/sdk/types/cosmwasmclient.d.ts +++ b/packages/sdk/types/cosmwasmclient.d.ts @@ -112,6 +112,7 @@ export declare class CosmWasmClient { /** Any address the chain considers valid (valid bech32 with proper prefix) */ protected anyValidAddress: string | undefined; private readonly codesCache; + private chainId; constructor(url: string, broadcastMode?: BroadcastMode); getChainId(): Promise; getHeight(): Promise;