encodeMultiKey static method

List<int> encodeMultiKey(
  1. List<SuiPublicKeyAndWeight> publicKeys,
  2. int threshold
)

encode Multi Public keys to MultiKey address

Implementation

static List<int> encodeMultiKey(
  List<SuiPublicKeyAndWeight> publicKeys,
  int threshold,
) {
  try {
    if (publicKeys.isEmpty) {
      throw AddressConverterException.addressKeyValidationFailed(
        reason: "At least one publickey required for multisig address.",
      );
    }
    final keys = publicKeys.map((e) => e.publicKey).toSet();
    if (keys.length != publicKeys.length) {
      throw AddressConverterException.addressKeyValidationFailed(
        reason: "Duplicate public key detected.",
      );
    }
    if (keys.length > SuiAddrConst.multisigAccountMaxPublicKey) {
      throw AddressConverterException.addressKeyValidationFailed(
        reason:
            "Exceeded the maximum allowed public keys for a multisig account.",
        details: {
          "maximum": SuiAddrConst.multisigAccountMaxPublicKey,
          "length": publicKeys.length,
        },
      );
    }

    if (threshold < SuiAddrConst.multisigAccountMinThreshold ||
        threshold > SuiAddrConst.multisigAccountMaxThreshold) {
      throw AddressConverterException.addressKeyValidationFailed(
        reason:
            "Invalid threshold. threshold must be between 1 and $BinaryOps.mask16 .",
      );
    }
    final sumWeight = publicKeys.fold<int>(0, (p, c) => p + c.weight);
    if (sumWeight < threshold) {
      throw AddressConverterException.addressKeyValidationFailed(
        reason: "Sum of publickey weights must reach the threshold.",
      );
    }
    final encode = publicKeys.map((e) => e.toBytes()).expand((e) => e);
    return hashKeyBytes(
      bytes: [...LayoutConst.u16().serialize(threshold), ...encode],
      scheme: SuiAddrConst.multisigAddressFlag,
    );
  } on AddressConverterException {
    rethrow;
  } catch (e) {
    throw AddressConverterException.addressKeyValidationFailed(
      details: {"error": e.toString()},
    );
  }
}