I'm having a problem passing an array from web3 to smart contract.
I have an array declared as names=[] with data parsed as int;
I am planning to send a value to my smart contract with the function:
function vote(uint[] memory candID,uint id,uint elid) public {
//code here
}
using this code in my frontend:
await contract.methods.vote([names],BigInt(election),BigInt(electClickedID)).send({ from: accounts[0], gas: 3000000 });
I always face an error, but when passing data manually, like :
await contract.methods.vote([0,1,5],BigInt(election),BigInt(electClickedID)).send({ from: accounts[0], gas: 3000000 });
it succeeds.
Your variable names is an empty 1-dimensional array, By wrapping it in the additional [] expression, you're effectively passing a 2-dimensional array to the Solidity function.
For example, if the value of names was [0,1,5], you'd be passing [[0,1,5]] - an array of one item, which [the item] is another array of three items.
Which is not valid, as the Solidity function accepts a 1D array.
Solution: Remove the array wrapper.
let names = [];
await contract.methods.vote(
names, // instead of `[names]`
BigInt(election),
BigInt(electClickedID)
).send({
from: accounts[0],
gas: 3000000
});