-
Notifications
You must be signed in to change notification settings - Fork 394
/
index.ts
2027 lines (1825 loc) · 64 KB
/
index.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 {
TransactionReceipt,
TransactionResponse,
} from "@ethersproject/providers"
import { ethers, utils } from "ethers"
import { Logger, UnsignedTransaction } from "ethers/lib/utils"
import logger from "../../lib/logger"
import getBlockPrices from "../../lib/gas"
import { HexString, NormalizedEVMAddress, UNIXTime } from "../../types"
import { AccountBalance, AddressOnNetwork } from "../../accounts"
import {
AnyEVMBlock,
AnyEVMTransaction,
EIP1559TransactionRequest,
EVMNetwork,
BlockPrices,
TransactionRequest,
TransactionRequestWithNonce,
SignedTransaction,
toHexChainID,
NetworkBaseAsset,
sameChainID,
} from "../../networks"
import {
AnyAssetAmount,
AssetTransfer,
SmartContractFungibleAsset,
} from "../../assets"
import {
HOUR,
ETHEREUM,
OPTIMISM,
NETWORK_BY_CHAIN_ID,
MINUTE,
CHAINS_WITH_MEMPOOL,
EIP_1559_COMPLIANT_CHAIN_IDS,
SECOND,
} from "../../constants"
import { FeatureFlags, isEnabled } from "../../features"
import PreferenceService from "../preferences"
import { ServiceCreatorFunction, ServiceLifecycleEvents } from "../types"
import { createDB, ChainDatabase, Transaction } from "./db"
import BaseService from "../base"
import {
blockFromEthersBlock,
blockFromProviderBlock,
enrichTransactionWithReceipt,
ethersTransactionFromSignedTransaction,
transactionFromEthersTransaction,
ethersTransactionFromTransactionRequest,
unsignedTransactionFromEVMTransaction,
} from "./utils"
import { normalizeEVMAddress, sameEVMAddress } from "../../lib/utils"
import type {
EnrichedEIP1559TransactionRequest,
EnrichedEIP1559TransactionSignatureRequest,
EnrichedEVMTransactionRequest,
EnrichedEVMTransactionSignatureRequest,
EnrichedLegacyTransactionRequest,
EnrichedLegacyTransactionSignatureRequest,
} from "../enrichment"
import SerialFallbackProvider, {
ProviderCreator,
makeSerialFallbackProvider,
} from "./serial-fallback-provider"
import AssetDataHelper from "./asset-data-helper"
import {
OPTIMISM_GAS_ORACLE_ABI,
OPTIMISM_GAS_ORACLE_ADDRESS,
} from "./utils/optimismGasPriceOracle"
import InternalSignerService, { SignerImportSource } from "../internal-signer"
import type { ValidatedAddEthereumChainParameter } from "../provider-bridge/utils"
import { ISLAND_NETWORK } from "../island/contracts"
// The number of blocks to query at a time for historic asset transfers.
// Unfortunately there's no "right" answer here that works well across different
// people's account histories. If the number is too large relative to a
// frequently used account, the first call will time out and waste provider
// resources... resulting in an exponential backoff. If it's too small,
// transaction history will appear "slow" to show up for newly imported
// accounts.
const BLOCKS_FOR_TRANSACTION_HISTORY = 128000
// The number of blocks before the current block height to start looking for
// asset transfers. This is important to allow nodes like Erigon and
// OpenEthereum with tracing to catch up to where we are.
const BLOCKS_TO_SKIP_FOR_TRANSACTION_HISTORY = 20
// Add a little bit of wiggle room
const NETWORK_POLLING_TIMEOUT = MINUTE * 2.05
// The number of milliseconds after a request to look up a transaction was
// first seen to continue looking in case the transaction fails to be found
// for either internal (request failure) or external (transaction dropped from
// mempool) reasons.
const TRANSACTION_CHECK_LIFETIME_MS = 10 * HOUR
const GAS_POLLS_PER_PERIOD = 4 // 4 times per minute
const GAS_POLLING_PERIOD = 1 // 1 minute
// Maximum number of transactions with priority.
// Transactions that will be retrieved before others for one account.
// Transactions with priority for individual accounts will keep the order of loading
// from adding accounts.
const TRANSACTIONS_WITH_PRIORITY_MAX_COUNT = 25
interface Events extends ServiceLifecycleEvents {
initializeActivities: {
transactions: Transaction[]
accounts: AddressOnNetwork[]
}
initializeActivitiesForAccount: {
transactions: Transaction[]
account: AddressOnNetwork
}
newAccountToTrack: AddressOnNetwork
supportedNetworks: EVMNetwork[]
accountsWithBalances: {
/**
* Retrieved balance for the network's base asset
*/
balances: AccountBalance[]
/**
* The respective address and network for this balance update
*/
addressOnNetwork: AddressOnNetwork
}
transactionSend: HexString
networkSubscribed: EVMNetwork
transactionSendFailure: undefined
assetTransfers: {
addressNetwork: AddressOnNetwork
assetTransfers: AssetTransfer[]
}
block: AnyEVMBlock
transaction: { forAccounts: string[]; transaction: AnyEVMTransaction }
blockPrices: { blockPrices: BlockPrices; network: EVMNetwork }
customChainAdded: ValidatedAddEthereumChainParameter
}
export type QueuedTxToRetrieve = {
network: EVMNetwork
hash: HexString
firstSeen: UNIXTime
}
/**
* The queue object contains transaction and priority.
* The priority value is a number. The value of the highest priority has not been set.
* The lowest possible priority is 0.
*/
export type PriorityQueuedTxToRetrieve = {
transaction: QueuedTxToRetrieve
priority: number
}
/**
* ChainService is responsible for basic network monitoring and interaction.
* Other services rely on the chain service rather than polling networks
* themselves.
*
* The service should provide
* * Basic cached network information, like the latest block hash and height
* * Cached account balances, account history, and transaction data
* * Gas estimation and transaction broadcasting
* * Event subscriptions, including events whenever
* * A new transaction relevant to accounts tracked is found or first
* confirmed
* * A historic account transaction is pulled and cached
* * Any asset transfers found for newly tracked accounts
* * A relevant account balance changes
* * New blocks
* * ... and finally, polling and websocket providers for supported networks, in
* case a service needs to interact with a network directly.
*/
export default class ChainService extends BaseService<Events> {
providers: { evm: { [networkName: string]: SerialFallbackProvider } } = {
evm: {},
}
subscribedAccounts: {
account: string
provider: SerialFallbackProvider
}[]
subscribedNetworks: {
network: EVMNetwork
provider: SerialFallbackProvider
}[]
private lastUserActivityOnNetwork: {
[chainID: string]: UNIXTime
} = {}
private lastUserActivityOnAddress: {
[address: HexString]: UNIXTime
} = {}
/**
* For each chain id, track an address's last seen nonce. The tracked nonce
* should generally not be allocated to a new transaction, nor should any
* nonces that precede it, unless the intent is deliberately to replace an
* unconfirmed transaction sharing the same nonce.
*/
private evmChainLastSeenNoncesByNormalizedAddress: {
[chainID: string]: { [normalizedAddress: string]: number }
} = {}
/**
* Modified FIFO queues with priority of transaction hashes per network that should be retrieved and
* cached, alongside information about when that hash request was first seen
* for expiration purposes. In the absence of priorities, it acts as a regular FIFO queue.
*/
private transactionsToRetrieve: PriorityQueuedTxToRetrieve[]
/**
* Internal timer for the transactionsToRetrieve FIFO queue.
* Starting multiple transaction requests at the same time is resource intensive
* on the user's machine and also can result in rate limitations with the provider.
*
* Because of this we need to smooth out the retrieval scheduling.
*
* Limitations
* - handlers can fire only in 1+ minute intervals
* - in manifest v3 / service worker context the background thread can be shut down any time.
* Because of this we need to keep the granular queue tied to the persisted list of txs
*/
private transactionToRetrieveGranularTimer: NodeJS.Timer | undefined
static create: ServiceCreatorFunction<
Events,
ChainService,
[Promise<PreferenceService>, Promise<InternalSignerService>]
> = async (preferenceService, internalSignerService) =>
new this(createDB(), await preferenceService, await internalSignerService)
supportedNetworks: EVMNetwork[] = []
private trackedNetworks: EVMNetwork[]
assetData: AssetDataHelper
private constructor(
private db: ChainDatabase,
private preferenceService: PreferenceService,
private internalSignerService: InternalSignerService,
) {
super({
queuedTransactions: {
schedule: {
delayInMinutes: 1,
periodInMinutes: 1,
},
handler: () => {
this.handleQueuedTransactionAlarm()
},
},
historicAssetTransfers: {
schedule: {
periodInMinutes: 60,
},
handler: () => {
this.handleHistoricAssetTransferAlarm()
},
runAtStart: false,
},
recentIncomingAssetTransfers: {
schedule: {
periodInMinutes: 1.5,
},
handler: () => {
this.handleRecentIncomingAssetTransferAlarm(true)
},
},
forceRecentAssetTransfers: {
schedule: {
periodInMinutes: (12 * HOUR) / MINUTE,
},
handler: () => {
this.handleRecentAssetTransferAlarm()
},
},
recentAssetTransfers: {
schedule: {
periodInMinutes: 15,
},
handler: () => {
this.handleRecentAssetTransferAlarm(true)
},
},
blockPrices: {
runAtStart: false,
schedule: {
periodInMinutes: GAS_POLLING_PERIOD,
},
handler: () => {
this.pollBlockPrices()
},
},
})
this.trackedNetworks = []
this.subscribedAccounts = []
this.subscribedNetworks = []
this.transactionsToRetrieve = []
this.assetData = new AssetDataHelper(this)
}
override async internalStartService(): Promise<void> {
await super.internalStartService()
await this.db.initialize()
await this.initializeNetworks()
const accounts = await this.getAccountsToTrack()
const trackedNetworks = await this.getTrackedNetworks()
const transactions = await this.db.getAllTransactions()
this.emitter.emit("initializeActivities", { transactions, accounts })
// get the latest blocks and subscribe for all active networks
Promise.allSettled(
accounts
.flatMap((an) => [
// subscribe to all account transactions
this.subscribeToAccountTransactions(an).catch((e) => {
logger.error(e)
}),
// do a base-asset balance check for every account
this.getLatestBaseAccountBalance(an).catch((e) => {
logger.error(e)
}),
])
.concat(
// Schedule any stored unconfirmed transactions for
// retrieval---either to confirm they no longer exist, or to
// read/monitor their status.
trackedNetworks.map((network) =>
this.db
.getNetworkPendingTransactions(network)
.then((pendingTransactions) => {
pendingTransactions.forEach(({ hash, firstSeen }) => {
logger.debug(
`Queuing pending transaction ${hash} for status lookup.`,
)
this.queueTransactionHashToRetrieve(network, hash, firstSeen)
})
})
.catch((e) => {
logger.error(e)
}),
),
),
)
}
async initializeNetworks(): Promise<void> {
const rpcUrls = await this.db.getAllRpcUrls()
const customRpcUrls = await this.db.getAllCustomRpcUrls()
await this.updateSupportedNetworks()
this.lastUserActivityOnNetwork =
Object.fromEntries(
this.supportedNetworks.map((network) => [network.chainID, 0]),
) || {}
this.providers = {
evm: Object.fromEntries(
this.supportedNetworks.map((network) => [
network.chainID,
makeSerialFallbackProvider(
network.chainID,
rpcUrls.find((v) => v.chainID === network.chainID)?.rpcUrls || [],
customRpcUrls.find((v) => v.chainID === network.chainID),
),
]),
),
}
}
/**
* Finds a provider for the given network, or returns undefined if no such
* provider exists.
*/
providerForNetwork(network: EVMNetwork): SerialFallbackProvider | undefined {
return isEnabled(FeatureFlags.USE_MAINNET_FORK)
? this.providers.evm[ETHEREUM.chainID]
: this.providers.evm[network.chainID]
}
async addCustomProvider(
chainID: string,
rpcUrl: string,
customProviderCreator: ProviderCreator,
): Promise<void> {
await this.db.addCustomRpcUrl(
chainID,
rpcUrl,
customProviderCreator.supportedMethods,
)
this.providers.evm[chainID]?.addCustomProvider(customProviderCreator)
}
async removeCustomProvider(chainID: string): Promise<void> {
await this.db.removeCustomRpcUrl(chainID)
this.providers.evm[chainID]?.removeCustomProvider()
}
/**
* Pulls the list of tracked networks from memory or indexedDB.
* Defaults to ethereum in the case that neither exist.
*/
async getTrackedNetworks(): Promise<EVMNetwork[]> {
if (this.trackedNetworks.length > 0) {
return this.trackedNetworks
}
// Since trackedNetworks will be an empty array at extension load (or reload time)
// we need a durable way to track which networks an extension is tracking.
// The below code should only be called once per extension reload for extensions
// with active accounts
const networksToTrack = await this.getNetworksToTrack()
await Promise.allSettled(
networksToTrack.map(async (network) =>
this.startTrackingNetworkOrThrow(network.chainID),
),
)
return this.trackedNetworks
}
private async subscribeToNetworkEvents(network: EVMNetwork): Promise<void> {
const provider = this.providerForNetwork(network)
if (provider) {
await Promise.allSettled([
this.fetchLatestBlockForNetwork(network),
this.subscribeToNewHeads(network),
])
} else {
logger.error(`Couldn't find provider for network ${network.name}`)
}
this.emitter.emit("networkSubscribed", network)
}
/**
* Adds a supported network to list of active networks.
*/
async startTrackingNetworkOrThrow(chainID: string): Promise<EVMNetwork> {
const trackedNetwork = this.trackedNetworks.find((network) =>
sameChainID(network.chainID, chainID),
)
if (trackedNetwork) {
logger.warn(
`${trackedNetwork.name} already being tracked - no need to activate it`,
)
return trackedNetwork
}
const networkToTrack = this.supportedNetworks.find((ntwrk) =>
sameChainID(ntwrk.chainID, chainID),
)
if (!networkToTrack) {
throw new Error(`Network with chainID ${chainID} is not supported`)
}
this.trackedNetworks.push(networkToTrack)
const existingSubscription = this.subscribedNetworks.find(
(networkSubscription) =>
networkSubscription.network.chainID === networkToTrack.chainID,
)
if (!existingSubscription) {
this.subscribeToNetworkEvents(networkToTrack)
const addressesToTrack = new Set(
(await this.getAccountsToTrack()).map((account) => account.address),
)
addressesToTrack.forEach((address) => {
this.addAccountToTrack({
address,
network: networkToTrack,
})
})
}
return networkToTrack
}
/**
* Finds a provider for the given network, or returns undefined if no such
* provider exists.
*/
providerForNetworkOrThrow(network: EVMNetwork): SerialFallbackProvider {
const provider = this.providerForNetwork(network)
if (!provider) {
logger.error(
"Request received for operation on an inactive network",
network,
"expected",
this.trackedNetworks,
)
throw new Error(
`Unexpected network ${network.name}, id: ${network.chainID}`,
)
}
return provider
}
/**
* Populates the provided partial legacy transaction request with all fields
* except the nonce. This leaves the transaction ready for user review, and
* the nonce ready to be filled in immediately prior to signing to minimize the
* likelihood for nonce reuse.
*
* Note that if the partial request already has a defined nonce, it is not
* cleared.
*/
private async populatePartialLegacyEVMTransactionRequest(
network: EVMNetwork,
partialRequest: EnrichedLegacyTransactionSignatureRequest,
): Promise<{
transactionRequest: EnrichedLegacyTransactionRequest
gasEstimationError: string | undefined
}> {
const {
from,
to,
value,
gasLimit,
input,
gasPrice,
nonce,
annotation,
broadcastOnSign,
} = partialRequest
// Basic transaction construction based on the provided options, with extra data from the chain service
const transactionRequest: EnrichedLegacyTransactionRequest = {
from,
to,
value: value ?? 0n,
gasLimit: gasLimit ?? 0n,
input: input ?? null,
// we know that a transactionRequest will fail with gasPrice 0
// and sometimes 3rd party api's (like 0x) may return transaction requests
// with gasPrice === 0, so we override the set gasPrice in those cases
gasPrice: gasPrice || (await this.estimateGasPrice(network)),
type: 0 as const,
network,
chainID: network.chainID,
nonce,
annotation,
estimatedRollupGwei:
network.chainID === OPTIMISM.chainID
? await this.estimateL1RollupGasPrice(network)
: 0n,
estimatedRollupFee: 0n,
broadcastOnSign,
}
if (network.chainID === OPTIMISM.chainID) {
transactionRequest.estimatedRollupFee =
await this.estimateL1RollupFeeForOptimism(
network,
unsignedTransactionFromEVMTransaction(transactionRequest),
)
}
// Always estimate gas to decide whether the transaction will likely fail.
let estimatedGasLimit: bigint | undefined
let gasEstimationError: string | undefined
try {
estimatedGasLimit = await this.estimateGasLimit(
network,
transactionRequest,
)
} catch (error) {
logger.error("Error estimating gas limit: ", error)
// Try to identify unpredictable gas errors to bubble that information
// out.
if (error instanceof Error) {
// Ethers does some heavily loose typing around errors to carry
// arbitrary info without subclassing Error, so an any cast is needed.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const anyError: any = error
if (
"code" in anyError &&
anyError.code === Logger.errors.UNPREDICTABLE_GAS_LIMIT
) {
gasEstimationError = anyError.error ?? "Unknown transaction error."
}
}
}
// We use the estimate as the actual limit only if user did not specify the
// gas explicitly or if it was set below the minimum network-allowed value.
if (
typeof estimatedGasLimit !== "undefined" &&
(typeof gasLimit === "undefined" || gasLimit < 21000n)
) {
transactionRequest.gasLimit = estimatedGasLimit
}
return { transactionRequest, gasEstimationError }
}
/**
* Populates the provided partial EIP1559 transaction request with all fields
* except the nonce. This leaves the transaction ready for user review, and
* the nonce ready to be filled in immediately prior to signing to minimize the
* likelihood for nonce reuse.
*
* Note that if the partial request already has a defined nonce, it is not
* cleared.
*/
private async populatePartialEIP1559TransactionRequest(
network: EVMNetwork,
partialRequest: EnrichedEIP1559TransactionSignatureRequest,
): Promise<{
transactionRequest: EnrichedEIP1559TransactionRequest
gasEstimationError: string | undefined
}> {
const {
from,
to,
value,
gasLimit,
input,
maxFeePerGas,
maxPriorityFeePerGas,
nonce,
annotation,
broadcastOnSign,
} = partialRequest
// Basic transaction construction based on the provided options, with extra data from the chain service
const transactionRequest: EnrichedEIP1559TransactionRequest = {
from,
to,
value: value ?? 0n,
gasLimit: gasLimit ?? 0n,
maxFeePerGas: maxFeePerGas ?? 0n,
maxPriorityFeePerGas: maxPriorityFeePerGas ?? 0n,
input: input ?? null,
type: 2 as const,
network,
chainID: network.chainID,
nonce,
annotation,
broadcastOnSign,
}
// Always estimate gas to decide whether the transaction will likely fail.
let estimatedGasLimit: bigint | undefined
let gasEstimationError: string | undefined
try {
estimatedGasLimit = await this.estimateGasLimit(
network,
transactionRequest,
)
} catch (error) {
// Try to identify unpredictable gas errors to bubble that information
// out.
if (error instanceof Error) {
// Ethers does some heavily loose typing around errors to carry
// arbitrary info without subclassing Error, so an any cast is needed.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const anyError: any = error
if (
"code" in anyError &&
anyError.code === Logger.errors.UNPREDICTABLE_GAS_LIMIT
) {
gasEstimationError = anyError.error ?? "Unknown transaction error."
}
}
}
// We use the estimate as the actual limit only if user did not specify the
// gas explicitly or if it was set below the minimum network-allowed value.
if (
typeof estimatedGasLimit !== "undefined" &&
(typeof partialRequest.gasLimit === "undefined" ||
partialRequest.gasLimit < 21000n)
) {
transactionRequest.gasLimit = estimatedGasLimit
}
return { transactionRequest, gasEstimationError }
}
async populatePartialTransactionRequest(
network: EVMNetwork,
partialRequest: EnrichedEVMTransactionSignatureRequest,
defaults: { maxFeePerGas: bigint; maxPriorityFeePerGas: bigint },
): Promise<{
transactionRequest: EnrichedEVMTransactionRequest
gasEstimationError: string | undefined
}> {
if (EIP_1559_COMPLIANT_CHAIN_IDS.has(network.chainID)) {
const {
maxFeePerGas = defaults.maxFeePerGas,
maxPriorityFeePerGas = defaults.maxPriorityFeePerGas,
} = partialRequest as EnrichedEIP1559TransactionSignatureRequest
const populated = await this.populatePartialEIP1559TransactionRequest(
network,
{
...(partialRequest as EnrichedEIP1559TransactionSignatureRequest),
maxFeePerGas,
maxPriorityFeePerGas,
},
)
return populated
}
// Legacy Transaction
const populated = await this.populatePartialLegacyEVMTransactionRequest(
network,
{
...(partialRequest as EnrichedLegacyTransactionRequest),
},
)
return populated
}
/**
* Populates the nonce for the passed EIP1559TransactionRequest, provided
* that it is not yet populated. This process generates a new nonce based on
* the known on-chain nonce state of the service, attempting to ensure that
* the nonce will be unique and an increase by 1 over any other confirmed or
* pending nonces in the mempool.
*
* Returns the transaction request with a guaranteed-defined nonce, suitable
* for signing by a signer.
*/
async populateEVMTransactionNonce(
transactionRequest: TransactionRequest,
): Promise<TransactionRequestWithNonce> {
if (typeof transactionRequest.nonce !== "undefined") {
// TS undefined checks don't narrow the containing object's type, so we
// have to cast `as` here.
return transactionRequest as EIP1559TransactionRequest & { nonce: number }
}
const { network, chainID } = transactionRequest
const normalizedAddress = normalizeEVMAddress(transactionRequest.from)
const provider = this.providerForNetworkOrThrow(network)
// https://docs.ethers.io/v5/single-page/#/v5/api/providers/provider/-%23-Provider-getTransactionCount
const chainTransactionCount = await provider.getTransactionCount(
transactionRequest.from,
"latest",
)
let knownNextNonce
// existingNonce handling only needed when there is a chance for it to
// be different from the onchain nonce. This can happen when a chain has
// mempool. Note: This does not necessarily mean that the chain is EIP-1559
// compliant.
if (CHAINS_WITH_MEMPOOL.has(chainID)) {
// @TODO: Update this implementation to handle pending txs and also be more
// resilient against missing nonce in the mempool.
const chainNonce = chainTransactionCount - 1
const existingNonce =
this.evmChainLastSeenNoncesByNormalizedAddress[chainID]?.[
normalizedAddress
] ?? chainNonce
this.evmChainLastSeenNoncesByNormalizedAddress[chainID] ??= {}
// Use the network count, if needed. Note that the assumption here is that
// all nonces for this address are increasing linearly and continuously; if
// the address has a pending transaction floating around with a nonce that
// is not an increase by one over previous transactions, this approach will
// allocate more nonces that won't mine.
this.evmChainLastSeenNoncesByNormalizedAddress[chainID][
normalizedAddress
] = Math.max(existingNonce, chainNonce)
// Allocate a new nonce by incrementing the last seen one.
this.evmChainLastSeenNoncesByNormalizedAddress[chainID][
normalizedAddress
] += 1
knownNextNonce =
this.evmChainLastSeenNoncesByNormalizedAddress[chainID][
normalizedAddress
]
logger.debug(
"Got chain nonce",
chainNonce,
"existing nonce",
existingNonce,
"using",
knownNextNonce,
)
}
return {
...transactionRequest,
nonce: knownNextNonce ?? chainTransactionCount,
}
}
/**
* Releases the specified nonce for the given network and address. This
* updates internal service state to allow that nonce to be reused. In cases
* where multiple nonces were seen in a row, this will make internally
* available for reuse all intervening nonces.
*/
releaseEVMTransactionNonce(
transactionRequest:
| TransactionRequestWithNonce
| SignedTransaction
| AnyEVMTransaction,
): void {
const chainID =
"chainID" in transactionRequest
? transactionRequest.chainID
: transactionRequest.network.chainID
if (CHAINS_WITH_MEMPOOL.has(chainID)) {
const { nonce } = transactionRequest
const normalizedAddress = normalizeEVMAddress(transactionRequest.from)
if (
!this.evmChainLastSeenNoncesByNormalizedAddress[chainID]?.[
normalizedAddress
]
) {
return
}
const lastSeenNonce =
this.evmChainLastSeenNoncesByNormalizedAddress[chainID][
normalizedAddress
]
// TODO Currently this assumes that the only place this nonce could have
// TODO been used is this service; however, another wallet or service
// TODO could have broadcast a transaction with this same nonce, in which
// TODO case the nonce release shouldn't take effect! This should be a
// TODO relatively rare edge case, but we should handle it at some point.
if (nonce === lastSeenNonce) {
this.evmChainLastSeenNoncesByNormalizedAddress[chainID][
normalizedAddress
] -= 1
} else if (nonce < lastSeenNonce) {
// If the nonce we're releasing is below the latest allocated nonce,
// release all intervening nonces. This risks transaction replacement
// issues, but ensures that we don't start allocating nonces that will
// never mine (because they will all be higher than the
// now-released-and-therefore-never-broadcast nonce).
this.evmChainLastSeenNoncesByNormalizedAddress[chainID][
normalizedAddress
] = nonce - 1
}
}
}
async getAccountsToTrack(
onlyActiveAccounts = false,
): Promise<AddressOnNetwork[]> {
const accounts = await this.db.getAccountsToTrack()
if (onlyActiveAccounts) {
return accounts.filter(
({ address, network }) =>
this.isCurrentlyActiveAddress(address) &&
this.isCurrentlyActiveChainID(network.chainID),
)
}
return accounts
}
async getTrackedAddressesOnNetwork(
network: EVMNetwork,
): Promise<AddressOnNetwork[]> {
return this.db.getTrackedAddressesOnNetwork(network)
}
async getNetworksToTrack(): Promise<EVMNetwork[]> {
const chainIDs = await this.db.getChainIDsToTrack()
if (chainIDs.size === 0) {
// Ethereum - default to tracking Ethereum so ENS resolution works during onboarding
// Arbitrum Sepolia - default to tracking so we can support Island Dapp
if (isEnabled(FeatureFlags.SUPPORT_THE_ISLAND)) {
return [ETHEREUM, ISLAND_NETWORK]
}
return [ETHEREUM]
}
if (isEnabled(FeatureFlags.SUPPORT_THE_ISLAND)) {
chainIDs.add(ISLAND_NETWORK.chainID)
}
const networks = await Promise.all(
[...chainIDs].map(async (chainID) => {
const network = NETWORK_BY_CHAIN_ID[chainID]
if (!network) {
return this.db.getEVMNetworkByChainID(chainID)
}
return network
}),
)
return networks.filter((network): network is EVMNetwork => !!network)
}
async removeAccountToTrack(address: string): Promise<void> {
await this.db.removeAccountToTrack(address)
}
async getLatestBaseAccountBalance({
address,
network,
}: AddressOnNetwork): Promise<AccountBalance> {
const normalizedAddress = normalizeEVMAddress(address)
const balance =
await this.providerForNetworkOrThrow(network).getBalance(
normalizedAddress,
)
const trackedAccounts = await this.getAccountsToTrack()
const allTrackedAddresses = new Set(
trackedAccounts.map((account) => account.address),
)
const accountBalance: AccountBalance = {
address: normalizedAddress,
network,
assetAmount: {
// Data stored in chain db for network base asset might be stale
asset: await this.db.getBaseAssetForNetwork(network.chainID),
amount: balance.toBigInt(),
},
dataSource: "alchemy", // TODO do this properly (eg provider isn't Alchemy)
retrievedAt: Date.now(),
}
// Don't emit or save if the account isn't tracked
if (allTrackedAddresses.has(normalizedAddress)) {
this.emitter.emit("accountsWithBalances", {
balances: [accountBalance],
addressOnNetwork: {
address: normalizedAddress,
network,
},
})
await this.db.addBalance(accountBalance)
}
return accountBalance
}
async addAccountToTrack(addressNetwork: AddressOnNetwork): Promise<void> {
const source = this.internalSignerService.getSignerSourceForAddress(
addressNetwork.address,
)
const isAccountOnNetworkAlreadyTracked =
await this.db.getTrackedAccountOnNetwork(addressNetwork)
if (!isAccountOnNetworkAlreadyTracked) {
// Skip save, emit and savedTransaction emission on resubmission
await this.db.addAccountToTrack(addressNetwork)
this.emitter.emit("newAccountToTrack", addressNetwork)
}
this.emitSavedTransactions(addressNetwork)
this.subscribeToAccountTransactions(addressNetwork).catch((e) => {
logger.error(
"chainService/addAccountToTrack: Error subscribing to account transactions",
e,
)
})
this.getLatestBaseAccountBalance(addressNetwork).catch((e) => {
logger.error(
"chainService/addAccountToTrack: Error getting latestBaseAccountBalance",
e,
)
})
if (source !== SignerImportSource.internal) {
this.loadHistoricAssetTransfers(addressNetwork).catch((e) => {
logger.error(
"chainService/addAccountToTrack: Error loading historic asset transfers",
e,
)
})
}
}
async getBlockHeight(network: EVMNetwork): Promise<number> {
const cachedBlock = await this.db.getLatestBlock(network)