Can't use Smart Contracts methods - Tx always reverts

Please provide the following details too when asking for help in this category:

  • SDK Version: “@web3auth/base”: “^7.0.1”,
    @web3auth/modal”: “^7.0.2”,
    @web3auth/openlogin-adapter”: “^7.0.1”,
  • Platform: React

Please provide the Web3Auth initialization and login code snippet below:

Hello there, I’m trying to set up a very basic Smart Contract that is a simple storage, just to test how to interact with smart contracts while using web3auth. My project is in React and I’m using this EthProvider from truffle react box:

import React, { useReducer, useCallback, useEffect } from "react";
import Web3 from "web3";
import EthContext from "./EthContext";
import { reducer, actions, initialState } from "./state";
import { useWeb3Auth } from '../../components/Auth/useWeb3Auth';

function EthProvider({ children }) {
  const [state, dispatch] = useReducer(reducer, initialState);

  const web3auth = useWeb3Auth();

  const init = useCallback(
    async artifact => {
      if (artifact) {
        const provider = await web3auth.connect();
        if (!provider) return;
        const web3 = new Web3(provider);
        console.log(web3);
        const accounts = await web3.eth.getAccounts();
        const networkID = await web3.eth.net.getId();
        const { abi } = artifact;
        let address, contract;
        try {
          address = artifact.networks[networkID].address;
          contract = new web3.eth.Contract(abi, address);
        } catch (err) {
          console.error(err);
        }
        dispatch({
          type: actions.init,
          data: { artifact, web3, accounts, networkID, contract }
        });
      }
    }, [web3auth]);

  useEffect(() => {
    const tryInit = async () => {
      try {
        const artifact = require("../../../build/contracts/SimpleStorage.json");
        init(artifact);
      } catch (err) {
        console.error(err);
      }
    };

    tryInit();
  }, [init]);

  useEffect(() => {
    const events = ["chainChanged", "accountsChanged"];
    const handleChange = () => {
      init(state.artifact);
    };

    events.forEach(e => window.ethereum.on(e, handleChange));
    return () => {
      events.forEach(e => window.ethereum.removeListener(e, handleChange));
    };
  }, [init, state.artifact]);

  return (
    <EthContext.Provider value={{
      state,
      dispatch
    }}>
      {children}
    </EthContext.Provider>
  );
}

export default EthProvider;

Here’s my useWeb3Auth that has all the web3Auth config:

import { useState, useEffect } from 'react';
import { Web3Auth } from "@web3auth/modal";
import { CHAIN_NAMESPACES, WALLET_ADAPTERS } from "@web3auth/base";
import { OpenloginAdapter } from "@web3auth/openlogin-adapter";

const polygonTestnet = {
    rpcUrl: 'https://rpc-mumbai.maticvigil.com/',
    chainId: 80001,
};

interface IWeb3Auth extends Web3Auth {
    // Add additional properties if necessary
}

export function useWeb3Auth(): IWeb3Auth | null {
    const [web3auth, setWeb3Auth] = useState<IWeb3Auth | null>(null);

    useEffect(() => {
        const clientId = "LEFT IN BLANK ON PURPOSE TO POST IT HERE";
        const authInstance = new Web3Auth({
            clientId,
            web3AuthNetwork: "testnet",
            uiConfig: { defaultLanguage: "pt" },
            chainConfig: {
                chainNamespace: CHAIN_NAMESPACES.EIP155,
                chainId: "0x13881",
                rpcTarget: polygonTestnet.rpcUrl,
            },
        });

        const openloginAdapter = new OpenloginAdapter({
            loginSettings: { mfaLevel: "default" },
            adapterSettings: {
                uxMode: "popup",
                whiteLabel: { defaultLanguage: "pt" }
            }
        });
        
        authInstance.configureAdapter(openloginAdapter);
        authInstance.initModal({
            modalConfig: {
                [WALLET_ADAPTERS.OPENLOGIN]: {
                    label: "openlogin",
                    loginMethods: {
                        // Disable facebook and reddit
                        facebook: {
                            name: "facebook",
                            showOnModal: false,
                        },
                        reddit: {
                            name: "reddit",
                            showOnModal: false,
                        },
                        discord: {
                            name: "discord",
                            showOnModal: false,
                        },
                        twitch: {
                            name: "twitch",
                            showOnModal: false,
                        },
                        apple: {
                            name: "apple",
                            showOnModal: false,
                        },
                        line: {
                            name: "line",
                            showOnModal: false,
                        },
                        github: {
                            name: "github",
                            showOnModal: false,
                        },
                        kakao: {
                            name: "kakao",
                            showOnModal: false,
                        },
                        linkedin: {
                            name: "linkedin",
                            showOnModal: false,
                        },
                        twitter: {
                            name: "twitter",
                            showOnModal: false,
                        },
                        weibo: {
                            name: "weibo",
                            showOnModal: false,
                        },
                        wechat: {
                            name: "wechat",
                            showOnModal: false,
                        },
                    },
                    // setting it to false will hide all social login methods from modal.
                    showOnModal: true,
                }
            }
        });

        setWeb3Auth(authInstance as IWeb3Auth); // Cast as IWeb3Auth if the Web3Auth class doesn't have any private or internal properties that are inaccessible
    }, []);

    return web3auth;
}

Then also using the Demo from Truffle React box I have this in place:

import { useState } from "react";
import useEth from "../../context/EthContext/useEth";

function ContractBtns({ setValue }) {
  const { state: { contract, accounts } } = useEth();
  const [inputValue, setInputValue] = useState("");

  const handleInputChange = e => {
    if (/^\d+$|^$/.test(e.target.value)) {
      setInputValue(e.target.value);
    }
  };

  const read = async () => {
    const value = await contract.methods.get().call({ from: accounts[0] });
    console.log(value);
    setValue(value);
  };

  const write = async e => {
    if (e.target.tagName === "INPUT") {
      return;
    }
    if (inputValue === "") {
      alert("Please enter a value to write.");
      return;
    }
    const newValue = parseInt(inputValue);
    console.log(newValue);
    console.log(contract);
    console.log(accounts[0]);
    try {
      const receipt = await contract.methods.set(newValue).send({ from: accounts[0] });
      console.log(receipt);
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <div className="btns">

      <button onClick={read}>
        read()
      </button>

      <input
          type="text"
          placeholder="uint"
          value={inputValue}
          onChange={handleInputChange}
        />
      <button onClick={write} className="input-btn">
        write
      </button>

    </div>
  );
}

export default ContractBtns;

And here’s the smart contract:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract SimpleStorage {
    uint256 private storedData;

    event DataChanged(uint256 newValue);

    function set(uint256 x) public {
        storedData = x;
        emit DataChanged(x);
    }

    function get() public view returns (uint256) {
        return storedData;
    }
}

When I click on the read button it works fine and I can retrieve the number from storedData but when I click on the write button after entering a number on the input the transaction always reverts without not even entering the set function (I already debugged with reverts statements) and with the message “TransactionRevertedWithoutReasonError: Transaction has been reverted by the EVM”. Here’s the full error message:

TransactionRevertedWithoutReasonError: Transaction has been reverted by the EVM:
 {"blockHash":"0x5739b87530267339d9722453cc7317c344f40237930001c69acbd0b29e7656ee","blockNumber":"40279431","cumulativeGasUsed":"585085","effectiveGasPrice":"1500000016","from":"0xaf2e276b0020c0f8b5000b14596293318ab641f5","gasUsed":"21070","logs":[{"address":"0x0000000000000000000000000000000000001010","topics":["0x4dfe1bbbcf077ddc3e01291eea2d5c70c2b422b415d95645b9adcfd678cb1d63","0x0000000000000000000000000000000000000000000000000000000000001010","0x000000000000000000000000af2e276b0020c0f8b5000b14596293318ab641f5","0x000000000000000000000000c26880a0af2ea0c7e8130e6ec47af756465452e8"],"data":"0x00000000000000000000000000000000000000000000000000001cbe9ccc52000000000000000000000000000000000000000000000000000dde9ad04945dbca0000000000000000000000000000000000000000000021d9f04bd637877c25530000000000000000000000000000000000000000000000000dde7e11ac7989ca0000000000000000000000000000000000000000000021d9f04bf2f624487753","blockNumber":"40279431","transactionHash":"0xd7dfe2ef5bd313483bb0a6849e47681575716c89dfd293a8b48c277070d6a954","transactionIndex":"5","blockHash":"0x5739b87530267339d9722453cc7317c344f40237930001c69acbd0b29e7656ee","logIndex":"26","removed":false}],"logsBloom":"0x00000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000800000000000000000000100000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000800000000000000000200000000000000020000000000000000001400020000000000000000000004000000000000000000001000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000100000","status":"0","to":"0xff7737a957f6546729da37b020afd86050fc93e9","transactionHash":"0xd7dfe2ef5bd313483bb0a6849e47681575716c89dfd293a8b48c277070d6a954","transactionIndex":"5","type":"2"}
    at get_transaction_error.ts:58:1
    at Generator.next (<anonymous>)
    at get_transaction_error.ts:1:1
    at new Promise (<anonymous>)
    at __awaiter (get_transaction_error.ts:1:1)
    at getTransactionError (get_transaction_error.ts:35:1)
    at rpc_method_wrappers.ts:630:1
    at Generator.next (<anonymous>)
    at fulfilled (rpc_method_wrappers.ts:1:1)

Also notice that I’m trying this on Polygon Mumbai, I followed the tutorial in here: Integrate Web3Auth with the Ethereum Blockchain in Javascript | Documentation | Web3Auth and the login modal and the login are working fine.

Can you guys help me? Am I doing something wrong?

Thank you!

Here you can check the contract on the Block Explorer: https://mumbai.polygonscan.com/address/0xff7737a957f6546729da37b020afd86050fc93e9

As you can see, when I tried with Remix it reached the correct function Set on the contract, but with web3auth it tried a simple Transfer to the contract instead of calling the Set function.

Also from this blockchain analysis tool: Tenderly Dashboard

We can see that the transaction reached the contract but then it doesn’t know which function to execute as it tried to call 0x as the function signature.

@vinicius.santiago Welcome Aboard!

What is the gas limit you have set? Can you increase it and check?

You can take a look at the possible causes:

Hey @vjgee thanks for replying, yep, I already tried to add gasLimit to the parameters of the send transaction but no luck. Tried a lot of different values for gasLimit from 500,000 to 21,000,000 and nothing worked out.

I tried like this:

const receipt = await contract.methods.set(newValue).send({ from: accounts[0], gasLimit: 6000000 });

I think the problem lies down on how web3Auth library is making the .send to a smart contract because it’s not reaching the correct function signature on the deployed contract.

Also already tried with:

const receipt = await contract.methods.set(newValue).send({ from: accounts[0], gas: 6000000 });

No luck too

Can you refer to this code snippet for sending the transaction:

/*
  Use code from the above Initializing Provider here
*/

// web3 is const web3 = new Web3(web3authProvider); from above.

// Get user's Ethereum public address
const fromAddress = (await web3.eth.getAccounts())[0];

const contractABI =
  '[{"inputs":[{"internalType":"string","name":"initMessage","type":"string"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"string","name":"newMessage","type":"string"}],"name":"update","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"message","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"}]';
const contractAddress = "0xD65AF91Bbb4334711A598dFD293596E6dc2d8313#code";
const contract = new web3.eth.Contract(JSON.parse(contractABI), contractAddress);

// Send transaction to smart contract to update message and wait to finish
const receipt = await contract.methods.update("NEW_MESSAGE").send({
  from: fromAddress,
  maxPriorityFeePerGas: "5000000000", // Max priority fee per gas
  maxFeePerGas: "6000000000000", // Max fee per gas
});

Same error:

TransactionRevertedWithoutReasonError: Transaction has been reverted by the EVM:
 {"blockHash":"0xf07a72184c7df106c03755d98d794b0bd8e9246d54eadf93f74e5dba52c7faeb","blockNumber":"40289308","cumulativeGasUsed":"21070","effectiveGasPrice":"5000000017","from":"0xaf2e276b0020c0f8b5000b14596293318ab641f5","gasUsed":"21070","logs":[{"address":"0x0000000000000000000000000000000000001010","topics":["0x4dfe1bbbcf077ddc3e01291eea2d5c70c2b422b415d95645b9adcfd678cb1d63","0x0000000000000000000000000000000000000000000000000000000000001010","0x000000000000000000000000af2e276b0020c0f8b5000b14596293318ab641f5","0x000000000000000000000000f903ba9e006193c1527bfbe65fe2123704ea3f99"],"data":"0x00000000000000000000000000000000000000000000000000005fd0b553bc000000000000000000000000000000000000000000000000000ddcdfdd9f437f5a000000000000000000000000000000000000000000001149d279b3b0d3697b4a0000000000000000000000000000000000000000000000000ddc800ce9efc35a000000000000000000000000000000000000000000001149d27a138188bd374a","blockNumber":"40289308","transactionHash":"0x8014c9a83d87cbe2cd01b4fadb256f837a45dde680b8a55b37f67d1fd0a32b00","transactionIndex":"0","blockHash":"0xf07a72184c7df106c03755d98d794b0bd8e9246d54eadf93f74e5dba52c7faeb","logIndex":"0","removed":false}],"logsBloom":"0x00000000000000000000000000000000000000000000000000000010000000000000000000000020000000000000000000008000000000000000000000000000000000000000000000000000000000800000000000000000000100000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000800000000000000000200000000000000000000000000000000000400020000000000000000000004000000000000000000001000000000000000000000000000000100000001000000000000000000000000000000000000000000000000000000000000000100000","status":"0","to":"0xff7737a957f6546729da37b020afd86050fc93e9","transactionHash":"0x8014c9a83d87cbe2cd01b4fadb256f837a45dde680b8a55b37f67d1fd0a32b00","transactionIndex":"0","type":"2"}
    at get_transaction_error.ts:58:1
    at Generator.next (<anonymous>)
    at get_transaction_error.ts:1:1
    at new Promise (<anonymous>)
    at __awaiter (get_transaction_error.ts:1:1)
    at getTransactionError (get_transaction_error.ts:35:1)
    at rpc_method_wrappers.ts:630:1
    at Generator.next (<anonymous>)
    at fulfilled (rpc_method_wrappers.ts:1:1)

https://mumbai.polygonscan.com/tx/0x8014c9a83d87cbe2cd01b4fadb256f837a45dde680b8a55b37f67d1fd0a32b00

Please compare those two transactions:

  1. Made with Remix and Metamask that was successful: Tenderly Dashboard

  2. Made with web3Auth, web3 and React that failed: Tenderly Dashboard

If you pay attention the first one reaches the function signature of 0x60fe47b1 at the smart contract correctly but the second one doesn’t, trying to send the transaction to 0x as the function signature.

What version of Web.js & React are you using?

Did all suggestions you gave and got the same error:

TransactionRevertedWithoutReasonError: Transaction has been reverted by the EVM:
 {"blockHash":"0x4042bd5cce0b1f8da7ef95641371513937a7b24f7fae200950bc78f952aa2511","blockNumber":"40290659","cumulativeGasUsed":"21070","effectiveGasPrice":"5000000017","from":"0xaf2e276b0020c0f8b5000b14596293318ab641f5","gasUsed":"21070","logs":[{"address":"0x0000000000000000000000000000000000001010","blockHash":"0x4042bd5cce0b1f8da7ef95641371513937a7b24f7fae200950bc78f952aa2511","blockNumber":"40290659","data":"0x00000000000000000000000000000000000000000000000000005fd0b553bc000000000000000000000000000000000000000000000000000ddb609ac9deb2a200000000000000000000000000000000000000000000114a48aab913c90b59f00000000000000000000000000000000000000000000000000ddb00ca148af6a200000000000000000000000000000000000000000000114a48ab18e47e5f15f0","logIndex":"0","removed":false,"topics":["0x4dfe1bbbcf077ddc3e01291eea2d5c70c2b422b415d95645b9adcfd678cb1d63","0x0000000000000000000000000000000000000000000000000000000000001010","0x000000000000000000000000af2e276b0020c0f8b5000b14596293318ab641f5","0x000000000000000000000000f903ba9e006193c1527bfbe65fe2123704ea3f99"],"transactionHash":"0x1874ad4df7c71a97ce21b28305c91cbdd83402f0d8552bbacb0458aec55c62a7","transactionIndex":"0"}],"logsBloom":"0x00000000000000000000000000000000000000000000000000000010000000000000000000000020000000000000000000008000000000000000000000000000000000000000000000000000000000800000000000000000000100000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000800000000000000000200000000000000000000000000000000000400020000000000000000000004000000000000000000001000000000000000000000000000000100000001000000000000000000000000000000000000000000000000000000000000000100000","status":"0","to":"0xff7737a957f6546729da37b020afd86050fc93e9","transactionHash":"0x1874ad4df7c71a97ce21b28305c91cbdd83402f0d8552bbacb0458aec55c62a7","transactionIndex":"0","type":"2"}
    at get_transaction_error.ts:58:1
    at Generator.next (<anonymous>)
    at get_transaction_error.ts:1:1
    at new Promise (<anonymous>)
    at __awaiter (get_transaction_error.ts:1:1)
    at getTransactionError (get_transaction_error.ts:35:1)
    at rpc_method_wrappers.ts:630:1
    at Generator.next (<anonymous>)
    at fulfilled (rpc_method_wrappers.ts:1:1)

I’m using those versions:

"@web3auth/base": "^7.0.1",
"@web3auth/modal": "^7.0.2",
"@web3auth/openlogin-adapter": "^7.0.1",

“react”: “^18.2.0”,
“react-countdown”: “^2.3.2”,
“react-dom”: “^18.2.0”,
“react-is”: “18.2.0”,
“react-redux”: “^8.0.2”,
“react-router-dom”: “^6.3.0”,
“react-scripts”: “5.0.1”,
“react-transition-group”: “^4.4.2”,
“redux”: “^4.2.0”,
“web3”: “^4.1.1”

Lastly, can you downgrade this to version v1.8.0 ?

It worked!!!

tx hash 0x8f32dfc59bd7277f705d91c52c8915c2d582e083da5552cc75411a5c34b42ac6

Thank you very much @vjgee !

But is it safe to use version 1.8.0 of web3? Do you know which is the most up-to-date version that I could use and still got it to work?

@vinicius.santiago Web3.js v4 has some breaking changes and our team are working to upgrade that. For now, you can continue to use v 1.8.0.

1 Like

Ok, thank you again @vjgee !

1 Like