-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathchain.ts
544 lines (511 loc) · 17 KB
/
chain.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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
import { AE_AMOUNT_FORMATS, formatAmount } from './utils/amount-formatter';
import verifyTransaction, { ValidatorResult } from './tx/validator';
import {
ensureError, isAccountNotFoundError, pause, unwrapProxy,
} from './utils/other';
import { isNameValid, produceNameId } from './tx/builder/helpers';
import { DRY_RUN_ACCOUNT } from './tx/builder/schema';
import { AensName } from './tx/builder/constants';
import {
AensPointerContextError, DryRunError, InvalidAensNameError, TransactionError,
TxTimedOutError, TxNotInChainError, InternalError,
} from './utils/errors';
import { TransformNodeType } from './node/Base';
import Node from './node/Direct';
import {
Account as AccountNode, ByteCode, ContractObject, DryRunResult, DryRunResults,
Generation, KeyBlock, MicroBlockHeader, NameEntry, SignedTx,
} from './apis/node';
import {
decode, encode, Encoded, Encoding,
} from './utils/encoder';
import AccountBase from './account/Base';
import { buildTxHash } from './tx/builder';
/**
* @category chain
* @param type - Type
* @param options - Options
*/
export function _getPollInterval(
type: 'block' | 'microblock', // TODO: rename to 'key-block' | 'micro-block'
{ _expectedMineRate = 180000, _microBlockCycle = 3000 }:
{ _expectedMineRate?: number; _microBlockCycle?: number },
): number {
const base = {
block: _expectedMineRate,
microblock: _microBlockCycle,
}[type];
return Math.floor(base / 3);
}
/**
* @category exception
*/
export class InvalidTxError extends TransactionError {
validation: ValidatorResult[];
transaction: Encoded.Transaction;
constructor(
message: string,
validation: ValidatorResult[],
transaction: Encoded.Transaction,
) {
super(message);
this.name = 'InvalidTxError';
this.validation = validation;
this.transaction = transaction;
}
}
const heightCache: WeakMap<Node, { time: number; height: number }> = new WeakMap();
/**
* Obtain current height of the chain
* @category chain
* @param options - Options
* @param options.cached - Get height from the cache. The lag behind the actual height shouldn't
* be more than 1 block. Use if needed to reduce requests count, and approximate value can be used.
* For example, for timeout check in transaction status polling.
* @returns Current chain height
*/
export async function getHeight(
{ cached = false, ...options }: {
onNode: Node;
cached?: boolean;
} & Parameters<typeof _getPollInterval>[1],
): Promise<number> {
const onNode = unwrapProxy(options.onNode);
if (cached) {
const cache = heightCache.get(onNode);
if (cache?.time != null && cache.time > Date.now() - _getPollInterval('block', options)) {
return cache.height;
}
}
const { height } = await onNode.getCurrentKeyBlockHeight();
heightCache.set(onNode, { height, time: Date.now() });
return height;
}
/**
* Wait for a transaction to be mined
* @category chain
* @param th - The hash of transaction to poll
* @param options - Options
* @param options.interval - Interval (in ms) at which to poll the chain
* @param options.blocks - Number of blocks mined after which to fail
* @param options.onNode - Node to use
* @returns The transaction as it was mined
*/
export async function poll(
th: Encoded.TxHash,
{
blocks = 5, interval, onNode, ...options
}:
{ blocks?: number; interval?: number; onNode: Node } & Parameters<typeof _getPollInterval>[1],
): Promise<TransformNodeType<SignedTx>> {
interval ??= _getPollInterval('microblock', options);
const max = await getHeight({ ...options, onNode, cached: true }) + blocks;
do {
const tx = await onNode.getTransactionByHash(th);
if (tx.blockHeight !== -1) return tx;
await pause(interval);
} while (await getHeight({ ...options, onNode, cached: true }) < max);
throw new TxTimedOutError(blocks, th);
}
/**
* Wait for the chain to reach a specific height
* @category chain
* @param height - Height to wait for
* @param options - Options
* @param options.interval - Interval (in ms) at which to poll the chain
* @param options.onNode - Node to use
* @returns Current chain height
*/
export async function awaitHeight(
height: number,
{ interval, onNode, ...options }:
{ interval?: number; onNode: Node } & Parameters<typeof _getPollInterval>[1],
): Promise<number> {
interval ??= Math.min(_getPollInterval('block', options), 5000);
let currentHeight;
do {
if (currentHeight != null) await pause(interval);
currentHeight = await getHeight({ onNode });
} while (currentHeight < height);
return currentHeight;
}
/**
* Wait for transaction confirmation
* @category chain
* @param txHash - Transaction hash
* @param options - Options
* @param options.confirm - Number of micro blocks to wait for transaction confirmation
* @param options.onNode - Node to use
* @returns Current Height
*/
export async function waitForTxConfirm(
txHash: Encoded.TxHash,
{ confirm = 3, onNode, ...options }:
{ confirm?: number; onNode: Node } & Parameters<typeof awaitHeight>[1],
): Promise<number> {
const { blockHeight } = await onNode.getTransactionByHash(txHash);
const height = await awaitHeight(blockHeight + confirm, { onNode, ...options });
const { blockHeight: newBlockHeight } = await onNode.getTransactionByHash(txHash);
switch (newBlockHeight) {
case -1:
throw new TxNotInChainError(txHash);
case blockHeight:
return height;
default:
return waitForTxConfirm(txHash, { onNode, confirm, ...options });
}
}
/**
* Signs and submits transaction for mining
* @category chain
* @param txUnsigned - Transaction to sign and submit
* @param options - Options
* @returns Transaction details
*/
export async function sendTransaction(
txUnsigned: Encoded.Transaction,
{
onNode, onAccount, verify = true, waitMined = true, confirm, innerTx, ...options
}:
SendTransactionOptions,
): Promise<SendTransactionReturnType> {
const tx = await onAccount.signTransaction(txUnsigned, {
...options,
onNode,
innerTx,
networkId: await onNode.getNetworkId(),
});
if (innerTx === true) return { hash: buildTxHash(tx), rawTx: tx };
if (verify) {
const validation = await verifyTransaction(tx, onNode);
if (validation.length > 0) {
const message = `Transaction verification errors: ${
validation.map((v: { message: string }) => v.message).join(', ')}`;
throw new InvalidTxError(message, validation, tx);
}
}
try {
let __queue;
try {
__queue = onAccount != null ? `tx-${onAccount.address}` : null;
} catch (error) {
__queue = null;
}
const { txHash } = await onNode.postTransaction(
{ tx },
__queue != null ? { requestOptions: { customHeaders: { __queue } } } : {},
);
if (waitMined) {
const pollResult = await poll(txHash, { onNode, ...options });
const txData = {
...pollResult,
hash: pollResult.hash as Encoded.TxHash,
rawTx: tx,
};
// wait for transaction confirmation
if (confirm != null && +confirm > 0) {
const c = typeof confirm === 'boolean' ? undefined : confirm;
return {
...txData,
confirmationHeight: await waitForTxConfirm(txHash, { onNode, confirm: c, ...options }),
};
}
return txData;
}
return { hash: txHash, rawTx: tx };
} catch (error) {
ensureError(error);
throw Object.assign(error, {
rawTx: tx,
verifyTx: async () => verifyTransaction(tx, onNode),
});
}
}
type SendTransactionOptionsType = {
/**
* Node to use
*/
onNode: Node;
/**
* Account to use
*/
onAccount: AccountBase;
/**
* Verify transaction before broadcast, throw error if not
*/
verify?: boolean;
/**
* Ensure that transaction get into block
*/
waitMined?: boolean;
/**
* Number of micro blocks that should be mined after tx get included
*/
confirm?: boolean | number;
} & Parameters<typeof poll>[1] & Omit<Parameters<typeof waitForTxConfirm>[1], 'confirm'>
& Parameters<AccountBase['signTransaction']>[1];
export interface SendTransactionOptions extends SendTransactionOptionsType {}
interface SendTransactionReturnType extends Partial<TransformNodeType<SignedTx>> {
hash: Encoded.TxHash;
rawTx: Encoded.Transaction;
confirmationHeight?: number;
}
/**
* Get account by account public key
* @category chain
* @param address - Account address (public key)
* @param options - Options
* @param options.height - Get account on specific block by block height
* @param options.hash - Get account on specific block by micro block hash or key block hash
* @param options.onNode - Node to use
*/
export async function getAccount(
address: Encoded.AccountAddress | Encoded.ContractAddress,
{ height, hash, onNode }:
{ height?: number; hash?: Encoded.KeyBlockHash | Encoded.MicroBlockHash; onNode: Node },
): Promise<TransformNodeType<AccountNode>> {
if (height != null) return onNode.getAccountByPubkeyAndHeight(address, height);
if (hash != null) return onNode.getAccountByPubkeyAndHash(address, hash);
return onNode.getAccountByPubkey(address);
}
/**
* Request the balance of specified account
* @category chain
* @param address - The public account address to obtain the balance for
* @param options - Options
* @param options.format
* @param options.height - The chain height at which to obtain the balance for
* (default: top of chain)
* @param options.hash - The block hash on which to obtain the balance for (default: top of chain)
*/
export async function getBalance(
address: Encoded.AccountAddress | Encoded.ContractAddress | Encoded.OracleAddress,
{ format = AE_AMOUNT_FORMATS.AETTOS, ...options }:
{ format?: AE_AMOUNT_FORMATS } & Parameters<typeof getAccount>[1],
): Promise<string> {
const addr = address.startsWith('ok_')
? encode(decode(address), Encoding.AccountAddress)
: address as Encoded.AccountAddress | Encoded.ContractAddress;
const { balance } = await getAccount(addr, options).catch((error) => {
if (!isAccountNotFoundError(error)) throw error;
return { balance: 0n };
});
return formatAmount(balance, { targetDenomination: format });
}
/**
* Obtain current generation
* @category chain
* @param options - Options
* @param options.onNode - Node to use
* @returns Current Generation
*/
export async function getCurrentGeneration(
{ onNode }: { onNode: Node },
): Promise<TransformNodeType<Generation>> {
return onNode.getCurrentGeneration();
}
/**
* Get generation by hash or height
* @category chain
* @param hashOrHeight - Generation hash or height
* @param options - Options
* @param options.onNode - Node to use
* @returns Generation
*/
export async function getGeneration(
hashOrHeight: Encoded.KeyBlockHash | number,
{ onNode }: { onNode: Node },
): Promise<TransformNodeType<Generation>> {
if (typeof hashOrHeight === 'number') return onNode.getGenerationByHeight(hashOrHeight);
return onNode.getGenerationByHash(hashOrHeight);
}
/**
* Get micro block transactions
* @category chain
* @param hash - Micro block hash
* @param options - Options
* @param options.onNode - Node to use
* @returns Transactions
*/
export async function getMicroBlockTransactions(
hash: Encoded.MicroBlockHash,
{ onNode }: { onNode: Node },
): Promise<TransformNodeType<SignedTx[]>> {
return (await onNode.getMicroBlockTransactionsByHash(hash)).transactions;
}
/**
* Get key block
* @category chain
* @param hashOrHeight - Key block hash or height
* @param options - Options
* @param options.onNode - Node to use
* @returns Key Block
*/
export async function getKeyBlock(
hashOrHeight: Encoded.KeyBlockHash | number,
{ onNode }: { onNode: Node },
): Promise<TransformNodeType<KeyBlock>> {
if (typeof hashOrHeight === 'number') return onNode.getKeyBlockByHeight(hashOrHeight);
return onNode.getKeyBlockByHash(hashOrHeight);
}
/**
* Get micro block header
* @category chain
* @param hash - Micro block hash
* @param options - Options
* @param options.onNode - Node to use
* @returns Micro block header
*/
export async function getMicroBlockHeader(
hash: Encoded.MicroBlockHash,
{ onNode }: { onNode: Node },
): Promise<TransformNodeType<MicroBlockHeader>> {
return onNode.getMicroBlockHeaderByHash(hash);
}
interface TxDryRunArguments {
tx: Encoded.Transaction;
accountAddress: Encoded.AccountAddress;
top?: number | Encoded.KeyBlockHash | Encoded.MicroBlockHash;
txEvents?: any;
resolve: Function;
reject: Function;
}
const txDryRunRequests: Map<string, TxDryRunArguments[] & { timeout?: NodeJS.Timeout }> = new Map();
async function txDryRunHandler(key: string, onNode: Node): Promise<void> {
const rs = txDryRunRequests.get(key);
txDryRunRequests.delete(key);
if (rs == null) throw new InternalError('Can\'t get dry-run request');
let dryRunRes;
try {
const top = typeof rs[0].top === 'number'
? (await getKeyBlock(rs[0].top, { onNode })).hash : rs[0].top;
dryRunRes = await onNode.protectedDryRunTxs({
top,
txEvents: rs[0].txEvents,
txs: rs.map((req) => ({ tx: req.tx })),
accounts: Array.from(new Set(rs.map((req) => req.accountAddress)))
.map((pubKey) => ({ pubKey, amount: DRY_RUN_ACCOUNT.amount })),
});
} catch (error) {
rs.forEach(({ reject }) => reject(error));
return;
}
const { results, txEvents } = dryRunRes;
results.forEach(({ result, reason, ...resultPayload }, idx) => {
const {
resolve, reject, tx, accountAddress,
} = rs[idx];
if (result === 'ok') resolve({ ...resultPayload, txEvents });
else reject(Object.assign(new DryRunError(reason as string), { tx, accountAddress }));
});
}
/**
* Transaction dry-run
* @category chain
* @param tx - transaction to execute
* @param accountAddress - address that will be used to execute transaction
* @param options - Options
* @param options.top - hash of block on which to make dry-run
* @param options.txEvents - collect and return on-chain tx events that would result from the call
* @param options.combine - Enables combining of similar requests to a single dry-run call
* @param options.onNode - Node to use
*/
export async function txDryRun(
tx: Encoded.Transaction,
accountAddress: Encoded.AccountAddress,
{
top, txEvents, combine, onNode,
}:
{ top?: TxDryRunArguments['top']; txEvents?: boolean; combine?: boolean; onNode: Node },
): Promise<{
txEvents?: TransformNodeType<DryRunResults['txEvents']>;
} & TransformNodeType<DryRunResult>> {
const key = combine === true ? [top, txEvents].join() : 'immediate';
const requests = txDryRunRequests.get(key) ?? [];
txDryRunRequests.set(key, requests);
return new Promise((resolve, reject) => {
requests.push({
tx, accountAddress, top, txEvents, resolve, reject,
});
if (combine !== true) {
void txDryRunHandler(key, onNode);
return;
}
requests.timeout ??= setTimeout(() => { void txDryRunHandler(key, onNode); });
});
}
/**
* Get contract byte code
* @category contract
* @param contractId - Contract address
* @param options - Options
* @param options.onNode - Node to use
*/
export async function getContractByteCode(
contractId: Encoded.ContractAddress,
{ onNode }: { onNode: Node },
): Promise<TransformNodeType<ByteCode>> {
return onNode.getContractCode(contractId);
}
/**
* Get contract entry
* @category contract
* @param contractId - Contract address
* @param options - Options
* @param options.onNode - Node to use
*/
export async function getContract(
contractId: Encoded.ContractAddress,
{ onNode }: { onNode: Node },
): Promise<TransformNodeType<ContractObject>> {
return onNode.getContract(contractId);
}
/**
* Get name entry
* @category AENS
* @param name - AENS name
* @param options - Options
* @param options.onNode - Node to use
*/
export async function getName(
name: AensName,
{ onNode }: { onNode: Node },
): Promise<TransformNodeType<NameEntry>> {
return onNode.getNameEntryByName(name);
}
/**
* Resolve AENS name and return name hash
* @category AENS
* @param nameOrId - AENS name or address
* @param key - in AENS pointers record
* @param options - Options
* @param options.verify - To ensure that name exist and have a corresponding pointer
* // TODO: avoid that to don't trust to current api gateway
* @param options.resolveByNode - Enables pointer resolving using node
* @param options.onNode - Node to use
* @returns Address or AENS name hash
*/
export async function resolveName <
Type extends Encoding.AccountAddress | Encoding.ContractAddress,
>(
nameOrId: AensName | Encoded.Generic<Type>,
key: string,
{ verify = true, resolveByNode = false, onNode }:
{ verify?: boolean; resolveByNode?: boolean; onNode: Node },
): Promise<Encoded.Generic<Type | Encoding.Name>> {
if (isNameValid(nameOrId)) {
if (verify || resolveByNode) {
const name = await onNode.getNameEntryByName(nameOrId);
const pointer = name.pointers.find((p) => p.key === key);
if (pointer == null) throw new AensPointerContextError(nameOrId, key);
if (resolveByNode) return pointer.id as Encoded.Generic<Type>;
}
return produceNameId(nameOrId);
}
try {
decode(nameOrId);
return nameOrId;
} catch (error) {
throw new InvalidAensNameError(`Invalid name or address: ${nameOrId}`);
}
}