decode static method

ContractFunctionWithValues decode({
  1. required Uint8List data,
  2. required ContractFunction function,
})

Try to decode the raw data using the function and return the decoded function If the decoding of the data with information from the function fails a NotDecodableContractFunction is returned

Implementation

static ContractFunctionWithValues decode({
  required Uint8List data,
  required ContractFunction function,
}) {
  try {
    if (data.length < 4) {
      throw FunctionDecodingException("Invalid data length: ${data.length}");
    }

    final function_selector = data.sublist(0, 4).toHex;

    if (function_selector != function.functionSelectorHex) {
      throw FunctionSelectorException(
        "Invalid function selector: $function_selector",
      );
    }

    var dataWithoutSelector = data.sublist(4);

    if (dataWithoutSelector.length % 32 != 0) {
      dataWithoutSelector = dataWithoutSelector.sublist(
        0,
        dataWithoutSelector.length - (dataWithoutSelector.length % 32),
      );
    }

    final decodedParams = decodeDataField(
      data: dataWithoutSelector,
      params: function.parameters,
    );

    if (function is LocalContractFunction) {
      return LocalContractFunctionWithValues(
        name: function.name,
        parameters: decodedParams,
        stateMutability: function.stateMutability,
        outputTypes: function.outputTypes,
      );
    }

    return ExternalContractFunctionWithValues(
      name: function.name,
      parameters: decodedParams,
    );
  } catch (e) {
    return NotDecodableContractFunction(
      data: data,
      error: e,
    );
  }
}