xclud / web3dart

Ethereum library, written in Dart.
https://pub.dev/packages/web3dart
MIT License
171 stars 94 forks source link

Address generated by this lib is different when you input the same mnemonic on wallets like Coinbase #25

Closed oliverbytes closed 2 years ago

oliverbytes commented 2 years ago

Any idea why it results in a different address?

fedser commented 2 years ago

@oliverbytes there are could be different derivePath of encoding (check function getPrivateKey at the bottom). Long time ago I solved it by additionally including another library "bitcoin_flutter" (here are fork for null_safety migration: https://github.com/fedser/bitcoin_flutter) for some functionality. Here are my example how I convert seed_phrase to privateKey, then privateKey, to publicKey:

import 'package:bip39/bip39.dart' as bip39;
import 'package:bitcoin_flutter/bitcoin_flutter.dart';

final normalisedSeedPhrase = this._seedPhraseNormalise(seedPhrase);
final String cryptMnemonic = bip39.mnemonicToEntropy(normalisedSeedPhrase);
final String privateKey = this.getPrivateKey(normalisedSeedPhrase: normalisedSeedPhrase);
final address = await this.getPublicAddress(privateKey);
debugPrint("pubKey = $address");
debugPrint("privKey = $privateKey");

Here are used functions:

String getPrivateKey({required String normalisedSeedPhrase}) {
    var seed = bip39.mnemonicToSeed(normalisedSeedPhrase);
    final hdWallet = new HDWallet.fromSeed(seed).derivePath("m/44'/60'/0'/0/0");
    final String? privKey = hdWallet.privKey;
    assert(privKey != null);
    return privKey ?? "";
 }

String _seedPhraseNormalise(String seedPhrase) {
    return _mnemonicWords(seedPhrase).join(" ");
 }

 List<String> _mnemonicWords(String mnemonic) {
    return mnemonic
        .split(" ")
        .where((item) => item.trim().isNotEmpty)
        .map((item) => item.trim())
        .toList();
 }

Future<EthereumAddress> getPublicAddress(String privateKey) async {
    final private = EthPrivateKey.fromHex(privateKey);
    final address = await private.extractAddress();
    return address;
}
oliverbytes commented 2 years ago

Sorry for my late response. All good now. Thank you very much

alexandrebottero commented 1 year ago

Did there is another way to avoid using another lib ?