cosmology-tech / cosmos-kit

Universal wallet connector for the Cosmos ⚛️
https://cosmology.zone/products/cosmos-kit
BSD 3-Clause Clear License
182 stars 133 forks source link

MsgVoteWeighted issue #187

Open chalabi2 opened 1 year ago

chalabi2 commented 1 year ago

I have a function that creates the transaction data for a MsgWeightedVote and uses stargate to sign and broadcast via any wallet provider ala cosmology tools.

Im receiving

Eror: Broadcasting transaction failed with code 4 (codespace: sdk). Log: signature verification failed; please verify account number (87516), sequence (479) and chain-id (osmosis-1): unauthorized at SigningStargateClient.broadcastTx

Typically this error is my own fault but ive gone over the parameters and they are all correct.

I read the issue from last year for MsgWeightedVote about inputting the correct number type for the weights.

The unsigned transaction is as follows

{ "account_number": "87516", "chain_id": "osmosis-1", "fee": { "gas": "500000", "amount": [ { "denom": "ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2", "amount": "888" } ] }, "memo": "", "msgs": [ { "type": "cosmos-sdk/MsgVoteWeighted", "value": { "options": [ { "option": 1, "weight": "500000000000000000" }, { "option": 2, "weight": "500000000000000000" } ], "proposal_id": "493", "voter": "osmo1dv3v662kd3pp6pxfagck4zyysas82adswgl2jf" } } ], "sequence": "479" }

I am using cosmos-kit from cosmology but I do not believe that is whats causing the issue as my normal vote transactions are working fine.

Please let me know if this is not the appropriate forum for this type of question

side-note: I get the same error with my unjail tx, figure whatever im doing wrong here I am also doing wrong there.

pyramation commented 1 year ago

are there decimal types in this message? Sometimes you have to deal with decimals in a special way

chalabi2 commented 1 year ago

In the CLI command the vote weights are decimals with 18 places. keplr expects the transaction message as i posted above or else it errors that it cant parse the weight into a big int.

Im constructing the message as such

export const weightedVoteTX = (
    getSigningStargateClient: () => Promise<SigningStargateClient>,
    setResp: (resp: string) => any,
    chainName: string,
    proposalId: Long,
    address: string,
    weightedVoteOptions: WeightedVoteOption[], // Add this parameter
    toast: ReturnType<typeof useToast>
  ) => {
    return async (event: React.MouseEvent) => {
      event.preventDefault();

      const chainInfo = chains.find(({ chain_name }) => chain_name === chainName);
      if (!chainInfo?.apis?.rpc) {
        console.error("REST endpoint not found for the given chainName");
        return;
      }
      const polkachuRpcEndpoint = chainInfo?.apis?.rpc.find(({ provider }) => provider === "Polkachu");
      const rpcEndpoint = polkachuRpcEndpoint ? polkachuRpcEndpoint.address : chainInfo.apis.rpc[0].address;

      const stargateClient = await getSigningStargateClient();
      if (!stargateClient || !address) {
        console.error("Stargate client undefined or address undefined.");
        return;
      }

      const { voteWeighted } = cosmos.gov.v1beta1.MessageComposer.withTypeUrl;
      const msgVoteWeighted = voteWeighted({
        proposalId: proposalId,
        voter: address,
        options: weightedVoteOptions,
      });

      const mainTokens = assets.find(({chain_name})=>chain_name=== chainName);
      const mainDenom = mainTokens?.assets[0].base ?? "";

      const fee: StdFee = {
        amount: [
          {
            denom: mainDenom,
            amount: '5000',
          },
        ],
        gas: '500000',
      };

      console.log("Raw unsigned transaction:", JSON.stringify({ body: { messages: [msgVoteWeighted] }, auth_info: { fee } }));

      try {
        const response = await stargateClient.signAndBroadcast(address, [msgVoteWeighted], fee);
        setResp(JSON.stringify(response, null, 2));
        showSuccessToast(toast, response.transactionHash, chainName);
      } catch (error) {
        console.error("Error signing and sending transaction:", error);
        if (error instanceof Error) {
          showErrorToast(toast, error.message);
        }
      }
    };
  };

and then im returning the values here

  const handleWeightedVoteTx = async (
    event: React.MouseEvent,
    proposalId: string,
    weightedVoteOption1: VoteOption,
    weightedInput1Value: number,
    weightedVoteOption2: VoteOption,
    weightedInput2Value: number
  ) => {
    setIsSigning(true);
    setIsError(false);

    const BigNumber = require("bignumber.js");

    function convertToDecimalWith18Places(decimalString: string) {
      return new BigNumber(decimalString)
        .dividedBy(100)
        .toFixed(18);
    }

    const weightedVoteOptionsArray = [
      {
        option: weightedVoteOption1,
        weight: convertToDecimalWith18Places(weightedInput1Value.toFixed(18)),
      },
      {
        option: weightedVoteOption2,
        weight: convertToDecimalWith18Places(weightedInput2Value.toFixed(18)),
      },
    ];

    try {
      await weightedVoteTX(
        getSigningStargateClient,
        setResp,
        chainName ?? "",
        proposalId,
        address ?? "",
        weightedVoteOptionsArray,
        toast
      )(event);
      setIsSigning(false);
      setIsSigned(true);
      setTimeout(() => setIsSigned(false), 3000); // Reset the checkmark after 5 seconds
    } catch (error) {
      setIsSigning(false);
      setIsError(true);
      setTimeout(() => setIsError(false), 3000); // Reset the error state after 5 seconds
    }
  };
pyramation commented 1 year ago

hey @faddat — is there something on Dig chain that is unique for this message? Apparently Dig chain is the only one that @chalabi2 is experiencing this issue if I understand it correctly.

chalabi2 commented 1 year ago

Thanks @pyramation , maybe you didn't see this message i sent earlier on TG but the dig issue wasn't the same as the issue i am having with the weighted vote and unjailing tx. None of the transactions from my application work on dig but i think that's separate.

pyramation commented 1 year ago

oh! sorry @faddat for tagging you!

@chalabi2 — I think you may want to checkout the https://github.com/osmosis-labs/telescope#typings-and-formating docs, you'll see the prototypes.typingsFormat.customTypes.useCosmosSDKDec option, used to show decimal fields with the custom type correctly. Highly recommend set to true

I think that may solve the issue?

chalabi2 commented 1 year ago

I have to regenerate the codegen directory with telescope and include that parameter to true in a telescope config file before i regenerate?

https://github.com/osmosis-labs/telescope#usage

chalabi2 commented 1 year ago

The main error i cant get around is

next-dev.js:20 Error signing and sending transaction: Error: Broadcasting transaction failed with code 4 (codespace: sdk). Log: signature verification failed; please verify account number (87516), sequence (500) and chain-id (osmosis-1): unauthorized at SigningStargateClient.broadcastTx (stargateclient.js:267:1)

when signing and broadcasting a weighted vote or unjail transaction.

I have the incorrect values in account number, sequence, & chain-id

Other people experiencing similar issues with cosmjs

https://github.com/cosmos/cosmjs/issues/1417

pyramation commented 1 year ago

yea so you'll want to regenerate by adding the new config, and that should help with the decimal issue.

example telescope config: https://github.com/osmosis-labs/osmojs/blob/main/packages/osmojs/scripts/codegen.js