-
-
Notifications
You must be signed in to change notification settings - Fork 200
/
Copy pathTransactionController.ts
1469 lines (1347 loc) · 46.7 KB
/
TransactionController.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
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 { EventEmitter } from 'events';
import { addHexPrefix, bufferToHex, BN } from 'ethereumjs-util';
import { ethErrors } from 'eth-rpc-errors';
import MethodRegistry from 'eth-method-registry';
import EthQuery from 'eth-query';
import Common from '@ethereumjs/common';
import { TransactionFactory, TypedTransaction } from '@ethereumjs/tx';
import { v1 as random } from 'uuid';
import { Mutex } from 'async-mutex';
import { BaseController, BaseConfig, BaseState } from '../BaseController';
import type {
NetworkState,
NetworkController,
} from '../network/NetworkController';
import {
BNToHex,
fractionBN,
hexToBN,
normalizeTransaction,
safelyExecute,
validateTransaction,
isSmartContractCode,
handleTransactionFetch,
query,
getIncreasedPriceFromExisting,
isEIP1559Transaction,
isGasPriceValue,
isFeeMarketEIP1559Values,
validateGasValues,
validateMinimumIncrease,
} from '../util';
import { MAINNET, RPC } from '../constants';
const HARDFORK = 'london';
/**
* @type Result
* @property result - Promise resolving to a new transaction hash
* @property transactionMeta - Meta information about this new transaction
*/
export interface Result {
result: Promise<string>;
transactionMeta: TransactionMeta;
}
/**
* @type Fetch All Options
* @property fromBlock - String containing a specific block decimal number
* @property etherscanApiKey - API key to be used to fetch token transactions
*/
export interface FetchAllOptions {
fromBlock?: string;
etherscanApiKey?: string;
}
/**
* @type Transaction
*
* Transaction representation
* @property chainId - Network ID as per EIP-155
* @property data - Data to pass with this transaction
* @property from - Address to send this transaction from
* @property gas - Gas to send with this transaction
* @property gasPrice - Price of gas with this transaction
* @property gasUsed - Gas used in the transaction
* @property nonce - Unique number to prevent replay attacks
* @property to - Address to send this transaction to
* @property value - Value associated with this transaction
*/
export interface Transaction {
chainId?: number;
data?: string;
from: string;
gas?: string;
gasPrice?: string;
gasUsed?: string;
nonce?: string;
to?: string;
value?: string;
maxFeePerGas?: string;
maxPriorityFeePerGas?: string;
estimatedBaseFee?: string;
}
export interface GasPriceValue {
gasPrice: string;
}
export interface FeeMarketEIP1559Values {
maxFeePerGas: string;
maxPriorityFeePerGas: string;
}
/**
* The status of the transaction. Each status represents the state of the transaction internally
* in the wallet. Some of these correspond with the state of the transaction on the network, but
* some are wallet-specific.
*/
export enum TransactionStatus {
approved = 'approved',
cancelled = 'cancelled',
confirmed = 'confirmed',
failed = 'failed',
rejected = 'rejected',
signed = 'signed',
submitted = 'submitted',
unapproved = 'unapproved',
}
/**
* Options for wallet device.
*/
export enum WalletDevice {
MM_MOBILE = 'metamask_mobile',
MM_EXTENSION = 'metamask_extension',
OTHER = 'other_device',
}
type TransactionMetaBase = {
isTransfer?: boolean;
transferInformation?: {
symbol: string;
contractAddress: string;
decimals: number;
};
id: string;
networkID?: string;
chainId?: string;
origin?: string;
rawTransaction?: string;
time: number;
toSmartContract?: boolean;
transaction: Transaction;
transactionHash?: string;
blockNumber?: string;
deviceConfirmedOn?: WalletDevice;
verifiedOnBlockchain?: boolean;
};
/**
* @type TransactionMeta
*
* TransactionMeta representation
* @property error - Synthesized error information for failed transactions
* @property id - Generated UUID associated with this transaction
* @property networkID - Network code as per EIP-155 for this transaction
* @property origin - Origin this transaction was sent from
* @property deviceConfirmedOn - string to indicate what device the transaction was confirmed
* @property rawTransaction - Hex representation of the underlying transaction
* @property status - String status of this transaction
* @property time - Timestamp associated with this transaction
* @property toSmartContract - Whether transaction recipient is a smart contract
* @property transaction - Underlying Transaction object
* @property transactionHash - Hash of a successful transaction
* @property blockNumber - Number of the block where the transaction has been included
*/
export type TransactionMeta =
| ({
status: Exclude<TransactionStatus, TransactionStatus.failed>;
} & TransactionMetaBase)
| ({ status: TransactionStatus.failed; error: Error } & TransactionMetaBase);
/**
* @type EtherscanTransactionMeta
*
* EtherscanTransactionMeta representation
* @property blockNumber - Number of the block where the transaction has been included
* @property timeStamp - Timestamp associated with this transaction
* @property hash - Hash of a successful transaction
* @property nonce - Nonce of the transaction
* @property blockHash - Hash of the block where the transaction has been included
* @property transactionIndex - Etherscan internal index for this transaction
* @property from - Address to send this transaction from
* @property to - Address to send this transaction to
* @property gas - Gas to send with this transaction
* @property gasPrice - Price of gas with this transaction
* @property isError - Synthesized error information for failed transactions
* @property txreceipt_status - Receipt status for this transaction
* @property input - input of the transaction
* @property contractAddress - Address of the contract
* @property cumulativeGasUsed - Amount of gas used
* @property confirmations - Number of confirmations
*/
export interface EtherscanTransactionMeta {
blockNumber: string;
timeStamp: string;
hash: string;
nonce: string;
blockHash: string;
transactionIndex: string;
from: string;
to: string;
value: string;
gas: string;
gasPrice: string;
cumulativeGasUsed: string;
gasUsed: string;
isError: string;
txreceipt_status: string;
input: string;
contractAddress: string;
confirmations: string;
tokenDecimal: string;
tokenSymbol: string;
}
/**
* @type TransactionConfig
*
* Transaction controller configuration
* @property interval - Polling interval used to fetch new currency rate
* @property provider - Provider used to create a new underlying EthQuery instance
* @property sign - Method used to sign transactions
*/
export interface TransactionConfig extends BaseConfig {
interval: number;
sign?: (transaction: Transaction, from: string) => Promise<any>;
txHistoryLimit: number;
}
/**
* @type MethodData
*
* Method data registry object
* @property registryMethod - Registry method raw string
* @property parsedRegistryMethod - Registry method object, containing name and method arguments
*/
export interface MethodData {
registryMethod: string;
parsedRegistryMethod: Record<string, unknown>;
}
/**
* @type TransactionState
*
* Transaction controller state
* @property transactions - A list of TransactionMeta objects
* @property methodData - Object containing all known method data information
*/
export interface TransactionState extends BaseState {
transactions: TransactionMeta[];
methodData: { [key: string]: MethodData };
}
/**
* Multiplier used to determine a transaction's increased gas fee during cancellation
*/
export const CANCEL_RATE = 1.5;
/**
* Multiplier used to determine a transaction's increased gas fee during speed up
*/
export const SPEED_UP_RATE = 1.1;
/**
* Controller responsible for submitting and managing transactions
*/
export class TransactionController extends BaseController<
TransactionConfig,
TransactionState
> {
private ethQuery: any;
private registry: any;
private handle?: NodeJS.Timer;
private mutex = new Mutex();
private getNetworkState: () => NetworkState;
private failTransaction(transactionMeta: TransactionMeta, error: Error) {
const newTransactionMeta = {
...transactionMeta,
error,
status: TransactionStatus.failed,
};
this.updateTransaction(newTransactionMeta);
this.hub.emit(`${transactionMeta.id}:finished`, newTransactionMeta);
}
private async registryLookup(fourBytePrefix: string): Promise<MethodData> {
const registryMethod = await this.registry.lookup(fourBytePrefix);
const parsedRegistryMethod = this.registry.parse(registryMethod);
return { registryMethod, parsedRegistryMethod };
}
/**
* Normalizes the transaction information from etherscan
* to be compatible with the TransactionMeta interface.
*
* @param txMeta - The transaction.
* @param currentNetworkID - The current network ID.
* @param currentChainId - The current chain ID.
* @returns The normalized transaction.
*/
private normalizeTx(
txMeta: EtherscanTransactionMeta,
currentNetworkID: string,
currentChainId: string,
): TransactionMeta {
const time = parseInt(txMeta.timeStamp, 10) * 1000;
const normalizedTransactionBase = {
blockNumber: txMeta.blockNumber,
id: random({ msecs: time }),
networkID: currentNetworkID,
chainId: currentChainId,
time,
transaction: {
data: txMeta.input,
from: txMeta.from,
gas: BNToHex(new BN(txMeta.gas)),
gasPrice: BNToHex(new BN(txMeta.gasPrice)),
gasUsed: BNToHex(new BN(txMeta.gasUsed)),
nonce: BNToHex(new BN(txMeta.nonce)),
to: txMeta.to,
value: BNToHex(new BN(txMeta.value)),
},
transactionHash: txMeta.hash,
verifiedOnBlockchain: false,
};
/* istanbul ignore else */
if (txMeta.isError === '0') {
return {
...normalizedTransactionBase,
status: TransactionStatus.confirmed,
};
}
/* istanbul ignore next */
return {
...normalizedTransactionBase,
error: new Error('Transaction failed'),
status: TransactionStatus.failed,
};
}
private normalizeTokenTx = (
txMeta: EtherscanTransactionMeta,
currentNetworkID: string,
currentChainId: string,
): TransactionMeta => {
const time = parseInt(txMeta.timeStamp, 10) * 1000;
const {
to,
from,
gas,
gasPrice,
gasUsed,
hash,
contractAddress,
tokenDecimal,
tokenSymbol,
value,
} = txMeta;
return {
id: random({ msecs: time }),
isTransfer: true,
networkID: currentNetworkID,
chainId: currentChainId,
status: TransactionStatus.confirmed,
time,
transaction: {
chainId: 1,
from,
gas,
gasPrice,
gasUsed,
to,
value,
},
transactionHash: hash,
transferInformation: {
contractAddress,
decimals: Number(tokenDecimal),
symbol: tokenSymbol,
},
verifiedOnBlockchain: false,
};
};
/**
* EventEmitter instance used to listen to specific transactional events
*/
hub = new EventEmitter();
/**
* Name of this controller used during composition
*/
name = 'TransactionController';
/**
* Method used to sign transactions
*/
sign?: (
transaction: TypedTransaction,
from: string,
) => Promise<TypedTransaction>;
/**
* Creates a TransactionController instance.
*
* @param options - The controller options.
* @param options.getNetworkState - Gets the state of the network controller.
* @param options.onNetworkStateChange - Allows subscribing to network controller state changes.
* @param options.getProvider - Returns a provider for the current network.
* @param config - Initial options used to configure this controller.
* @param state - Initial state to set on this controller.
*/
constructor(
{
getNetworkState,
onNetworkStateChange,
getProvider,
}: {
getNetworkState: () => NetworkState;
onNetworkStateChange: (listener: (state: NetworkState) => void) => void;
getProvider: () => NetworkController['provider'];
},
config?: Partial<TransactionConfig>,
state?: Partial<TransactionState>,
) {
super(config, state);
this.defaultConfig = {
interval: 15000,
txHistoryLimit: 40,
};
this.defaultState = {
methodData: {},
transactions: [],
};
this.initialize();
const provider = getProvider();
this.getNetworkState = getNetworkState;
this.ethQuery = new EthQuery(provider);
this.registry = new MethodRegistry({ provider });
onNetworkStateChange(() => {
const newProvider = getProvider();
this.ethQuery = new EthQuery(newProvider);
this.registry = new MethodRegistry({ provider: newProvider });
});
this.poll();
}
/**
* Starts a new polling interval.
*
* @param interval - The polling interval used to fetch new transaction statuses.
*/
async poll(interval?: number): Promise<void> {
interval && this.configure({ interval }, false, false);
this.handle && clearTimeout(this.handle);
await safelyExecute(() => this.queryTransactionStatuses());
this.handle = setTimeout(() => {
this.poll(this.config.interval);
}, this.config.interval);
}
/**
* Handle new method data request.
*
* @param fourBytePrefix - The method prefix.
* @returns The method data object corresponding to the given signature prefix.
*/
async handleMethodData(fourBytePrefix: string): Promise<MethodData> {
const releaseLock = await this.mutex.acquire();
try {
const { methodData } = this.state;
const knownMethod = Object.keys(methodData).find(
(knownFourBytePrefix) => fourBytePrefix === knownFourBytePrefix,
);
if (knownMethod) {
return methodData[fourBytePrefix];
}
const registry = await this.registryLookup(fourBytePrefix);
this.update({
methodData: { ...methodData, ...{ [fourBytePrefix]: registry } },
});
return registry;
} finally {
releaseLock();
}
}
/**
* Add a new unapproved transaction to state. Parameters will be validated, a
* unique transaction id will be generated, and gas and gasPrice will be calculated
* if not provided. If A `<tx.id>:unapproved` hub event will be emitted once added.
*
* @param transaction - The transaction object to add.
* @param origin - The domain origin to append to the generated TransactionMeta.
* @param deviceConfirmedOn - An enum to indicate what device the transaction was confirmed to append to the generated TransactionMeta.
* @returns Object containing a promise resolving to the transaction hash if approved.
*/
async addTransaction(
transaction: Transaction,
origin?: string,
deviceConfirmedOn?: WalletDevice,
): Promise<Result> {
const { provider, network } = this.getNetworkState();
const { transactions } = this.state;
transaction = normalizeTransaction(transaction);
validateTransaction(transaction);
const transactionMeta: TransactionMeta = {
id: random(),
networkID: network,
chainId: provider.chainId,
origin,
status: TransactionStatus.unapproved as TransactionStatus.unapproved,
time: Date.now(),
transaction,
deviceConfirmedOn,
verifiedOnBlockchain: false,
};
try {
const { gas } = await this.estimateGas(transaction);
transaction.gas = gas;
} catch (error: any) {
this.failTransaction(transactionMeta, error);
return Promise.reject(error);
}
const result: Promise<string> = new Promise((resolve, reject) => {
this.hub.once(
`${transactionMeta.id}:finished`,
(meta: TransactionMeta) => {
switch (meta.status) {
case TransactionStatus.submitted:
return resolve(meta.transactionHash as string);
case TransactionStatus.rejected:
return reject(
ethErrors.provider.userRejectedRequest(
'User rejected the transaction',
),
);
case TransactionStatus.cancelled:
return reject(
ethErrors.rpc.internal('User cancelled the transaction'),
);
case TransactionStatus.failed:
return reject(ethErrors.rpc.internal(meta.error.message));
/* istanbul ignore next */
default:
return reject(
ethErrors.rpc.internal(
`MetaMask Tx Signature: Unknown problem: ${JSON.stringify(
meta,
)}`,
),
);
}
},
);
});
transactions.push(transactionMeta);
this.update({ transactions: this.trimTransactionsForState(transactions) });
this.hub.emit(`unapprovedTransaction`, transactionMeta);
return { result, transactionMeta };
}
prepareUnsignedEthTx(txParams: Record<string, unknown>): TypedTransaction {
return TransactionFactory.fromTxData(txParams, {
common: this.getCommonConfiguration(),
freeze: false,
});
}
/**
* `@ethereumjs/tx` uses `@ethereumjs/common` as a configuration tool for
* specifying which chain, network, hardfork and EIPs to support for
* a transaction. By referencing this configuration, and analyzing the fields
* specified in txParams, @ethereumjs/tx is able to determine which EIP-2718
* transaction type to use.
*
* @returns {Common} common configuration object
*/
getCommonConfiguration(): Common {
const {
network: networkId,
provider: { type: chain, chainId, nickname: name },
} = this.getNetworkState();
if (chain !== RPC) {
return new Common({ chain, hardfork: HARDFORK });
}
const customChainParams = {
name,
chainId: parseInt(chainId, undefined),
networkId: parseInt(networkId, undefined),
};
return Common.forCustomChain(MAINNET, customChainParams, HARDFORK);
}
/**
* Approves a transaction and updates it's status in state. If this is not a
* retry transaction, a nonce will be generated. The transaction is signed
* using the sign configuration property, then published to the blockchain.
* A `<tx.id>:finished` hub event is fired after success or failure.
*
* @param transactionID - The ID of the transaction to approve.
*/
async approveTransaction(transactionID: string) {
const { transactions } = this.state;
const releaseLock = await this.mutex.acquire();
const { provider } = this.getNetworkState();
const { chainId: currentChainId } = provider;
const index = transactions.findIndex(({ id }) => transactionID === id);
const transactionMeta = transactions[index];
const { nonce } = transactionMeta.transaction;
try {
const { from } = transactionMeta.transaction;
if (!this.sign) {
releaseLock();
this.failTransaction(
transactionMeta,
new Error('No sign method defined.'),
);
return;
} else if (!currentChainId) {
releaseLock();
this.failTransaction(transactionMeta, new Error('No chainId defined.'));
return;
}
const chainId = parseInt(currentChainId, undefined);
const { approved: status } = TransactionStatus;
const txNonce =
nonce ||
(await query(this.ethQuery, 'getTransactionCount', [from, 'pending']));
transactionMeta.status = status;
transactionMeta.transaction.nonce = txNonce;
transactionMeta.transaction.chainId = chainId;
const baseTxParams = {
...transactionMeta.transaction,
gasLimit: transactionMeta.transaction.gas,
chainId,
nonce: txNonce,
status,
};
const isEIP1559 = isEIP1559Transaction(transactionMeta.transaction);
const txParams = isEIP1559
? {
...baseTxParams,
maxFeePerGas: transactionMeta.transaction.maxFeePerGas,
maxPriorityFeePerGas:
transactionMeta.transaction.maxPriorityFeePerGas,
estimatedBaseFee: transactionMeta.transaction.estimatedBaseFee,
// specify type 2 if maxFeePerGas and maxPriorityFeePerGas are set
type: 2,
}
: baseTxParams;
// delete gasPrice if maxFeePerGas and maxPriorityFeePerGas are set
if (isEIP1559) {
delete txParams.gasPrice;
}
const unsignedEthTx = this.prepareUnsignedEthTx(txParams);
const signedTx = await this.sign(unsignedEthTx, from);
transactionMeta.status = TransactionStatus.signed;
this.updateTransaction(transactionMeta);
const rawTransaction = bufferToHex(signedTx.serialize());
transactionMeta.rawTransaction = rawTransaction;
this.updateTransaction(transactionMeta);
const transactionHash = await query(this.ethQuery, 'sendRawTransaction', [
rawTransaction,
]);
transactionMeta.transactionHash = transactionHash;
transactionMeta.status = TransactionStatus.submitted;
this.updateTransaction(transactionMeta);
this.hub.emit(`${transactionMeta.id}:finished`, transactionMeta);
} catch (error: any) {
this.failTransaction(transactionMeta, error);
} finally {
releaseLock();
}
}
/**
* Cancels a transaction based on its ID by setting its status to "rejected"
* and emitting a `<tx.id>:finished` hub event.
*
* @param transactionID - The ID of the transaction to cancel.
*/
cancelTransaction(transactionID: string) {
const transactionMeta = this.state.transactions.find(
({ id }) => id === transactionID,
);
if (!transactionMeta) {
return;
}
transactionMeta.status = TransactionStatus.rejected;
this.hub.emit(`${transactionMeta.id}:finished`, transactionMeta);
const transactions = this.state.transactions.filter(
({ id }) => id !== transactionID,
);
this.update({ transactions: this.trimTransactionsForState(transactions) });
}
/**
* Attempts to cancel a transaction based on its ID by setting its status to "rejected"
* and emitting a `<tx.id>:finished` hub event.
*
* @param transactionID - The ID of the transaction to cancel.
* @param gasValues - The gas values to use for the cancellation transation.
*/
async stopTransaction(
transactionID: string,
gasValues?: GasPriceValue | FeeMarketEIP1559Values,
) {
if (gasValues) {
validateGasValues(gasValues);
}
const transactionMeta = this.state.transactions.find(
({ id }) => id === transactionID,
);
if (!transactionMeta) {
return;
}
if (!this.sign) {
throw new Error('No sign method defined.');
}
// gasPrice (legacy non EIP1559)
const minGasPrice = getIncreasedPriceFromExisting(
transactionMeta.transaction.gasPrice,
CANCEL_RATE,
);
const gasPriceFromValues = isGasPriceValue(gasValues) && gasValues.gasPrice;
const newGasPrice =
(gasPriceFromValues &&
validateMinimumIncrease(gasPriceFromValues, minGasPrice)) ||
minGasPrice;
// maxFeePerGas (EIP1559)
const existingMaxFeePerGas = transactionMeta.transaction?.maxFeePerGas;
const minMaxFeePerGas = getIncreasedPriceFromExisting(
existingMaxFeePerGas,
CANCEL_RATE,
);
const maxFeePerGasValues =
isFeeMarketEIP1559Values(gasValues) && gasValues.maxFeePerGas;
const newMaxFeePerGas =
(maxFeePerGasValues &&
validateMinimumIncrease(maxFeePerGasValues, minMaxFeePerGas)) ||
(existingMaxFeePerGas && minMaxFeePerGas);
// maxPriorityFeePerGas (EIP1559)
const existingMaxPriorityFeePerGas =
transactionMeta.transaction?.maxPriorityFeePerGas;
const minMaxPriorityFeePerGas = getIncreasedPriceFromExisting(
existingMaxPriorityFeePerGas,
CANCEL_RATE,
);
const maxPriorityFeePerGasValues =
isFeeMarketEIP1559Values(gasValues) && gasValues.maxPriorityFeePerGas;
const newMaxPriorityFeePerGas =
(maxPriorityFeePerGasValues &&
validateMinimumIncrease(
maxPriorityFeePerGasValues,
minMaxPriorityFeePerGas,
)) ||
(existingMaxPriorityFeePerGas && minMaxPriorityFeePerGas);
const txParams =
newMaxFeePerGas && newMaxPriorityFeePerGas
? {
from: transactionMeta.transaction.from,
gasLimit: transactionMeta.transaction.gas,
maxFeePerGas: newMaxFeePerGas,
maxPriorityFeePerGas: newMaxPriorityFeePerGas,
type: 2,
nonce: transactionMeta.transaction.nonce,
to: transactionMeta.transaction.from,
value: '0x0',
}
: {
from: transactionMeta.transaction.from,
gasLimit: transactionMeta.transaction.gas,
gasPrice: newGasPrice,
nonce: transactionMeta.transaction.nonce,
to: transactionMeta.transaction.from,
value: '0x0',
};
const unsignedEthTx = this.prepareUnsignedEthTx(txParams);
const signedTx = await this.sign(
unsignedEthTx,
transactionMeta.transaction.from,
);
const rawTransaction = bufferToHex(signedTx.serialize());
await query(this.ethQuery, 'sendRawTransaction', [rawTransaction]);
transactionMeta.status = TransactionStatus.cancelled;
this.hub.emit(`${transactionMeta.id}:finished`, transactionMeta);
}
/**
* Attemps to speed up a transaction increasing transaction gasPrice by ten percent.
*
* @param transactionID - The ID of the transaction to speed up.
* @param gasValues - The gas values to use for the speed up transation.
*/
async speedUpTransaction(
transactionID: string,
gasValues?: GasPriceValue | FeeMarketEIP1559Values,
) {
if (gasValues) {
validateGasValues(gasValues);
}
const transactionMeta = this.state.transactions.find(
({ id }) => id === transactionID,
);
/* istanbul ignore next */
if (!transactionMeta) {
return;
}
/* istanbul ignore next */
if (!this.sign) {
throw new Error('No sign method defined.');
}
const { transactions } = this.state;
// gasPrice (legacy non EIP1559)
const minGasPrice = getIncreasedPriceFromExisting(
transactionMeta.transaction.gasPrice,
SPEED_UP_RATE,
);
const gasPriceFromValues = isGasPriceValue(gasValues) && gasValues.gasPrice;
const newGasPrice =
(gasPriceFromValues &&
validateMinimumIncrease(gasPriceFromValues, minGasPrice)) ||
minGasPrice;
// maxFeePerGas (EIP1559)
const existingMaxFeePerGas = transactionMeta.transaction?.maxFeePerGas;
const minMaxFeePerGas = getIncreasedPriceFromExisting(
existingMaxFeePerGas,
SPEED_UP_RATE,
);
const maxFeePerGasValues =
isFeeMarketEIP1559Values(gasValues) && gasValues.maxFeePerGas;
const newMaxFeePerGas =
(maxFeePerGasValues &&
validateMinimumIncrease(maxFeePerGasValues, minMaxFeePerGas)) ||
(existingMaxFeePerGas && minMaxFeePerGas);
// maxPriorityFeePerGas (EIP1559)
const existingMaxPriorityFeePerGas =
transactionMeta.transaction?.maxPriorityFeePerGas;
const minMaxPriorityFeePerGas = getIncreasedPriceFromExisting(
existingMaxPriorityFeePerGas,
SPEED_UP_RATE,
);
const maxPriorityFeePerGasValues =
isFeeMarketEIP1559Values(gasValues) && gasValues.maxPriorityFeePerGas;
const newMaxPriorityFeePerGas =
(maxPriorityFeePerGasValues &&
validateMinimumIncrease(
maxPriorityFeePerGasValues,
minMaxPriorityFeePerGas,
)) ||
(existingMaxPriorityFeePerGas && minMaxPriorityFeePerGas);
const txParams =
newMaxFeePerGas && newMaxPriorityFeePerGas
? {
...transactionMeta.transaction,
gasLimit: transactionMeta.transaction.gas,
maxFeePerGas: newMaxFeePerGas,
maxPriorityFeePerGas: newMaxPriorityFeePerGas,
type: 2,
}
: {
...transactionMeta.transaction,
gasLimit: transactionMeta.transaction.gas,
gasPrice: newGasPrice,
};
const unsignedEthTx = this.prepareUnsignedEthTx(txParams);
const signedTx = await this.sign(
unsignedEthTx,
transactionMeta.transaction.from,
);
const rawTransaction = bufferToHex(signedTx.serialize());
const transactionHash = await query(this.ethQuery, 'sendRawTransaction', [
rawTransaction,
]);
const baseTransactionMeta = {
...transactionMeta,
id: random(),
time: Date.now(),
transactionHash,
};
const newTransactionMeta =
newMaxFeePerGas && newMaxPriorityFeePerGas
? {
...baseTransactionMeta,
transaction: {
...transactionMeta.transaction,
maxFeePerGas: newMaxFeePerGas,
maxPriorityFeePerGas: newMaxPriorityFeePerGas,
},
}
: {
...baseTransactionMeta,
transaction: {
...transactionMeta.transaction,
gasPrice: newGasPrice,
},
};
transactions.push(newTransactionMeta);
this.update({ transactions: this.trimTransactionsForState(transactions) });
this.hub.emit(`${transactionMeta.id}:speedup`, newTransactionMeta);
}
/**
* Estimates required gas for a given transaction.
*
* @param transaction - The transaction to estimate gas for.
* @returns The gas and gas price.
*/
async estimateGas(transaction: Transaction) {
const estimatedTransaction = { ...transaction };
const {
gas,
gasPrice: providedGasPrice,
to,
value,
data,
} = estimatedTransaction;
const gasPrice =
typeof providedGasPrice === 'undefined'
? await query(this.ethQuery, 'gasPrice')
: providedGasPrice;
const { isCustomNetwork } = this.getNetworkState();
// 1. If gas is already defined on the transaction, use it
if (typeof gas !== 'undefined') {
return { gas, gasPrice };
}
const { gasLimit } = await query(this.ethQuery, 'getBlockByNumber', [
'latest',
false,
]);
// 2. If to is not defined or this is not a contract address, and there is no data use 0x5208 / 21000.
// If the newtwork is a custom network then bypass this check and fetch 'estimateGas'.
/* istanbul ignore next */
const code = to ? await query(this.ethQuery, 'getCode', [to]) : undefined;
/* istanbul ignore next */
if (
!isCustomNetwork &&
(!to || (to && !data && (!code || code === '0x')))
) {
return { gas: '0x5208', gasPrice };
}
// if data, should be hex string format
estimatedTransaction.data = !data
? data
: /* istanbul ignore next */ addHexPrefix(data);
// 3. If this is a contract address, safely estimate gas using RPC
estimatedTransaction.value =
typeof value === 'undefined' ? '0x0' : /* istanbul ignore next */ value;
const gasLimitBN = hexToBN(gasLimit);
estimatedTransaction.gas = BNToHex(fractionBN(gasLimitBN, 19, 20));
const gasHex = await query(this.ethQuery, 'estimateGas', [
estimatedTransaction,
]);
// 4. Pad estimated gas without exceeding the most recent block gasLimit. If the network is a
// a custom network then return the eth_estimateGas value.
const gasBN = hexToBN(gasHex);
const maxGasBN = gasLimitBN.muln(0.9);
const paddedGasBN = gasBN.muln(1.5);
/* istanbul ignore next */