Cache getCodeDetails calls

This commit is contained in:
Simon Warta 2020-03-09 00:04:45 +01:00
parent d53d4a34b7
commit 76936122ea
3 changed files with 22 additions and 2 deletions

View File

@ -276,6 +276,19 @@ describe("CosmWasmClient", () => {
// check data
expect(new Sha256(result.data).digest()).toEqual(fromHex(expectedInfo.checksum));
});
it("caches downloads", async () => {
pendingWithoutWasmd();
const client = new CosmWasmClient(wasmdEndpoint);
const openedClient = (client as unknown) as PrivateCosmWasmClient;
const getCodeSpy = spyOn(openedClient.restClient, "getCode").and.callThrough();
const result1 = await client.getCodeDetails(deployedErc20.codeId); // from network
const result2 = await client.getCodeDetails(deployedErc20.codeId); // from cache
expect(result2).toEqual(result1);
expect(getCodeSpy).toHaveBeenCalledTimes(1);
});
});
describe("getContracts", () => {

View File

@ -147,6 +147,8 @@ export class CosmWasmClient {
/** Any address the chain considers valid (valid bech32 with proper prefix) */
protected anyValidAddress: string | undefined;
private readonly codesCache = new Map<number, CodeDetails>();
public constructor(url: string, broadcastMode = BroadcastMode.Block) {
this.restClient = new RestClient(url, broadcastMode);
}
@ -312,9 +314,11 @@ export class CosmWasmClient {
}
public async getCodeDetails(codeId: number): Promise<CodeDetails> {
const getCodeResult = await this.restClient.getCode(codeId);
const cached = this.codesCache.get(codeId);
if (cached) return cached;
return {
const getCodeResult = await this.restClient.getCode(codeId);
const codeDetails: CodeDetails = {
id: getCodeResult.id,
creator: getCodeResult.creator,
checksum: Encoding.toHex(Encoding.fromHex(getCodeResult.data_hash)),
@ -322,6 +326,8 @@ export class CosmWasmClient {
builder: getCodeResult.builder || undefined,
data: Encoding.fromBase64(getCodeResult.data),
};
this.codesCache.set(codeId, codeDetails);
return codeDetails;
}
public async getContracts(codeId: number): Promise<readonly Contract[]> {

View File

@ -111,6 +111,7 @@ export declare class CosmWasmClient {
protected readonly restClient: RestClient;
/** Any address the chain considers valid (valid bech32 with proper prefix) */
protected anyValidAddress: string | undefined;
private readonly codesCache;
constructor(url: string, broadcastMode?: BroadcastMode);
chainId(): Promise<string>;
getHeight(): Promise<number>;