0

I am working on a dapp solution that has this following function in smart contract:

function addFood(string memory _name, uint _price, bool _available) public onlyOwner {
    foods[numberOfFoods].name = _name;
    foods[numberOfFoods].price = _price;
    foods[numberOfFoods].available = _available;
    emit addedFood(numberOfFoods, _name);
    numberOfFoods++;
}

Now, I'm trying to connect this function with MetaMask by this Javascript code:

const Web3 = require('web3');
const FoodOrder = require('../build/contracts/FoodOrder.json');
const url = 'http://localhost:8545';

const sendEthButton = document.querySelector('.sendEthButton');

sendEthButton.addEventListener('click', async () => {

    const address = '0xACAC449F1B8153175c5435465D348D1a8c9B473D'; //address of the smart contract

    const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
    const account = accounts[0];

    const web3 = new Web3(url);
    const networkId = await web3.eth.net.getId();
    const myContract = new web3.eth.Contract(
        FoodOrder.abi,
        FoodOrder.networks[networkId].address
    );

    const tx = myContract.methods.addFood('tea', 16, true);

    const gas = await tx.estimateGas({from: address}).toString();
    const gasPrice = await web3.eth.getGasPrice().toString();
    const data = tx.encodeABI().toString();

    ethereum
        .request({
        method: 'eth_sendTransaction',
        params: [
            {
            from: account,
            data: data,
            to: '0xACAC449F1B8153175c5435465D348D1a8c9B473D',
            value: '0x00',
            gasPrice: gasPrice,
            gas: gas,
            chainId: networkId,
            },
        ],
        })
    .then((txHash) => console.log(txHash))
    .catch((error) => console.error);
});

But after executing this script, MetaMask opens up and throws this error:

MetaMask encountered an error. Message: new BigNumber() not a base 16 number: 0x[object Promise]. Code: BigNumber Error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.