@aztec/ethereum 0.0.0-test.1 → 0.0.1-commit.017a351
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/dest/account.d.ts +2 -0
- package/dest/account.d.ts.map +1 -0
- package/dest/account.js +4 -0
- package/dest/chain.d.ts +1 -1
- package/dest/client.d.ts +28 -4
- package/dest/client.d.ts.map +1 -1
- package/dest/client.js +73 -3
- package/dest/config.d.ts +70 -23
- package/dest/config.d.ts.map +1 -1
- package/dest/config.js +151 -34
- package/dest/constants.d.ts +1 -1
- package/dest/contracts/chain_state_override.d.ts +78 -0
- package/dest/contracts/chain_state_override.d.ts.map +1 -0
- package/dest/contracts/chain_state_override.js +137 -0
- package/dest/contracts/empire_base.d.ts +25 -8
- package/dest/contracts/empire_base.d.ts.map +1 -1
- package/dest/contracts/empire_base.js +75 -2
- package/dest/contracts/errors.d.ts +7 -0
- package/dest/contracts/errors.d.ts.map +1 -0
- package/dest/contracts/errors.js +12 -0
- package/dest/contracts/fee_asset_handler.d.ts +20 -0
- package/dest/contracts/fee_asset_handler.d.ts.map +1 -0
- package/dest/contracts/fee_asset_handler.js +59 -0
- package/dest/contracts/fee_asset_price_oracle.d.ts +105 -0
- package/dest/contracts/fee_asset_price_oracle.d.ts.map +1 -0
- package/dest/contracts/fee_asset_price_oracle.js +656 -0
- package/dest/contracts/fee_juice.d.ts +6 -7
- package/dest/contracts/fee_juice.d.ts.map +1 -1
- package/dest/contracts/fee_juice.js +27 -20
- package/dest/contracts/governance.d.ts +131 -43
- package/dest/contracts/governance.d.ts.map +1 -1
- package/dest/contracts/governance.js +281 -87
- package/dest/contracts/governance_proposer.d.ts +49 -13
- package/dest/contracts/governance_proposer.d.ts.map +1 -1
- package/dest/contracts/governance_proposer.js +483 -26
- package/dest/contracts/gse.d.ts +32 -0
- package/dest/contracts/gse.d.ts.map +1 -0
- package/dest/contracts/gse.js +72 -0
- package/dest/contracts/inbox.d.ts +47 -0
- package/dest/contracts/inbox.d.ts.map +1 -0
- package/dest/contracts/inbox.js +85 -0
- package/dest/contracts/index.d.ts +11 -2
- package/dest/contracts/index.d.ts.map +1 -1
- package/dest/contracts/index.js +10 -1
- package/dest/contracts/log.d.ts +13 -0
- package/dest/contracts/log.d.ts.map +1 -0
- package/dest/contracts/log.js +1 -0
- package/dest/contracts/multicall.d.ts +136 -0
- package/dest/contracts/multicall.d.ts.map +1 -0
- package/dest/contracts/multicall.js +264 -0
- package/dest/contracts/outbox.d.ts +64 -0
- package/dest/contracts/outbox.d.ts.map +1 -0
- package/dest/contracts/outbox.js +113 -0
- package/dest/contracts/registry.d.ts +12 -5
- package/dest/contracts/registry.d.ts.map +1 -1
- package/dest/contracts/registry.js +74 -17
- package/dest/contracts/rollup.d.ts +5526 -52
- package/dest/contracts/rollup.d.ts.map +1 -1
- package/dest/contracts/rollup.js +1446 -118
- package/dest/contracts/slasher_contract.d.ts +44 -0
- package/dest/contracts/slasher_contract.d.ts.map +1 -0
- package/dest/contracts/slasher_contract.js +75 -0
- package/dest/contracts/slashing_proposer.d.ts +133 -15
- package/dest/contracts/slashing_proposer.d.ts.map +1 -1
- package/dest/contracts/slashing_proposer.js +293 -22
- package/dest/contracts/utils.d.ts +3 -0
- package/dest/contracts/utils.d.ts.map +1 -0
- package/dest/contracts/utils.js +11 -0
- package/dest/deploy_aztec_l1_contracts.d.ts +256 -0
- package/dest/deploy_aztec_l1_contracts.d.ts.map +1 -0
- package/dest/deploy_aztec_l1_contracts.js +411 -0
- package/dest/deploy_l1_contract.d.ts +68 -0
- package/dest/deploy_l1_contract.d.ts.map +1 -0
- package/dest/deploy_l1_contract.js +312 -0
- package/dest/eth-signer/eth-signer.d.ts +21 -0
- package/dest/eth-signer/eth-signer.d.ts.map +1 -0
- package/dest/eth-signer/eth-signer.js +5 -0
- package/dest/eth-signer/index.d.ts +2 -0
- package/dest/eth-signer/index.d.ts.map +1 -0
- package/dest/eth-signer/index.js +1 -0
- package/dest/forwarder_proxy.d.ts +32 -0
- package/dest/forwarder_proxy.d.ts.map +1 -0
- package/dest/forwarder_proxy.js +93 -0
- package/dest/generated/l1-contracts-defaults.d.ts +30 -0
- package/dest/generated/l1-contracts-defaults.d.ts.map +1 -0
- package/dest/generated/l1-contracts-defaults.js +30 -0
- package/dest/l1_artifacts.d.ts +79270 -0
- package/dest/l1_artifacts.d.ts.map +1 -0
- package/dest/l1_artifacts.js +151 -0
- package/dest/l1_contract_addresses.d.ts +61 -45
- package/dest/l1_contract_addresses.d.ts.map +1 -1
- package/dest/l1_contract_addresses.js +99 -76
- package/dest/l1_reader.d.ts +8 -6
- package/dest/l1_reader.d.ts.map +1 -1
- package/dest/l1_reader.js +20 -12
- package/dest/l1_tx_utils/config.d.ts +65 -0
- package/dest/l1_tx_utils/config.d.ts.map +1 -0
- package/dest/l1_tx_utils/config.js +109 -0
- package/dest/l1_tx_utils/constants.d.ts +12 -0
- package/dest/l1_tx_utils/constants.d.ts.map +1 -0
- package/dest/l1_tx_utils/constants.js +39 -0
- package/dest/l1_tx_utils/factory.d.ts +32 -0
- package/dest/l1_tx_utils/factory.d.ts.map +1 -0
- package/dest/l1_tx_utils/factory.js +22 -0
- package/dest/l1_tx_utils/fee-strategies/index.d.ts +10 -0
- package/dest/l1_tx_utils/fee-strategies/index.d.ts.map +1 -0
- package/dest/l1_tx_utils/fee-strategies/index.js +12 -0
- package/dest/l1_tx_utils/fee-strategies/p75_competitive.d.ts +8 -0
- package/dest/l1_tx_utils/fee-strategies/p75_competitive.d.ts.map +1 -0
- package/dest/l1_tx_utils/fee-strategies/p75_competitive.js +129 -0
- package/dest/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.d.ts +23 -0
- package/dest/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.d.ts.map +1 -0
- package/dest/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.js +191 -0
- package/dest/l1_tx_utils/fee-strategies/types.d.ts +51 -0
- package/dest/l1_tx_utils/fee-strategies/types.d.ts.map +1 -0
- package/dest/l1_tx_utils/fee-strategies/types.js +3 -0
- package/dest/l1_tx_utils/forwarder_l1_tx_utils.d.ts +41 -0
- package/dest/l1_tx_utils/forwarder_l1_tx_utils.d.ts.map +1 -0
- package/dest/l1_tx_utils/forwarder_l1_tx_utils.js +42 -0
- package/dest/l1_tx_utils/index-blobs.d.ts +3 -0
- package/dest/l1_tx_utils/index-blobs.d.ts.map +1 -0
- package/dest/l1_tx_utils/index-blobs.js +2 -0
- package/dest/l1_tx_utils/index.d.ts +13 -0
- package/dest/l1_tx_utils/index.d.ts.map +1 -0
- package/dest/l1_tx_utils/index.js +13 -0
- package/dest/l1_tx_utils/interfaces.d.ts +76 -0
- package/dest/l1_tx_utils/interfaces.d.ts.map +1 -0
- package/dest/l1_tx_utils/interfaces.js +4 -0
- package/dest/l1_tx_utils/l1_fee_analyzer.d.ts +233 -0
- package/dest/l1_tx_utils/l1_fee_analyzer.d.ts.map +1 -0
- package/dest/l1_tx_utils/l1_fee_analyzer.js +506 -0
- package/dest/l1_tx_utils/l1_tx_utils.d.ts +113 -0
- package/dest/l1_tx_utils/l1_tx_utils.d.ts.map +1 -0
- package/dest/l1_tx_utils/l1_tx_utils.js +658 -0
- package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts +83 -0
- package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts.map +1 -0
- package/dest/l1_tx_utils/readonly_l1_tx_utils.js +328 -0
- package/dest/l1_tx_utils/signer.d.ts +4 -0
- package/dest/l1_tx_utils/signer.d.ts.map +1 -0
- package/dest/l1_tx_utils/signer.js +16 -0
- package/dest/l1_tx_utils/tx_delayer.d.ts +58 -0
- package/dest/l1_tx_utils/tx_delayer.d.ts.map +1 -0
- package/dest/l1_tx_utils/tx_delayer.js +223 -0
- package/dest/l1_tx_utils/types.d.ts +67 -0
- package/dest/l1_tx_utils/types.d.ts.map +1 -0
- package/dest/l1_tx_utils/types.js +26 -0
- package/dest/l1_tx_utils/utils.d.ts +4 -0
- package/dest/l1_tx_utils/utils.d.ts.map +1 -0
- package/dest/l1_tx_utils/utils.js +14 -0
- package/dest/l1_types.d.ts +6 -0
- package/dest/l1_types.d.ts.map +1 -0
- package/dest/l1_types.js +1 -0
- package/dest/publisher_manager.d.ts +30 -0
- package/dest/publisher_manager.d.ts.map +1 -0
- package/dest/publisher_manager.js +162 -0
- package/dest/queries.d.ts +17 -4
- package/dest/queries.d.ts.map +1 -1
- package/dest/queries.js +120 -12
- package/dest/test/chain_monitor.d.ts +95 -0
- package/dest/test/chain_monitor.d.ts.map +1 -0
- package/dest/test/chain_monitor.js +249 -0
- package/dest/test/eth_cheat_codes.d.ts +237 -0
- package/dest/test/eth_cheat_codes.d.ts.map +1 -0
- package/dest/test/eth_cheat_codes.js +573 -0
- package/dest/test/eth_cheat_codes_with_state.d.ts +2 -2
- package/dest/test/eth_cheat_codes_with_state.d.ts.map +1 -1
- package/dest/test/eth_cheat_codes_with_state.js +1 -1
- package/dest/test/index.d.ts +4 -3
- package/dest/test/index.d.ts.map +1 -1
- package/dest/test/index.js +3 -2
- package/dest/test/rollup_cheat_codes.d.ts +118 -0
- package/dest/test/rollup_cheat_codes.d.ts.map +1 -0
- package/dest/test/rollup_cheat_codes.js +344 -0
- package/dest/test/start_anvil.d.ts +30 -2
- package/dest/test/start_anvil.d.ts.map +1 -1
- package/dest/test/start_anvil.js +147 -24
- package/dest/test/upgrade_utils.d.ts +6 -5
- package/dest/test/upgrade_utils.d.ts.map +1 -1
- package/dest/test/upgrade_utils.js +23 -16
- package/dest/types.d.ts +62 -8
- package/dest/types.d.ts.map +1 -1
- package/dest/types.js +3 -1
- package/dest/utils.d.ts +25 -4
- package/dest/utils.d.ts.map +1 -1
- package/dest/utils.js +142 -91
- package/dest/zkPassportVerifierAddress.d.ts +15 -0
- package/dest/zkPassportVerifierAddress.d.ts.map +1 -0
- package/dest/zkPassportVerifierAddress.js +11 -0
- package/package.json +52 -26
- package/src/account.ts +5 -0
- package/src/client.ts +107 -5
- package/src/config.ts +218 -43
- package/src/contracts/README.md +157 -0
- package/src/contracts/chain_state_override.ts +200 -0
- package/src/contracts/empire_base.ts +77 -7
- package/src/contracts/errors.ts +13 -0
- package/src/contracts/fee_asset_handler.ts +66 -0
- package/src/contracts/fee_asset_price_oracle.ts +285 -0
- package/src/contracts/fee_juice.ts +29 -15
- package/src/contracts/governance.ts +343 -74
- package/src/contracts/governance_proposer.ts +128 -25
- package/src/contracts/gse.ts +88 -0
- package/src/contracts/inbox.ts +123 -0
- package/src/contracts/index.ts +10 -1
- package/src/contracts/log.ts +13 -0
- package/src/contracts/multicall.ts +296 -0
- package/src/contracts/outbox.ts +132 -0
- package/src/contracts/registry.ts +81 -26
- package/src/contracts/rollup.ts +1246 -90
- package/src/contracts/slasher_contract.ts +89 -0
- package/src/contracts/slashing_proposer.ts +296 -27
- package/src/contracts/utils.ts +14 -0
- package/src/deploy_aztec_l1_contracts.ts +646 -0
- package/src/deploy_l1_contract.ts +362 -0
- package/src/eth-signer/eth-signer.ts +25 -0
- package/src/eth-signer/index.ts +1 -0
- package/src/forwarder_proxy.ts +108 -0
- package/src/generated/l1-contracts-defaults.ts +32 -0
- package/src/l1_artifacts.ts +231 -0
- package/src/l1_contract_addresses.ts +121 -80
- package/src/l1_reader.ts +31 -16
- package/src/l1_tx_utils/README.md +177 -0
- package/src/l1_tx_utils/config.ts +181 -0
- package/src/l1_tx_utils/constants.ts +29 -0
- package/src/l1_tx_utils/factory.ts +64 -0
- package/src/l1_tx_utils/fee-strategies/index.ts +22 -0
- package/src/l1_tx_utils/fee-strategies/p75_competitive.ts +163 -0
- package/src/l1_tx_utils/fee-strategies/p75_competitive_blob_txs_only.ts +245 -0
- package/src/l1_tx_utils/fee-strategies/types.ts +56 -0
- package/src/l1_tx_utils/forwarder_l1_tx_utils.ts +108 -0
- package/src/l1_tx_utils/index-blobs.ts +2 -0
- package/src/l1_tx_utils/index.ts +15 -0
- package/src/l1_tx_utils/interfaces.ts +86 -0
- package/src/l1_tx_utils/l1_fee_analyzer.ts +803 -0
- package/src/l1_tx_utils/l1_tx_utils.ts +789 -0
- package/src/l1_tx_utils/readonly_l1_tx_utils.ts +424 -0
- package/src/l1_tx_utils/signer.ts +28 -0
- package/src/l1_tx_utils/tx_delayer.ts +303 -0
- package/src/l1_tx_utils/types.ts +85 -0
- package/src/l1_tx_utils/utils.ts +16 -0
- package/src/l1_types.ts +6 -0
- package/src/publisher_manager.ts +203 -0
- package/src/queries.ts +149 -17
- package/src/test/chain_monitor.ts +307 -0
- package/src/test/eth_cheat_codes.ts +600 -0
- package/src/test/eth_cheat_codes_with_state.ts +1 -1
- package/src/test/index.ts +3 -2
- package/src/test/rollup_cheat_codes.ts +388 -0
- package/src/test/start_anvil.ts +189 -22
- package/src/test/upgrade_utils.ts +30 -21
- package/src/types.ts +71 -7
- package/src/utils.ts +164 -96
- package/src/zkPassportVerifierAddress.ts +15 -0
- package/dest/contracts/forwarder.d.ts +0 -24
- package/dest/contracts/forwarder.d.ts.map +0 -1
- package/dest/contracts/forwarder.js +0 -101
- package/dest/deploy_l1_contracts.d.ts +0 -21210
- package/dest/deploy_l1_contracts.d.ts.map +0 -1
- package/dest/deploy_l1_contracts.js +0 -687
- package/dest/eth_cheat_codes.d.ts +0 -147
- package/dest/eth_cheat_codes.d.ts.map +0 -1
- package/dest/eth_cheat_codes.js +0 -303
- package/dest/index.d.ts +0 -14
- package/dest/index.d.ts.map +0 -1
- package/dest/index.js +0 -13
- package/dest/l1_tx_utils.d.ts +0 -192
- package/dest/l1_tx_utils.d.ts.map +0 -1
- package/dest/l1_tx_utils.js +0 -641
- package/dest/l1_tx_utils_with_blobs.d.ts +0 -12
- package/dest/l1_tx_utils_with_blobs.d.ts.map +0 -1
- package/dest/l1_tx_utils_with_blobs.js +0 -64
- package/dest/test/delayed_tx_utils.d.ts +0 -8
- package/dest/test/delayed_tx_utils.d.ts.map +0 -1
- package/dest/test/delayed_tx_utils.js +0 -21
- package/dest/test/tx_delayer.d.ts +0 -25
- package/dest/test/tx_delayer.d.ts.map +0 -1
- package/dest/test/tx_delayer.js +0 -116
- package/src/contracts/forwarder.ts +0 -132
- package/src/deploy_l1_contracts.ts +0 -948
- package/src/eth_cheat_codes.ts +0 -314
- package/src/index.ts +0 -13
- package/src/l1_tx_utils.ts +0 -847
- package/src/l1_tx_utils_with_blobs.ts +0 -86
- package/src/test/delayed_tx_utils.ts +0 -24
- package/src/test/tx_delayer.ts +0 -163
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
import { omit } from '@aztec/foundation/collection';
|
|
2
|
+
import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
|
|
3
|
+
import { retryUntil } from '@aztec/foundation/retry';
|
|
4
|
+
import type { DateProvider } from '@aztec/foundation/timer';
|
|
5
|
+
|
|
6
|
+
import { inspect } from 'util';
|
|
7
|
+
import {
|
|
8
|
+
type Client,
|
|
9
|
+
type Hex,
|
|
10
|
+
type PublicClient,
|
|
11
|
+
type TransactionSerializableEIP4844,
|
|
12
|
+
type TransactionSerialized,
|
|
13
|
+
keccak256,
|
|
14
|
+
parseTransaction,
|
|
15
|
+
publicActions,
|
|
16
|
+
recoverTransactionAddress,
|
|
17
|
+
serializeTransaction,
|
|
18
|
+
walletActions,
|
|
19
|
+
} from 'viem';
|
|
20
|
+
|
|
21
|
+
import type { ExtendedViemWalletClient, ViemClient } from '../types.js';
|
|
22
|
+
|
|
23
|
+
const MAX_WAIT_TIME_SECONDS = 180;
|
|
24
|
+
|
|
25
|
+
export function waitUntilBlock<T extends Client>(
|
|
26
|
+
client: T,
|
|
27
|
+
blockNumber: number | bigint,
|
|
28
|
+
logger?: Logger,
|
|
29
|
+
timeout?: number,
|
|
30
|
+
) {
|
|
31
|
+
const publicClient =
|
|
32
|
+
'getBlockNumber' in client && typeof client.getBlockNumber === 'function'
|
|
33
|
+
? (client as unknown as PublicClient)
|
|
34
|
+
: client.extend(publicActions);
|
|
35
|
+
|
|
36
|
+
return retryUntil(
|
|
37
|
+
async () => {
|
|
38
|
+
const currentBlockNumber = await publicClient.getBlockNumber({ cacheTime: 0 });
|
|
39
|
+
logger?.debug(`Block number is ${currentBlockNumber} (waiting until ${blockNumber})`);
|
|
40
|
+
return currentBlockNumber >= BigInt(blockNumber);
|
|
41
|
+
},
|
|
42
|
+
`Wait until L1 block ${blockNumber}`,
|
|
43
|
+
timeout ?? MAX_WAIT_TIME_SECONDS,
|
|
44
|
+
0.1,
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function waitUntilL1Timestamp<T extends Client>(
|
|
49
|
+
client: T,
|
|
50
|
+
timestamp: number | bigint,
|
|
51
|
+
logger?: Logger,
|
|
52
|
+
timeout?: number,
|
|
53
|
+
) {
|
|
54
|
+
const publicClient =
|
|
55
|
+
'getBlockNumber' in client && typeof client.getBlockNumber === 'function'
|
|
56
|
+
? (client as unknown as PublicClient)
|
|
57
|
+
: client.extend(publicActions);
|
|
58
|
+
|
|
59
|
+
let lastBlock: bigint | undefined = undefined;
|
|
60
|
+
return retryUntil(
|
|
61
|
+
async () => {
|
|
62
|
+
const currentBlockNumber = await publicClient.getBlockNumber({ cacheTime: 0 });
|
|
63
|
+
if (currentBlockNumber === lastBlock) {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
lastBlock = currentBlockNumber;
|
|
67
|
+
const currentBlock = await publicClient.getBlock({ includeTransactions: false, blockNumber: currentBlockNumber });
|
|
68
|
+
const currentTs = currentBlock.timestamp;
|
|
69
|
+
logger?.debug(`Block timstamp is ${currentTs} (waiting until ${timestamp})`);
|
|
70
|
+
return currentTs >= BigInt(timestamp);
|
|
71
|
+
},
|
|
72
|
+
`Wait until L1 timestamp ${timestamp}`,
|
|
73
|
+
timeout ?? MAX_WAIT_TIME_SECONDS,
|
|
74
|
+
0.1,
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Manages tx delaying for testing, intercepting sendRawTransaction calls to delay or cancel them. */
|
|
79
|
+
export class Delayer {
|
|
80
|
+
private logger: Logger;
|
|
81
|
+
|
|
82
|
+
public maxInclusionTimeIntoSlot: number | undefined = undefined;
|
|
83
|
+
public ethereumSlotDuration: bigint;
|
|
84
|
+
public nextWait:
|
|
85
|
+
| { l1Timestamp: bigint; timeoutSeconds?: number }
|
|
86
|
+
| { l1BlockNumber: bigint; timeoutSeconds?: number }
|
|
87
|
+
| { indefinitely: true }
|
|
88
|
+
| undefined = undefined;
|
|
89
|
+
public sentTxHashes: Hex[] = [];
|
|
90
|
+
public cancelledTxs: Hex[] = [];
|
|
91
|
+
|
|
92
|
+
constructor(
|
|
93
|
+
public dateProvider: DateProvider,
|
|
94
|
+
opts: { ethereumSlotDuration: bigint | number },
|
|
95
|
+
bindings: LoggerBindings,
|
|
96
|
+
) {
|
|
97
|
+
this.ethereumSlotDuration = BigInt(opts.ethereumSlotDuration);
|
|
98
|
+
this.logger = createLogger('ethereum:tx_delayer', bindings);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Returns the logger instance used by this delayer. */
|
|
102
|
+
getLogger(): Logger {
|
|
103
|
+
return this.logger;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Returns the hashes of all effectively sent txs. */
|
|
107
|
+
getSentTxHashes() {
|
|
108
|
+
return this.sentTxHashes;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Returns the raw hex for all cancelled txs. */
|
|
112
|
+
getCancelledTxs(): Hex[] {
|
|
113
|
+
return this.cancelledTxs;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Delays the next tx to be sent so it lands on the given L1 block number. */
|
|
117
|
+
pauseNextTxUntilBlock(l1BlockNumber: number | bigint, timeoutSeconds?: number) {
|
|
118
|
+
this.nextWait = { l1BlockNumber: BigInt(l1BlockNumber), timeoutSeconds };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Delays the next tx to be sent so it lands on the given timestamp. */
|
|
122
|
+
pauseNextTxUntilTimestamp(l1Timestamp: number | bigint, timeoutSeconds?: number) {
|
|
123
|
+
this.nextWait = { l1Timestamp: BigInt(l1Timestamp), timeoutSeconds };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Delays the next tx to be sent indefinitely. */
|
|
127
|
+
cancelNextTx() {
|
|
128
|
+
this.nextWait = { indefinitely: true };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Sets max inclusion time into slot. If more than this many seconds have passed
|
|
133
|
+
* since the last L1 block was mined, then any tx will not be mined in the current
|
|
134
|
+
* L1 slot but will be deferred for the next one.
|
|
135
|
+
*/
|
|
136
|
+
setMaxInclusionTimeIntoSlot(seconds: number | undefined) {
|
|
137
|
+
this.maxInclusionTimeIntoSlot = seconds;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Creates a new Delayer instance. Exposed so callers can create a single shared delayer
|
|
143
|
+
* and pass it to multiple `wrapClientWithDelayer` calls.
|
|
144
|
+
*/
|
|
145
|
+
export function createDelayer(
|
|
146
|
+
dateProvider: DateProvider,
|
|
147
|
+
opts: { ethereumSlotDuration: bigint | number },
|
|
148
|
+
bindings: LoggerBindings,
|
|
149
|
+
): Delayer {
|
|
150
|
+
return new Delayer(dateProvider, opts, bindings);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Tries to recover the sender address from a serialized signed transaction. */
|
|
154
|
+
async function tryRecoverSender(serializedTransaction: Hex): Promise<string | undefined> {
|
|
155
|
+
try {
|
|
156
|
+
return await recoverTransactionAddress({
|
|
157
|
+
serializedTransaction: serializedTransaction as TransactionSerialized,
|
|
158
|
+
});
|
|
159
|
+
} catch {
|
|
160
|
+
return undefined;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Wraps a viem client with tx delaying logic. Returns the wrapped client.
|
|
166
|
+
* The delayer intercepts sendRawTransaction calls and delays them based on the delayer's state.
|
|
167
|
+
*/
|
|
168
|
+
export function wrapClientWithDelayer<T extends ViemClient>(client: T, delayer: Delayer): T {
|
|
169
|
+
const logger = delayer.getLogger();
|
|
170
|
+
|
|
171
|
+
// Cast to ExtendedViemWalletClient for the extend chain since it has sendRawTransaction.
|
|
172
|
+
// The sendRawTransaction override is applied to all clients regardless of type.
|
|
173
|
+
const withRawTx = (client as unknown as ExtendedViemWalletClient)
|
|
174
|
+
// Tweak sendRawTransaction so it uses the delay defined in the delayer.
|
|
175
|
+
// Note that this will only work with local accounts (ie accounts for which we have the private key).
|
|
176
|
+
// Transactions signed by the node will not be delayed since they use sendTransaction directly,
|
|
177
|
+
// but we do not use them in our codebase at all.
|
|
178
|
+
.extend(client => ({
|
|
179
|
+
async sendRawTransaction(...args) {
|
|
180
|
+
let wait: Promise<unknown> | undefined;
|
|
181
|
+
let txHash: Hex | undefined;
|
|
182
|
+
|
|
183
|
+
const { serializedTransaction } = args[0];
|
|
184
|
+
const publicClient = client as unknown as PublicClient;
|
|
185
|
+
const sender = await tryRecoverSender(serializedTransaction);
|
|
186
|
+
|
|
187
|
+
if (delayer.nextWait !== undefined) {
|
|
188
|
+
// Check if we have been instructed to delay the next tx.
|
|
189
|
+
const waitUntil = delayer.nextWait;
|
|
190
|
+
delayer.nextWait = undefined;
|
|
191
|
+
|
|
192
|
+
// Compute the tx hash manually so we emulate sendRawTransaction response
|
|
193
|
+
txHash = computeTxHash(serializedTransaction);
|
|
194
|
+
|
|
195
|
+
// Cancel tx outright if instructed
|
|
196
|
+
if ('indefinitely' in waitUntil && waitUntil.indefinitely) {
|
|
197
|
+
logger.info(`Cancelling tx ${txHash}`, { sender });
|
|
198
|
+
delayer.cancelledTxs.push(serializedTransaction);
|
|
199
|
+
return Promise.resolve(txHash);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// Or wait until the desired block number or timestamp
|
|
203
|
+
wait =
|
|
204
|
+
'l1BlockNumber' in waitUntil
|
|
205
|
+
? waitUntilBlock(publicClient, waitUntil.l1BlockNumber - 1n, logger, waitUntil.timeoutSeconds)
|
|
206
|
+
: 'l1Timestamp' in waitUntil
|
|
207
|
+
? waitUntilL1Timestamp(
|
|
208
|
+
publicClient,
|
|
209
|
+
waitUntil.l1Timestamp - delayer.ethereumSlotDuration,
|
|
210
|
+
logger,
|
|
211
|
+
waitUntil.timeoutSeconds,
|
|
212
|
+
)
|
|
213
|
+
: undefined;
|
|
214
|
+
|
|
215
|
+
logger.info(`Delaying tx ${txHash} until ${inspect(waitUntil)}`, {
|
|
216
|
+
sender,
|
|
217
|
+
argsLen: args.length,
|
|
218
|
+
...omit(parseTransaction(serializedTransaction), 'data', 'sidecars'),
|
|
219
|
+
});
|
|
220
|
+
} else if (delayer.maxInclusionTimeIntoSlot !== undefined) {
|
|
221
|
+
// Check if we need to delay txs sent too close to the end of the slot.
|
|
222
|
+
const currentBlock = await publicClient.getBlock({ includeTransactions: false });
|
|
223
|
+
const { timestamp: lastBlockTimestamp, number } = currentBlock;
|
|
224
|
+
const now = delayer.dateProvider.now();
|
|
225
|
+
|
|
226
|
+
txHash = computeTxHash(serializedTransaction);
|
|
227
|
+
const logData = {
|
|
228
|
+
sender,
|
|
229
|
+
...omit(parseTransaction(serializedTransaction), 'data', 'sidecars'),
|
|
230
|
+
lastBlockTimestamp,
|
|
231
|
+
now,
|
|
232
|
+
maxInclusionTimeIntoSlot: delayer.maxInclusionTimeIntoSlot,
|
|
233
|
+
};
|
|
234
|
+
|
|
235
|
+
if (now / 1000 - Number(lastBlockTimestamp) > delayer.maxInclusionTimeIntoSlot) {
|
|
236
|
+
// If the last block was mined more than `maxInclusionTimeIntoSlot` seconds ago, then we cannot include
|
|
237
|
+
// any txs in the current slot, so we delay the tx until the next slot.
|
|
238
|
+
logger.info(`Delaying inclusion of tx ${txHash} until the next slot since it was sent too late`, logData);
|
|
239
|
+
wait = waitUntilBlock(publicClient, number + 1n, logger);
|
|
240
|
+
} else {
|
|
241
|
+
logger.debug(`Immediately sending tx ${txHash} as it was received early enough in the slot`, logData);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
if (wait !== undefined) {
|
|
246
|
+
// Do not await here so we can return the tx hash immediately as if it had been sent on the spot.
|
|
247
|
+
// Instead, delay it so it lands on the desired block number or timestamp, assuming anvil will
|
|
248
|
+
// mine it immediately.
|
|
249
|
+
void wait!
|
|
250
|
+
.then(async () => {
|
|
251
|
+
const clientTxHash = await client.sendRawTransaction(...args);
|
|
252
|
+
if (clientTxHash !== txHash) {
|
|
253
|
+
logger.error(`Tx hash returned by the client does not match computed one`, {
|
|
254
|
+
clientTxHash,
|
|
255
|
+
computedTxHash: txHash,
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
logger.info(`Sent previously delayed tx ${clientTxHash}`, { sender });
|
|
259
|
+
delayer.sentTxHashes.push(clientTxHash);
|
|
260
|
+
})
|
|
261
|
+
.catch(err => logger.error(`Error sending tx after delay`, err));
|
|
262
|
+
return Promise.resolve(txHash!);
|
|
263
|
+
} else {
|
|
264
|
+
const txHash = await client.sendRawTransaction(...args);
|
|
265
|
+
logger.debug(`Sent tx immediately ${txHash}`, { sender });
|
|
266
|
+
delayer.sentTxHashes.push(txHash);
|
|
267
|
+
return txHash;
|
|
268
|
+
}
|
|
269
|
+
},
|
|
270
|
+
}));
|
|
271
|
+
|
|
272
|
+
// Only re-bind wallet actions (sendTransaction, writeContract, deployContract) for wallet clients.
|
|
273
|
+
// This is needed for tests that use wallet actions directly rather than sendRawTransaction.
|
|
274
|
+
const isWalletClient = 'account' in client && client.account !== undefined;
|
|
275
|
+
const extended = isWalletClient
|
|
276
|
+
? withRawTx
|
|
277
|
+
// Re-extend with sendTransaction so it uses the modified sendRawTransaction.
|
|
278
|
+
.extend(client => ({ sendTransaction: walletActions(client).sendTransaction }))
|
|
279
|
+
// And with the actions that depend on the modified sendTransaction
|
|
280
|
+
.extend(client => ({
|
|
281
|
+
writeContract: walletActions(client).writeContract,
|
|
282
|
+
deployContract: walletActions(client).deployContract,
|
|
283
|
+
}))
|
|
284
|
+
: withRawTx;
|
|
285
|
+
|
|
286
|
+
return extended as T;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Compute the tx hash given the serialized tx. Note that if this is a blob tx, we need to
|
|
291
|
+
* exclude the blobs, commitments, and proofs from the hash.
|
|
292
|
+
*/
|
|
293
|
+
function computeTxHash(serializedTransaction: Hex) {
|
|
294
|
+
if (serializedTransaction.startsWith('0x03')) {
|
|
295
|
+
const parsed = parseTransaction(serializedTransaction);
|
|
296
|
+
if (parsed.blobs || parsed.sidecars) {
|
|
297
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
298
|
+
const { blobs, sidecars, ...rest } = parsed;
|
|
299
|
+
return keccak256(serializeTransaction({ type: 'eip4844', ...rest } as TransactionSerializableEIP4844));
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
return keccak256(serializedTransaction);
|
|
303
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { BlobKzgInstance } from '@aztec/blob-lib/types';
|
|
2
|
+
import { EthAddress } from '@aztec/foundation/eth-address';
|
|
3
|
+
import type { ViemTransactionSignature } from '@aztec/foundation/eth-signature';
|
|
4
|
+
|
|
5
|
+
import type { Abi, Address, Hex, TransactionReceipt, TransactionSerializable } from 'viem';
|
|
6
|
+
|
|
7
|
+
import type { L1TxUtilsConfig } from './config.js';
|
|
8
|
+
|
|
9
|
+
export interface L1TxRequest {
|
|
10
|
+
to: Address | null;
|
|
11
|
+
data?: Hex;
|
|
12
|
+
value?: bigint;
|
|
13
|
+
abi?: Abi;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export type L1TxConfig = Partial<L1TxUtilsConfig> & { gasLimit?: bigint; txTimeoutAt?: Date };
|
|
17
|
+
|
|
18
|
+
export interface L1BlobInputs {
|
|
19
|
+
blobs: Uint8Array[];
|
|
20
|
+
kzg: BlobKzgInstance;
|
|
21
|
+
maxFeePerBlobGas?: bigint;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface GasPrice {
|
|
25
|
+
maxFeePerGas: bigint;
|
|
26
|
+
maxPriorityFeePerGas: bigint;
|
|
27
|
+
maxFeePerBlobGas?: bigint;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export type TransactionStats = {
|
|
31
|
+
/** Address of the sender. */
|
|
32
|
+
sender: string;
|
|
33
|
+
/** Hash of the transaction. */
|
|
34
|
+
transactionHash: string;
|
|
35
|
+
/** Size in bytes of the tx calldata */
|
|
36
|
+
calldataSize: number;
|
|
37
|
+
/** Gas required to pay for the calldata inclusion (depends on size and number of zeros) */
|
|
38
|
+
calldataGas: number;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
export enum TxUtilsState {
|
|
42
|
+
IDLE,
|
|
43
|
+
SENT,
|
|
44
|
+
SPEED_UP,
|
|
45
|
+
CANCELLED,
|
|
46
|
+
NOT_MINED,
|
|
47
|
+
MINED,
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export const TerminalTxUtilsState = [TxUtilsState.IDLE, TxUtilsState.MINED, TxUtilsState.NOT_MINED];
|
|
51
|
+
|
|
52
|
+
export type L1TxState = {
|
|
53
|
+
id: number;
|
|
54
|
+
txHashes: Hex[];
|
|
55
|
+
cancelTxHashes: Hex[];
|
|
56
|
+
gasLimit: bigint;
|
|
57
|
+
gasPrice: GasPrice;
|
|
58
|
+
txConfigOverrides: L1TxConfig;
|
|
59
|
+
request: L1TxRequest;
|
|
60
|
+
status: TxUtilsState;
|
|
61
|
+
nonce: number;
|
|
62
|
+
sentAtL1Ts: Date;
|
|
63
|
+
lastSentAtL1Ts: Date;
|
|
64
|
+
receipt?: TransactionReceipt;
|
|
65
|
+
blobInputs: L1BlobInputs | undefined;
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
export type SigningCallback = (
|
|
69
|
+
transaction: TransactionSerializable,
|
|
70
|
+
signingAddress: EthAddress,
|
|
71
|
+
) => Promise<ViemTransactionSignature>;
|
|
72
|
+
|
|
73
|
+
export class UnknownMinedTxError extends Error {
|
|
74
|
+
constructor(nonce: number, account: string) {
|
|
75
|
+
super(`Nonce ${nonce} from account ${account} is MINED but not by one of our expected transactions`);
|
|
76
|
+
this.name = 'UnknownMinedTxError';
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export class DroppedTransactionError extends Error {
|
|
81
|
+
constructor(nonce: number, account: string) {
|
|
82
|
+
super(`Transaction with nonce ${nonce} from account ${account} was dropped from the mempool`);
|
|
83
|
+
this.name = 'DroppedTransactionError';
|
|
84
|
+
}
|
|
85
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { compactArray } from '@aztec/foundation/collection';
|
|
2
|
+
|
|
3
|
+
import type { ContractFunctionExecutionError } from 'viem';
|
|
4
|
+
|
|
5
|
+
export function tryGetCustomErrorNameContractFunction(err: ContractFunctionExecutionError) {
|
|
6
|
+
return compactArray([err.shortMessage, ...(err.metaMessages ?? []).slice(0, 2).map(s => s.trim())]).join(' ');
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/*
|
|
10
|
+
* Returns cost of calldata usage in Ethereum.
|
|
11
|
+
* @param data - Calldata.
|
|
12
|
+
* @returns 4 for each zero byte, 16 for each nonzero.
|
|
13
|
+
*/
|
|
14
|
+
export function getCalldataGasUsage(data: Uint8Array) {
|
|
15
|
+
return data.filter(byte => byte === 0).length * 4 + data.filter(byte => byte !== 0).length * 16;
|
|
16
|
+
}
|
package/src/l1_types.ts
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { pick } from '@aztec/foundation/collection';
|
|
2
|
+
import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
|
|
3
|
+
import { RunningPromise } from '@aztec/foundation/running-promise';
|
|
4
|
+
|
|
5
|
+
import { Multicall3 } from './contracts/multicall.js';
|
|
6
|
+
import { L1TxUtils, TxUtilsState } from './l1_tx_utils/index.js';
|
|
7
|
+
|
|
8
|
+
// Defines the order in which we prioritise publishers based on their state (first is better)
|
|
9
|
+
const sortOrder = [
|
|
10
|
+
// Always prefer sending from idle publishers
|
|
11
|
+
TxUtilsState.IDLE,
|
|
12
|
+
// Then from publishers that have sent a tx and it got mined
|
|
13
|
+
TxUtilsState.MINED,
|
|
14
|
+
// Then from publishers that have sent a tx but it's in-flight
|
|
15
|
+
TxUtilsState.SPEED_UP,
|
|
16
|
+
TxUtilsState.SENT,
|
|
17
|
+
// We leave cancelled and not-mined states for last, since these represent failures to mines and could be problematic
|
|
18
|
+
TxUtilsState.CANCELLED,
|
|
19
|
+
TxUtilsState.NOT_MINED,
|
|
20
|
+
];
|
|
21
|
+
|
|
22
|
+
// Which states represent a busy publisher that we should avoid if possible
|
|
23
|
+
const busyStates: TxUtilsState[] = [
|
|
24
|
+
TxUtilsState.SENT,
|
|
25
|
+
TxUtilsState.SPEED_UP,
|
|
26
|
+
TxUtilsState.CANCELLED,
|
|
27
|
+
TxUtilsState.NOT_MINED,
|
|
28
|
+
];
|
|
29
|
+
|
|
30
|
+
export type PublisherFilter<UtilsType extends L1TxUtils> = (utils: UtilsType) => boolean;
|
|
31
|
+
|
|
32
|
+
/** Config accepted by PublisherManager. */
|
|
33
|
+
type PublisherManagerConfig = {
|
|
34
|
+
publisherAllowInvalidStates?: boolean;
|
|
35
|
+
publisherFundingThreshold?: bigint;
|
|
36
|
+
publisherFundingAmount?: bigint;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
export class PublisherManager<UtilsType extends L1TxUtils = L1TxUtils> {
|
|
40
|
+
private log: Logger;
|
|
41
|
+
private config: PublisherManagerConfig;
|
|
42
|
+
private static readonly FUNDING_CHECK_INTERVAL_MS = 2 * 60 * 1000;
|
|
43
|
+
private funder?: UtilsType;
|
|
44
|
+
private fundingPromise?: RunningPromise;
|
|
45
|
+
|
|
46
|
+
constructor(
|
|
47
|
+
private publishers: UtilsType[],
|
|
48
|
+
config: PublisherManagerConfig,
|
|
49
|
+
opts?: { bindings?: LoggerBindings; funder?: UtilsType },
|
|
50
|
+
) {
|
|
51
|
+
this.funder = opts?.funder;
|
|
52
|
+
this.log = createLogger('publisher:manager', opts?.bindings);
|
|
53
|
+
this.log.info(`PublisherManager initialized with ${publishers.length} publishers.`);
|
|
54
|
+
this.publishers = publishers;
|
|
55
|
+
this.config = pick(config, 'publisherAllowInvalidStates', 'publisherFundingThreshold', 'publisherFundingAmount');
|
|
56
|
+
|
|
57
|
+
const hasThreshold = this.config.publisherFundingThreshold !== undefined;
|
|
58
|
+
const hasAmount = this.config.publisherFundingAmount !== undefined;
|
|
59
|
+
if (hasThreshold !== hasAmount) {
|
|
60
|
+
this.log.warn(`Incomplete funding config: both publisherFundingThreshold and publisherFundingAmount must be set`);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
if (this.funder) {
|
|
64
|
+
const funderAddress = this.funder.getSenderAddress();
|
|
65
|
+
if (publishers.some(p => p.getSenderAddress().equals(funderAddress))) {
|
|
66
|
+
this.log.error(`Funding account ${funderAddress} is also a publisher, disabling funding to avoid self-funding`);
|
|
67
|
+
this.funder = undefined;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Loads the state of all publishers and the funder, and starts periodic funding checks. */
|
|
73
|
+
public async start(): Promise<void> {
|
|
74
|
+
await Promise.all([
|
|
75
|
+
...this.publishers.map(pub => pub.loadStateAndResumeMonitoring()),
|
|
76
|
+
this.funder?.loadStateAndResumeMonitoring(),
|
|
77
|
+
]);
|
|
78
|
+
|
|
79
|
+
if (
|
|
80
|
+
this.funder &&
|
|
81
|
+
this.config.publisherFundingThreshold !== undefined &&
|
|
82
|
+
this.config.publisherFundingAmount !== undefined
|
|
83
|
+
) {
|
|
84
|
+
this.fundingPromise = new RunningPromise(
|
|
85
|
+
() => this.triggerFundingIfNeeded(),
|
|
86
|
+
this.log,
|
|
87
|
+
PublisherManager.FUNDING_CHECK_INTERVAL_MS,
|
|
88
|
+
);
|
|
89
|
+
this.fundingPromise.start();
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Stops the funding loop and interrupts all publishers. */
|
|
94
|
+
public async stop(): Promise<void> {
|
|
95
|
+
await this.fundingPromise?.stop();
|
|
96
|
+
this.publishers.forEach(pub => pub.interrupt());
|
|
97
|
+
this.funder?.interrupt();
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Finds and prioritises available publishers based on
|
|
101
|
+
// 1. Validity as per the provided filter function
|
|
102
|
+
// 2. Validity based on the state the publisher is in
|
|
103
|
+
// 3. Priority based on state as defined by sortOrder
|
|
104
|
+
// 4. Then priority based on highest balance
|
|
105
|
+
// 5. Then priority based on least recently used
|
|
106
|
+
public async getAvailablePublisher(filter: PublisherFilter<UtilsType> = () => true): Promise<UtilsType> {
|
|
107
|
+
this.log.debug(`Getting available publisher`, {
|
|
108
|
+
publishers: this.publishers.map(p => ({
|
|
109
|
+
address: p.getSenderAddress(),
|
|
110
|
+
state: p.state,
|
|
111
|
+
lastMined: p.lastMinedAtBlockNumber,
|
|
112
|
+
})),
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
// Extract the valid publishers
|
|
116
|
+
let validPublishers = this.publishers.filter((pub: UtilsType) => !busyStates.includes(pub.state) && filter(pub));
|
|
117
|
+
|
|
118
|
+
// If none found but we allow invalid (busy) states, try again including them
|
|
119
|
+
if (validPublishers.length === 0 && this.config.publisherAllowInvalidStates) {
|
|
120
|
+
this.log.warn(`No valid publishers found. Trying again including invalid states.`);
|
|
121
|
+
validPublishers = this.publishers.filter(pub => filter(pub));
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Error if none found
|
|
125
|
+
if (validPublishers.length === 0) {
|
|
126
|
+
throw new Error(`Failed to find an available publisher.`);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// Get the balances
|
|
130
|
+
const publishersWithBalance = await Promise.all(
|
|
131
|
+
validPublishers.map(async pub => {
|
|
132
|
+
return { balance: await pub.getSenderBalance(), publisher: pub };
|
|
133
|
+
}),
|
|
134
|
+
);
|
|
135
|
+
|
|
136
|
+
// Sort based on state, then balance, then time since last use
|
|
137
|
+
const sortedPublishers = publishersWithBalance.sort((a, b) => {
|
|
138
|
+
const stateComparison = sortOrder.indexOf(a.publisher.state) - sortOrder.indexOf(b.publisher.state);
|
|
139
|
+
if (stateComparison !== 0) {
|
|
140
|
+
return stateComparison;
|
|
141
|
+
}
|
|
142
|
+
const balanceComparison = Number(b.balance - a.balance);
|
|
143
|
+
if (balanceComparison !== 0) {
|
|
144
|
+
return balanceComparison;
|
|
145
|
+
}
|
|
146
|
+
const lastUsedComparison = Number(
|
|
147
|
+
(a.publisher.lastMinedAtBlockNumber ?? 0n) - (b.publisher.lastMinedAtBlockNumber ?? 0n),
|
|
148
|
+
);
|
|
149
|
+
return lastUsedComparison;
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
return sortedPublishers[0].publisher;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Check all publisher balances and fund those below threshold. */
|
|
156
|
+
private async triggerFundingIfNeeded(): Promise<void> {
|
|
157
|
+
const { funder, config } = this;
|
|
158
|
+
if (!funder || config.publisherFundingThreshold === undefined || config.publisherFundingAmount === undefined) {
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const allBalances = await Promise.all(
|
|
163
|
+
this.publishers.map(async pub => ({ balance: await pub.getSenderBalance(), publisher: pub })),
|
|
164
|
+
);
|
|
165
|
+
const lowBalance = allBalances.filter(p => p.balance < config.publisherFundingThreshold!);
|
|
166
|
+
if (lowBalance.length === 0) {
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const fundingAmount = config.publisherFundingAmount!;
|
|
171
|
+
const funderBalance = await funder.getSenderBalance();
|
|
172
|
+
|
|
173
|
+
if (funderBalance < 10n * fundingAmount) {
|
|
174
|
+
this.log.warn(`Funding account balance is low`, { funderBalance, threshold: 10n * fundingAmount });
|
|
175
|
+
}
|
|
176
|
+
const affordableCount = Number(funderBalance / fundingAmount);
|
|
177
|
+
if (affordableCount === 0) {
|
|
178
|
+
this.log.error(`Funding account balance too low to fund any publisher`, { funderBalance, fundingAmount });
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
if (affordableCount < lowBalance.length) {
|
|
182
|
+
this.log.warn(`Funder can only afford ${affordableCount}/${lowBalance.length} publishers`, {
|
|
183
|
+
funderBalance,
|
|
184
|
+
fundingAmount,
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const toFund = lowBalance.slice(0, affordableCount).map(p => p.publisher);
|
|
189
|
+
await this.fundPublishers(toFund);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Fund publishers via a single Multicall3 aggregate3Value transaction. */
|
|
193
|
+
private async fundPublishers(publishers: UtilsType[]): Promise<void> {
|
|
194
|
+
const fundingAmount = this.config.publisherFundingAmount!;
|
|
195
|
+
const calls = publishers.map(pub => ({
|
|
196
|
+
to: pub.getSenderAddress().toString(),
|
|
197
|
+
value: fundingAmount,
|
|
198
|
+
}));
|
|
199
|
+
|
|
200
|
+
await Multicall3.forwardValue(calls, this.funder!, this.log);
|
|
201
|
+
this.log.info(`Funded ${publishers.length} publishers`);
|
|
202
|
+
}
|
|
203
|
+
}
|