cosmos / cosmjs

The Swiss Army knife to power JavaScript based client solutions ranging from Web apps/explorers over browser extensions to server-side clients like faucets/scrapers.
https://cosmos.github.io/cosmjs/
Apache License 2.0
645 stars 329 forks source link

SigningStargateClient Simulation fix #1213

Open takacsdotattila opened 2 years ago

takacsdotattila commented 2 years ago

Since the simulation does not need the correct public key please modify the code, or extend or i dont know for the next release:

public async simulate( signerAddress: string, messages: readonly EncodeObject[], memo: string | undefined,)
: Promise<number> {
    const anyMsgs = messages.map((m) => this.registry.encodeAsAny(m));
    const accountFromSigner = (await this.signer.getAccounts()).find(
      (account) => account.address === signerAddress,
    );
    if (!accountFromSigner) {
      throw new Error("Failed to retrieve account from signer");
    }
    const pubkey = encodeSecp256k1Pubkey(accountFromSigner.pubkey);
    const { sequence } = await this.getSequence(signerAddress);
    const { gasInfo } = await this.forceGetQueryClient().tx.simulate(anyMsgs, memo, pubkey, sequence);
    assertDefined(gasInfo);
    return Uint53.fromString(gasInfo.gasUsed.toString()).toNumber();
  }

What I did as a hack for now in my project, but can be used even in the simple StargateClient as well:

public override async simulate(signerAddress: string, messages: readonly EncodeObject[], memo: string | undefined
  ): Promise<number> {
    const anyMsgs = messages.map((m) => this.registry.encodeAsAny(m));
    const pubkey = {
      type: pubkeyType.secp256k1,
      value: toBase64((await(await DirectSecp256k1HdWallet.generate(24)).getAccounts())[0].pubkey),
    };
    const { sequence } = await this.getSequence(signerAddress);
    const { gasInfo } = await this.forceGetQueryClient().tx.simulate(anyMsgs, memo, pubkey, sequence);
    if(!gasInfo){
      throw Error("gas info was not returned");
    }
    return Uint53.fromString(gasInfo.gasUsed.toString()).toNumber();
  }

btw what can i do with this gas used value? where can i get the gas prices from? (in case of terra there is an endpoint on the chain where i can query, does cosmos has stg like that?)

jmrossy commented 6 months ago

+1 for enabling simulate calls on StargateClient instead of just SigningStargateClient. This makes it more comparable to Provider in Ethers.js or Connection in Solana web3.js.

taitruong commented 2 months ago

Any updates here? I'm also getting Failed to retrieve account from signer while testing on terra2 testnet.