-
Notifications
You must be signed in to change notification settings - Fork 55
/
InMemoryTransactionTracker.ts
132 lines (119 loc) · 4.83 KB
/
InMemoryTransactionTracker.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
import { TransactionTracker, TransactionTrackerEvents } from './types';
import Emittery from 'emittery';
import { Hash16, Slot, Tip } from '@cardano-ogmios/schema';
import { CardanoProvider, CardanoProviderError, CardanoSerializationLib, CSL } from '@cardano-sdk/core';
import { TransactionError, TransactionFailure } from './Transaction/TransactionError';
import { Logger } from 'ts-log';
export type Milliseconds = number;
export interface InMemoryTransactionTrackerProps {
provider: CardanoProvider;
csl: CardanoSerializationLib;
logger: Logger;
maxTipFailures?: number;
pollInterval?: Milliseconds;
}
const delay = (time: Milliseconds) => new Promise<void>((resolve) => setTimeout(resolve, time));
export class InMemoryTransactionTracker extends Emittery<TransactionTrackerEvents> implements TransactionTracker {
readonly #provider: CardanoProvider;
readonly #pendingTransactions = new Map<string, Promise<void>>();
readonly #csl: CardanoSerializationLib;
readonly #logger: Logger;
readonly #maxTipFailures: number;
readonly #pollInterval: number;
constructor({ provider, csl, logger, maxTipFailures = 3, pollInterval = 2000 }: InMemoryTransactionTrackerProps) {
super();
this.#provider = provider;
this.#csl = csl;
this.#logger = logger;
this.#maxTipFailures = maxTipFailures;
this.#pollInterval = pollInterval;
}
async trackTransaction(transaction: CSL.Transaction): Promise<void> {
const body = transaction.body();
const hash = Buffer.from(this.#csl.hash_transaction(body).to_bytes()).toString('hex');
if (this.#pendingTransactions.has(hash)) {
return this.#pendingTransactions.get(hash)!;
}
const invalidHereafter = body.ttl();
if (!invalidHereafter) {
throw new TransactionError(TransactionFailure.CannotTrack, undefined, 'no TTL');
}
const promise = this.#trackTransaction(hash, invalidHereafter);
this.#pendingTransactions.set(hash, promise);
this.emit('transaction', { transaction, confirmed: promise });
// eslint-disable-next-line promise/catch-or-return
promise.catch(() => void 0).then(() => this.#pendingTransactions.delete(hash));
return promise;
}
async #trackTransaction(hash: Hash16, invalidHereafter: Slot, numTipFailures = 0): Promise<void> {
await delay(this.#pollInterval);
try {
const tx = await this.#provider.queryTransactionsByHashes([hash]);
if (tx.length > 0) return; // done
return this.#onTransactionNotFound(hash, invalidHereafter, numTipFailures);
} catch (error: unknown) {
const providerError = this.#formatCardanoProviderError(error);
if (providerError.status_code !== 404) {
throw new TransactionError(TransactionFailure.CannotTrack, error);
}
return this.#onTransactionNotFound(hash, invalidHereafter, numTipFailures);
}
}
async #onTransactionNotFound(hash: string, invalidHereafter: number, numTipFailures: number) {
let tip: Tip | undefined;
try {
tip = await this.#provider.ledgerTip();
} catch (error: unknown) {
if (++numTipFailures > this.#maxTipFailures) {
throw new TransactionError(
TransactionFailure.CannotTrack,
error,
"can't query tip to check for transaction timeout"
);
}
this.#logger.debug(
`Failed to query ledgerTip, transaction ${hash} might already be timed out ` +
`(attempt ${numTipFailures} out of ${this.#maxTipFailures}).`,
error
);
}
if (tip && tip.slot > invalidHereafter) {
throw new TransactionError(TransactionFailure.Timeout);
}
return this.#trackTransaction(hash, invalidHereafter, numTipFailures);
}
#formatCardanoProviderError(error: unknown) {
const cardanoProviderError = error as CardanoProviderError;
if (typeof cardanoProviderError === 'string') {
throw new TransactionError(TransactionFailure.Unknown, error, cardanoProviderError);
}
if (typeof cardanoProviderError !== 'object') {
throw new TransactionError(TransactionFailure.Unknown, error, 'failed to parse error (response type)');
}
const errorAsType1 = cardanoProviderError as {
status_code: number;
message: string;
error: string;
};
if (errorAsType1.status_code) {
return errorAsType1;
}
const errorAsType2 = cardanoProviderError as {
errno: number;
message: string;
code: string;
};
if (errorAsType2.code) {
const status_code = Number.parseInt(errorAsType2.code);
if (!status_code) {
throw new TransactionError(TransactionFailure.Unknown, error, 'failed to parse error (status code)');
}
return {
status_code,
message: errorAsType1.message,
error: errorAsType2.errno.toString()
};
}
throw new TransactionError(TransactionFailure.Unknown, error, 'failed to parse error (response json)');
}
}