@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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,yBAAyB,CAAC;AACxC,YAAY,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAC5D,OAAO,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AAC/C,cAAc,SAAS,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.isEIP1559Transaction = void 0;
18
+ __exportStar(require("./TransactionController"), exports);
19
+ var utils_1 = require("./utils");
20
+ Object.defineProperty(exports, "isEIP1559Transaction", { enumerable: true, get: function () { return utils_1.isEIP1559Transaction; } });
21
+ __exportStar(require("./types"), exports);
22
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,0DAAwC;AAExC,iCAA+C;AAAtC,6GAAA,oBAAoB,OAAA;AAC7B,0CAAwB","sourcesContent":["export * from './TransactionController';\nexport type { EtherscanTransactionMeta } from './etherscan';\nexport { isEIP1559Transaction } from './utils';\nexport * from './types';\n"]}
@@ -0,0 +1,189 @@
1
+ import type { Hex } from '@metamask/utils';
2
+ /**
3
+ * @type TransactionMeta
4
+ *
5
+ * TransactionMeta representation
6
+ * @property baseFeePerGas - Base fee of the block as a hex value, introduced in EIP-1559.
7
+ * @property error - Synthesized error information for failed transactions.
8
+ * @property id - Generated UUID associated with this transaction.
9
+ * @property networkID - Network code as per EIP-155 for this transaction.
10
+ * @property origin - Origin this transaction was sent from.
11
+ * @property deviceConfirmedOn - string to indicate what device the transaction was confirmed.
12
+ * @property rawTransaction - Hex representation of the underlying transaction.
13
+ * @property status - String status of this transaction.
14
+ * @property time - Timestamp associated with this transaction.
15
+ * @property toSmartContract - Whether transaction recipient is a smart contract.
16
+ * @property transaction - Underlying Transaction object.
17
+ * @property txReceipt - Transaction receipt.
18
+ * @property transactionHash - Hash of a successful transaction.
19
+ * @property blockNumber - Number of the block where the transaction has been included.
20
+ */
21
+ export declare type TransactionMeta = ({
22
+ status: Exclude<TransactionStatus, TransactionStatus.failed>;
23
+ } & TransactionMetaBase) | ({
24
+ status: TransactionStatus.failed;
25
+ error: Error;
26
+ } & TransactionMetaBase);
27
+ declare type TransactionMetaBase = {
28
+ baseFeePerGas?: Hex;
29
+ blockNumber?: string;
30
+ chainId?: Hex;
31
+ deviceConfirmedOn?: WalletDevice;
32
+ id: string;
33
+ isTransfer?: boolean;
34
+ networkID?: string;
35
+ origin?: string;
36
+ rawTransaction?: string;
37
+ time: number;
38
+ toSmartContract?: boolean;
39
+ transaction: Transaction;
40
+ transactionHash?: string;
41
+ transferInformation?: {
42
+ contractAddress: string;
43
+ decimals: number;
44
+ symbol: string;
45
+ };
46
+ verifiedOnBlockchain?: boolean;
47
+ txReceipt?: TransactionReceipt;
48
+ };
49
+ /**
50
+ * The status of the transaction. Each status represents the state of the transaction internally
51
+ * in the wallet. Some of these correspond with the state of the transaction on the network, but
52
+ * some are wallet-specific.
53
+ */
54
+ export declare enum TransactionStatus {
55
+ approved = "approved",
56
+ cancelled = "cancelled",
57
+ confirmed = "confirmed",
58
+ failed = "failed",
59
+ rejected = "rejected",
60
+ signed = "signed",
61
+ submitted = "submitted",
62
+ unapproved = "unapproved"
63
+ }
64
+ /**
65
+ * Options for wallet device.
66
+ */
67
+ export declare enum WalletDevice {
68
+ MM_MOBILE = "metamask_mobile",
69
+ MM_EXTENSION = "metamask_extension",
70
+ OTHER = "other_device"
71
+ }
72
+ /**
73
+ * @type Transaction
74
+ *
75
+ * Transaction representation
76
+ * @property chainId - Network ID as per EIP-155
77
+ * @property data - Data to pass with this transaction
78
+ * @property from - Address to send this transaction from
79
+ * @property gas - Gas to send with this transaction
80
+ * @property gasPrice - Price of gas with this transaction
81
+ * @property gasUsed - Gas used in the transaction
82
+ * @property nonce - Unique number to prevent replay attacks
83
+ * @property to - Address to send this transaction to
84
+ * @property value - Value associated with this transaction
85
+ */
86
+ export interface Transaction {
87
+ chainId?: Hex;
88
+ data?: string;
89
+ from: string;
90
+ gas?: string;
91
+ gasPrice?: string;
92
+ gasUsed?: string;
93
+ nonce?: string;
94
+ to?: string;
95
+ value?: string;
96
+ maxFeePerGas?: string;
97
+ maxPriorityFeePerGas?: string;
98
+ estimatedBaseFee?: string;
99
+ estimateGasError?: string;
100
+ }
101
+ /**
102
+ * Standard data concerning a transaction processed by the blockchain.
103
+ */
104
+ export interface TransactionReceipt {
105
+ /**
106
+ * The block hash of the block that this transaction was included in.
107
+ */
108
+ blockHash?: string;
109
+ /**
110
+ * The block number of the block that this transaction was included in.
111
+ */
112
+ blockNumber?: string;
113
+ /**
114
+ * Effective gas price the transaction was charged at.
115
+ */
116
+ effectiveGasPrice?: string;
117
+ /**
118
+ * Gas used in the transaction.
119
+ */
120
+ gasUsed?: string;
121
+ /**
122
+ * Total used gas in hex.
123
+ */
124
+ l1Fee?: string;
125
+ /**
126
+ * All the logs emitted by this transaction.
127
+ */
128
+ logs?: Log[];
129
+ /**
130
+ * The status of the transaction.
131
+ */
132
+ status?: string;
133
+ /**
134
+ * The index of this transaction in the list of transactions included in the block this transaction was mined in.
135
+ */
136
+ transactionIndex?: number;
137
+ }
138
+ /**
139
+ * Represents an event that has been included in a transaction using the EVM `LOG` opcode.
140
+ */
141
+ export interface Log {
142
+ /**
143
+ * Address of the contract that generated log.
144
+ */
145
+ address?: string;
146
+ /**
147
+ * List of topics for log.
148
+ */
149
+ topics?: string;
150
+ }
151
+ /**
152
+ * The configuration required to fetch transaction data from a RemoteTransactionSource.
153
+ */
154
+ export interface RemoteTransactionSourceRequest {
155
+ /**
156
+ * The address of the account to fetch transactions for.
157
+ */
158
+ address: string;
159
+ /**
160
+ * API key if required by the remote source.
161
+ */
162
+ apiKey?: string;
163
+ /**
164
+ * The chainId of the current network.
165
+ */
166
+ currentChainId: Hex;
167
+ /**
168
+ * The networkId of the current network.
169
+ */
170
+ currentNetworkId: string;
171
+ /**
172
+ * Block number to start fetching transactions from.
173
+ */
174
+ fromBlock?: number;
175
+ /**
176
+ * Maximum number of transactions to retrieve.
177
+ */
178
+ limit?: number;
179
+ }
180
+ /**
181
+ * An object capable of fetching transaction data from a remote source.
182
+ * Used by the IncomingTransactionHelper to retrieve remote transaction data.
183
+ */
184
+ export interface RemoteTransactionSource {
185
+ isSupportedNetwork: (chainId: Hex, networkId: string) => boolean;
186
+ fetchTransactions: (request: RemoteTransactionSourceRequest) => Promise<TransactionMeta[]>;
187
+ }
188
+ export {};
189
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAE3C;;;;;;;;;;;;;;;;;;GAkBG;AACH,oBAAY,eAAe,GACvB,CAAC;IACC,MAAM,EAAE,OAAO,CAAC,iBAAiB,EAAE,iBAAi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gB,EAAE,MAAM,CAAC;IAEzB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED;;;GAGG;AACH,MAAM,WAAW,uBAAuB;IACtC,kBAAkB,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,KAAK,OAAO,CAAC;IAEjE,iBAAiB,EAAE,CACjB,OAAO,EAAE,8BAA8B,KACpC,OAAO,CAAC,eAAe,EAAE,CAAC,CAAC;CACjC"}
package/dist/types.js ADDED
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WalletDevice = exports.TransactionStatus = void 0;
4
+ /**
5
+ * The status of the transaction. Each status represents the state of the transaction internally
6
+ * in the wallet. Some of these correspond with the state of the transaction on the network, but
7
+ * some are wallet-specific.
8
+ */
9
+ var TransactionStatus;
10
+ (function (TransactionStatus) {
11
+ TransactionStatus["approved"] = "approved";
12
+ TransactionStatus["cancelled"] = "cancelled";
13
+ TransactionStatus["confirmed"] = "confirmed";
14
+ TransactionStatus["failed"] = "failed";
15
+ TransactionStatus["rejected"] = "rejected";
16
+ TransactionStatus["signed"] = "signed";
17
+ TransactionStatus["submitted"] = "submitted";
18
+ TransactionStatus["unapproved"] = "unapproved";
19
+ })(TransactionStatus = exports.TransactionStatus || (exports.TransactionStatus = {}));
20
+ /**
21
+ * Options for wallet device.
22
+ */
23
+ var WalletDevice;
24
+ (function (WalletDevice) {
25
+ WalletDevice["MM_MOBILE"] = "metamask_mobile";
26
+ WalletDevice["MM_EXTENSION"] = "metamask_extension";
27
+ WalletDevice["OTHER"] = "other_device";
28
+ })(WalletDevice = exports.WalletDevice || (exports.WalletDevice = {}));
29
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;AAkDA;;;;GAIG;AACH,IAAY,iBASX;AATD,WAAY,iBAAiB;IAC3B,0CAAqB,CAAA;IACrB,4CAAuB,CAAA;IACvB,4CAAuB,CAAA;IACvB,sCAAiB,CAAA;IACjB,0CAAqB,CAAA;IACrB,sCAAiB,CAAA;IACjB,4CAAuB,CAAA;IACvB,8CAAyB,CAAA;AAC3B,CAAC,EATW,iBAAiB,GAAjB,yBAAiB,KAAjB,yBAAiB,QAS5B;AAED;;GAEG;AACH,IAAY,YAIX;AAJD,WAAY,YAAY;IACtB,6CAA6B,CAAA;IAC7B,mDAAmC,CAAA;IACnC,sCAAsB,CAAA;AACxB,CAAC,EAJW,YAAY,GAAZ,oBAAY,KAAZ,oBAAY,QAIvB","sourcesContent":["import type { Hex } from '@metamask/utils';\n\n/**\n * @type TransactionMeta\n *\n * TransactionMeta representation\n * @property baseFeePerGas - Base fee of the block as a hex value, introduced in EIP-1559.\n * @property error - Synthesized error information for failed transactions.\n * @property id - Generated UUID associated with this transaction.\n * @property networkID - Network code as per EIP-155 for this transaction.\n * @property origin - Origin this transaction was sent from.\n * @property deviceConfirmedOn - string to indicate what device the transaction was confirmed.\n * @property rawTransaction - Hex representation of the underlying transaction.\n * @property status - String status of this transaction.\n * @property time - Timestamp associated with this transaction.\n * @property toSmartContract - Whether transaction recipient is a smart contract.\n * @property transaction - Underlying Transaction object.\n * @property txReceipt - Transaction receipt.\n * @property transactionHash - Hash of a successful transaction.\n * @property blockNumber - Number of the block where the transaction has been included.\n */\nexport type TransactionMeta =\n | ({\n status: Exclude<TransactionStatus, TransactionStatus.failed>;\n } & TransactionMetaBase)\n | ({ status: TransactionStatus.failed; error: Error } & TransactionMetaBase);\n\ntype TransactionMetaBase = {\n baseFeePerGas?: Hex;\n blockNumber?: string;\n chainId?: Hex;\n deviceConfirmedOn?: WalletDevice;\n id: string;\n isTransfer?: boolean;\n networkID?: string;\n origin?: string;\n rawTransaction?: string;\n time: number;\n toSmartContract?: boolean;\n transaction: Transaction;\n transactionHash?: string;\n transferInformation?: {\n contractAddress: string;\n decimals: number;\n symbol: string;\n };\n verifiedOnBlockchain?: boolean;\n txReceipt?: TransactionReceipt;\n};\n\n/**\n * The status of the transaction. Each status represents the state of the transaction internally\n * in the wallet. Some of these correspond with the state of the transaction on the network, but\n * some are wallet-specific.\n */\nexport enum TransactionStatus {\n approved = 'approved',\n cancelled = 'cancelled',\n confirmed = 'confirmed',\n failed = 'failed',\n rejected = 'rejected',\n signed = 'signed',\n submitted = 'submitted',\n unapproved = 'unapproved',\n}\n\n/**\n * Options for wallet device.\n */\nexport enum WalletDevice {\n MM_MOBILE = 'metamask_mobile',\n MM_EXTENSION = 'metamask_extension',\n OTHER = 'other_device',\n}\n\n/**\n * @type Transaction\n *\n * Transaction representation\n * @property chainId - Network ID as per EIP-155\n * @property data - Data to pass with this transaction\n * @property from - Address to send this transaction from\n * @property gas - Gas to send with this transaction\n * @property gasPrice - Price of gas with this transaction\n * @property gasUsed - Gas used in the transaction\n * @property nonce - Unique number to prevent replay attacks\n * @property to - Address to send this transaction to\n * @property value - Value associated with this transaction\n */\nexport interface Transaction {\n chainId?: Hex;\n data?: string;\n from: string;\n gas?: string;\n gasPrice?: string;\n gasUsed?: string;\n nonce?: string;\n to?: string;\n value?: string;\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n estimatedBaseFee?: string;\n estimateGasError?: string;\n}\n\n/**\n * Standard data concerning a transaction processed by the blockchain.\n */\nexport interface TransactionReceipt {\n /**\n * The block hash of the block that this transaction was included in.\n */\n blockHash?: string;\n\n /**\n * The block number of the block that this transaction was included in.\n */\n blockNumber?: string;\n\n /**\n * Effective gas price the transaction was charged at.\n */\n effectiveGasPrice?: string;\n\n /**\n * Gas used in the transaction.\n */\n gasUsed?: string;\n\n /**\n * Total used gas in hex.\n */\n l1Fee?: string;\n\n /**\n * All the logs emitted by this transaction.\n */\n logs?: Log[];\n\n /**\n * The status of the transaction.\n */\n status?: string;\n\n /**\n * The index of this transaction in the list of transactions included in the block this transaction was mined in.\n */\n transactionIndex?: number;\n}\n\n/**\n * Represents an event that has been included in a transaction using the EVM `LOG` opcode.\n */\nexport interface Log {\n /**\n * Address of the contract that generated log.\n */\n address?: string;\n /**\n * List of topics for log.\n */\n topics?: string;\n}\n\n/**\n * The configuration required to fetch transaction data from a RemoteTransactionSource.\n */\nexport interface RemoteTransactionSourceRequest {\n /**\n * The address of the account to fetch transactions for.\n */\n address: string;\n\n /**\n * API key if required by the remote source.\n */\n apiKey?: string;\n\n /**\n * The chainId of the current network.\n */\n currentChainId: Hex;\n\n /**\n * The networkId of the current network.\n */\n currentNetworkId: string;\n\n /**\n * Block number to start fetching transactions from.\n */\n fromBlock?: number;\n\n /**\n * Maximum number of transactions to retrieve.\n */\n limit?: number;\n}\n\n/**\n * An object capable of fetching transaction data from a remote source.\n * Used by the IncomingTransactionHelper to retrieve remote transaction data.\n */\nexport interface RemoteTransactionSource {\n isSupportedNetwork: (chainId: Hex, networkId: string) => boolean;\n\n fetchTransactions: (\n request: RemoteTransactionSourceRequest,\n ) => Promise<TransactionMeta[]>;\n}\n"]}
@@ -0,0 +1,61 @@
1
+ import type { Hex } from '@metamask/utils';
2
+ import type { Transaction as NonceTrackerTransaction } from 'nonce-tracker/dist/NonceTracker';
3
+ import type { GasPriceValue, FeeMarketEIP1559Values } from './TransactionController';
4
+ import type { Transaction, TransactionMeta, TransactionStatus } from './types';
5
+ export declare const ESTIMATE_GAS_ERROR = "eth_estimateGas rpc method error";
6
+ /**
7
+ * Normalizes properties on a Transaction object.
8
+ *
9
+ * @param transaction - Transaction object to normalize.
10
+ * @returns Normalized Transaction object.
11
+ */
12
+ export declare function normalizeTransaction(transaction: Transaction): Transaction;
13
+ /**
14
+ * Validates a Transaction object for required properties and throws in
15
+ * the event of any validation error.
16
+ *
17
+ * @param transaction - Transaction object to validate.
18
+ */
19
+ export declare function validateTransaction(transaction: Transaction): void;
20
+ /**
21
+ * Checks if a transaction is EIP-1559 by checking for the existence of
22
+ * maxFeePerGas and maxPriorityFeePerGas within its parameters.
23
+ *
24
+ * @param transaction - Transaction object to add.
25
+ * @returns Boolean that is true if the transaction is EIP-1559 (has maxFeePerGas and maxPriorityFeePerGas), otherwise returns false.
26
+ */
27
+ export declare const isEIP1559Transaction: (transaction: Transaction) => boolean;
28
+ export declare const validateGasValues: (gasValues: GasPriceValue | FeeMarketEIP1559Values) => void;
29
+ export declare const isFeeMarketEIP1559Values: (gasValues?: GasPriceValue | FeeMarketEIP1559Values | undefined) => gasValues is FeeMarketEIP1559Values;
30
+ export declare const isGasPriceValue: (gasValues?: GasPriceValue | FeeMarketEIP1559Values | undefined) => gasValues is GasPriceValue;
31
+ export declare const getIncreasedPriceHex: (value: number, rate: number) => string;
32
+ export declare const getIncreasedPriceFromExisting: (value: string | undefined, rate: number) => string;
33
+ /**
34
+ * Validates that the proposed value is greater than or equal to the minimum value.
35
+ *
36
+ * @param proposed - The proposed value.
37
+ * @param min - The minimum value.
38
+ * @returns The proposed value.
39
+ * @throws Will throw if the proposed value is too low.
40
+ */
41
+ export declare function validateMinimumIncrease(proposed: string, min: string): string;
42
+ /**
43
+ * Helper function to filter and format transactions for the nonce tracker.
44
+ *
45
+ * @param fromAddress - Address of the account from which the transactions to filter from are sent.
46
+ * @param transactionStatus - Status of the transactions for which to filter.
47
+ * @param transactions - Array of transactionMeta objects that have been prefiltered.
48
+ * @returns Array of transactions formatted for the nonce tracker.
49
+ */
50
+ export declare function getAndFormatTransactionsForNonceTracker(fromAddress: string, transactionStatus: TransactionStatus, transactions: TransactionMeta[]): NonceTrackerTransaction[];
51
+ /**
52
+ * Checks whether a given transaction matches the specified network or chain ID.
53
+ * This function is used to determine if a transaction is relevant to the current network or chain.
54
+ *
55
+ * @param transaction - The transaction metadata to check.
56
+ * @param chainId - The chain ID of the current network.
57
+ * @param networkId - The network ID of the current network.
58
+ * @returns A boolean value indicating whether the transaction matches the current network or chain ID.
59
+ */
60
+ export declare function transactionMatchesNetwork(transaction: TransactionMeta, chainId: Hex, networkId: string | null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BAAgB,yBAAyB,CACvC,WAAW,EAAE,eAAe,EAC5B,OAAO,EAAE,GAAG,EACZ,SAAS,EAAE,MAAM,GAAG,IAAI,WASzB"}
package/dist/utils.js ADDED
@@ -0,0 +1,178 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.transactionMatchesNetwork = exports.getAndFormatTransactionsForNonceTracker = exports.validateMinimumIncrease = exports.getIncreasedPriceFromExisting = exports.getIncreasedPriceHex = exports.isGasPriceValue = exports.isFeeMarketEIP1559Values = exports.validateGasValues = exports.isEIP1559Transaction = exports.validateTransaction = exports.normalizeTransaction = exports.ESTIMATE_GAS_ERROR = void 0;
4
+ const controller_utils_1 = require("@metamask/controller-utils");
5
+ const ethereumjs_util_1 = require("ethereumjs-util");
6
+ exports.ESTIMATE_GAS_ERROR = 'eth_estimateGas rpc method error';
7
+ const NORMALIZERS = {
8
+ data: (data) => (0, ethereumjs_util_1.addHexPrefix)(data),
9
+ from: (from) => (0, ethereumjs_util_1.addHexPrefix)(from).toLowerCase(),
10
+ gas: (gas) => (0, ethereumjs_util_1.addHexPrefix)(gas),
11
+ gasPrice: (gasPrice) => (0, ethereumjs_util_1.addHexPrefix)(gasPrice),
12
+ nonce: (nonce) => (0, ethereumjs_util_1.addHexPrefix)(nonce),
13
+ to: (to) => (0, ethereumjs_util_1.addHexPrefix)(to).toLowerCase(),
14
+ value: (value) => (0, ethereumjs_util_1.addHexPrefix)(value),
15
+ maxFeePerGas: (maxFeePerGas) => (0, ethereumjs_util_1.addHexPrefix)(maxFeePerGas),
16
+ maxPriorityFeePerGas: (maxPriorityFeePerGas) => (0, ethereumjs_util_1.addHexPrefix)(maxPriorityFeePerGas),
17
+ estimatedBaseFee: (maxPriorityFeePerGas) => (0, ethereumjs_util_1.addHexPrefix)(maxPriorityFeePerGas),
18
+ };
19
+ /**
20
+ * Normalizes properties on a Transaction object.
21
+ *
22
+ * @param transaction - Transaction object to normalize.
23
+ * @returns Normalized Transaction object.
24
+ */
25
+ function normalizeTransaction(transaction) {
26
+ const normalizedTransaction = { from: '' };
27
+ let key;
28
+ for (key in NORMALIZERS) {
29
+ if (transaction[key]) {
30
+ normalizedTransaction[key] = NORMALIZERS[key](transaction[key]);
31
+ }
32
+ }
33
+ return normalizedTransaction;
34
+ }
35
+ exports.normalizeTransaction = normalizeTransaction;
36
+ /**
37
+ * Validates a Transaction object for required properties and throws in
38
+ * the event of any validation error.
39
+ *
40
+ * @param transaction - Transaction object to validate.
41
+ */
42
+ function validateTransaction(transaction) {
43
+ if (!transaction.from ||
44
+ typeof transaction.from !== 'string' ||
45
+ !(0, controller_utils_1.isValidHexAddress)(transaction.from)) {
46
+ throw new Error(`Invalid "from" address: ${transaction.from} must be a valid string.`);
47
+ }
48
+ if (transaction.to === '0x' || transaction.to === undefined) {
49
+ if (transaction.data) {
50
+ delete transaction.to;
51
+ }
52
+ else {
53
+ throw new Error(`Invalid "to" address: ${transaction.to} must be a valid string.`);
54
+ }
55
+ }
56
+ else if (transaction.to !== undefined &&
57
+ !(0, controller_utils_1.isValidHexAddress)(transaction.to)) {
58
+ throw new Error(`Invalid "to" address: ${transaction.to} must be a valid string.`);
59
+ }
60
+ if (transaction.value !== undefined) {
61
+ const value = transaction.value.toString();
62
+ if (value.includes('-')) {
63
+ throw new Error(`Invalid "value": ${value} is not a positive number.`);
64
+ }
65
+ if (value.includes('.')) {
66
+ throw new Error(`Invalid "value": ${value} number must be denominated in wei.`);
67
+ }
68
+ const intValue = parseInt(transaction.value, 10);
69
+ const isValid = Number.isFinite(intValue) &&
70
+ !Number.isNaN(intValue) &&
71
+ !isNaN(Number(value)) &&
72
+ Number.isSafeInteger(intValue);
73
+ if (!isValid) {
74
+ throw new Error(`Invalid "value": ${value} number must be a valid number.`);
75
+ }
76
+ }
77
+ }
78
+ exports.validateTransaction = validateTransaction;
79
+ /**
80
+ * Checks if a transaction is EIP-1559 by checking for the existence of
81
+ * maxFeePerGas and maxPriorityFeePerGas within its parameters.
82
+ *
83
+ * @param transaction - Transaction object to add.
84
+ * @returns Boolean that is true if the transaction is EIP-1559 (has maxFeePerGas and maxPriorityFeePerGas), otherwise returns false.
85
+ */
86
+ const isEIP1559Transaction = (transaction) => {
87
+ const hasOwnProp = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
88
+ return (hasOwnProp(transaction, 'maxFeePerGas') &&
89
+ hasOwnProp(transaction, 'maxPriorityFeePerGas'));
90
+ };
91
+ exports.isEIP1559Transaction = isEIP1559Transaction;
92
+ const validateGasValues = (gasValues) => {
93
+ Object.keys(gasValues).forEach((key) => {
94
+ const value = gasValues[key];
95
+ if (typeof value !== 'string' || !(0, ethereumjs_util_1.isHexString)(value)) {
96
+ throw new TypeError(`expected hex string for ${key} but received: ${value}`);
97
+ }
98
+ });
99
+ };
100
+ exports.validateGasValues = validateGasValues;
101
+ const isFeeMarketEIP1559Values = (gasValues) => (gasValues === null || gasValues === void 0 ? void 0 : gasValues.maxFeePerGas) !== undefined ||
102
+ (gasValues === null || gasValues === void 0 ? void 0 : gasValues.maxPriorityFeePerGas) !== undefined;
103
+ exports.isFeeMarketEIP1559Values = isFeeMarketEIP1559Values;
104
+ const isGasPriceValue = (gasValues) => (gasValues === null || gasValues === void 0 ? void 0 : gasValues.gasPrice) !== undefined;
105
+ exports.isGasPriceValue = isGasPriceValue;
106
+ const getIncreasedPriceHex = (value, rate) => (0, ethereumjs_util_1.addHexPrefix)(`${parseInt(`${value * rate}`, 10).toString(16)}`);
107
+ exports.getIncreasedPriceHex = getIncreasedPriceHex;
108
+ const getIncreasedPriceFromExisting = (value, rate) => {
109
+ return (0, exports.getIncreasedPriceHex)((0, controller_utils_1.convertHexToDecimal)(value), rate);
110
+ };
111
+ exports.getIncreasedPriceFromExisting = getIncreasedPriceFromExisting;
112
+ /**
113
+ * Validates that the proposed value is greater than or equal to the minimum value.
114
+ *
115
+ * @param proposed - The proposed value.
116
+ * @param min - The minimum value.
117
+ * @returns The proposed value.
118
+ * @throws Will throw if the proposed value is too low.
119
+ */
120
+ function validateMinimumIncrease(proposed, min) {
121
+ const proposedDecimal = (0, controller_utils_1.convertHexToDecimal)(proposed);
122
+ const minDecimal = (0, controller_utils_1.convertHexToDecimal)(min);
123
+ if (proposedDecimal >= minDecimal) {
124
+ return proposed;
125
+ }
126
+ const errorMsg = `The proposed value: ${proposedDecimal} should meet or exceed the minimum value: ${minDecimal}`;
127
+ throw new Error(errorMsg);
128
+ }
129
+ exports.validateMinimumIncrease = validateMinimumIncrease;
130
+ /**
131
+ * Helper function to filter and format transactions for the nonce tracker.
132
+ *
133
+ * @param fromAddress - Address of the account from which the transactions to filter from are sent.
134
+ * @param transactionStatus - Status of the transactions for which to filter.
135
+ * @param transactions - Array of transactionMeta objects that have been prefiltered.
136
+ * @returns Array of transactions formatted for the nonce tracker.
137
+ */
138
+ function getAndFormatTransactionsForNonceTracker(fromAddress, transactionStatus, transactions) {
139
+ return transactions
140
+ .filter(({ status, transaction: { from } }) => status === transactionStatus &&
141
+ from.toLowerCase() === fromAddress.toLowerCase())
142
+ .map(({ status, transaction: { from, gas, value, nonce } }) => {
143
+ // the only value we care about is the nonce
144
+ // but we need to return the other values to satisfy the type
145
+ // TODO: refactor nonceTracker to not require this
146
+ return {
147
+ status,
148
+ history: [{}],
149
+ txParams: {
150
+ from: from !== null && from !== void 0 ? from : '',
151
+ gas: gas !== null && gas !== void 0 ? gas : '',
152
+ value: value !== null && value !== void 0 ? value : '',
153
+ nonce: nonce !== null && nonce !== void 0 ? nonce : '',
154
+ },
155
+ };
156
+ });
157
+ }
158
+ exports.getAndFormatTransactionsForNonceTracker = getAndFormatTransactionsForNonceTracker;
159
+ /**
160
+ * Checks whether a given transaction matches the specified network or chain ID.
161
+ * This function is used to determine if a transaction is relevant to the current network or chain.
162
+ *
163
+ * @param transaction - The transaction metadata to check.
164
+ * @param chainId - The chain ID of the current network.
165
+ * @param networkId - The network ID of the current network.
166
+ * @returns A boolean value indicating whether the transaction matches the current network or chain ID.
167
+ */
168
+ function transactionMatchesNetwork(transaction, chainId, networkId) {
169
+ if (transaction.chainId) {
170
+ return transaction.chainId === chainId;
171
+ }
172
+ if (transaction.networkID) {
173
+ return transaction.networkID === networkId;
174
+ }
175
+ return false;
176
+ }
177
+ exports.transactionMatchesNetwork = transactionMatchesNetwork;
178
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;AAAA,iEAGoC;AAEpC,qDAA4D;AAS/C,QAAA,kBAAkB,GAAG,kCAAkC,CAAC;AAErE,MAAM,WAAW,GAA0C;IACzD,IAAI,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,IAAA,8BAAY,EAAC,IAAI,CAAC;IAC1C,IAAI,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,IAAA,8BAAY,EAAC,IAAI,CAAC,CAAC,WAAW,EAAE;IACxD,GAAG,EAAE,CAAC,GAAW,EAAE,EAAE,CAAC,IAAA,8BAAY,EAAC,GAAG,CAAC;IACvC,QAAQ,EAAE,CAAC,QAAgB,EAAE,EAAE,CAAC,IAAA,8BAAY,EAAC,QAAQ,CAAC;IACtD,KAAK,EAAE,CAAC,KAAa,EAAE,EAAE,CAAC,IAAA,8BAAY,EAAC,KAAK,CAAC;IAC7C,EAAE,EAAE,CAAC,EAAU,EAAE,EAAE,CAAC,IAAA,8BAAY,EAAC,EAAE,CAAC,CAAC,WAAW,EAAE;IAClD,KAAK,EAAE,CAAC,KAAa,EAAE,EAAE,CAAC,IAAA,8BAAY,EAAC,KAAK,CAAC;IAC7C,YAAY,EAAE,CAAC,YAAoB,EAAE,EAAE,CAAC,IAAA,8BAAY,EAAC,YAAY,CAAC;IAClE,oBAAoB,EAAE,CAAC,oBAA4B,EAAE,EAAE,CACrD,IAAA,8BAAY,EAAC,oBAAoB,CAAC;IACpC,gBAAgB,EAAE,CAAC,oBAA4B,EAAE,EAAE,CACjD,IAAA,8BAAY,EAA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AAO,CAAC;KACxC;IACD,IAAI,WAAW,CAAC,SAAS,EAAE;QACzB,OAAO,WAAW,CAAC,SAAS,KAAK,SAAS,CAAC;KAC5C;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAZD,8DAYC","sourcesContent":["import {\n convertHexToDecimal,\n isValidHexAddress,\n} from '@metamask/controller-utils';\nimport type { Hex } from '@metamask/utils';\nimport { addHexPrefix, isHexString } from 'ethereumjs-util';\nimport type { Transaction as NonceTrackerTransaction } from 'nonce-tracker/dist/NonceTracker';\n\nimport type {\n GasPriceValue,\n FeeMarketEIP1559Values,\n} from './TransactionController';\nimport type { Transaction, TransactionMeta, TransactionStatus } from './types';\n\nexport const ESTIMATE_GAS_ERROR = 'eth_estimateGas rpc method error';\n\nconst NORMALIZERS: { [param in keyof Transaction]: any } = {\n data: (data: string) => addHexPrefix(data),\n from: (from: string) => addHexPrefix(from).toLowerCase(),\n gas: (gas: string) => addHexPrefix(gas),\n gasPrice: (gasPrice: string) => addHexPrefix(gasPrice),\n nonce: (nonce: string) => addHexPrefix(nonce),\n to: (to: string) => addHexPrefix(to).toLowerCase(),\n value: (value: string) => addHexPrefix(value),\n maxFeePerGas: (maxFeePerGas: string) => addHexPrefix(maxFeePerGas),\n maxPriorityFeePerGas: (maxPriorityFeePerGas: string) =>\n addHexPrefix(maxPriorityFeePerGas),\n estimatedBaseFee: (maxPriorityFeePerGas: string) =>\n addHexPrefix(maxPriorityFeePerGas),\n};\n\n/**\n * Normalizes properties on a Transaction object.\n *\n * @param transaction - Transaction object to normalize.\n * @returns Normalized Transaction object.\n */\nexport function normalizeTransaction(transaction: Transaction) {\n const normalizedTransaction: Transaction = { from: '' };\n let key: keyof Transaction;\n for (key in NORMALIZERS) {\n if (transaction[key as keyof Transaction]) {\n normalizedTransaction[key] = NORMALIZERS[key](transaction[key]) as never;\n }\n }\n return normalizedTransaction;\n}\n\n/**\n * Validates a Transaction object for required properties and throws in\n * the event of any validation error.\n *\n * @param transaction - Transaction object to validate.\n */\nexport function validateTransaction(transaction: Transaction) {\n if (\n !transaction.from ||\n typeof transaction.from !== 'string' ||\n !isValidHexAddress(transaction.from)\n ) {\n throw new Error(\n `Invalid \"from\" address: ${transaction.from} must be a valid string.`,\n );\n }\n\n if (transaction.to === '0x' || transaction.to === undefined) {\n if (transaction.data) {\n delete transaction.to;\n } else {\n throw new Error(\n `Invalid \"to\" address: ${transaction.to} must be a valid string.`,\n );\n }\n } else if (\n transaction.to !== undefined &&\n !isValidHexAddress(transaction.to)\n ) {\n throw new Error(\n `Invalid \"to\" address: ${transaction.to} must be a valid string.`,\n );\n }\n\n if (transaction.value !== undefined) {\n const value = transaction.value.toString();\n if (value.includes('-')) {\n throw new Error(`Invalid \"value\": ${value} is not a positive number.`);\n }\n\n if (value.includes('.')) {\n throw new Error(\n `Invalid \"value\": ${value} number must be denominated in wei.`,\n );\n }\n const intValue = parseInt(transaction.value, 10);\n const isValid =\n Number.isFinite(intValue) &&\n !Number.isNaN(intValue) &&\n !isNaN(Number(value)) &&\n Number.isSafeInteger(intValue);\n if (!isValid) {\n throw new Error(\n `Invalid \"value\": ${value} number must be a valid number.`,\n );\n }\n }\n}\n\n/**\n * Checks if a transaction is EIP-1559 by checking for the existence of\n * maxFeePerGas and maxPriorityFeePerGas within its parameters.\n *\n * @param transaction - Transaction object to add.\n * @returns Boolean that is true if the transaction is EIP-1559 (has maxFeePerGas and maxPriorityFeePerGas), otherwise returns false.\n */\nexport const isEIP1559Transaction = (transaction: Transaction): boolean => {\n const hasOwnProp = (obj: Transaction, key: string) =>\n Object.prototype.hasOwnProperty.call(obj, key);\n return (\n hasOwnProp(transaction, 'maxFeePerGas') &&\n hasOwnProp(transaction, 'maxPriorityFeePerGas')\n );\n};\n\nexport const validateGasValues = (\n gasValues: GasPriceValue | FeeMarketEIP1559Values,\n) => {\n Object.keys(gasValues).forEach((key) => {\n const value = (gasValues as any)[key];\n if (typeof value !== 'string' || !isHexString(value)) {\n throw new TypeError(\n `expected hex string for ${key} but received: ${value}`,\n );\n }\n });\n};\n\nexport const isFeeMarketEIP1559Values = (\n gasValues?: GasPriceValue | FeeMarketEIP1559Values,\n): gasValues is FeeMarketEIP1559Values =>\n (gasValues as FeeMarketEIP1559Values)?.maxFeePerGas !== undefined ||\n (gasValues as FeeMarketEIP1559Values)?.maxPriorityFeePerGas !== undefined;\n\nexport const isGasPriceValue = (\n gasValues?: GasPriceValue | FeeMarketEIP1559Values,\n): gasValues is GasPriceValue =>\n (gasValues as GasPriceValue)?.gasPrice !== undefined;\n\nexport const getIncreasedPriceHex = (value: number, rate: number): string =>\n addHexPrefix(`${parseInt(`${value * rate}`, 10).toString(16)}`);\n\nexport const getIncreasedPriceFromExisting = (\n value: string | undefined,\n rate: number,\n): string => {\n return getIncreasedPriceHex(convertHexToDecimal(value), rate);\n};\n\n/**\n * Validates that the proposed value is greater than or equal to the minimum value.\n *\n * @param proposed - The proposed value.\n * @param min - The minimum value.\n * @returns The proposed value.\n * @throws Will throw if the proposed value is too low.\n */\nexport function validateMinimumIncrease(proposed: string, min: string) {\n const proposedDecimal = convertHexToDecimal(proposed);\n const minDecimal = convertHexToDecimal(min);\n if (proposedDecimal >= minDecimal) {\n return proposed;\n }\n const errorMsg = `The proposed value: ${proposedDecimal} should meet or exceed the minimum value: ${minDecimal}`;\n throw new Error(errorMsg);\n}\n\n/**\n * Helper function to filter and format transactions for the nonce tracker.\n *\n * @param fromAddress - Address of the account from which the transactions to filter from are sent.\n * @param transactionStatus - Status of the transactions for which to filter.\n * @param transactions - Array of transactionMeta objects that have been prefiltered.\n * @returns Array of transactions formatted for the nonce tracker.\n */\nexport function getAndFormatTransactionsForNonceTracker(\n fromAddress: string,\n transactionStatus: TransactionStatus,\n transactions: TransactionMeta[],\n): NonceTrackerTransaction[] {\n return transactions\n .filter(\n ({ status, transaction: { from } }) =>\n status === transactionStatus &&\n from.toLowerCase() === fromAddress.toLowerCase(),\n )\n .map(({ status, transaction: { from, gas, value, nonce } }) => {\n // the only value we care about is the nonce\n // but we need to return the other values to satisfy the type\n // TODO: refactor nonceTracker to not require this\n return {\n status,\n history: [{}],\n txParams: {\n from: from ?? '',\n gas: gas ?? '',\n value: value ?? '',\n nonce: nonce ?? '',\n },\n };\n });\n}\n\n/**\n * Checks whether a given transaction matches the specified network or chain ID.\n * This function is used to determine if a transaction is relevant to the current network or chain.\n *\n * @param transaction - The transaction metadata to check.\n * @param chainId - The chain ID of the current network.\n * @param networkId - The network ID of the current network.\n * @returns A boolean value indicating whether the transaction matches the current network or chain ID.\n */\nexport function transactionMatchesNetwork(\n transaction: TransactionMeta,\n chainId: Hex,\n networkId: string | null,\n) {\n if (transaction.chainId) {\n return transaction.chainId === chainId;\n }\n if (transaction.networkID) {\n return transaction.networkID === networkId;\n }\n return false;\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,72 @@
1
+ {
2
+ "name": "@metamask-previews/transaction-controller",
3
+ "version": "8.0.1-preview.d32a7cc",
4
+ "description": "Stores transactions alongside their periodically updated statuses and manages interactions such as approval and cancellation",
5
+ "keywords": [
6
+ "MetaMask",
7
+ "Ethereum"
8
+ ],
9
+ "homepage": "https://github.com/MetaMask/core/tree/main/packages/transaction-controller#readme",
10
+ "bugs": {
11
+ "url": "https://github.com/MetaMask/core/issues"
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://github.com/MetaMask/core.git"
16
+ },
17
+ "license": "MIT",
18
+ "main": "./dist/index.js",
19
+ "types": "./dist/index.d.ts",
20
+ "files": [
21
+ "dist/"
22
+ ],
23
+ "scripts": {
24
+ "build:docs": "typedoc",
25
+ "changelog:validate": "../../scripts/validate-changelog.sh @metamask/transaction-controller",
26
+ "publish:preview": "yarn npm publish --tag preview",
27
+ "test": "jest",
28
+ "test:watch": "jest --watch"
29
+ },
30
+ "dependencies": {
31
+ "@ethereumjs/common": "^3.2.0",
32
+ "@ethereumjs/tx": "^4.2.0",
33
+ "@metamask-previews/approval-controller": "3.5.0-preview.d32a7cc",
34
+ "@metamask-previews/base-controller": "3.2.0-preview.d32a7cc",
35
+ "@metamask-previews/controller-utils": "4.3.1-preview.d32a7cc",
36
+ "@metamask-previews/network-controller": "12.1.1-preview.d32a7cc",
37
+ "@metamask/eth-query": "^3.0.1",
38
+ "@metamask/utils": "^6.2.0",
39
+ "async-mutex": "^0.2.6",
40
+ "eth-method-registry": "1.1.0",
41
+ "eth-rpc-errors": "^4.0.2",
42
+ "ethereumjs-util": "^7.0.10",
43
+ "nonce-tracker": "^1.1.0",
44
+ "uuid": "^8.3.2"
45
+ },
46
+ "devDependencies": {
47
+ "@metamask/auto-changelog": "^3.1.0",
48
+ "@types/jest": "^27.4.1",
49
+ "@types/node": "^16.18.24",
50
+ "babel-runtime": "^6.26.0",
51
+ "deepmerge": "^4.2.2",
52
+ "ethjs-provider-http": "^0.1.6",
53
+ "jest": "^27.5.1",
54
+ "sinon": "^9.2.4",
55
+ "ts-jest": "^27.1.4",
56
+ "typedoc": "^0.22.15",
57
+ "typedoc-plugin-missing-exports": "^0.22.6",
58
+ "typescript": "~4.6.3"
59
+ },
60
+ "peerDependencies": {
61
+ "@metamask-previews/approval-controller": "3.5.0-preview.d32a7cc",
62
+ "@metamask-previews/network-controller": "12.1.1-preview.d32a7cc",
63
+ "babel-runtime": "^6.26.0"
64
+ },
65
+ "engines": {
66
+ "node": ">=16.0.0"
67
+ },
68
+ "publishConfig": {
69
+ "access": "public",
70
+ "registry": "https://registry.npmjs.org/"
71
+ }
72
+ }