CosmosWallet.derive constructor

CosmosWallet.derive(
  1. List<String> mnemonic,
  2. CosmosNetworkInfo networkInfo, {
  3. String derivationPath = derivationPath,
})

Derives the private key from the given mnemonic using the specified networkInfo.

Implementation

factory CosmosWallet.derive(
  List<String> mnemonic,
  CosmosNetworkInfo networkInfo, {
  String derivationPath = derivationPath,
}) {
  try {
    // Convert the mnemonic to a BIP32 instance
    final seed = BIP39.mnemonicToSeed(mnemonic.join(' '));
    final root = BIP32.fromSeed(seed);

    // Get the node from the derivation path
    final derivedNode = root.derivePath(derivationPath);

    // Get the curve data
    final secp256k1 = ECCurve_secp256k1();
    final point = secp256k1.G;

    // Compute the curve point associated to the private key
    final bigInt = BigInt.parse(HEX.encode(derivedNode.privateKey!), radix: 16);
    final curvePoint = point * bigInt;

    // Get the public key
    final publicKeyBytes = curvePoint!.getEncoded();

    // Get the address
    final sha256Digest = SHA256Digest().process(publicKeyBytes);
    final address = RIPEMD160Digest().process(sha256Digest);

    // Return the key bytes
    return CosmosWallet(
      address: address,
      publicKey: publicKeyBytes,
      privateKey: derivedNode.privateKey!,
      networkInfo: networkInfo,
    );
  } catch (e) {
    throw Exception('Invalid mnemonic');
  }
}