0

I have im my js file 3 variables:

var stringData = "stingData";
var intNonce = 1234;
var hexData = "0x65225648";

I want to concatenate then and send to my contract:

var data = stringData+intNonce+hexData;
myContract.contractFunction(data);

And im my contract i want to recover the 3 variables;

contract MyContract {
   contractFunction(bytes memory _data){
      //recover 3 variables
}
}

I read that the best way to do this is through Assembly but I have no idea how to implement this

1

1 Answer 1

0

You could use web3.eth.abi.encodeParameters to encode parameters from the js side.

const result = web3.eth.abi.encodeParameters(
    ['string','uint256','bytes32'],
    ["stingData", 1234, "0x65225648"],
)
console.log(result)

Which returns

0x000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000004d2652256480000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000097374696e67446174610000000000000000000000000000000000000000000000

Then you can decode from the solidity side using abi.decode. In the example it will look like this

// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;

contract A {
    function foo(bytes memory data) public pure returns (string memory, uint256, bytes32) {
        (string memory aString, uint256 aUint, bytes32 aBytes32) = abi.decode(
            data,
            (string, uint256, bytes32)
        );
        return (aString, aUint, aBytes32);
    }
}
1
  • Hi! thanks a lot! That was exactly that I needed
    – Villa
    Feb 16, 2022 at 15:09

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.