Principal.fromText constructor

Principal.fromText(
  1. String text
)

Implementation

factory Principal.fromText(String text) {
  if (text.endsWith('.')) {
    throw ArgumentError(
      'The representation is not canonical: '
      'default subaccount should be omitted.',
    );
  }
  final paths = text.split('.');
  final String? subAccountHex;
  if (paths.length > 1) {
    subAccountHex = paths.last;
  } else {
    subAccountHex = null;
  }
  if (subAccountHex != null && subAccountHex.startsWith('0')) {
    throw ArgumentError.value(
      subAccountHex,
      'subAccount',
      'The representation is not canonical: '
          'leading zeros are not allowed in subaccounts.',
    );
  }
  String prePrincipal = paths.first;
  // Removes the checksum if sub-account is valid.
  if (subAccountHex != null) {
    final list = prePrincipal.split('-');
    final checksum = list.removeLast();
    // Checksum is 7 digits.
    if (checksum.length != 7) {
      throw ArgumentError.value(
        prePrincipal,
        'principal',
        'Missing checksum',
      );
    }
    prePrincipal = list.join('-');
  }
  final canisterIdNoDash = prePrincipal.toLowerCase().replaceAll('-', '');
  Uint8List arr = base32Decode(canisterIdNoDash);
  arr = arr.sublist(4, arr.length);
  final subAccount = subAccountHex?.padLeft(64, '0').toU8a();
  final principal = Principal(arr, subAccount: subAccount);
  if (principal.toText() != text) {
    throw ArgumentError.value(
      text,
      'principal',
      'The principal is expected to be ${principal.toText()} but got',
    );
  }
  return principal;
}