3

Here I have a smart contract with one method batch that accepts array of users to push into users state variable.

contract UserFactory {
  struct User {
    string name;
    uint age;
  }

  User[] users;

  function batch(User[] _users) public {
    // logic to add _users to users array
  }
}

Here on the JavaScript side I'm using web3.eth.abi.encodeParameter to create bytes type for some design purpose. But the problem is I have no idea how to encode User[] with encodeParameter. There is a solution to create a type like tuple(string,uint256)[] and pass [['John', 26], ['Doe', 99]] but again for design purpose I have to use the {name: "John", age: 26} so my alternative solution wont help.

// Trying to somehow create with array of users like [{name: "John", age: 26}, {name: "Doe", age: 99}]
const payload = web3.eth.abi.encodeParameter(
  {
    User: {
      name: "string",
      age: "uint256",
    },
  },
  {
    name: "John",
    age: 26,
  }
);

// This one working fine
const alternativePayload = const payload = web3.eth.abi.encodeParameter(
  'tuple(string,uint256)[]',
  [['John', 26], ['Doe', 99]]
);
1
  • encodeParameter is a low level function it doesn't seem to be user friendly. I'd suggest to write a wrapper function accept an input like the description and create the tuple parameter for encodeParameter.
    – Ismael
    Apr 18, 2021 at 15:53

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.