-
Notifications
You must be signed in to change notification settings - Fork 54
/
getOnChainAddressBalances.ts
144 lines (141 loc) · 5.92 KB
/
getOnChainAddressBalances.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
/* eslint-disable complexity */
import { GeneratorMetadata } from '../Content';
import { Intersection } from '@cardano-sdk/core';
import { Logger } from 'ts-log';
import { Ogmios, ogmiosToCore } from '@cardano-sdk/ogmios';
import { applyValue } from './applyValue';
export type AddressBalances = {
[address: string]: Ogmios.Schema.Value;
};
export type AddressBalancesResponse = GeneratorMetadata & {
balances: { [blockHeight: string]: AddressBalances };
};
export const getOnChainAddressBalances = (
addresses: string[],
atBlocks: number[],
options: {
logger: Logger;
ogmiosConnectionConfig: Ogmios.ConnectionConfig;
onBlock?: (slot: number) => void;
}
): Promise<AddressBalancesResponse> => {
const { logger, ogmiosConnectionConfig, onBlock } = options;
const trackedAddressBalances: AddressBalances = Object.fromEntries(
addresses.map((address) => [address, { assets: {}, coins: 0n }])
);
const trackedTxs: { id: Ogmios.Schema.TxId; inputs: Ogmios.Schema.TxIn[]; outputs: Ogmios.Schema.TxOut[] }[] = [];
// eslint-disable-next-line sonarjs/cognitive-complexity
return new Promise(async (resolve, reject) => {
let currentBlock: number;
// Required to ensure existing messages in the pipe are not processed after the completion
// condition is met
let draining = false;
const response: AddressBalancesResponse = {
balances: {},
metadata: {
cardano: {
compactGenesis: ogmiosToCore.genesis(
await Ogmios.StateQuery.genesisConfig(
await Ogmios.createInteractionContext(reject, logger.info, { connection: ogmiosConnectionConfig })
)
),
intersection: undefined as unknown as Intersection
}
}
};
try {
const syncClient = await Ogmios.createChainSyncClient(
await Ogmios.createInteractionContext(reject, logger.info, { connection: ogmiosConnectionConfig }),
{
rollBackward: async (_res, requestNext) => {
requestNext();
},
// eslint-disable-next-line max-statements
rollForward: async ({ block }, requestNext) => {
if (draining) return;
let b:
| Ogmios.Schema.BlockByron
| Ogmios.Schema.StandardBlock
| Ogmios.Schema.BlockShelley
| Ogmios.Schema.BlockAllegra
| Ogmios.Schema.BlockMary
| Ogmios.Schema.BlockAlonzo
| Ogmios.Schema.BlockBabbage;
let blockBody:
| undefined
| Ogmios.Schema.StandardBlock['body']['txPayload']
| Ogmios.Schema.BlockShelley['body']
| Ogmios.Schema.BlockAllegra['body']
| Ogmios.Schema.BlockMary['body']
| Ogmios.Schema.BlockAlonzo['body']
| Ogmios.Schema.BlockBabbage['body'];
if (Ogmios.isByronStandardBlock(block)) {
b = block.byron as Ogmios.Schema.StandardBlock;
blockBody = b.body.txPayload;
} else if (Ogmios.isShelleyBlock(block)) {
b = block.shelley as Ogmios.Schema.BlockShelley;
blockBody = b.body;
} else if (Ogmios.isAllegraBlock(block)) {
b = block.allegra as Ogmios.Schema.BlockAllegra;
blockBody = b.body;
} else if (Ogmios.isMaryBlock(block)) {
b = block.mary as Ogmios.Schema.BlockMary;
blockBody = b.body;
} else if (Ogmios.isAlonzoBlock(block)) {
b = block.alonzo as Ogmios.Schema.BlockAlonzo;
blockBody = b.body;
} else if (Ogmios.isBabbageBlock(block)) {
b = block.babbage as Ogmios.Schema.BlockBabbage;
blockBody = b.body;
} else if (Ogmios.isByronEpochBoundaryBlock(block)) {
b = block.byron as Ogmios.Schema.BlockByron;
} else {
throw new Error('No support for block');
}
if (b !== undefined) {
currentBlock = b.header!.blockHeight;
if (onBlock !== undefined) {
onBlock(currentBlock);
}
if (blockBody) {
for (const tx of blockBody) {
for (const output of tx.body.outputs) {
if (trackedAddressBalances[output.address] !== undefined) {
const addressBalance = { ...trackedAddressBalances[output.address] };
trackedTxs.push({ id: tx.id, inputs: tx.body.inputs, outputs: tx.body.outputs });
trackedAddressBalances[output.address] = applyValue(addressBalance, output.value);
}
}
for (const input of tx.body.inputs) {
const trackedInput = trackedTxs.find((t) => t.id === input.txId)?.outputs[input.index];
if (trackedInput !== undefined && trackedAddressBalances[trackedInput?.address] !== undefined) {
const addressBalance = { ...trackedAddressBalances[trackedInput.address] };
trackedAddressBalances[trackedInput.address] = applyValue(
addressBalance,
trackedInput.value,
true
);
}
}
}
if (atBlocks.includes(currentBlock)) {
response.balances[currentBlock] = { ...trackedAddressBalances };
if (atBlocks[atBlocks.length - 1] === currentBlock) {
draining = true;
await syncClient.shutdown();
return resolve(response);
}
}
}
}
requestNext();
}
}
);
response.metadata.cardano.intersection = (await syncClient.startSync(['origin'])) as Intersection;
} catch (error) {
logger.error(error);
return reject(error);
}
});
};