I am interacting with a smart contract and i do not understand correctly how to encode the data using Web3j to interact with the smart contract since I had never interacted with a contract that required multiple byte-encoded data.

//this is a small example of what i have

//Solidity example contract

pragma solidity 0.8.7;

contract example {

function exampleFunction(bytes memory params){

    //Decode Data.
    (address[] memory array0, uint numberExample, address[] memory array1) = abi.decode(params, (address[], uint, address[]));
    //do more...



//prepare example data

List<String> array0 = new ArrayList<String>();

BigInteger numberExample = new BigInteger("4234242342424");

List<String> array1 = new ArrayList<String>();

//this is my problem as it is my first time sending encoded data.

byte[] params = ????;

//how to correctly encode the data?

//load contract

MixExecutor Contract = example.load(exampleContractAddress, web3j, transactionManager, gasPrice, gasLimit);

//Execute function

TransactionReceipt Tx = Contract.exampleFunction(params).sendAsync().get();

String hash = Tx.getTransactionHash();

//Contract Wrap

public RemoteCall<TransactionReceipt> exampleFunction(byte[] params) {
    final Function function = new Function(
            Arrays.<Type>asList(new org.web3j.abi.datatypes.DynamicBytes(params),
    return executeRemoteCallTransaction(function);

//I tried this but when executing the smart contract it gave an error.

String data = Arrays.<Type>asList(
            new org.web3j.abi.datatypes.DynamicArray<org.web3j.abi.datatypes.Address>(
                    array0, org.web3j.abi.datatypes.Address.class
            new org.web3j.abi.datatypes.generated.Uint256(numberExample),
            new org.web3j.abi.datatypes.DynamicArray<org.web3j.abi.datatypes.Address>(
                    array1, org.web3j.abi.datatypes.Address.class

byte[] params = data.getBytes();

I think this might help me, I'll keep looking.

I wonder if I will have to change the smart contract so that instead of receiving a data bytes it receives a Struct.

1 Answer 1

  ['address[]', 'uint256', 'address[]'],
    ['0x000000000000000000000000000000000000dEaD', '0x000000000000000000000000000000000000dEaD'],

You can read more about it in the docs: https://web3js.readthedocs.io/en/v1.2.11/web3-eth-abi.html

There's also encodeFunctionCall to encode a full function with parameters.

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.