Search code examples
javascriptarraysethereumsmartcontractsweb3js

how to pass uint32[], uint8[] parameter to smart contract in web3.js


I'm doing estimateGas. here's my code.

var sdate = new Date('2021-07-01 00:00:00');
var edate = new Date('2021-07-31 00:00:00');
var arrDate = [];
arrDate.push(sdate/1000);
arrDate.push(edate/1000);
var arrCategory = [1,12,14];


var param1 = web3.eth.abi.encodeParameter('uint32[]',arrDate);
var param2 = web3.eth.abi.encodeParameter('uint8[]',arrCategory);


let Contract = new web3.eth.Contract(myPack.abi, myPack.ca);
Contract.methods.createTicket(param1, param2).estimateGas({from: accounts[0]})
.then(console.log);

and I met error

Uncaught TypeError: t.map is not a function
at h.formatParam (index.js:218)
at index.js:100
at Array.map ()
at h.encodeParameters (index.js:94)
at index.js:439
at Array.map ()
at Object.d._encodeMethodABI (index.js:438)
at Object.d._processExecuteArguments (index.js:701)
at Object.d._executeMethod (index.js:720)
at estimateGas (issuecfm:257)

I tried something before encodeParameter

BigNumber

var BN =  web3.utils.BN;
arrDate = arrDate.map(item => {return new BN(item)});
arrCategory = arrCategory.map(item => {return new BN(item)});

and String

arrDate = arrDate.map(item => {return item.toString()});
arrCategory = arrCategory.map(item => {return item.toString()});

After a lot of searching, I tried what I could. but I still get the same error. I would really appreciate it if you could teach me how to modify my code.


Solution

  • Using the web3 contract helper function, you need to pass the "raw" JS params, not the ABI-encoded data.

    let contract = new web3.eth.Contract(myPack.abi, myPack.ca);
    
    // mind the `arrDate` and `arrCategory` instead of `param1` and `param2`
    contract.methods.createTicket(arrDate, arrCategory)
        .estimateGas({from: accounts[0]})
        .then(console.log);