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

Villa
  • 1
  • 1
  • May be a dupe of this: https://ethereum.stackexchange.com/questions/2519/how-to-convert-a-bytes32-to-string – ori Jan 20 '22 at 05:53

1 Answers1

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); } }

Ismael
  • 30,570
  • 21
  • 53
  • 96