getEncryptionPublicKey method

String getEncryptionPublicKey(
  1. String privateKeyHex
)

Lấy encryption public key từ private key sử dụng web3dart

Implementation

String getEncryptionPublicKey(String privateKeyHex) {
  try {
    final trimmed = privateKeyHex.trim();
    final hexNoPrefix =
        trimmed.startsWith('0x') ? trimmed.substring(2) : trimmed;
    if (!RegExp(r'^[0-9a-fA-F]{64}$').hasMatch(hexNoPrefix)) {
      throw WalletException('Invalid private key hex', code: -32602);
    }
    final privateKey = EthPrivateKey.fromHex(hexNoPrefix);

    // web3dart 2.7: encodedPublicKey = 65 bytes (0x04 || x32 || y32)
    final pub = privateKey.encodedPublicKey;
    if (pub.length != 65 || pub[0] != 0x04) {
      throw WalletException('Unexpected public key format');
    }
    final yIsEven = (pub[64] & 1) == 0;
    final compressedPubKey = Uint8List(33);
    compressedPubKey[0] = yIsEven ? 0x02 : 0x03;
    compressedPubKey.setRange(1, 33, pub.sublist(1, 33));

    return '0x${HEX.encode(compressedPubKey)}';
  } catch (e) {
    if (e is WalletException) rethrow;
    throw WalletException('Failed to get encryption public key: $e');
  }
}