This repository was archived by the owner on Dec 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathethService.ts
More file actions
1462 lines (1381 loc) · 52.3 KB
/
ethService.ts
File metadata and controls
1462 lines (1381 loc) · 52.3 KB
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
FullChannelState,
IVectorChainService,
MinimalTransaction,
ChainError,
Result,
ERC20Abi,
IChainServiceStore,
TransactionReason,
FullTransferState,
UINT_MAX,
jsonifyError,
ChainServiceEvents,
ChainServiceEvent,
ChainServiceEventMap,
StringifiedTransactionReceipt,
StringifiedTransactionResponse,
getConfirmationsForChain,
StoredTransaction,
} from "@connext/vector-types";
import {
delay,
encodeTransferResolver,
encodeTransferState,
getRandomBytes32,
generateMerkleTreeData,
hashCoreTransferState,
} from "@connext/vector-utils";
import { Signer } from "@ethersproject/abstract-signer";
import { BigNumber } from "@ethersproject/bignumber";
import { Contract } from "@ethersproject/contracts";
import { JsonRpcProvider, TransactionReceipt, TransactionResponse } from "@ethersproject/providers";
import { Wallet } from "@ethersproject/wallet";
import { BaseLogger } from "pino";
import PriorityQueue from "p-queue";
import { AddressZero, HashZero } from "@ethersproject/constants";
import { Evt } from "evt";
import { v4 as uuidV4 } from "uuid";
import { ChannelFactory, VectorChannel } from "../artifacts";
import { EthereumChainReader } from "./ethReader";
import { parseUnits } from "ethers/lib/utils";
// The amount of time (ms) to wait before a confirmation polling period times out,
// indiciating we should resubmit tx with higher gas if the tx is not confirmed.
export const CONFIRMATION_TIMEOUT = 45_000;
// Multiplier for timeout once we get at least 1 confirmation.
const CONFIRMATION_MULTIPLIER = 4;
// The min percentage to bump gas.
export const GAS_BUMP_PERCENT = 20;
// 1M gas should cover all Connext txs. Gas won't exceed this amount.
export const BIG_GAS_LIMIT = BigNumber.from(2_000_000);
// nothing should ever be this expensive... _should_
export const BIG_GAS_PRICE = parseUnits("1500", "gwei");
// TODO: Deprecate. Note that this is used in autoRebalance.ts.
export const waitForTransaction = async (
provider: JsonRpcProvider,
transactionHash: string,
confirmations?: number,
timeout?: number,
): Promise<Result<TransactionReceipt, ChainError>> => {
try {
const receipt = await provider.waitForTransaction(transactionHash, confirmations, timeout);
if (!receipt) {
return Result.fail(new ChainError(ChainError.reasons.TransferNotFound, { receipt }));
}
if (receipt.status === 0) {
return Result.fail(new ChainError(ChainError.reasons.TxReverted, { receipt }));
}
return Result.ok(receipt);
} catch (e) {
return Result.fail(e);
}
};
export class EthereumChainService extends EthereumChainReader implements IVectorChainService {
private nonces: Map<number, number> = new Map();
private signers: Map<number, Signer> = new Map();
private queues: Map<number, PriorityQueue> = new Map();
private evts: { [eventName in ChainServiceEvent]: Evt<ChainServiceEventMap[eventName]> } = {
...this.disputeEvts,
[ChainServiceEvents.TRANSACTION_SUBMITTED]: new Evt(),
[ChainServiceEvents.TRANSACTION_MINED]: new Evt(),
[ChainServiceEvents.TRANSACTION_FAILED]: new Evt(),
};
constructor(
private readonly store: IChainServiceStore,
chainProviders: { [chainId: string]: JsonRpcProvider },
signer: string | Signer,
log: BaseLogger,
private readonly defaultRetries = 3,
) {
super(chainProviders, log);
Object.entries(chainProviders).forEach(([chainId, provider]) => {
this.signers.set(
parseInt(chainId),
typeof signer === "string" ? new Wallet(signer, provider) : (signer.connect(provider) as Signer),
);
this.queues.set(parseInt(chainId), new PriorityQueue({ concurrency: 1 }));
});
// TODO: Check to see which tx's are still active / unresolved, and resolve them.
// this.revitalizeTxs();
}
private getSigner(chainId: number): Signer | undefined {
const signer = this.signers.get(chainId);
return signer;
}
/// Upsert tx submission to store, fire tx submit event.
private async handleTxSubmit(
onchainTransactionId: string,
method: string,
methodId: string,
channelAddress: string,
reason: TransactionReason,
response: TransactionResponse,
): Promise<void> {
this.log.info(
{
method,
methodId,
channelAddress,
reason,
hash: response.hash,
gasPrice: response.gasPrice?.toString() ?? "unknown",
nonce: response.nonce,
},
"Tx submitted.",
);
await this.store.saveTransactionAttempt(onchainTransactionId, channelAddress, reason, response);
this.evts[ChainServiceEvents.TRANSACTION_SUBMITTED].post({
response: Object.fromEntries(
Object.entries(response).map(([key, value]) => {
return [key, BigNumber.isBigNumber(value) ? value.toString() : value];
}),
) as StringifiedTransactionResponse,
channelAddress,
reason,
});
}
/// Save the tx receipt in the store and fire tx mined event.
private async handleTxMined(
onchainTransactionId: string,
method: string,
methodId: string,
channelAddress: string,
reason: TransactionReason,
receipt: TransactionReceipt,
) {
this.log.info({ method, methodId, onchainTransactionId, reason, receipt }, "Tx mined.");
await this.store.saveTransactionReceipt(onchainTransactionId, receipt);
this.evts[ChainServiceEvents.TRANSACTION_MINED].post({
receipt: Object.fromEntries(
Object.entries(receipt).map(([key, value]) => {
return [key, BigNumber.isBigNumber(value) ? value.toString() : value];
}),
) as StringifiedTransactionReceipt,
channelAddress,
reason,
});
}
/// Save tx failure in store and fire tx failed event.
private async handleTxFail(
onchainTransactionId: string,
method: string,
methodId: string,
channelAddress: string,
reason: TransactionReason,
receipt?: TransactionReceipt,
error?: Error,
message: string = "Tx reverted",
) {
this.log.error({ method, methodId, error: error ? jsonifyError(error) : message }, message);
await this.store.saveTransactionFailure(onchainTransactionId, error?.message ?? message, receipt);
this.evts[ChainServiceEvents.TRANSACTION_FAILED].post({
error,
channelAddress,
reason,
...(receipt
? {
receipt: Object.fromEntries(
Object.entries(receipt).map(([key, value]) => {
return [key, BigNumber.isBigNumber(value) ? value.toString() : value];
}),
) as StringifiedTransactionReceipt,
}
: {}),
});
}
/// Helper method to wrap queuing up a transaction and waiting for response.
private async sendTx(
txFn: (gasPrice: BigNumber, nonce: number) => Promise<TransactionResponse | undefined>,
gasPrice: BigNumber,
signer: Signer,
chainId: number,
nonce?: number,
): Promise<Result<TransactionResponse | undefined, Error>> {
// Queue up the execution of the transaction.
if (!this.queues.has(chainId)) {
return Result.fail(new ChainError(ChainError.reasons.SignerNotFound));
}
// Define task to send tx with proper nonce
const task = async (): Promise<Result<TransactionResponse | undefined, Error>> => {
try {
// If a nonce is supplied, use that
if (typeof nonce !== "undefined") {
this.log.info({ nonce, chainId, gasPrice: gasPrice.toString() }, "Resubmitting tx");
const response: TransactionResponse | undefined = await txFn(gasPrice, nonce);
return Result.ok(response);
}
// Otherwise, send tx using highest stored or pending nonce
const stored = this.nonces.get(chainId) ?? 0;
const pending = await signer.getTransactionCount("pending");
const nonceToUse = stored > pending ? stored : pending;
this.log.info({ nonce, chainId, gasPrice: gasPrice.toString() }, "Submitting tx");
const response: TransactionResponse | undefined = await txFn(gasPrice, nonceToUse);
// Store the incremented nonce
this.nonces.set(chainId, nonceToUse + 1);
return Result.ok(response);
} catch (e) {
return Result.fail(e);
}
};
const result = await this.queues.get(chainId)!.add(task);
return result;
}
/// Check to see if any txs were left in an unfinished state. This should only execute on
/// contructor / init.
public async revitalizeTxs() {
// Get all txs from store that were left in submitted state. Resubmit them.
const storedTransactions: StoredTransaction[] = await this.store.getActiveTransactions();
for (const tx of storedTransactions) {
const latestAttempt = tx.attempts[tx.attempts.length - 1];
const txResponseRes = await this.getTxResponseFromHash(tx.chainId, latestAttempt.transactionHash);
if (txResponseRes.isError) {
this.log.error({ error: txResponseRes.getError(), tx }, "Error in getTxResponseFromHash");
continue;
}
const txResponse = txResponseRes.getValue();
if (txResponse.receipt) {
this.log.info({ txHash: txResponse.receipt.transactionHash }, "Tx mined, saving to db");
// receipt should be available
await this.store.saveTransactionReceipt(tx.channelAddress, txResponse.receipt);
continue;
}
this.sendTxWithRetries(tx.to, tx.chainId, tx.reason, async () => {
const signer = this.getSigner(tx.chainId);
if (!signer) {
throw new ChainError(ChainError.reasons.SignerNotFound, { chainId: tx.chainId });
}
return signer.sendTransaction({
to: tx.to,
data: tx.data,
chainId: tx.chainId,
gasPrice: latestAttempt.gasPrice,
nonce: tx.nonce,
value: BigNumber.from(tx.value || 0),
});
});
}
}
/// Helper method to grab signer from chain ID and check provider for a transaction.
/// Returns the transaction if found.
/// Throws ChainError if signer not found, tx not found, or tx already mined.
public async getTxResponseFromHash(
chainId: number,
txHash: string,
): Promise<Result<{ response?: TransactionResponse; receipt?: TransactionReceipt }, ChainError>> {
const provider = this.chainProviders[chainId];
if (!provider) {
return Result.fail(new ChainError(ChainError.reasons.ProviderNotFound, { chainId }));
}
try {
const response = await provider.getTransaction(txHash);
let receipt: TransactionReceipt | undefined;
if (response?.confirmations > 0) {
receipt = await provider.send("eth_getTransactionReceipt", [txHash]);
}
return Result.ok({ response, receipt });
} catch (e) {
return Result.fail(new ChainError(ChainError.reasons.TxNotFound, { error: e, transactionHash: txHash }));
}
}
public async sendTxWithRetries(
channelAddress: string,
chainId: number,
reason: TransactionReason,
// should return undefined IFF tx didnt send based on validation in
// fn
txFn: (gasPrice: BigNumber, nonce: number) => Promise<undefined | TransactionResponse>,
): Promise<Result<TransactionReceipt | undefined, ChainError>> {
const method = "sendTxWithRetries";
const methodId = getRandomBytes32();
const errors = [];
for (let attempt = 0; attempt < this.defaultRetries; attempt++) {
this.log.info(
{
method,
methodId,
retries: this.defaultRetries,
attempt,
channelAddress,
chainId,
reason,
},
"Attempting to send tx",
);
const receipt = await this.sendAndConfirmTx(channelAddress, chainId, reason, txFn);
if (!receipt.isError) {
this.log.info(
{
method,
methodId,
transactionHash: receipt.getValue()?.transactionHash,
channelAddress,
chainId,
},
receipt.getValue() ? "Tx confirmed" : "Tx was not sent",
);
return receipt;
}
// Otherwise, handle error
const error = receipt.getError()!;
if (!error.canRetry) {
this.log.error(
{ error: error.message, channelAddress, reason, stack: error.stack, method, methodId },
"Failed to send tx, will not retry",
);
return receipt;
}
// wait before retrying
errors.push(error);
this.log.warn(
{ error: error.message, channelAddress, attempt, retries: this.defaultRetries, method, methodId },
"Tx failed, waiting before retry",
);
await delay(1000);
}
return Result.fail(
new ChainError(ChainError.reasons.FailedToSendTx, {
errors: errors.map((e) => e.message).toString(),
retries: this.defaultRetries,
channelAddress,
reason,
}),
);
}
public async sendAndConfirmTx(
channelAddress: string,
chainId: number,
reason: TransactionReason,
// tx fn can return undefined so that just in time logic to stop txs can be made
txFn: (gasPrice: BigNumber, nonce: number) => Promise<TransactionResponse | undefined>,
presetGasPrice?: BigNumber,
): Promise<Result<TransactionReceipt | undefined, ChainError>> {
const method = "sendAndConfirmTx";
const methodId = getRandomBytes32();
const signer = this.signers.get(chainId);
if (!signer) {
return Result.fail(new ChainError(ChainError.reasons.SignerNotFound));
}
// Used to track the number of attempts, regardless of whether a tx was successfully submitted
// on each.
let tryNumber: number = 0;
// TODO: Add an optional argument above to take in an onchainTransactionId, and then fill
// in this data with the already-existing store record of the tx.
let responses: TransactionResponse[] = [];
let nonce: number | undefined;
let nonceExpired: boolean = false;
let receipt: TransactionReceipt | undefined;
let gasPrice: BigNumber;
try {
// Get (initial) gas price if there is not a preset amount passed into this method.
gasPrice =
presetGasPrice ??
(await (async (): Promise<BigNumber> => {
const price = await this.getGasPrice(chainId);
if (price.isError) {
throw price.getError()!;
}
return price.getValue();
})());
} catch (e) {
return Result.fail(e);
}
// This is the gas bump loop.
// We will raise gas price for a tx if the confirmation of the tx times out.
// (Default timeout is GAS_BUMP_THRESHOLD)
let onchainTransactionId = uuidV4();
while (!receipt) {
tryNumber += 1;
try {
/// SUBMIT
// NOTE: Nonce will persist across iterations, as soon as it is defined in the first one.
this.log.debug(
{ method, methodId, nonce, tryNumber, channelAddress, gasPrice: gasPrice.toString() },
"Attempting to send transaction",
);
const result = await this.sendTx(txFn, gasPrice, signer, chainId, nonce);
if (!result.isError) {
const response = result.getValue();
if (response) {
// Save nonce.
if (nonce === undefined) {
nonce = response.nonce;
} else if (response.nonce != nonce) {
// TODO: Is this edge case possible?
// Only if the callback txFn() *disobeys* us in not passing in the nonce.
// throw new ChainError(ChainError.reasons.)
}
this.log.info(
{
hash: response.hash,
gas: response.gasPrice?.toString() ?? "unknown",
channelAddress,
method,
methodId,
nonce: response.nonce,
},
"Tx submitted",
);
// Add this response to our local response history.
responses.push(response);
// NOTE: Response MUST be defined here because if it was NEVER defined (i.e. undefined on first iteration),
// we would have returned in prev block, and if it was undefined on this iteration we would not overwrite
// that value.
// Tx was submitted: handle saving to store.
await this.handleTxSubmit(onchainTransactionId, method, methodId, channelAddress, reason, response);
} else {
// If response returns undefined, we assume the tx was not sent. This will happen if some logic was
// passed into txFn to bail out at the time of sending.
this.log.info(
{ method, methodId, channelAddress, reason, tryNumber, nonce, gasPrice: gasPrice.toString() },
"Did not attempt tx.",
);
if (responses.length === 0) {
// Iff this is the only iteration, then we want to go ahead return w/o saving anything.
this.log.info(
{ method, methodId, channelAddress, tryNumber, nonce, gasPrice: gasPrice.toString() },
"Tx not needed",
);
return Result.ok(undefined);
} else {
this.log.info(
{ method, methodId, channelAddress, reason, tryNumber, nonce, gasPrice: gasPrice.toString() },
`txFn returned undefined, proceeding to confirmation step.`,
);
}
}
} else {
// If an error occurred, throw it to handle it in the catch block.
const error = result.getError()!;
// If the nonce has already been used, one of the original txs must have been mined and the tx
// we attempted here was a duplicate with bumped gas. Assuming we're on a subsuquent attempt,
// handle this by simply proceeding to confirm (each prev tx) without throwing.
if (
responses.length >= 1 &&
(error.message.includes("nonce has already been used") ||
// If we get a 'nonce is too low' message, a previous tx has been mined, and ethers thought
// we were making another tx attempt with the same nonce.
error.message.includes("Transaction nonce is too low.") ||
// Another ethers message that we could potentially be getting back.
error.message.includes("There is another transaction with same nonce in the queue."))
) {
nonceExpired = true;
this.log.info(
{ method, methodId, channelAddress, reason, nonce, error: error.message },
"Nonce already used: proceeding to check for confirmation in previous transactions.",
);
} else {
this.log.error(
{ method, methodId, channelAddress, reason, nonce, tryNumber, gasPrice, error },
"Error occurred while executing tx submit.",
);
throw error;
}
}
/// CONFIRM
// Now we wait for confirmation and get tx receipt.
receipt = await this.waitForConfirmation(chainId, responses);
// Check status in event of tx reversion.
if (receipt && receipt.status === 0) {
throw new ChainError(ChainError.reasons.TxReverted, { receipt });
}
} catch (e) {
// Check if the error was a confirmation timeout.
if (e.message === ChainError.reasons.ConfirmationTimeout) {
if (nonceExpired) {
const error = new ChainError(ChainError.reasons.NonceExpired, {
methodId,
method,
});
await this.handleTxFail(
onchainTransactionId,
method,
methodId,
channelAddress,
reason,
receipt,
error,
"Nonce expired and could not confirm tx",
);
return Result.fail(error);
}
// Scale up gas by percentage as specified by GAS_BUMP_PERCENT.
// From ethers docs:
// Generally, the new gas price should be about 50% + 1 wei more, so if a gas price
// of 10 gwei was used, the replacement should be 15.000000001 gwei.
const bumpedGasPrice = gasPrice.add(gasPrice.mul(GAS_BUMP_PERCENT).div(100)).add(1);
this.log.info(
{
channelAddress,
reason,
method,
methodId,
gasPrice: gasPrice.toString(),
bumpedGasPrice: bumpedGasPrice.toString(),
},
"Tx timed out waiting for confirmation. Bumping gas price and reattempting.",
);
gasPrice = bumpedGasPrice;
// if the gas price is past the max, return a failure.
if (gasPrice.gt(BIG_GAS_PRICE)) {
const error = new ChainError(ChainError.reasons.MaxGasPriceReached, {
gasPrice: gasPrice.toString(),
methodId,
method,
max: BIG_GAS_PRICE,
});
await this.handleTxFail(
onchainTransactionId,
method,
methodId,
channelAddress,
reason,
receipt,
error,
"Max gas price reached",
);
return Result.fail(error);
}
// NOTE: This is just some syntactic sugar for readability. This is the only event where we
// should continue in this loop: to proceed to a subsuquent tx with a raised gas price.
continue;
} else {
let error = e;
if (e.message.includes("sender doesn't have enough funds")) {
error = new ChainError(ChainError.reasons.NotEnoughFunds);
}
// Don't save tx if it failed to submit (i.e. never received response), only if it fails to mine.
if (responses.length > 0) {
// If we get any other error here, we classify this event as a tx failure.
await this.handleTxFail(
onchainTransactionId,
method,
methodId,
channelAddress,
reason,
receipt,
e,
"Tx reverted",
);
} else {
this.log.error(
{ method, methodId, channelAddress, reason, error: jsonifyError(error) },
"Tx was never sent due to error",
);
}
return Result.fail(error);
}
}
}
// Success! Save mined tx receipt.
await this.handleTxMined(onchainTransactionId, method, methodId, channelAddress, reason, receipt);
return Result.ok(receipt);
}
/**
* Will wait for any of the given TransactionResponses to return
* a receipt. Once a receipt is returned by any of the responses,
* it will wait for X confirmations of the given receipt against
* a timeout. If within the timeout there are *not* X confirmations,
* the tx will be resubmitted at the same nonce.
*/
public async waitForConfirmation(chainId: number, responses: TransactionResponse[]): Promise<TransactionReceipt> {
const provider: JsonRpcProvider = this.chainProviders[chainId];
if (!provider) {
throw new ChainError(ChainError.reasons.ProviderNotFound);
}
const numConfirmations = getConfirmationsForChain(chainId);
// A flag for marking when we have received at least 1 confirmation. We'll extend the wait period by 2x
// if this is the case.
let receivedConfirmation: boolean = false;
// An anon fn to get the tx receipts for all responses.
// We must check for confirmation in all previous transactions. Although it's most likely
// that it's the previous one, any of them could have been confirmed.
const pollForReceipt = async (): Promise<TransactionReceipt | undefined> => {
// Save all reverted receipts for a check in case our Promise.race evaluates to be undefined.
let reverted: TransactionReceipt[] = [];
// Make a pool of promises for resolving each receipt call (once it reaches target confirmations).
const receipt = await Promise.race<any>(
responses
.map((response) => {
return new Promise(async (resolve) => {
const r = await provider.getTransactionReceipt(response.hash);
if (r) {
if (r.status === 0) {
reverted.push(r);
} else if (r.confirmations >= numConfirmations) {
return resolve(r);
} else if (r.confirmations >= 1) {
receivedConfirmation = true;
}
}
});
})
// Add a promise returning undefined with a delay of 2 seconds to the pool.
// This will execute in the event that none of the provider.getTransactionReceipt calls work,
// and/or none of them have the number of confirmations we want.
.concat(delay(2_000)),
);
if (!!receipt) {
if (reverted.length === responses.length) {
// We know every tx was reverted.
// NOTE: The first reverted receipt in the array will be entirely arbitrary.
// TODO: Should we return the reverted receipt belonging to the latest tx instead?
return reverted[0];
}
}
return receipt;
};
// Poll for receipt.
let receipt: TransactionReceipt | undefined = await pollForReceipt();
// NOTE: This loop won't execute if receipt is valid (not undefined).
let timeElapsed: number = 0;
const startMark = new Date().getTime();
while (
!receipt &&
timeElapsed < (receivedConfirmation ? CONFIRMATION_TIMEOUT * CONFIRMATION_MULTIPLIER : CONFIRMATION_TIMEOUT)
) {
receipt = await pollForReceipt();
// Update elapsed time.
timeElapsed = new Date().getTime() - startMark;
}
// If there is no receipt, we timed out in our polling operation.
if (!receipt) {
throw new ChainError(ChainError.reasons.ConfirmationTimeout);
}
return receipt;
}
public async sendDeployChannelTx(
channelState: FullChannelState,
deposit?: { amount: string; assetId: string }, // Included IFF createChannelAndDepositAlice
): Promise<Result<TransactionReceipt, ChainError>> {
const method = "sendDeployChannelTx";
const methodId = getRandomBytes32();
const signer = this.signers.get(channelState.networkContext.chainId);
if (!signer?._isSigner) {
return Result.fail(new ChainError(ChainError.reasons.SignerNotFound));
}
const sender = await signer.getAddress();
// check if multisig must be deployed
const multisigRes = await this.getCode(channelState.channelAddress, channelState.networkContext.chainId);
if (multisigRes.isError) {
return Result.fail(multisigRes.getError()!);
}
if (multisigRes.getValue() !== `0x`) {
return Result.fail(new ChainError(ChainError.reasons.MultisigDeployed));
}
const channelFactory = new Contract(channelState.networkContext.channelFactoryAddress, ChannelFactory.abi, signer);
// If there is no deposit information, just create the channel
if (!deposit) {
// Deploy multisig tx
this.log.info(
{ channelAddress: channelState.channelAddress, sender, method, methodId },
"Deploying channel without deposit",
);
const result = await this.sendTxWithRetries(
channelState.channelAddress,
channelState.networkContext.chainId,
TransactionReason.deploy,
async (gasPrice: BigNumber, nonce: number) => {
const multisigRes = await this.getCode(channelState.channelAddress, channelState.networkContext.chainId);
if (multisigRes.isError) {
throw multisigRes.getError()!;
}
if (multisigRes.getValue() !== `0x`) {
return undefined;
}
return channelFactory.createChannel(channelState.alice, channelState.bob, {
gasPrice: gasPrice,
gasLimit: BIG_GAS_LIMIT,
nonce,
});
},
);
if (result.isError) {
return result as Result<any, ChainError>;
}
if (!result.getValue()) {
return Result.fail(new ChainError(ChainError.reasons.MultisigDeployed));
}
return Result.ok(result.getValue()!);
}
// Deploy a channel with a deposit (only alice can do this)
if (sender !== channelState.alice) {
return Result.fail(
new ChainError(ChainError.reasons.FailedToDeploy, {
message: "Sender is not alice",
sender,
alice: channelState.alice,
channel: channelState.channelAddress,
}),
);
}
const { assetId, amount } = deposit;
const balanceRes = await this.getOnchainBalance(assetId, channelState.alice, channelState.networkContext.chainId);
if (balanceRes.isError) {
return Result.fail(balanceRes.getError()!);
}
const balance = balanceRes.getValue();
if (balance.lt(amount)) {
return Result.fail(
new ChainError(ChainError.reasons.NotEnoughFunds, {
balance: balance.toString(),
amount,
assetId,
chainId: channelState.networkContext.chainId,
}),
);
}
this.log.info(
{ balance: balance.toString(), method, methodId, assetId, chainId: channelState.networkContext.chainId },
"Onchain balance sufficient",
);
// Handle eth deposits
if (assetId === AddressZero) {
const res = await this.sendTxWithRetries(
channelState.channelAddress,
channelState.networkContext.chainId,
TransactionReason.deployWithDepositAlice,
async (gasPrice: BigNumber, nonce: number) => {
const multisigRes = await this.getCode(channelState.channelAddress, channelState.networkContext.chainId);
if (multisigRes.isError) {
throw multisigRes.getError()!;
}
if (multisigRes.getValue() !== `0x`) {
// multisig deployed, just send deposit
return undefined;
}
// otherwise deploy with deposit
return channelFactory.createChannelAndDepositAlice(channelState.alice, channelState.bob, assetId, amount, {
value: amount,
gasPrice: gasPrice,
gasLimit: BIG_GAS_LIMIT,
nonce,
});
},
);
if (res.isError) {
return Result.fail(res.getError()!);
}
if (!res.getValue()) {
return Result.fail(new ChainError(ChainError.reasons.MultisigDeployed));
}
return Result.ok(res.getValue()!);
}
// Must be token deposit, first approve the token transfer
this.log.info({ assetId, amount, channel: channelState.channelAddress, sender }, "Approving tokens");
const approveRes = await this.approveTokens(
channelState.channelAddress,
channelState.networkContext.channelFactoryAddress,
sender,
amount,
assetId,
channelState.networkContext.chainId,
);
if (approveRes.isError) {
return Result.fail(approveRes.getError()!);
}
if (approveRes.getValue()) {
const receipt = approveRes.getValue()!;
if (receipt.status === 0) {
return Result.fail(new ChainError(ChainError.reasons.TxReverted, { receipt }));
}
this.log.info({ txHash: receipt.transactionHash, method, assetId }, "Token approval confirmed");
}
const res = await this.sendTxWithRetries(
channelState.channelAddress,
channelState.networkContext.chainId,
TransactionReason.deployWithDepositAlice,
async (gasPrice: BigNumber, nonce: number) => {
const multisigRes = await this.getCode(channelState.channelAddress, channelState.networkContext.chainId);
if (multisigRes.isError) {
throw multisigRes.getError()!;
}
if (multisigRes.getValue() !== `0x`) {
// multisig deployed, just send deposit (will check allowance)
return undefined;
}
return channelFactory.createChannelAndDepositAlice(channelState.alice, channelState.bob, assetId, amount, {
gasPrice: gasPrice,
gasLimit: BIG_GAS_LIMIT,
nonce,
});
},
);
if (res.isError) {
return Result.fail(res.getError()!);
}
if (!res.getValue()) {
return Result.fail(new ChainError(ChainError.reasons.MultisigDeployed));
}
return Result.ok(res.getValue()!);
}
public async sendWithdrawTx(
channelState: FullChannelState,
minTx: MinimalTransaction,
): Promise<Result<TransactionReceipt, ChainError>> {
const method = "sendWithdrawTx";
const methodId = getRandomBytes32();
const signer = this.signers.get(channelState.networkContext.chainId);
if (!signer?._isSigner) {
return Result.fail(new ChainError(ChainError.reasons.SignerNotFound));
}
const sender = await signer.getAddress();
if (channelState.alice !== sender && channelState.bob !== sender) {
return Result.fail(new ChainError(ChainError.reasons.SenderNotInChannel));
}
// check if multisig must be deployed
const multisigRes = await this.getCode(channelState.channelAddress, channelState.networkContext.chainId);
if (multisigRes.isError) {
return Result.fail(multisigRes.getError()!);
}
if (multisigRes.getValue() === `0x`) {
// Deploy multisig tx
this.log.info({ channelAddress: channelState.channelAddress, sender, method, methodId }, "Deploying channel");
const txRes = await this.sendDeployChannelTx(channelState);
if (txRes.isError && txRes.getError()?.message !== ChainError.reasons.MultisigDeployed) {
return Result.fail(
new ChainError(ChainError.reasons.FailedToDeploy, {
method,
error: txRes.getError()!.message,
channel: channelState.channelAddress,
}),
);
}
}
this.log.info({ sender, method, methodId, channel: channelState.channelAddress }, "Sending withdraw tx to chain");
const res = await this.sendTxWithRetries(
channelState.channelAddress,
channelState.networkContext.chainId,
TransactionReason.withdraw,
async (gasPrice: BigNumber, nonce: number) => {
return signer.sendTransaction({ ...minTx, gasPrice, gasLimit: BIG_GAS_LIMIT, from: sender, nonce });
},
);
if (res.isError) {
return Result.fail(res.getError()!);
}
return Result.ok(res.getValue()!);
}
public async sendDepositTx(
channelState: FullChannelState,
sender: string,
amount: string,
assetId: string,
): Promise<Result<TransactionReceipt, ChainError>> {
const method = "sendDepositTx";
const methodId = getRandomBytes32();
const signer = this.signers.get(channelState.networkContext.chainId);
if (!signer?._isSigner) {
return Result.fail(new ChainError(ChainError.reasons.SignerNotFound));
}
if (channelState.alice !== sender && channelState.bob !== sender) {
return Result.fail(new ChainError(ChainError.reasons.SenderNotInChannel));
}
const toDeposit = BigNumber.from(amount);
if (toDeposit.isNegative()) {
return Result.fail(new ChainError(ChainError.reasons.NegativeDepositAmount));
}
// first check if multisig is needed to deploy
const multisigRes = await this.getCode(channelState.channelAddress, channelState.networkContext.chainId);
if (multisigRes.isError) {
return Result.fail(multisigRes.getError()!);
}
const multisigCode = multisigRes.getValue();
// alice needs to deploy the multisig
if (multisigCode === `0x` && sender === channelState.alice) {
this.log.info(
{
method,
methodId,
channelAddress: channelState.channelAddress,
assetId,
amount,
senderAddress: await signer.getAddress(),
},
`Deploying channel with deposit`,
);
const deployResult = await this.sendDeployChannelTx(channelState, { amount, assetId });
if (deployResult.isError) {
const error = deployResult.getError()!;
if (!(error.message === ChainError.reasons.MultisigDeployed)) {
return Result.fail(deployResult.getError()!);
}
// NOTE: If the multisig is already deployed, then our tx to deploy must have been reverted.
// We can proceed to making the deposit here ourselves in the code below.
} else {
// Deploy and deposit succeeded.
return Result.ok(deployResult.getValue()!);
}
}
const balanceRes = await this.getOnchainBalance(assetId, sender, channelState.networkContext.chainId);
if (balanceRes.isError) {
return Result.fail(balanceRes.getError()!);
}
const balance = balanceRes.getValue();
if (balance.lt(amount)) {
return Result.fail(
new ChainError(ChainError.reasons.NotEnoughFunds, {
balance: balance.toString(),
amount,
assetId,
chainId: channelState.networkContext.chainId,
}),
);
}
this.log.info(
{ balance: balance.toString(), method, methodId, assetId, chainId: channelState.networkContext.chainId },
"Onchain balance sufficient",
);
this.log.info({ method, methodId, assetId, amount }, "Channel is deployed, sending deposit");
if (sender === channelState.alice) {
this.log.info(
{ method, sender, alice: channelState.alice, bob: channelState.bob },
"Detected participant A, sending tx",
);
const txRes = await this.sendDepositATx(channelState, amount, assetId);
if (txRes.isError) {
this.log.error({ method, error: txRes.getError()!.message }, "Error sending tx");
} else {
this.log.info({ method, txHash: txRes.getValue().transactionHash }, "Tx mined");
}
return txRes;
} else {
this.log.info(
{ method, sender, alice: channelState.alice, bob: channelState.bob },
"Detected participant B, sendng tx",
);
const txRes = await this.sendDepositBTx(channelState, amount, assetId);
if (txRes.isError) {