encodeType function

Uint8List encodeType(
  1. String type,
  2. dynamic data
)

Implementation

Uint8List encodeType(String type, dynamic data) {
  switch (type) {
    case 'string':
      return encodeString(data);
    case 'address':
      return encodeAddress(data);
    case 'bool':
      return encodeBool(data);
    case 'bytes':
      return encodeBytes(data);
  }

  var reg = RegExp(r"^([a-z\d\[\]\(\),]{1,})\[([\d]*)\]$");
  var match = reg.firstMatch(type);
  if(match != null) {
    var baseType = match.group(1);
    var repeatCount = match.group(2);
    if(repeatCount == "") {
      return encodeList(data, baseType!);
    } else {
      int repeat = int.parse(repeatCount!);
      return encodeFixedLengthList(data, baseType!, repeat);
    }
  }

  if(type.startsWith('uint')) {
    if(data is BigInt) {
      return encodeUint256(data);
    } else if(data is String) {
      String d = data.toLowerCase();
      if(d.startsWith('0x')) {
        return encodeUint256(BigInt.parse(d.substring(2), radix: 16));
      } else if(d.contains(RegExp(r'[a-f]'))) {
        return encodeUint256(BigInt.parse(d, radix: 16));
      } else {
        return encodeUint256(BigInt.parse(d));
      }
    } else {
      return encodeInt(data);
    }
  }

  if(type.startsWith('int')) {
    if(data is BigInt) {
      return encodeInt256(data);
    } else if(data is String) {
      String d = data.toLowerCase();
      if(d.startsWith('0x')) {
        return encodeInt256(BigInt.parse(d.substring(2), radix: 16));
      } else if(d.contains(RegExp(r'[a-f]'))) {
        return encodeInt256(BigInt.parse(d, radix: 16));
      } else {
        return encodeInt256(BigInt.parse(d));
      }
    } else {
      return encodeInt(data);
    }
  }

  if(type.startsWith('bytes')) {
    var length = int.parse(type.substring(5));
    return encodeFixedBytes(data, length);
  }

  if(type.startsWith('(') && type.endsWith(')')) {
    var types = type.substring(1, type.length - 1);
    var subtypes = splitTypes(types);
    if(subtypes.length != (data as List).length) {
      throw Exception("incompatibal input length and contract abi arguments for $type");
    }

    List<int> headers = [];
    List<int> contents = [];

    int baseOffset = 0;
    for(var i = 0; i < subtypes.length; i++) {
      if(isDynamicType(subtypes[i])) {
        baseOffset += 32;
      } else {
        baseOffset += sizeOfStaticType(subtypes[i]);
      }
    }

    for(var i = 0; i < subtypes.length; i++) {
      if(isDynamicType(subtypes[i])) {
        headers.addAll(encodeInt(baseOffset + contents.length));
        contents.addAll(encodeType(subtypes[i], data[i]));
      } else {
        headers.addAll(encodeType(subtypes[i], data[i]));
      }
    }
    return Uint8List.fromList(headers + contents);
  }
  throw Exception('');
}