-
-
Notifications
You must be signed in to change notification settings - Fork 283
/
Copy pathgetAccountUtxo.ts
60 lines (51 loc) · 2.06 KB
/
getAccountUtxo.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { throwError } from '@trezor/utils';
import { discovery } from '@trezor/utxo-lib';
import type { GetAccountUtxo as Req } from '@trezor/blockchain-link-types/src/messages';
import type { GetAccountUtxo as Res } from '@trezor/blockchain-link-types/src/responses';
import type { Utxo } from '@trezor/blockchain-link-types/src/electrum';
import { Api, tryGetScripthash, discoverAddress } from '../utils';
const transformUtxo =
(currentHeight: number, addressInfo: { address?: string; path?: string } = {}) =>
({ height, tx_hash, tx_pos, value }: Utxo): Res['payload'][number] => ({
txid: tx_hash,
vout: tx_pos,
amount: value.toString(),
address: '',
path: '',
...addressInfo,
...(height
? {
blockHeight: height,
confirmations: currentHeight - height + 1,
}
: {
blockHeight: -1,
confirmations: 0,
}),
});
const getAccountUtxo: Api<Req, Res> = async (client, descriptor) => {
const {
block: { height },
network,
} = client.getInfo() || throwError('Client not initialized');
const parsed = tryGetScripthash(descriptor, network);
if (parsed.valid) {
const utxos = await client.request('blockchain.scripthash.listunspent', parsed.scripthash);
return utxos.map(transformUtxo(height));
}
const discover = discoverAddress(client);
const receive = await discovery(discover, descriptor, 'receive', network);
const change = await discovery(discover, descriptor, 'change', network);
const result = await Promise.all(
receive
.concat(change)
.filter(a => a.history.length)
.map(({ address, path, scripthash }) =>
client
.request('blockchain.scripthash.listunspent', scripthash)
.then(utxos => utxos.map(transformUtxo(height, { address, path }))),
),
).then(res => res.flat());
return result;
};
export default getAccountUtxo;