-
Notifications
You must be signed in to change notification settings - Fork 118
/
operation.ts
195 lines (169 loc) · 6.19 KB
/
operation.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
import { BlockResponse, OperationContentsAndResult, OperationResultStatusEnum } from '@taquito/rpc';
import { combineLatest, from, Observable, of, ReplaySubject } from 'rxjs';
import {
catchError,
distinctUntilChanged,
filter,
first,
map,
shareReplay,
takeWhile,
tap,
} from 'rxjs/operators';
import { Context } from '../context';
import { Receipt, receiptFromOperation } from './receipt';
import { validateOperation, ValidationResult, InvalidOperationHashError } from '@taquito/utils';
import { BlockIdentifier } from '../read-provider/interface';
import { InvalidConfirmationCountError, ConfirmationUndefinedError } from '../error';
export type OperationStatus = 'pending' | 'unknown' | OperationResultStatusEnum;
/**
* @category Error
* @description Error that indicates a missed block when polling to retrieve new head block. This may happen when the polling interval is greater than the time between blocks.
*/
export class MissedBlockDuringConfirmationError extends Error {
name = 'MissedBlockDuringConfirmationError';
constructor() {
super(
'Taquito missed a block while waiting for operation confirmation and was not able to find the operation'
);
}
}
const MAX_BRANCH_ANCESTORS = 60;
/**
* @description WalletOperation allows to monitor operation inclusion on chains and surface information related to the operation
*/
export class WalletOperation {
protected _operationResult = new ReplaySubject<OperationContentsAndResult[]>(1);
protected _includedInBlock = new ReplaySubject<BlockResponse>(1);
protected _included = false;
private lastHead: BlockResponse | undefined;
protected newHead$: Observable<BlockResponse> = this._newHead$.pipe(
tap((newHead) => {
if (
!this._included &&
this.lastHead &&
newHead.header.level - this.lastHead.header.level > 1
) {
throw new MissedBlockDuringConfirmationError();
}
this.lastHead = newHead;
}),
shareReplay({ bufferSize: 1, refCount: true })
);
// Observable that emit once operation is seen in a block
private confirmed$ = this.newHead$.pipe(
map((head) => {
for (const opGroup of head.operations) {
for (const op of opGroup) {
if (op.hash === this.opHash) {
this._included = true;
this._includedInBlock.next(head);
this._operationResult.next(op.contents as OperationContentsAndResult[]);
// Return the block where the operation was found
return head;
}
}
}
}),
filter<BlockResponse | undefined, BlockResponse>((x): x is BlockResponse => {
return typeof x !== 'undefined';
}),
first(),
shareReplay({ bufferSize: 1, refCount: true })
);
async operationResults() {
return this._operationResult.pipe(first()).toPromise();
}
/**
* @description Receipt expose the total amount of tezos token burn and spent on fees
* The promise returned by receipt will resolve only once the transaction is included
*/
async receipt(): Promise<Receipt> {
return receiptFromOperation(await this.operationResults());
}
/**
*
* @param opHash Operation hash
* @param raw Raw operation that was injected
* @param context Taquito context allowing access to rpc and signer
*/
constructor(
public readonly opHash: string,
protected readonly context: Context,
private _newHead$: Observable<BlockResponse>
) {
if (validateOperation(this.opHash) !== ValidationResult.VALID) {
throw new InvalidOperationHashError(this.opHash);
}
this.confirmed$
.pipe(
first(),
catchError(() => of(undefined))
)
.subscribe();
}
async getCurrentConfirmation() {
if (!this._included) {
return 0;
}
return combineLatest([this._includedInBlock, from(this.context.readProvider.getBlock('head'))])
.pipe(
map(([foundAtBlock, head]) => {
return head.header.level - foundAtBlock.header.level + 1;
}),
first()
)
.toPromise();
}
async isInCurrentBranch(tipBlockIdentifier: BlockIdentifier = 'head') {
// By default it is assumed that the operation is in the current branch
if (!this._included) {
return true;
}
const tipBlockHeaderLevel = await this.context.readProvider.getBlockLevel(tipBlockIdentifier);
const inclusionBlock = await this._includedInBlock.pipe(first()).toPromise();
const levelDiff = tipBlockHeaderLevel - inclusionBlock.header.level;
// Block produced before the operation is included are assumed to be part of the current branch
if (levelDiff <= 0) {
return true;
}
const tipBlockLevel = Math.min(
inclusionBlock.header.level + levelDiff,
inclusionBlock.header.level + MAX_BRANCH_ANCESTORS
);
const blocks = new Set(await this.context.readProvider.getLiveBlocks(tipBlockLevel));
return blocks.has(inclusionBlock.hash);
}
confirmationObservable(confirmations?: number) {
if (typeof confirmations !== 'undefined' && confirmations < 1) {
throw new InvalidConfirmationCountError('Confirmation count must be at least 1');
}
const { defaultConfirmationCount } = this.context.config;
const conf = confirmations !== undefined ? confirmations : defaultConfirmationCount;
if (conf === undefined) {
throw new ConfirmationUndefinedError('Default confirmation count can not be undefined!');
}
return combineLatest([this._includedInBlock, this.newHead$]).pipe(
distinctUntilChanged(([, previousHead], [, newHead]) => {
return previousHead.hash === newHead.hash;
}),
map(([foundAtBlock, head]) => {
return {
block: head,
expectedConfirmation: conf,
currentConfirmation: head.header.level - foundAtBlock.header.level + 1,
completed: head.header.level - foundAtBlock.header.level >= conf - 1,
isInCurrentBranch: () => this.isInCurrentBranch(head.hash as BlockIdentifier),
};
}),
takeWhile(({ completed }) => !completed, true)
);
}
/**
*
* @param confirmations [0] Number of confirmation to wait for
*/
confirmation(confirmations?: number) {
return this.confirmationObservable(confirmations).toPromise();
}
}