Solidity VM Exception – Fixing Returned Error: Out of Gas While Processing Transaction

solidity

My contract

pragma solidity ^0.8.0;

contract CRUD {
 uint public maxId = 1; 
 struct User {
  uint id;
  string name;
 }

 User[] public users;

    // get index for id
    function getUserIndex(uint _id) view internal returns(uint index){
        for( uint i = 0; i < users.length ; i++){
            if(users[i].id == _id){
                return i;
            }
        }
        revert('User does not exist');
    }
    // get user 
    function getUser(uint _id) view public returns(uint, string memory){
        uint userIndex = getUserIndex(_id);
        return (users[userIndex].id,users[userIndex].name);
    }
   // get all user 
    function getAll() view public returns(User[] memory){
        return users;
    }

    // add
    function addUser(string memory _name) public returns(uint){
        users.push(User(maxId,_name));
        maxId++;
        return users.length;
    }
}

Now when I am trying to test this on remix its all working but with web UI it's throwing err

Returned error: VM Exception while processing transaction: out of gas

const initWeb3 = () => {
  console.log(window)
    return new Promise((resolve, reject) => {
    if(typeof window.ethereum !== 'undefined') {
      const web3 = new window.Web3(window.ethereum);
      window.ethereum.enable()
        .then(() => resolve(new window.Web3(window.ethereum)))
        .catch(e => reject(e));
      return;
    }
    if(typeof window.web3 !== 'undefined') {
      return resolve(
        new Web3(window.web3.currentProvider)
      );
    }
        resolve(new Web3('http://127.0.0.1:7545'))
    })
}
const initContract = () => {
    return new web3.eth.Contract(ABI,ADDRESS)
}
const getSetAccounts = () => {
  web3.eth.getAccounts()
    .then( _accounts => accounts = _accounts )
}

addUserBtn.addEventListener('click',async (e)=>{
  e.preventDefault()
  const inputUserName = usernameInput.value
  console.log(await web3.eth.getBalance(accounts[0]))
  crud.methods.addUser(inputUserName)
  .send({from: accounts[0]})
    .then( res => console.log("res",res))
    .catch(e => console.log(e.message))
})

I can see balance is 99 eth. Any idea what went wrong?
I am opening HTML file so its connecting to ganace instance

Best Answer

this should help:

addUserBtn.addEventListener('click',async (e)=>{
  e.preventDefault()
  const inputUserName = usernameInput.value
  console.log(await web3.eth.getBalance(accounts[0]))
  await crud.methods.addUser(inputUserName)
  .send({
   from: accounts[0],
   gas: 3000000,
   gasPrice: web3.toWei(10, 'gwei')
   })
    .then( res => console.log("res",res))
    .catch(e => console.log(e.message))
})

for more details : Error: VM Exception while processing transaction: out of gas

Related Topic