3

I'm trying to call a method in a contract and the method is like this:

function myMethod(uint8 tid, bytes calldata _bytes)
    public
    view
    returns (string memory)
{ ... }

I'm using Web3.js to call the methods and I have done successful ones on other methods but I can't find a way to pass bytes data to call this method. I would appreciate it if you could help me.

1 Answer 1

0

bytes is a variable type that holds a sequence of bytes from 1 to up to 32, you can read more about it in the docs.

On Web3 you use numberToHex or utf8ToHex for strings.

For example (a very general one), if your message is a string -

const contract = new web3.eth.Contract(CONTRACT_ABI, CONTRACT_ADDRESS);
const method = contract.methods.MyFunction( web3.utils.utf8ToHex('my message') );
const txData = method.encodeABI(); 
const txConfig: TxData = {
    nonce,
    gasPrice,
    gasLimit,
    to: web3.utils.toChecksumAddress(RECEIVER_ADDRESS),
    value: 0,
    data: txData,
};
...
9
  • I used web3.utils.hexToBytes but didn't work
    – Farzad Z
    Commented May 9, 2022 at 14:42
  • Use hex string 0x..., added to answer. Would help if you stated what type you're trying to send.
    – Kof
    Commented May 9, 2022 at 17:41
  • The first parameter is uint8 which is the token id and the next one is an array of bytes (the bytes type in solidity)
    – Farzad Z
    Commented May 9, 2022 at 20:38
  • @Kof this answer would be more helpful if you actually answered the question. Commented Dec 7, 2023 at 0:55
  • @NicSzerman I actually answered. Let me spell it out again On Web3 you use numberToHex or utf8ToHex for strings. - that's how you pass bytes parameter to a contract. If OP wants more a more specific answer, he should ask a more specific question, paste code, etc.
    – Kof
    Commented Dec 14, 2023 at 8:27

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.