|
1 | 1 | /* eslint-disable class-methods-use-this */
|
2 | 2 |
|
| 3 | +import * as ecc from '@bitcoin-js/tiny-secp256k1-asmjs'; |
| 4 | +import { BIP32Factory } from 'bip32'; |
| 5 | +import { payments, networks } from 'bitcoinjs-lib'; |
| 6 | +import type { IHdWalletAccount } from '@/types'; |
3 | 7 | import { BaseProtocolAdapter } from '@/protocols/BaseProtocolAdapter';
|
| 8 | +import { MAXIMUM_ACCOUNTS_TO_DISCOVER } from '@/constants'; |
4 | 9 |
|
5 | 10 | export class BitcoinAdapter extends BaseProtocolAdapter {
|
| 11 | + bip32 = BIP32Factory(ecc); |
| 12 | + |
6 | 13 | // eslint-disable-next-line @typescript-eslint/no-unused-vars
|
7 |
| - async getBalance(address: string): Promise<string> { |
8 |
| - // TODO: Implement this with bitcoin adapter |
9 |
| - throw new Error('Method not implemented.'); |
| 14 | + override async getBalance(address: string): Promise<string> { |
| 15 | + // TODO: Implement this once the mdw is ready |
| 16 | + return Promise.resolve('989983200000000000'); |
| 17 | + } |
| 18 | + |
| 19 | + // eslint-disable-next-line @typescript-eslint/no-unused-vars |
| 20 | + override async isAccountUsed(address: string): Promise<boolean> { |
| 21 | + // TODO: Implement this |
| 22 | + return true; |
| 23 | + } |
| 24 | + |
| 25 | + override getHdWalletAccountFromMnemonicSeed( |
| 26 | + seed: Uint8Array, |
| 27 | + accountIndex: number, |
| 28 | + ): IHdWalletAccount { |
| 29 | + const node = this.bip32.fromSeed(Buffer.from(seed)); |
| 30 | + const path = `m/84'/0'/${accountIndex}'/0/0`; // 44 for Legacy |
| 31 | + const child = node.derivePath(path); |
| 32 | + const { address } = payments.p2wpkh({ // p2pkh for Legacy |
| 33 | + pubkey: child.publicKey, |
| 34 | + // TODO: use bitcoin.networks.testnet once the network selection is ready |
| 35 | + network: networks.bitcoin, |
| 36 | + }); |
| 37 | + const secretKey = child.toWIF(); |
| 38 | + |
| 39 | + return { |
| 40 | + secretKey, |
| 41 | + publicKey: child.publicKey!.toString('utf8'), |
| 42 | + address: address!, |
| 43 | + }; |
| 44 | + } |
| 45 | + |
| 46 | + override async discoverAccounts(seed: Uint8Array): Promise<number> { |
| 47 | + let lastNotEmptyIdx = 0; |
| 48 | + |
| 49 | + for (let i = 0; i < MAXIMUM_ACCOUNTS_TO_DISCOVER; i += 1) { |
| 50 | + const account = this.getHdWalletAccountFromMnemonicSeed(seed, i); |
| 51 | + // eslint-disable-next-line no-await-in-loop |
| 52 | + if (await this.isAccountUsed(account.publicKey)) { |
| 53 | + lastNotEmptyIdx = i; |
| 54 | + } |
| 55 | + } |
| 56 | + return lastNotEmptyIdx; |
10 | 57 | }
|
11 | 58 | }
|
0 commit comments