solidityHexValue static method

Uint8List solidityHexValue(
  1. String type,
  2. dynamic value,
  3. dynamic bitsize
)

Implementation

static Uint8List solidityHexValue(String type, value, bitsize) {
  // pass in bitsize = null if use default bitsize
  var size, num;
  if (isArray(type)) {
    var subType = type.replaceAll('/\[.*?\]/', '');
    if (!isArray(subType)) {
      var arraySize = parseTypeArray(type);
      if (arraySize != 'dynamic' &&
          arraySize != 0 &&
          value.length > arraySize) {
        throw new ArgumentError('Elements exceed array size: ' + arraySize);
      }
    }
    var ret = BytesBuffer();
    value?.forEach((v) {
      ret.add(solidityHexValue(subType, v, 256));
    });
    return ret.toBytes();
  } else if (type == 'bytes') {
    return value;
  } else if (type == 'string') {
    return Uint8List.fromList(utf8.encode(value));
  } else if (type == 'bool') {
    bitsize = bitsize != null ? 256 : 8;
    var padding = List.generate((bitsize) / 4, (index) => '').join('0');
    return Uint8List.fromList(
        hex.decode(value ? padding + '1' : padding + '0'));
  } else if (type == 'address') {
    var bytesize = 20;
    if (bitsize != null) {
      bytesize = bitsize ~/ 8;
    }
    return setLengthLeft(value, bytesize);
  } else if (type.startsWith('bytes')) {
    size = parseTypeN(type);
    if (size < 1 || size > 32) {
      throw new ArgumentError('Invalid bytes<N> width: ' + size);
    }

    return setLengthRight(value, size);
  } else if (type.startsWith('uint')) {
    size = parseTypeN(type);
    if ((size % 8 != 0) || (size < 8) || (size > 256)) {
      throw new ArgumentError('Invalid uint<N> width: ' + size);
    }

    num = parseNumber(value);
    if (num.bitLength > size) {
      throw new ArgumentError(
          'Supplied uint exceeds width: ' + size + ' vs ' + num.bitLength);
    }

    bitsize = bitsize != null ? 256 : size;
    return encodeBigInt(num, length: bitsize ~/ 8);
  } else if (type.startsWith('int')) {
    size = parseTypeN(type);
    if ((size % 8 != 0) || (size < 8) || (size > 256)) {
      throw new ArgumentError('Invalid int<N> width: ' + size);
    }

    num = parseNumber(value);
    if (num.bitLength > size) {
      throw new ArgumentError(
          'Supplied int exceeds width: ' + size + ' vs ' + num.bitLength);
    }

    bitsize = bitsize != null ? 256 : size;
    return encodeBigInt(num.toUnsigned(size), length: bitsize ~/ 8);
  } else {
    // FIXME: support all other types
    throw new ArgumentError('Unsupported or invalid type: ' + type);
  }
}