@metamask-previews/transaction-controller 8.0.1-preview.d32a7cc
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +113 -0
- package/LICENSE +20 -0
- package/README.md +15 -0
- package/dist/EtherscanRemoteTransactionSource.d.ts +15 -0
- package/dist/EtherscanRemoteTransactionSource.d.ts.map +1 -0
- package/dist/EtherscanRemoteTransactionSource.js +99 -0
- package/dist/EtherscanRemoteTransactionSource.js.map +1 -0
- package/dist/IncomingTransactionHelper.d.ts +24 -0
- package/dist/IncomingTransactionHelper.d.ts.map +1 -0
- package/dist/IncomingTransactionHelper.js +188 -0
- package/dist/IncomingTransactionHelper.js.map +1 -0
- package/dist/TransactionController.d.ts +327 -0
- package/dist/TransactionController.d.ts.map +1 -0
- package/dist/TransactionController.js +887 -0
- package/dist/TransactionController.js.map +1 -0
- package/dist/constants.d.ts +119 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/constants.js +124 -0
- package/dist/constants.js.map +1 -0
- package/dist/etherscan.d.ts +65 -0
- package/dist/etherscan.d.ts.map +1 -0
- package/dist/etherscan.js +116 -0
- package/dist/etherscan.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +22 -0
- package/dist/index.js.map +1 -0
- package/dist/types.d.ts +189 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +29 -0
- package/dist/types.js.map +1 -0
- package/dist/utils.d.ts +61 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/utils.js +178 -0
- package/dist/utils.js.map +1 -0
- package/package.json +72 -0
|
@@ -0,0 +1,887 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
12
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
13
|
+
};
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.TransactionController = exports.SPEED_UP_RATE = exports.CANCEL_RATE = exports.HARDFORK = void 0;
|
|
16
|
+
const common_1 = require("@ethereumjs/common");
|
|
17
|
+
const tx_1 = require("@ethereumjs/tx");
|
|
18
|
+
const base_controller_1 = require("@metamask/base-controller");
|
|
19
|
+
const controller_utils_1 = require("@metamask/controller-utils");
|
|
20
|
+
const eth_query_1 = __importDefault(require("@metamask/eth-query"));
|
|
21
|
+
const async_mutex_1 = require("async-mutex");
|
|
22
|
+
const eth_method_registry_1 = __importDefault(require("eth-method-registry"));
|
|
23
|
+
const eth_rpc_errors_1 = require("eth-rpc-errors");
|
|
24
|
+
const ethereumjs_util_1 = require("ethereumjs-util");
|
|
25
|
+
const events_1 = require("events");
|
|
26
|
+
const nonce_tracker_1 = __importDefault(require("nonce-tracker"));
|
|
27
|
+
const uuid_1 = require("uuid");
|
|
28
|
+
const EtherscanRemoteTransactionSource_1 = require("./EtherscanRemoteTransactionSource");
|
|
29
|
+
const IncomingTransactionHelper_1 = require("./IncomingTransactionHelper");
|
|
30
|
+
const types_1 = require("./types");
|
|
31
|
+
const utils_1 = require("./utils");
|
|
32
|
+
exports.HARDFORK = common_1.Hardfork.London;
|
|
33
|
+
/**
|
|
34
|
+
* Multiplier used to determine a transaction's increased gas fee during cancellation
|
|
35
|
+
*/
|
|
36
|
+
exports.CANCEL_RATE = 1.5;
|
|
37
|
+
/**
|
|
38
|
+
* Multiplier used to determine a transaction's increased gas fee during speed up
|
|
39
|
+
*/
|
|
40
|
+
exports.SPEED_UP_RATE = 1.1;
|
|
41
|
+
/**
|
|
42
|
+
* The name of the {@link TransactionController}.
|
|
43
|
+
*/
|
|
44
|
+
const controllerName = 'TransactionController';
|
|
45
|
+
/**
|
|
46
|
+
* Controller responsible for submitting and managing transactions.
|
|
47
|
+
*/
|
|
48
|
+
class TransactionController extends base_controller_1.BaseController {
|
|
49
|
+
/**
|
|
50
|
+
* Creates a TransactionController instance.
|
|
51
|
+
*
|
|
52
|
+
* @param options - The controller options.
|
|
53
|
+
* @param options.blockTracker - The block tracker used to poll for new blocks data.
|
|
54
|
+
* @param options.getNetworkState - Gets the state of the network controller.
|
|
55
|
+
* @param options.getSelectedAddress - Gets the address of the currently selected account.
|
|
56
|
+
* @param options.incomingTransactions - Configuration options for incoming transaction support.
|
|
57
|
+
* @param options.incomingTransactions.apiKey - An optional API key to use when fetching remote transaction data.
|
|
58
|
+
* @param options.incomingTransactions.includeTokenTransfers - Whether or not to include ERC20 token transfers.
|
|
59
|
+
* @param options.incomingTransactions.isEnabled - Whether or not incoming transaction retrieval is enabled.
|
|
60
|
+
* @param options.incomingTransactions.updateTransactions - Whether or not to update local transactions using remote transaction data.
|
|
61
|
+
* @param options.messenger - The controller messenger.
|
|
62
|
+
* @param options.onNetworkStateChange - Allows subscribing to network controller state changes.
|
|
63
|
+
* @param options.provider - The provider used to create the underlying EthQuery instance.
|
|
64
|
+
* @param config - Initial options used to configure this controller.
|
|
65
|
+
* @param state - Initial state to set on this controller.
|
|
66
|
+
*/
|
|
67
|
+
constructor({ blockTracker, getNetworkState, getSelectedAddress, incomingTransactions = {}, messenger, onNetworkStateChange, provider, }, config, state) {
|
|
68
|
+
super(config, state);
|
|
69
|
+
this.mutex = new async_mutex_1.Mutex();
|
|
70
|
+
/**
|
|
71
|
+
* EventEmitter instance used to listen to specific transactional events
|
|
72
|
+
*/
|
|
73
|
+
this.hub = new events_1.EventEmitter();
|
|
74
|
+
/**
|
|
75
|
+
* Name of this controller used during composition
|
|
76
|
+
*/
|
|
77
|
+
this.name = 'TransactionController';
|
|
78
|
+
this.defaultConfig = {
|
|
79
|
+
interval: 15000,
|
|
80
|
+
txHistoryLimit: 40,
|
|
81
|
+
};
|
|
82
|
+
this.defaultState = {
|
|
83
|
+
methodData: {},
|
|
84
|
+
transactions: [],
|
|
85
|
+
lastFetchedBlockNumbers: {},
|
|
86
|
+
};
|
|
87
|
+
this.initialize();
|
|
88
|
+
this.provider = provider;
|
|
89
|
+
this.messagingSystem = messenger;
|
|
90
|
+
this.getNetworkState = getNetworkState;
|
|
91
|
+
this.ethQuery = new eth_query_1.default(provider);
|
|
92
|
+
this.registry = new eth_method_registry_1.default({ provider });
|
|
93
|
+
this.nonceTracker = new nonce_tracker_1.default({
|
|
94
|
+
provider,
|
|
95
|
+
blockTracker,
|
|
96
|
+
getPendingTransactions: (address) => (0, utils_1.getAndFormatTransactionsForNonceTracker)(address, types_1.TransactionStatus.submitted, this.state.transactions),
|
|
97
|
+
getConfirmedTransactions: (address) => (0, utils_1.getAndFormatTransactionsForNonceTracker)(address, types_1.TransactionStatus.confirmed, this.state.transactions),
|
|
98
|
+
});
|
|
99
|
+
this.incomingTransactionHelper = new IncomingTransactionHelper_1.IncomingTransactionHelper({
|
|
100
|
+
blockTracker,
|
|
101
|
+
getCurrentAccount: getSelectedAddress,
|
|
102
|
+
getNetworkState,
|
|
103
|
+
isEnabled: incomingTransactions.isEnabled,
|
|
104
|
+
remoteTransactionSource: new EtherscanRemoteTransactionSource_1.EtherscanRemoteTransactionSource({
|
|
105
|
+
apiKey: incomingTransactions.apiKey,
|
|
106
|
+
includeTokenTransfers: incomingTransactions.includeTokenTransfers,
|
|
107
|
+
}),
|
|
108
|
+
transactionLimit: this.config.txHistoryLimit,
|
|
109
|
+
updateTransactions: incomingTransactions.updateTransactions,
|
|
110
|
+
});
|
|
111
|
+
this.incomingTransactionHelper.hub.on('transactions', this.onIncomingTransactions.bind(this));
|
|
112
|
+
this.incomingTransactionHelper.hub.on('updatedLastFetchedBlockNumbers', this.onUpdatedLastFetchedBlockNumbers.bind(this));
|
|
113
|
+
onNetworkStateChange(() => {
|
|
114
|
+
this.ethQuery = new eth_query_1.default(this.provider);
|
|
115
|
+
this.registry = new eth_method_registry_1.default({ provider: this.provider });
|
|
116
|
+
});
|
|
117
|
+
this.poll();
|
|
118
|
+
}
|
|
119
|
+
failTransaction(transactionMeta, error) {
|
|
120
|
+
const newTransactionMeta = Object.assign(Object.assign({}, transactionMeta), { error, status: types_1.TransactionStatus.failed });
|
|
121
|
+
this.updateTransaction(newTransactionMeta);
|
|
122
|
+
this.hub.emit(`${transactionMeta.id}:finished`, newTransactionMeta);
|
|
123
|
+
}
|
|
124
|
+
registryLookup(fourBytePrefix) {
|
|
125
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
126
|
+
const registryMethod = yield this.registry.lookup(fourBytePrefix);
|
|
127
|
+
const parsedRegistryMethod = this.registry.parse(registryMethod);
|
|
128
|
+
return { registryMethod, parsedRegistryMethod };
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Starts a new polling interval.
|
|
133
|
+
*
|
|
134
|
+
* @param interval - The polling interval used to fetch new transaction statuses.
|
|
135
|
+
*/
|
|
136
|
+
poll(interval) {
|
|
137
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
138
|
+
interval && this.configure({ interval }, false, false);
|
|
139
|
+
this.handle && clearTimeout(this.handle);
|
|
140
|
+
yield (0, controller_utils_1.safelyExecute)(() => this.queryTransactionStatuses());
|
|
141
|
+
this.handle = setTimeout(() => {
|
|
142
|
+
this.poll(this.config.interval);
|
|
143
|
+
}, this.config.interval);
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Handle new method data request.
|
|
148
|
+
*
|
|
149
|
+
* @param fourBytePrefix - The method prefix.
|
|
150
|
+
* @returns The method data object corresponding to the given signature prefix.
|
|
151
|
+
*/
|
|
152
|
+
handleMethodData(fourBytePrefix) {
|
|
153
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
154
|
+
const releaseLock = yield this.mutex.acquire();
|
|
155
|
+
try {
|
|
156
|
+
const { methodData } = this.state;
|
|
157
|
+
const knownMethod = Object.keys(methodData).find((knownFourBytePrefix) => fourBytePrefix === knownFourBytePrefix);
|
|
158
|
+
if (knownMethod) {
|
|
159
|
+
return methodData[fourBytePrefix];
|
|
160
|
+
}
|
|
161
|
+
const registry = yield this.registryLookup(fourBytePrefix);
|
|
162
|
+
this.update({
|
|
163
|
+
methodData: Object.assign(Object.assign({}, methodData), { [fourBytePrefix]: registry }),
|
|
164
|
+
});
|
|
165
|
+
return registry;
|
|
166
|
+
}
|
|
167
|
+
finally {
|
|
168
|
+
releaseLock();
|
|
169
|
+
}
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Add a new unapproved transaction to state. Parameters will be validated, a
|
|
174
|
+
* unique transaction id will be generated, and gas and gasPrice will be calculated
|
|
175
|
+
* if not provided. If A `<tx.id>:unapproved` hub event will be emitted once added.
|
|
176
|
+
*
|
|
177
|
+
* @param transaction - The transaction object to add.
|
|
178
|
+
* @param opts - Additional options to control how the transaction is added.
|
|
179
|
+
* @param opts.deviceConfirmedOn - An enum to indicate what device confirmed the transaction.
|
|
180
|
+
* @param opts.origin - The origin of the transaction request, such as a dApp hostname.
|
|
181
|
+
* @param opts.requireApproval - Whether the transaction requires approval by the user, defaults to true unless explicitly disabled.
|
|
182
|
+
* @returns Object containing a promise resolving to the transaction hash if approved.
|
|
183
|
+
*/
|
|
184
|
+
addTransaction(transaction, { deviceConfirmedOn, origin, requireApproval, } = {}) {
|
|
185
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
186
|
+
const { chainId, networkId } = this.getChainAndNetworkId();
|
|
187
|
+
const { transactions } = this.state;
|
|
188
|
+
transaction = (0, utils_1.normalizeTransaction)(transaction);
|
|
189
|
+
(0, utils_1.validateTransaction)(transaction);
|
|
190
|
+
const transactionMeta = {
|
|
191
|
+
id: (0, uuid_1.v1)(),
|
|
192
|
+
networkID: networkId !== null && networkId !== void 0 ? networkId : undefined,
|
|
193
|
+
chainId,
|
|
194
|
+
origin,
|
|
195
|
+
status: types_1.TransactionStatus.unapproved,
|
|
196
|
+
time: Date.now(),
|
|
197
|
+
transaction,
|
|
198
|
+
deviceConfirmedOn,
|
|
199
|
+
verifiedOnBlockchain: false,
|
|
200
|
+
};
|
|
201
|
+
try {
|
|
202
|
+
const { gas, estimateGasError } = yield this.estimateGas(transaction);
|
|
203
|
+
transaction.gas = gas;
|
|
204
|
+
transaction.estimateGasError = estimateGasError;
|
|
205
|
+
}
|
|
206
|
+
catch (error) {
|
|
207
|
+
this.failTransaction(transactionMeta, error);
|
|
208
|
+
return Promise.reject(error);
|
|
209
|
+
}
|
|
210
|
+
transactions.push(transactionMeta);
|
|
211
|
+
this.update({ transactions: this.trimTransactionsForState(transactions) });
|
|
212
|
+
this.hub.emit(`unapprovedTransaction`, transactionMeta);
|
|
213
|
+
return {
|
|
214
|
+
result: this.processApproval(transactionMeta, {
|
|
215
|
+
requireApproval,
|
|
216
|
+
}),
|
|
217
|
+
transactionMeta,
|
|
218
|
+
};
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
startIncomingTransactionPolling() {
|
|
222
|
+
this.incomingTransactionHelper.start();
|
|
223
|
+
}
|
|
224
|
+
stopIncomingTransactionPolling() {
|
|
225
|
+
this.incomingTransactionHelper.stop();
|
|
226
|
+
}
|
|
227
|
+
updateIncomingTransactions() {
|
|
228
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
229
|
+
yield this.incomingTransactionHelper.update();
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Creates approvals for all unapproved transactions persisted.
|
|
234
|
+
*/
|
|
235
|
+
initApprovals() {
|
|
236
|
+
const { networkId, chainId } = this.getChainAndNetworkId();
|
|
237
|
+
const unapprovedTxs = this.state.transactions.filter((transaction) => transaction.status === types_1.TransactionStatus.unapproved &&
|
|
238
|
+
(0, utils_1.transactionMatchesNetwork)(transaction, chainId, networkId));
|
|
239
|
+
for (const txMeta of unapprovedTxs) {
|
|
240
|
+
this.processApproval(txMeta, {
|
|
241
|
+
shouldShowRequest: false,
|
|
242
|
+
}).catch((error) => {
|
|
243
|
+
/* istanbul ignore next */
|
|
244
|
+
console.error('Error during persisted transaction approval', error);
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Attempts to cancel a transaction based on its ID by setting its status to "rejected"
|
|
250
|
+
* and emitting a `<tx.id>:finished` hub event.
|
|
251
|
+
*
|
|
252
|
+
* @param transactionID - The ID of the transaction to cancel.
|
|
253
|
+
* @param gasValues - The gas values to use for the cancellation transaction.
|
|
254
|
+
*/
|
|
255
|
+
stopTransaction(transactionID, gasValues) {
|
|
256
|
+
var _a, _b;
|
|
257
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
258
|
+
if (gasValues) {
|
|
259
|
+
(0, utils_1.validateGasValues)(gasValues);
|
|
260
|
+
}
|
|
261
|
+
const transactionMeta = this.state.transactions.find(({ id }) => id === transactionID);
|
|
262
|
+
if (!transactionMeta) {
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
if (!this.sign) {
|
|
266
|
+
throw new Error('No sign method defined.');
|
|
267
|
+
}
|
|
268
|
+
// gasPrice (legacy non EIP1559)
|
|
269
|
+
const minGasPrice = (0, utils_1.getIncreasedPriceFromExisting)(transactionMeta.transaction.gasPrice, exports.CANCEL_RATE);
|
|
270
|
+
const gasPriceFromValues = (0, utils_1.isGasPriceValue)(gasValues) && gasValues.gasPrice;
|
|
271
|
+
const newGasPrice = (gasPriceFromValues &&
|
|
272
|
+
(0, utils_1.validateMinimumIncrease)(gasPriceFromValues, minGasPrice)) ||
|
|
273
|
+
minGasPrice;
|
|
274
|
+
// maxFeePerGas (EIP1559)
|
|
275
|
+
const existingMaxFeePerGas = (_a = transactionMeta.transaction) === null || _a === void 0 ? void 0 : _a.maxFeePerGas;
|
|
276
|
+
const minMaxFeePerGas = (0, utils_1.getIncreasedPriceFromExisting)(existingMaxFeePerGas, exports.CANCEL_RATE);
|
|
277
|
+
const maxFeePerGasValues = (0, utils_1.isFeeMarketEIP1559Values)(gasValues) && gasValues.maxFeePerGas;
|
|
278
|
+
const newMaxFeePerGas = (maxFeePerGasValues &&
|
|
279
|
+
(0, utils_1.validateMinimumIncrease)(maxFeePerGasValues, minMaxFeePerGas)) ||
|
|
280
|
+
(existingMaxFeePerGas && minMaxFeePerGas);
|
|
281
|
+
// maxPriorityFeePerGas (EIP1559)
|
|
282
|
+
const existingMaxPriorityFeePerGas = (_b = transactionMeta.transaction) === null || _b === void 0 ? void 0 : _b.maxPriorityFeePerGas;
|
|
283
|
+
const minMaxPriorityFeePerGas = (0, utils_1.getIncreasedPriceFromExisting)(existingMaxPriorityFeePerGas, exports.CANCEL_RATE);
|
|
284
|
+
const maxPriorityFeePerGasValues = (0, utils_1.isFeeMarketEIP1559Values)(gasValues) && gasValues.maxPriorityFeePerGas;
|
|
285
|
+
const newMaxPriorityFeePerGas = (maxPriorityFeePerGasValues &&
|
|
286
|
+
(0, utils_1.validateMinimumIncrease)(maxPriorityFeePerGasValues, minMaxPriorityFeePerGas)) ||
|
|
287
|
+
(existingMaxPriorityFeePerGas && minMaxPriorityFeePerGas);
|
|
288
|
+
const txParams = newMaxFeePerGas && newMaxPriorityFeePerGas
|
|
289
|
+
? {
|
|
290
|
+
from: transactionMeta.transaction.from,
|
|
291
|
+
gasLimit: transactionMeta.transaction.gas,
|
|
292
|
+
maxFeePerGas: newMaxFeePerGas,
|
|
293
|
+
maxPriorityFeePerGas: newMaxPriorityFeePerGas,
|
|
294
|
+
type: 2,
|
|
295
|
+
nonce: transactionMeta.transaction.nonce,
|
|
296
|
+
to: transactionMeta.transaction.from,
|
|
297
|
+
value: '0x0',
|
|
298
|
+
}
|
|
299
|
+
: {
|
|
300
|
+
from: transactionMeta.transaction.from,
|
|
301
|
+
gasLimit: transactionMeta.transaction.gas,
|
|
302
|
+
gasPrice: newGasPrice,
|
|
303
|
+
nonce: transactionMeta.transaction.nonce,
|
|
304
|
+
to: transactionMeta.transaction.from,
|
|
305
|
+
value: '0x0',
|
|
306
|
+
};
|
|
307
|
+
const unsignedEthTx = this.prepareUnsignedEthTx(txParams);
|
|
308
|
+
const signedTx = yield this.sign(unsignedEthTx, transactionMeta.transaction.from);
|
|
309
|
+
const rawTransaction = (0, ethereumjs_util_1.bufferToHex)(signedTx.serialize());
|
|
310
|
+
yield (0, controller_utils_1.query)(this.ethQuery, 'sendRawTransaction', [rawTransaction]);
|
|
311
|
+
transactionMeta.status = types_1.TransactionStatus.cancelled;
|
|
312
|
+
this.hub.emit(`${transactionMeta.id}:finished`, transactionMeta);
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Attempts to speed up a transaction increasing transaction gasPrice by ten percent.
|
|
317
|
+
*
|
|
318
|
+
* @param transactionID - The ID of the transaction to speed up.
|
|
319
|
+
* @param gasValues - The gas values to use for the speed up transation.
|
|
320
|
+
*/
|
|
321
|
+
speedUpTransaction(transactionID, gasValues) {
|
|
322
|
+
var _a, _b;
|
|
323
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
324
|
+
if (gasValues) {
|
|
325
|
+
(0, utils_1.validateGasValues)(gasValues);
|
|
326
|
+
}
|
|
327
|
+
const transactionMeta = this.state.transactions.find(({ id }) => id === transactionID);
|
|
328
|
+
/* istanbul ignore next */
|
|
329
|
+
if (!transactionMeta) {
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
/* istanbul ignore next */
|
|
333
|
+
if (!this.sign) {
|
|
334
|
+
throw new Error('No sign method defined.');
|
|
335
|
+
}
|
|
336
|
+
const { transactions } = this.state;
|
|
337
|
+
// gasPrice (legacy non EIP1559)
|
|
338
|
+
const minGasPrice = (0, utils_1.getIncreasedPriceFromExisting)(transactionMeta.transaction.gasPrice, exports.SPEED_UP_RATE);
|
|
339
|
+
const gasPriceFromValues = (0, utils_1.isGasPriceValue)(gasValues) && gasValues.gasPrice;
|
|
340
|
+
const newGasPrice = (gasPriceFromValues &&
|
|
341
|
+
(0, utils_1.validateMinimumIncrease)(gasPriceFromValues, minGasPrice)) ||
|
|
342
|
+
minGasPrice;
|
|
343
|
+
// maxFeePerGas (EIP1559)
|
|
344
|
+
const existingMaxFeePerGas = (_a = transactionMeta.transaction) === null || _a === void 0 ? void 0 : _a.maxFeePerGas;
|
|
345
|
+
const minMaxFeePerGas = (0, utils_1.getIncreasedPriceFromExisting)(existingMaxFeePerGas, exports.SPEED_UP_RATE);
|
|
346
|
+
const maxFeePerGasValues = (0, utils_1.isFeeMarketEIP1559Values)(gasValues) && gasValues.maxFeePerGas;
|
|
347
|
+
const newMaxFeePerGas = (maxFeePerGasValues &&
|
|
348
|
+
(0, utils_1.validateMinimumIncrease)(maxFeePerGasValues, minMaxFeePerGas)) ||
|
|
349
|
+
(existingMaxFeePerGas && minMaxFeePerGas);
|
|
350
|
+
// maxPriorityFeePerGas (EIP1559)
|
|
351
|
+
const existingMaxPriorityFeePerGas = (_b = transactionMeta.transaction) === null || _b === void 0 ? void 0 : _b.maxPriorityFeePerGas;
|
|
352
|
+
const minMaxPriorityFeePerGas = (0, utils_1.getIncreasedPriceFromExisting)(existingMaxPriorityFeePerGas, exports.SPEED_UP_RATE);
|
|
353
|
+
const maxPriorityFeePerGasValues = (0, utils_1.isFeeMarketEIP1559Values)(gasValues) && gasValues.maxPriorityFeePerGas;
|
|
354
|
+
const newMaxPriorityFeePerGas = (maxPriorityFeePerGasValues &&
|
|
355
|
+
(0, utils_1.validateMinimumIncrease)(maxPriorityFeePerGasValues, minMaxPriorityFeePerGas)) ||
|
|
356
|
+
(existingMaxPriorityFeePerGas && minMaxPriorityFeePerGas);
|
|
357
|
+
const txParams = newMaxFeePerGas && newMaxPriorityFeePerGas
|
|
358
|
+
? Object.assign(Object.assign({}, transactionMeta.transaction), { gasLimit: transactionMeta.transaction.gas, maxFeePerGas: newMaxFeePerGas, maxPriorityFeePerGas: newMaxPriorityFeePerGas, type: 2 }) : Object.assign(Object.assign({}, transactionMeta.transaction), { gasLimit: transactionMeta.transaction.gas, gasPrice: newGasPrice });
|
|
359
|
+
const unsignedEthTx = this.prepareUnsignedEthTx(txParams);
|
|
360
|
+
const signedTx = yield this.sign(unsignedEthTx, transactionMeta.transaction.from);
|
|
361
|
+
const rawTransaction = (0, ethereumjs_util_1.bufferToHex)(signedTx.serialize());
|
|
362
|
+
const transactionHash = yield (0, controller_utils_1.query)(this.ethQuery, 'sendRawTransaction', [
|
|
363
|
+
rawTransaction,
|
|
364
|
+
]);
|
|
365
|
+
const baseTransactionMeta = Object.assign(Object.assign({}, transactionMeta), { id: (0, uuid_1.v1)(), time: Date.now(), transactionHash });
|
|
366
|
+
const newTransactionMeta = newMaxFeePerGas && newMaxPriorityFeePerGas
|
|
367
|
+
? Object.assign(Object.assign({}, baseTransactionMeta), { transaction: Object.assign(Object.assign({}, transactionMeta.transaction), { maxFeePerGas: newMaxFeePerGas, maxPriorityFeePerGas: newMaxPriorityFeePerGas }) }) : Object.assign(Object.assign({}, baseTransactionMeta), { transaction: Object.assign(Object.assign({}, transactionMeta.transaction), { gasPrice: newGasPrice }) });
|
|
368
|
+
transactions.push(newTransactionMeta);
|
|
369
|
+
this.update({ transactions: this.trimTransactionsForState(transactions) });
|
|
370
|
+
this.hub.emit(`${transactionMeta.id}:speedup`, newTransactionMeta);
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* Estimates required gas for a given transaction.
|
|
375
|
+
*
|
|
376
|
+
* @param transaction - The transaction to estimate gas for.
|
|
377
|
+
* @returns The gas and gas price.
|
|
378
|
+
*/
|
|
379
|
+
estimateGas(transaction) {
|
|
380
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
381
|
+
const estimatedTransaction = Object.assign({}, transaction);
|
|
382
|
+
const { gas, gasPrice: providedGasPrice, to, value, data, } = estimatedTransaction;
|
|
383
|
+
const gasPrice = typeof providedGasPrice === 'undefined'
|
|
384
|
+
? yield (0, controller_utils_1.query)(this.ethQuery, 'gasPrice')
|
|
385
|
+
: providedGasPrice;
|
|
386
|
+
const { providerConfig } = this.getNetworkState();
|
|
387
|
+
const isCustomNetwork = providerConfig.type === controller_utils_1.NetworkType.rpc;
|
|
388
|
+
// 1. If gas is already defined on the transaction, use it
|
|
389
|
+
if (typeof gas !== 'undefined') {
|
|
390
|
+
return { gas, gasPrice };
|
|
391
|
+
}
|
|
392
|
+
const { gasLimit } = yield (0, controller_utils_1.query)(this.ethQuery, 'getBlockByNumber', [
|
|
393
|
+
'latest',
|
|
394
|
+
false,
|
|
395
|
+
]);
|
|
396
|
+
// 2. If to is not defined or this is not a contract address, and there is no data use 0x5208 / 21000.
|
|
397
|
+
// If the newtwork is a custom network then bypass this check and fetch 'estimateGas'.
|
|
398
|
+
/* istanbul ignore next */
|
|
399
|
+
const code = to ? yield (0, controller_utils_1.query)(this.ethQuery, 'getCode', [to]) : undefined;
|
|
400
|
+
/* istanbul ignore next */
|
|
401
|
+
if (!isCustomNetwork &&
|
|
402
|
+
(!to || (to && !data && (!code || code === '0x')))) {
|
|
403
|
+
return { gas: '0x5208', gasPrice };
|
|
404
|
+
}
|
|
405
|
+
// if data, should be hex string format
|
|
406
|
+
estimatedTransaction.data = !data
|
|
407
|
+
? data
|
|
408
|
+
: /* istanbul ignore next */ (0, ethereumjs_util_1.addHexPrefix)(data);
|
|
409
|
+
// 3. If this is a contract address, safely estimate gas using RPC
|
|
410
|
+
estimatedTransaction.value =
|
|
411
|
+
typeof value === 'undefined' ? '0x0' : /* istanbul ignore next */ value;
|
|
412
|
+
const gasLimitBN = (0, controller_utils_1.hexToBN)(gasLimit);
|
|
413
|
+
estimatedTransaction.gas = (0, controller_utils_1.BNToHex)((0, controller_utils_1.fractionBN)(gasLimitBN, 19, 20));
|
|
414
|
+
let gasHex;
|
|
415
|
+
let estimateGasError;
|
|
416
|
+
try {
|
|
417
|
+
gasHex = yield (0, controller_utils_1.query)(this.ethQuery, 'estimateGas', [
|
|
418
|
+
estimatedTransaction,
|
|
419
|
+
]);
|
|
420
|
+
}
|
|
421
|
+
catch (error) {
|
|
422
|
+
estimateGasError = utils_1.ESTIMATE_GAS_ERROR;
|
|
423
|
+
}
|
|
424
|
+
// 4. Pad estimated gas without exceeding the most recent block gasLimit. If the network is a
|
|
425
|
+
// a custom network then return the eth_estimateGas value.
|
|
426
|
+
const gasBN = (0, controller_utils_1.hexToBN)(gasHex);
|
|
427
|
+
const maxGasBN = gasLimitBN.muln(0.9);
|
|
428
|
+
const paddedGasBN = gasBN.muln(1.5);
|
|
429
|
+
/* istanbul ignore next */
|
|
430
|
+
if (gasBN.gt(maxGasBN) || isCustomNetwork) {
|
|
431
|
+
return { gas: (0, ethereumjs_util_1.addHexPrefix)(gasHex), gasPrice, estimateGasError };
|
|
432
|
+
}
|
|
433
|
+
/* istanbul ignore next */
|
|
434
|
+
if (paddedGasBN.lt(maxGasBN)) {
|
|
435
|
+
return {
|
|
436
|
+
gas: (0, ethereumjs_util_1.addHexPrefix)((0, controller_utils_1.BNToHex)(paddedGasBN)),
|
|
437
|
+
gasPrice,
|
|
438
|
+
estimateGasError,
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
return { gas: (0, ethereumjs_util_1.addHexPrefix)((0, controller_utils_1.BNToHex)(maxGasBN)), gasPrice, estimateGasError };
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
/**
|
|
445
|
+
* Check the status of submitted transactions on the network to determine whether they have
|
|
446
|
+
* been included in a block. Any that have been included in a block are marked as confirmed.
|
|
447
|
+
*/
|
|
448
|
+
queryTransactionStatuses() {
|
|
449
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
450
|
+
const { transactions } = this.state;
|
|
451
|
+
const { chainId: currentChainId, networkId: currentNetworkID } = this.getChainAndNetworkId();
|
|
452
|
+
let gotUpdates = false;
|
|
453
|
+
yield (0, controller_utils_1.safelyExecute)(() => Promise.all(transactions.map((meta, index) => __awaiter(this, void 0, void 0, function* () {
|
|
454
|
+
// Using fallback to networkID only when there is no chainId present.
|
|
455
|
+
// Should be removed when networkID is completely removed.
|
|
456
|
+
const txBelongsToCurrentChain = meta.chainId === currentChainId ||
|
|
457
|
+
(!meta.chainId && meta.networkID === currentNetworkID);
|
|
458
|
+
if (!meta.verifiedOnBlockchain && txBelongsToCurrentChain) {
|
|
459
|
+
const [reconciledTx, updateRequired] = yield this.blockchainTransactionStateReconciler(meta);
|
|
460
|
+
if (updateRequired) {
|
|
461
|
+
transactions[index] = reconciledTx;
|
|
462
|
+
gotUpdates = updateRequired;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
}))));
|
|
466
|
+
/* istanbul ignore else */
|
|
467
|
+
if (gotUpdates) {
|
|
468
|
+
this.update({
|
|
469
|
+
transactions: this.trimTransactionsForState(transactions),
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
});
|
|
473
|
+
}
|
|
474
|
+
/**
|
|
475
|
+
* Updates an existing transaction in state.
|
|
476
|
+
*
|
|
477
|
+
* @param transactionMeta - The new transaction to store in state.
|
|
478
|
+
*/
|
|
479
|
+
updateTransaction(transactionMeta) {
|
|
480
|
+
const { transactions } = this.state;
|
|
481
|
+
transactionMeta.transaction = (0, utils_1.normalizeTransaction)(transactionMeta.transaction);
|
|
482
|
+
(0, utils_1.validateTransaction)(transactionMeta.transaction);
|
|
483
|
+
const index = transactions.findIndex(({ id }) => transactionMeta.id === id);
|
|
484
|
+
transactions[index] = transactionMeta;
|
|
485
|
+
this.update({ transactions: this.trimTransactionsForState(transactions) });
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* Removes all transactions from state, optionally based on the current network.
|
|
489
|
+
*
|
|
490
|
+
* @param ignoreNetwork - Determines whether to wipe all transactions, or just those on the
|
|
491
|
+
* current network. If `true`, all transactions are wiped.
|
|
492
|
+
* @param address - If specified, only transactions originating from this address will be
|
|
493
|
+
* wiped on current network.
|
|
494
|
+
*/
|
|
495
|
+
wipeTransactions(ignoreNetwork, address) {
|
|
496
|
+
/* istanbul ignore next */
|
|
497
|
+
if (ignoreNetwork && !address) {
|
|
498
|
+
this.update({ transactions: [] });
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
const { chainId: currentChainId, networkId: currentNetworkID } = this.getChainAndNetworkId();
|
|
502
|
+
const newTransactions = this.state.transactions.filter(({ networkID, chainId, transaction }) => {
|
|
503
|
+
var _a;
|
|
504
|
+
// Using fallback to networkID only when there is no chainId present. Should be removed when networkID is completely removed.
|
|
505
|
+
const isMatchingNetwork = ignoreNetwork ||
|
|
506
|
+
chainId === currentChainId ||
|
|
507
|
+
(!chainId && networkID === currentNetworkID);
|
|
508
|
+
if (!isMatchingNetwork) {
|
|
509
|
+
return true;
|
|
510
|
+
}
|
|
511
|
+
const isMatchingAddress = !address || ((_a = transaction.from) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === address.toLowerCase();
|
|
512
|
+
return !isMatchingAddress;
|
|
513
|
+
});
|
|
514
|
+
this.update({
|
|
515
|
+
transactions: this.trimTransactionsForState(newTransactions),
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
startIncomingTransactionProcessing() {
|
|
519
|
+
this.incomingTransactionHelper.start();
|
|
520
|
+
}
|
|
521
|
+
stopIncomingTransactionProcessing() {
|
|
522
|
+
this.incomingTransactionHelper.stop();
|
|
523
|
+
}
|
|
524
|
+
processApproval(transactionMeta, { requireApproval, shouldShowRequest = true, }) {
|
|
525
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
526
|
+
const transactionId = transactionMeta.id;
|
|
527
|
+
let resultCallbacks;
|
|
528
|
+
try {
|
|
529
|
+
if (requireApproval !== false) {
|
|
530
|
+
const acceptResult = yield this.requestApproval(transactionMeta, {
|
|
531
|
+
shouldShowRequest,
|
|
532
|
+
});
|
|
533
|
+
resultCallbacks = acceptResult.resultCallbacks;
|
|
534
|
+
}
|
|
535
|
+
const { meta, isCompleted } = this.isTransactionCompleted(transactionId);
|
|
536
|
+
if (meta && !isCompleted) {
|
|
537
|
+
yield this.approveTransaction(transactionId);
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
catch (error) {
|
|
541
|
+
const { meta, isCompleted } = this.isTransactionCompleted(transactionId);
|
|
542
|
+
if (meta && !isCompleted) {
|
|
543
|
+
if (error.code === eth_rpc_errors_1.errorCodes.provider.userRejectedRequest) {
|
|
544
|
+
this.cancelTransaction(transactionId);
|
|
545
|
+
throw eth_rpc_errors_1.ethErrors.provider.userRejectedRequest('User rejected the transaction');
|
|
546
|
+
}
|
|
547
|
+
else {
|
|
548
|
+
this.failTransaction(meta, error);
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
const finalMeta = this.getTransaction(transactionId);
|
|
553
|
+
switch (finalMeta === null || finalMeta === void 0 ? void 0 : finalMeta.status) {
|
|
554
|
+
case types_1.TransactionStatus.failed:
|
|
555
|
+
resultCallbacks === null || resultCallbacks === void 0 ? void 0 : resultCallbacks.error(finalMeta.error);
|
|
556
|
+
throw eth_rpc_errors_1.ethErrors.rpc.internal(finalMeta.error.message);
|
|
557
|
+
case types_1.TransactionStatus.cancelled:
|
|
558
|
+
const cancelError = eth_rpc_errors_1.ethErrors.rpc.internal('User cancelled the transaction');
|
|
559
|
+
resultCallbacks === null || resultCallbacks === void 0 ? void 0 : resultCallbacks.error(cancelError);
|
|
560
|
+
throw cancelError;
|
|
561
|
+
case types_1.TransactionStatus.submitted:
|
|
562
|
+
resultCallbacks === null || resultCallbacks === void 0 ? void 0 : resultCallbacks.success();
|
|
563
|
+
return finalMeta.transactionHash;
|
|
564
|
+
default:
|
|
565
|
+
const internalError = eth_rpc_errors_1.ethErrors.rpc.internal(`MetaMask Tx Signature: Unknown problem: ${JSON.stringify(finalMeta || transactionId)}`);
|
|
566
|
+
resultCallbacks === null || resultCallbacks === void 0 ? void 0 : resultCallbacks.error(internalError);
|
|
567
|
+
throw internalError;
|
|
568
|
+
}
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* Approves a transaction and updates it's status in state. If this is not a
|
|
573
|
+
* retry transaction, a nonce will be generated. The transaction is signed
|
|
574
|
+
* using the sign configuration property, then published to the blockchain.
|
|
575
|
+
* A `<tx.id>:finished` hub event is fired after success or failure.
|
|
576
|
+
*
|
|
577
|
+
* @param transactionID - The ID of the transaction to approve.
|
|
578
|
+
*/
|
|
579
|
+
approveTransaction(transactionID) {
|
|
580
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
581
|
+
const { transactions } = this.state;
|
|
582
|
+
const releaseLock = yield this.mutex.acquire();
|
|
583
|
+
const { chainId } = this.getChainAndNetworkId();
|
|
584
|
+
const index = transactions.findIndex(({ id }) => transactionID === id);
|
|
585
|
+
const transactionMeta = transactions[index];
|
|
586
|
+
const { transaction: { nonce, from }, } = transactionMeta;
|
|
587
|
+
let nonceLock;
|
|
588
|
+
try {
|
|
589
|
+
if (!this.sign) {
|
|
590
|
+
releaseLock();
|
|
591
|
+
this.failTransaction(transactionMeta, new Error('No sign method defined.'));
|
|
592
|
+
return;
|
|
593
|
+
}
|
|
594
|
+
else if (!chainId) {
|
|
595
|
+
releaseLock();
|
|
596
|
+
this.failTransaction(transactionMeta, new Error('No chainId defined.'));
|
|
597
|
+
return;
|
|
598
|
+
}
|
|
599
|
+
const { approved: status } = types_1.TransactionStatus;
|
|
600
|
+
let nonceToUse = nonce;
|
|
601
|
+
// if a nonce already exists on the transactionMeta it means this is a speedup or cancel transaction
|
|
602
|
+
// so we want to reuse that nonce and hope that it beats the previous attempt to chain. Otherwise use a new locked nonce
|
|
603
|
+
if (!nonceToUse) {
|
|
604
|
+
nonceLock = yield this.nonceTracker.getNonceLock(from);
|
|
605
|
+
nonceToUse = (0, ethereumjs_util_1.addHexPrefix)(nonceLock.nextNonce.toString(16));
|
|
606
|
+
}
|
|
607
|
+
transactionMeta.status = status;
|
|
608
|
+
transactionMeta.transaction.nonce = nonceToUse;
|
|
609
|
+
transactionMeta.transaction.chainId = chainId;
|
|
610
|
+
const baseTxParams = Object.assign(Object.assign({}, transactionMeta.transaction), { gasLimit: transactionMeta.transaction.gas });
|
|
611
|
+
const isEIP1559 = (0, utils_1.isEIP1559Transaction)(transactionMeta.transaction);
|
|
612
|
+
const txParams = isEIP1559
|
|
613
|
+
? Object.assign(Object.assign({}, baseTxParams), { maxFeePerGas: transactionMeta.transaction.maxFeePerGas, maxPriorityFeePerGas: transactionMeta.transaction.maxPriorityFeePerGas, estimatedBaseFee: transactionMeta.transaction.estimatedBaseFee,
|
|
614
|
+
// specify type 2 if maxFeePerGas and maxPriorityFeePerGas are set
|
|
615
|
+
type: 2 }) : baseTxParams;
|
|
616
|
+
// delete gasPrice if maxFeePerGas and maxPriorityFeePerGas are set
|
|
617
|
+
if (isEIP1559) {
|
|
618
|
+
delete txParams.gasPrice;
|
|
619
|
+
}
|
|
620
|
+
const unsignedEthTx = this.prepareUnsignedEthTx(txParams);
|
|
621
|
+
const signedTx = yield this.sign(unsignedEthTx, from);
|
|
622
|
+
transactionMeta.status = types_1.TransactionStatus.signed;
|
|
623
|
+
this.updateTransaction(transactionMeta);
|
|
624
|
+
const rawTransaction = (0, ethereumjs_util_1.bufferToHex)(signedTx.serialize());
|
|
625
|
+
transactionMeta.rawTransaction = rawTransaction;
|
|
626
|
+
this.updateTransaction(transactionMeta);
|
|
627
|
+
const transactionHash = yield (0, controller_utils_1.query)(this.ethQuery, 'sendRawTransaction', [
|
|
628
|
+
rawTransaction,
|
|
629
|
+
]);
|
|
630
|
+
transactionMeta.transactionHash = transactionHash;
|
|
631
|
+
transactionMeta.status = types_1.TransactionStatus.submitted;
|
|
632
|
+
this.updateTransaction(transactionMeta);
|
|
633
|
+
this.hub.emit(`${transactionMeta.id}:finished`, transactionMeta);
|
|
634
|
+
}
|
|
635
|
+
catch (error) {
|
|
636
|
+
this.failTransaction(transactionMeta, error);
|
|
637
|
+
}
|
|
638
|
+
finally {
|
|
639
|
+
// must set transaction to submitted/failed before releasing lock
|
|
640
|
+
if (nonceLock) {
|
|
641
|
+
nonceLock.releaseLock();
|
|
642
|
+
}
|
|
643
|
+
releaseLock();
|
|
644
|
+
}
|
|
645
|
+
});
|
|
646
|
+
}
|
|
647
|
+
/**
|
|
648
|
+
* Cancels a transaction based on its ID by setting its status to "rejected"
|
|
649
|
+
* and emitting a `<tx.id>:finished` hub event.
|
|
650
|
+
*
|
|
651
|
+
* @param transactionID - The ID of the transaction to cancel.
|
|
652
|
+
*/
|
|
653
|
+
cancelTransaction(transactionID) {
|
|
654
|
+
const transactionMeta = this.state.transactions.find(({ id }) => id === transactionID);
|
|
655
|
+
if (!transactionMeta) {
|
|
656
|
+
return;
|
|
657
|
+
}
|
|
658
|
+
transactionMeta.status = types_1.TransactionStatus.rejected;
|
|
659
|
+
this.hub.emit(`${transactionMeta.id}:finished`, transactionMeta);
|
|
660
|
+
const transactions = this.state.transactions.filter(({ id }) => id !== transactionID);
|
|
661
|
+
this.update({ transactions: this.trimTransactionsForState(transactions) });
|
|
662
|
+
}
|
|
663
|
+
/**
|
|
664
|
+
* Trim the amount of transactions that are set on the state. Checks
|
|
665
|
+
* if the length of the tx history is longer then desired persistence
|
|
666
|
+
* limit and then if it is removes the oldest confirmed or rejected tx.
|
|
667
|
+
* Pending or unapproved transactions will not be removed by this
|
|
668
|
+
* operation. For safety of presenting a fully functional transaction UI
|
|
669
|
+
* representation, this function will not break apart transactions with the
|
|
670
|
+
* same nonce, created on the same day, per network. Not accounting for transactions of the same
|
|
671
|
+
* nonce, same day and network combo can result in confusing or broken experiences
|
|
672
|
+
* in the UI. The transactions are then updated using the BaseController update.
|
|
673
|
+
*
|
|
674
|
+
* @param transactions - The transactions to be applied to the state.
|
|
675
|
+
* @returns The trimmed list of transactions.
|
|
676
|
+
*/
|
|
677
|
+
trimTransactionsForState(transactions) {
|
|
678
|
+
const nonceNetworkSet = new Set();
|
|
679
|
+
const txsToKeep = transactions.reverse().filter((tx) => {
|
|
680
|
+
const { chainId, networkID, status, transaction, time } = tx;
|
|
681
|
+
if (transaction) {
|
|
682
|
+
const key = `${transaction.nonce}-${chainId ? (0, controller_utils_1.convertHexToDecimal)(chainId) : networkID}-${new Date(time).toDateString()}`;
|
|
683
|
+
if (nonceNetworkSet.has(key)) {
|
|
684
|
+
return true;
|
|
685
|
+
}
|
|
686
|
+
else if (nonceNetworkSet.size < this.config.txHistoryLimit ||
|
|
687
|
+
!this.isFinalState(status)) {
|
|
688
|
+
nonceNetworkSet.add(key);
|
|
689
|
+
return true;
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
return false;
|
|
693
|
+
});
|
|
694
|
+
txsToKeep.reverse();
|
|
695
|
+
return txsToKeep;
|
|
696
|
+
}
|
|
697
|
+
/**
|
|
698
|
+
* Determines if the transaction is in a final state.
|
|
699
|
+
*
|
|
700
|
+
* @param status - The transaction status.
|
|
701
|
+
* @returns Whether the transaction is in a final state.
|
|
702
|
+
*/
|
|
703
|
+
isFinalState(status) {
|
|
704
|
+
return (status === types_1.TransactionStatus.rejected ||
|
|
705
|
+
status === types_1.TransactionStatus.confirmed ||
|
|
706
|
+
status === types_1.TransactionStatus.failed ||
|
|
707
|
+
status === types_1.TransactionStatus.cancelled);
|
|
708
|
+
}
|
|
709
|
+
/**
|
|
710
|
+
* Whether the transaction has at least completed all local processing.
|
|
711
|
+
*
|
|
712
|
+
* @param status - The transaction status.
|
|
713
|
+
* @returns Whether the transaction is in a final state.
|
|
714
|
+
*/
|
|
715
|
+
isLocalFinalState(status) {
|
|
716
|
+
return [
|
|
717
|
+
types_1.TransactionStatus.cancelled,
|
|
718
|
+
types_1.TransactionStatus.confirmed,
|
|
719
|
+
types_1.TransactionStatus.failed,
|
|
720
|
+
types_1.TransactionStatus.rejected,
|
|
721
|
+
types_1.TransactionStatus.submitted,
|
|
722
|
+
].includes(status);
|
|
723
|
+
}
|
|
724
|
+
/**
|
|
725
|
+
* Method to verify the state of a transaction using the Blockchain as a source of truth.
|
|
726
|
+
*
|
|
727
|
+
* @param meta - The local transaction to verify on the blockchain.
|
|
728
|
+
* @returns A tuple containing the updated transaction, and whether or not an update was required.
|
|
729
|
+
*/
|
|
730
|
+
blockchainTransactionStateReconciler(meta) {
|
|
731
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
732
|
+
const { status, transactionHash } = meta;
|
|
733
|
+
switch (status) {
|
|
734
|
+
case types_1.TransactionStatus.confirmed:
|
|
735
|
+
const txReceipt = yield (0, controller_utils_1.query)(this.ethQuery, 'getTransactionReceipt', [
|
|
736
|
+
transactionHash,
|
|
737
|
+
]);
|
|
738
|
+
if (!txReceipt) {
|
|
739
|
+
return [meta, false];
|
|
740
|
+
}
|
|
741
|
+
const txBlock = yield (0, controller_utils_1.query)(this.ethQuery, 'getBlockByHash', [
|
|
742
|
+
txReceipt.blockHash,
|
|
743
|
+
]);
|
|
744
|
+
meta.verifiedOnBlockchain = true;
|
|
745
|
+
meta.transaction.gasUsed = txReceipt.gasUsed;
|
|
746
|
+
meta.txReceipt = txReceipt;
|
|
747
|
+
meta.baseFeePerGas = txBlock === null || txBlock === void 0 ? void 0 : txBlock.baseFeePerGas;
|
|
748
|
+
// According to the Web3 docs:
|
|
749
|
+
// TRUE if the transaction was successful, FALSE if the EVM reverted the transaction.
|
|
750
|
+
if (Number(txReceipt.status) === 0) {
|
|
751
|
+
const error = new Error('Transaction failed. The transaction was reversed');
|
|
752
|
+
this.failTransaction(meta, error);
|
|
753
|
+
return [meta, false];
|
|
754
|
+
}
|
|
755
|
+
return [meta, true];
|
|
756
|
+
case types_1.TransactionStatus.submitted:
|
|
757
|
+
const txObj = yield (0, controller_utils_1.query)(this.ethQuery, 'getTransactionByHash', [
|
|
758
|
+
transactionHash,
|
|
759
|
+
]);
|
|
760
|
+
if (!txObj) {
|
|
761
|
+
const receiptShowsFailedStatus = yield this.checkTxReceiptStatusIsFailed(transactionHash);
|
|
762
|
+
// Case the txObj is evaluated as false, a second check will
|
|
763
|
+
// determine if the tx failed or it is pending or confirmed
|
|
764
|
+
if (receiptShowsFailedStatus) {
|
|
765
|
+
const error = new Error('Transaction failed. The transaction was dropped or replaced by a new one');
|
|
766
|
+
this.failTransaction(meta, error);
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
/* istanbul ignore next */
|
|
770
|
+
if (txObj === null || txObj === void 0 ? void 0 : txObj.blockNumber) {
|
|
771
|
+
meta.status = types_1.TransactionStatus.confirmed;
|
|
772
|
+
this.hub.emit(`${meta.id}:confirmed`, meta);
|
|
773
|
+
return [meta, true];
|
|
774
|
+
}
|
|
775
|
+
return [meta, false];
|
|
776
|
+
default:
|
|
777
|
+
return [meta, false];
|
|
778
|
+
}
|
|
779
|
+
});
|
|
780
|
+
}
|
|
781
|
+
/**
|
|
782
|
+
* Method to check if a tx has failed according to their receipt
|
|
783
|
+
* According to the Web3 docs:
|
|
784
|
+
* TRUE if the transaction was successful, FALSE if the EVM reverted the transaction.
|
|
785
|
+
* The receipt is not available for pending transactions and returns null.
|
|
786
|
+
*
|
|
787
|
+
* @param txHash - The transaction hash.
|
|
788
|
+
* @returns Whether the transaction has failed.
|
|
789
|
+
*/
|
|
790
|
+
checkTxReceiptStatusIsFailed(txHash) {
|
|
791
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
792
|
+
const txReceipt = yield (0, controller_utils_1.query)(this.ethQuery, 'getTransactionReceipt', [
|
|
793
|
+
txHash,
|
|
794
|
+
]);
|
|
795
|
+
if (!txReceipt) {
|
|
796
|
+
// Transaction is pending
|
|
797
|
+
return false;
|
|
798
|
+
}
|
|
799
|
+
return Number(txReceipt.status) === 0;
|
|
800
|
+
});
|
|
801
|
+
}
|
|
802
|
+
requestApproval(txMeta, { shouldShowRequest }) {
|
|
803
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
804
|
+
const id = this.getApprovalId(txMeta);
|
|
805
|
+
const { origin } = txMeta;
|
|
806
|
+
const type = controller_utils_1.ApprovalType.Transaction;
|
|
807
|
+
const requestData = { txId: txMeta.id };
|
|
808
|
+
return (yield this.messagingSystem.call('ApprovalController:addRequest', {
|
|
809
|
+
id,
|
|
810
|
+
origin: origin || controller_utils_1.ORIGIN_METAMASK,
|
|
811
|
+
type,
|
|
812
|
+
requestData,
|
|
813
|
+
expectsResult: true,
|
|
814
|
+
}, shouldShowRequest));
|
|
815
|
+
});
|
|
816
|
+
}
|
|
817
|
+
getTransaction(transactionID) {
|
|
818
|
+
const { transactions } = this.state;
|
|
819
|
+
return transactions.find(({ id }) => id === transactionID);
|
|
820
|
+
}
|
|
821
|
+
getApprovalId(txMeta) {
|
|
822
|
+
return String(txMeta.id);
|
|
823
|
+
}
|
|
824
|
+
isTransactionCompleted(transactionid) {
|
|
825
|
+
const transaction = this.getTransaction(transactionid);
|
|
826
|
+
if (!transaction) {
|
|
827
|
+
return { meta: undefined, isCompleted: false };
|
|
828
|
+
}
|
|
829
|
+
const isCompleted = this.isLocalFinalState(transaction.status);
|
|
830
|
+
return { meta: transaction, isCompleted };
|
|
831
|
+
}
|
|
832
|
+
getChainAndNetworkId() {
|
|
833
|
+
const { networkId, providerConfig } = this.getNetworkState();
|
|
834
|
+
const chainId = providerConfig === null || providerConfig === void 0 ? void 0 : providerConfig.chainId;
|
|
835
|
+
return { networkId, chainId };
|
|
836
|
+
}
|
|
837
|
+
prepareUnsignedEthTx(txParams) {
|
|
838
|
+
return tx_1.TransactionFactory.fromTxData(txParams, {
|
|
839
|
+
common: this.getCommonConfiguration(),
|
|
840
|
+
freeze: false,
|
|
841
|
+
});
|
|
842
|
+
}
|
|
843
|
+
/**
|
|
844
|
+
* `@ethereumjs/tx` uses `@ethereumjs/common` as a configuration tool for
|
|
845
|
+
* specifying which chain, network, hardfork and EIPs to support for
|
|
846
|
+
* a transaction. By referencing this configuration, and analyzing the fields
|
|
847
|
+
* specified in txParams, @ethereumjs/tx is able to determine which EIP-2718
|
|
848
|
+
* transaction type to use.
|
|
849
|
+
*
|
|
850
|
+
* @returns common configuration object
|
|
851
|
+
*/
|
|
852
|
+
getCommonConfiguration() {
|
|
853
|
+
const { networkId, providerConfig: { type: chain, chainId, nickname: name }, } = this.getNetworkState();
|
|
854
|
+
if (chain !== controller_utils_1.RPC &&
|
|
855
|
+
chain !== controller_utils_1.NetworkType['linea-goerli'] &&
|
|
856
|
+
chain !== controller_utils_1.NetworkType['linea-mainnet']) {
|
|
857
|
+
return new common_1.Common({ chain, hardfork: exports.HARDFORK });
|
|
858
|
+
}
|
|
859
|
+
const customChainParams = {
|
|
860
|
+
name,
|
|
861
|
+
chainId: parseInt(chainId, 16),
|
|
862
|
+
networkId: networkId === null ? NaN : parseInt(networkId, undefined),
|
|
863
|
+
defaultHardfork: exports.HARDFORK,
|
|
864
|
+
};
|
|
865
|
+
return common_1.Common.custom(customChainParams);
|
|
866
|
+
}
|
|
867
|
+
onIncomingTransactions({ added, updated, }) {
|
|
868
|
+
const { transactions: currentTransactions } = this.state;
|
|
869
|
+
const updatedTransactions = [
|
|
870
|
+
...added,
|
|
871
|
+
...currentTransactions.map((originalTransaction) => {
|
|
872
|
+
const updatedTransaction = updated.find(({ transactionHash }) => transactionHash === originalTransaction.transactionHash);
|
|
873
|
+
return updatedTransaction !== null && updatedTransaction !== void 0 ? updatedTransaction : originalTransaction;
|
|
874
|
+
}),
|
|
875
|
+
];
|
|
876
|
+
this.update({
|
|
877
|
+
transactions: this.trimTransactionsForState(updatedTransactions),
|
|
878
|
+
});
|
|
879
|
+
}
|
|
880
|
+
onUpdatedLastFetchedBlockNumbers({ lastFetchedBlockNumbers, blockNumber, }) {
|
|
881
|
+
this.update({ lastFetchedBlockNumbers });
|
|
882
|
+
this.hub.emit('incomingTransactionBlock', blockNumber);
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
exports.TransactionController = TransactionController;
|
|
886
|
+
exports.default = TransactionController;
|
|
887
|
+
//# sourceMappingURL=TransactionController.js.map
|