@aztec/sequencer-client 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.
Files changed (185) hide show
  1. package/README.md +281 -21
  2. package/dest/client/index.d.ts +1 -1
  3. package/dest/client/sequencer-client.d.ts +43 -33
  4. package/dest/client/sequencer-client.d.ts.map +1 -1
  5. package/dest/client/sequencer-client.js +117 -62
  6. package/dest/config.d.ts +38 -17
  7. package/dest/config.d.ts.map +1 -1
  8. package/dest/config.js +172 -85
  9. package/dest/global_variable_builder/fee_predictor.d.ts +37 -0
  10. package/dest/global_variable_builder/fee_predictor.d.ts.map +1 -0
  11. package/dest/global_variable_builder/fee_predictor.js +128 -0
  12. package/dest/global_variable_builder/fee_provider.d.ts +21 -0
  13. package/dest/global_variable_builder/fee_provider.d.ts.map +1 -0
  14. package/dest/global_variable_builder/fee_provider.js +58 -0
  15. package/dest/global_variable_builder/global_builder.d.ts +26 -17
  16. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  17. package/dest/global_variable_builder/global_builder.js +45 -61
  18. package/dest/global_variable_builder/index.d.ts +4 -2
  19. package/dest/global_variable_builder/index.d.ts.map +1 -1
  20. package/dest/global_variable_builder/index.js +2 -0
  21. package/dest/index.d.ts +2 -4
  22. package/dest/index.d.ts.map +1 -1
  23. package/dest/index.js +1 -3
  24. package/dest/publisher/config.d.ts +60 -27
  25. package/dest/publisher/config.d.ts.map +1 -1
  26. package/dest/publisher/config.js +124 -32
  27. package/dest/publisher/index.d.ts +4 -1
  28. package/dest/publisher/index.d.ts.map +1 -1
  29. package/dest/publisher/index.js +3 -0
  30. package/dest/publisher/l1_tx_failed_store/factory.d.ts +11 -0
  31. package/dest/publisher/l1_tx_failed_store/factory.d.ts.map +1 -0
  32. package/dest/publisher/l1_tx_failed_store/factory.js +22 -0
  33. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +58 -0
  34. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -0
  35. package/dest/publisher/l1_tx_failed_store/failed_tx_store.js +1 -0
  36. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts +15 -0
  37. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts.map +1 -0
  38. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.js +34 -0
  39. package/dest/publisher/l1_tx_failed_store/index.d.ts +4 -0
  40. package/dest/publisher/l1_tx_failed_store/index.d.ts.map +1 -0
  41. package/dest/publisher/l1_tx_failed_store/index.js +2 -0
  42. package/dest/publisher/sequencer-bundle-simulator.d.ts +96 -0
  43. package/dest/publisher/sequencer-bundle-simulator.d.ts.map +1 -0
  44. package/dest/publisher/sequencer-bundle-simulator.js +198 -0
  45. package/dest/publisher/sequencer-publisher-factory.d.ts +50 -0
  46. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -0
  47. package/dest/publisher/sequencer-publisher-factory.js +75 -0
  48. package/dest/publisher/sequencer-publisher-metrics.d.ts +5 -4
  49. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -1
  50. package/dest/publisher/sequencer-publisher-metrics.js +34 -62
  51. package/dest/publisher/sequencer-publisher.d.ts +170 -97
  52. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  53. package/dest/publisher/sequencer-publisher.js +1255 -276
  54. package/dest/sequencer/automine/automine_factory.d.ts +54 -0
  55. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -0
  56. package/dest/sequencer/automine/automine_factory.js +84 -0
  57. package/dest/sequencer/automine/automine_sequencer.d.ts +151 -0
  58. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
  59. package/dest/sequencer/automine/automine_sequencer.js +509 -0
  60. package/dest/sequencer/chain_state_overrides.d.ts +61 -0
  61. package/dest/sequencer/chain_state_overrides.d.ts.map +1 -0
  62. package/dest/sequencer/chain_state_overrides.js +98 -0
  63. package/dest/sequencer/checkpoint_proposal_job.d.ts +150 -0
  64. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -0
  65. package/dest/sequencer/checkpoint_proposal_job.js +1792 -0
  66. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  67. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  68. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  69. package/dest/sequencer/checkpoint_voter.d.ts +34 -0
  70. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -0
  71. package/dest/sequencer/checkpoint_voter.js +106 -0
  72. package/dest/sequencer/config.d.ts +7 -1
  73. package/dest/sequencer/config.d.ts.map +1 -1
  74. package/dest/sequencer/errors.d.ts +11 -0
  75. package/dest/sequencer/errors.d.ts.map +1 -0
  76. package/dest/sequencer/errors.js +15 -0
  77. package/dest/sequencer/events.d.ts +92 -0
  78. package/dest/sequencer/events.d.ts.map +1 -0
  79. package/dest/sequencer/events.js +1 -0
  80. package/dest/sequencer/index.d.ts +6 -2
  81. package/dest/sequencer/index.d.ts.map +1 -1
  82. package/dest/sequencer/index.js +5 -1
  83. package/dest/sequencer/metrics.d.ts +64 -13
  84. package/dest/sequencer/metrics.d.ts.map +1 -1
  85. package/dest/sequencer/metrics.js +309 -68
  86. package/dest/sequencer/sequencer.d.ts +205 -135
  87. package/dest/sequencer/sequencer.d.ts.map +1 -1
  88. package/dest/sequencer/sequencer.js +1208 -523
  89. package/dest/sequencer/timetable.d.ts +85 -25
  90. package/dest/sequencer/timetable.d.ts.map +1 -1
  91. package/dest/sequencer/timetable.js +177 -60
  92. package/dest/sequencer/types.d.ts +3 -0
  93. package/dest/sequencer/types.d.ts.map +1 -0
  94. package/dest/sequencer/types.js +1 -0
  95. package/dest/sequencer/utils.d.ts +20 -38
  96. package/dest/sequencer/utils.d.ts.map +1 -1
  97. package/dest/sequencer/utils.js +12 -47
  98. package/dest/test/index.d.ts +9 -3
  99. package/dest/test/index.d.ts.map +1 -1
  100. package/dest/test/index.js +0 -4
  101. package/dest/test/mock_checkpoint_builder.d.ts +95 -0
  102. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -0
  103. package/dest/test/mock_checkpoint_builder.js +231 -0
  104. package/dest/test/utils.d.ts +53 -0
  105. package/dest/test/utils.d.ts.map +1 -0
  106. package/dest/test/utils.js +105 -0
  107. package/package.json +46 -45
  108. package/src/client/sequencer-client.ts +158 -103
  109. package/src/config.ts +201 -99
  110. package/src/global_variable_builder/README.md +44 -0
  111. package/src/global_variable_builder/fee_predictor.ts +172 -0
  112. package/src/global_variable_builder/fee_provider.ts +75 -0
  113. package/src/global_variable_builder/global_builder.ts +68 -76
  114. package/src/global_variable_builder/index.ts +3 -1
  115. package/src/index.ts +10 -3
  116. package/src/publisher/config.ts +184 -59
  117. package/src/publisher/index.ts +7 -0
  118. package/src/publisher/l1_tx_failed_store/factory.ts +32 -0
  119. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +57 -0
  120. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +46 -0
  121. package/src/publisher/l1_tx_failed_store/index.ts +3 -0
  122. package/src/publisher/sequencer-bundle-simulator.ts +254 -0
  123. package/src/publisher/sequencer-publisher-factory.ts +121 -0
  124. package/src/publisher/sequencer-publisher-metrics.ts +33 -63
  125. package/src/publisher/sequencer-publisher.ts +1101 -350
  126. package/src/sequencer/README.md +243 -0
  127. package/src/sequencer/automine/README.md +46 -0
  128. package/src/sequencer/automine/automine_factory.ts +145 -0
  129. package/src/sequencer/automine/automine_sequencer.ts +595 -0
  130. package/src/sequencer/chain_state_overrides.ts +162 -0
  131. package/src/sequencer/checkpoint_proposal_job.ts +1632 -0
  132. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  133. package/src/sequencer/checkpoint_voter.ts +119 -0
  134. package/src/sequencer/config.ts +8 -0
  135. package/src/sequencer/errors.ts +21 -0
  136. package/src/sequencer/events.ts +76 -0
  137. package/src/sequencer/index.ts +5 -1
  138. package/src/sequencer/metrics.ts +397 -75
  139. package/src/sequencer/sequencer.ts +1013 -579
  140. package/src/sequencer/timetable.ts +225 -60
  141. package/src/sequencer/types.ts +6 -0
  142. package/src/sequencer/utils.ts +28 -60
  143. package/src/test/index.ts +11 -5
  144. package/src/test/mock_checkpoint_builder.ts +323 -0
  145. package/src/test/utils.ts +185 -0
  146. package/dest/sequencer/allowed.d.ts +0 -3
  147. package/dest/sequencer/allowed.d.ts.map +0 -1
  148. package/dest/sequencer/allowed.js +0 -27
  149. package/dest/slasher/factory.d.ts +0 -7
  150. package/dest/slasher/factory.d.ts.map +0 -1
  151. package/dest/slasher/factory.js +0 -8
  152. package/dest/slasher/index.d.ts +0 -3
  153. package/dest/slasher/index.d.ts.map +0 -1
  154. package/dest/slasher/index.js +0 -2
  155. package/dest/slasher/slasher_client.d.ts +0 -75
  156. package/dest/slasher/slasher_client.d.ts.map +0 -1
  157. package/dest/slasher/slasher_client.js +0 -132
  158. package/dest/tx_validator/archive_cache.d.ts +0 -14
  159. package/dest/tx_validator/archive_cache.d.ts.map +0 -1
  160. package/dest/tx_validator/archive_cache.js +0 -22
  161. package/dest/tx_validator/gas_validator.d.ts +0 -14
  162. package/dest/tx_validator/gas_validator.d.ts.map +0 -1
  163. package/dest/tx_validator/gas_validator.js +0 -78
  164. package/dest/tx_validator/nullifier_cache.d.ts +0 -16
  165. package/dest/tx_validator/nullifier_cache.d.ts.map +0 -1
  166. package/dest/tx_validator/nullifier_cache.js +0 -24
  167. package/dest/tx_validator/phases_validator.d.ts +0 -12
  168. package/dest/tx_validator/phases_validator.d.ts.map +0 -1
  169. package/dest/tx_validator/phases_validator.js +0 -80
  170. package/dest/tx_validator/test_utils.d.ts +0 -23
  171. package/dest/tx_validator/test_utils.d.ts.map +0 -1
  172. package/dest/tx_validator/test_utils.js +0 -26
  173. package/dest/tx_validator/tx_validator_factory.d.ts +0 -18
  174. package/dest/tx_validator/tx_validator_factory.d.ts.map +0 -1
  175. package/dest/tx_validator/tx_validator_factory.js +0 -50
  176. package/src/sequencer/allowed.ts +0 -36
  177. package/src/slasher/factory.ts +0 -15
  178. package/src/slasher/index.ts +0 -2
  179. package/src/slasher/slasher_client.ts +0 -193
  180. package/src/tx_validator/archive_cache.ts +0 -28
  181. package/src/tx_validator/gas_validator.ts +0 -101
  182. package/src/tx_validator/nullifier_cache.ts +0 -30
  183. package/src/tx_validator/phases_validator.ts +0 -98
  184. package/src/tx_validator/test_utils.ts +0 -48
  185. package/src/tx_validator/tx_validator_factory.ts +0 -120
@@ -1,98 +1,625 @@
1
- import { Blob } from '@aztec/blob-lib';
2
- import { createBlobSinkClient } from '@aztec/blob-sink/client';
3
- import { FormattedViemError, RollupContract, formatViemError } from '@aztec/ethereum';
4
- import { toHex } from '@aztec/foundation/bigint-buffer';
1
+ function applyDecs2203RFactory() {
2
+ function createAddInitializerMethod(initializers, decoratorFinishedRef) {
3
+ return function addInitializer(initializer) {
4
+ assertNotFinished(decoratorFinishedRef, "addInitializer");
5
+ assertCallable(initializer, "An initializer");
6
+ initializers.push(initializer);
7
+ };
8
+ }
9
+ function memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value) {
10
+ var kindStr;
11
+ switch(kind){
12
+ case 1:
13
+ kindStr = "accessor";
14
+ break;
15
+ case 2:
16
+ kindStr = "method";
17
+ break;
18
+ case 3:
19
+ kindStr = "getter";
20
+ break;
21
+ case 4:
22
+ kindStr = "setter";
23
+ break;
24
+ default:
25
+ kindStr = "field";
26
+ }
27
+ var ctx = {
28
+ kind: kindStr,
29
+ name: isPrivate ? "#" + name : name,
30
+ static: isStatic,
31
+ private: isPrivate,
32
+ metadata: metadata
33
+ };
34
+ var decoratorFinishedRef = {
35
+ v: false
36
+ };
37
+ ctx.addInitializer = createAddInitializerMethod(initializers, decoratorFinishedRef);
38
+ var get, set;
39
+ if (kind === 0) {
40
+ if (isPrivate) {
41
+ get = desc.get;
42
+ set = desc.set;
43
+ } else {
44
+ get = function() {
45
+ return this[name];
46
+ };
47
+ set = function(v) {
48
+ this[name] = v;
49
+ };
50
+ }
51
+ } else if (kind === 2) {
52
+ get = function() {
53
+ return desc.value;
54
+ };
55
+ } else {
56
+ if (kind === 1 || kind === 3) {
57
+ get = function() {
58
+ return desc.get.call(this);
59
+ };
60
+ }
61
+ if (kind === 1 || kind === 4) {
62
+ set = function(v) {
63
+ desc.set.call(this, v);
64
+ };
65
+ }
66
+ }
67
+ ctx.access = get && set ? {
68
+ get: get,
69
+ set: set
70
+ } : get ? {
71
+ get: get
72
+ } : {
73
+ set: set
74
+ };
75
+ try {
76
+ return dec(value, ctx);
77
+ } finally{
78
+ decoratorFinishedRef.v = true;
79
+ }
80
+ }
81
+ function assertNotFinished(decoratorFinishedRef, fnName) {
82
+ if (decoratorFinishedRef.v) {
83
+ throw new Error("attempted to call " + fnName + " after decoration was finished");
84
+ }
85
+ }
86
+ function assertCallable(fn, hint) {
87
+ if (typeof fn !== "function") {
88
+ throw new TypeError(hint + " must be a function");
89
+ }
90
+ }
91
+ function assertValidReturnValue(kind, value) {
92
+ var type = typeof value;
93
+ if (kind === 1) {
94
+ if (type !== "object" || value === null) {
95
+ throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");
96
+ }
97
+ if (value.get !== undefined) {
98
+ assertCallable(value.get, "accessor.get");
99
+ }
100
+ if (value.set !== undefined) {
101
+ assertCallable(value.set, "accessor.set");
102
+ }
103
+ if (value.init !== undefined) {
104
+ assertCallable(value.init, "accessor.init");
105
+ }
106
+ } else if (type !== "function") {
107
+ var hint;
108
+ if (kind === 0) {
109
+ hint = "field";
110
+ } else if (kind === 10) {
111
+ hint = "class";
112
+ } else {
113
+ hint = "method";
114
+ }
115
+ throw new TypeError(hint + " decorators must return a function or void 0");
116
+ }
117
+ }
118
+ function applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata) {
119
+ var decs = decInfo[0];
120
+ var desc, init, value;
121
+ if (isPrivate) {
122
+ if (kind === 0 || kind === 1) {
123
+ desc = {
124
+ get: decInfo[3],
125
+ set: decInfo[4]
126
+ };
127
+ } else if (kind === 3) {
128
+ desc = {
129
+ get: decInfo[3]
130
+ };
131
+ } else if (kind === 4) {
132
+ desc = {
133
+ set: decInfo[3]
134
+ };
135
+ } else {
136
+ desc = {
137
+ value: decInfo[3]
138
+ };
139
+ }
140
+ } else if (kind !== 0) {
141
+ desc = Object.getOwnPropertyDescriptor(base, name);
142
+ }
143
+ if (kind === 1) {
144
+ value = {
145
+ get: desc.get,
146
+ set: desc.set
147
+ };
148
+ } else if (kind === 2) {
149
+ value = desc.value;
150
+ } else if (kind === 3) {
151
+ value = desc.get;
152
+ } else if (kind === 4) {
153
+ value = desc.set;
154
+ }
155
+ var newValue, get, set;
156
+ if (typeof decs === "function") {
157
+ newValue = memberDec(decs, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
158
+ if (newValue !== void 0) {
159
+ assertValidReturnValue(kind, newValue);
160
+ if (kind === 0) {
161
+ init = newValue;
162
+ } else if (kind === 1) {
163
+ init = newValue.init;
164
+ get = newValue.get || value.get;
165
+ set = newValue.set || value.set;
166
+ value = {
167
+ get: get,
168
+ set: set
169
+ };
170
+ } else {
171
+ value = newValue;
172
+ }
173
+ }
174
+ } else {
175
+ for(var i = decs.length - 1; i >= 0; i--){
176
+ var dec = decs[i];
177
+ newValue = memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
178
+ if (newValue !== void 0) {
179
+ assertValidReturnValue(kind, newValue);
180
+ var newInit;
181
+ if (kind === 0) {
182
+ newInit = newValue;
183
+ } else if (kind === 1) {
184
+ newInit = newValue.init;
185
+ get = newValue.get || value.get;
186
+ set = newValue.set || value.set;
187
+ value = {
188
+ get: get,
189
+ set: set
190
+ };
191
+ } else {
192
+ value = newValue;
193
+ }
194
+ if (newInit !== void 0) {
195
+ if (init === void 0) {
196
+ init = newInit;
197
+ } else if (typeof init === "function") {
198
+ init = [
199
+ init,
200
+ newInit
201
+ ];
202
+ } else {
203
+ init.push(newInit);
204
+ }
205
+ }
206
+ }
207
+ }
208
+ }
209
+ if (kind === 0 || kind === 1) {
210
+ if (init === void 0) {
211
+ init = function(instance, init) {
212
+ return init;
213
+ };
214
+ } else if (typeof init !== "function") {
215
+ var ownInitializers = init;
216
+ init = function(instance, init) {
217
+ var value = init;
218
+ for(var i = 0; i < ownInitializers.length; i++){
219
+ value = ownInitializers[i].call(instance, value);
220
+ }
221
+ return value;
222
+ };
223
+ } else {
224
+ var originalInitializer = init;
225
+ init = function(instance, init) {
226
+ return originalInitializer.call(instance, init);
227
+ };
228
+ }
229
+ ret.push(init);
230
+ }
231
+ if (kind !== 0) {
232
+ if (kind === 1) {
233
+ desc.get = value.get;
234
+ desc.set = value.set;
235
+ } else if (kind === 2) {
236
+ desc.value = value;
237
+ } else if (kind === 3) {
238
+ desc.get = value;
239
+ } else if (kind === 4) {
240
+ desc.set = value;
241
+ }
242
+ if (isPrivate) {
243
+ if (kind === 1) {
244
+ ret.push(function(instance, args) {
245
+ return value.get.call(instance, args);
246
+ });
247
+ ret.push(function(instance, args) {
248
+ return value.set.call(instance, args);
249
+ });
250
+ } else if (kind === 2) {
251
+ ret.push(value);
252
+ } else {
253
+ ret.push(function(instance, args) {
254
+ return value.call(instance, args);
255
+ });
256
+ }
257
+ } else {
258
+ Object.defineProperty(base, name, desc);
259
+ }
260
+ }
261
+ }
262
+ function applyMemberDecs(Class, decInfos, metadata) {
263
+ var ret = [];
264
+ var protoInitializers;
265
+ var staticInitializers;
266
+ var existingProtoNonFields = new Map();
267
+ var existingStaticNonFields = new Map();
268
+ for(var i = 0; i < decInfos.length; i++){
269
+ var decInfo = decInfos[i];
270
+ if (!Array.isArray(decInfo)) continue;
271
+ var kind = decInfo[1];
272
+ var name = decInfo[2];
273
+ var isPrivate = decInfo.length > 3;
274
+ var isStatic = kind >= 5;
275
+ var base;
276
+ var initializers;
277
+ if (isStatic) {
278
+ base = Class;
279
+ kind = kind - 5;
280
+ staticInitializers = staticInitializers || [];
281
+ initializers = staticInitializers;
282
+ } else {
283
+ base = Class.prototype;
284
+ protoInitializers = protoInitializers || [];
285
+ initializers = protoInitializers;
286
+ }
287
+ if (kind !== 0 && !isPrivate) {
288
+ var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields;
289
+ var existingKind = existingNonFields.get(name) || 0;
290
+ if (existingKind === true || existingKind === 3 && kind !== 4 || existingKind === 4 && kind !== 3) {
291
+ throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + name);
292
+ } else if (!existingKind && kind > 2) {
293
+ existingNonFields.set(name, kind);
294
+ } else {
295
+ existingNonFields.set(name, true);
296
+ }
297
+ }
298
+ applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata);
299
+ }
300
+ pushInitializers(ret, protoInitializers);
301
+ pushInitializers(ret, staticInitializers);
302
+ return ret;
303
+ }
304
+ function pushInitializers(ret, initializers) {
305
+ if (initializers) {
306
+ ret.push(function(instance) {
307
+ for(var i = 0; i < initializers.length; i++){
308
+ initializers[i].call(instance);
309
+ }
310
+ return instance;
311
+ });
312
+ }
313
+ }
314
+ function applyClassDecs(targetClass, classDecs, metadata) {
315
+ if (classDecs.length > 0) {
316
+ var initializers = [];
317
+ var newClass = targetClass;
318
+ var name = targetClass.name;
319
+ for(var i = classDecs.length - 1; i >= 0; i--){
320
+ var decoratorFinishedRef = {
321
+ v: false
322
+ };
323
+ try {
324
+ var nextNewClass = classDecs[i](newClass, {
325
+ kind: "class",
326
+ name: name,
327
+ addInitializer: createAddInitializerMethod(initializers, decoratorFinishedRef),
328
+ metadata
329
+ });
330
+ } finally{
331
+ decoratorFinishedRef.v = true;
332
+ }
333
+ if (nextNewClass !== undefined) {
334
+ assertValidReturnValue(10, nextNewClass);
335
+ newClass = nextNewClass;
336
+ }
337
+ }
338
+ return [
339
+ defineMetadata(newClass, metadata),
340
+ function() {
341
+ for(var i = 0; i < initializers.length; i++){
342
+ initializers[i].call(newClass);
343
+ }
344
+ }
345
+ ];
346
+ }
347
+ }
348
+ function defineMetadata(Class, metadata) {
349
+ return Object.defineProperty(Class, Symbol.metadata || Symbol.for("Symbol.metadata"), {
350
+ configurable: true,
351
+ enumerable: true,
352
+ value: metadata
353
+ });
354
+ }
355
+ return function applyDecs2203R(targetClass, memberDecs, classDecs, parentClass) {
356
+ if (parentClass !== void 0) {
357
+ var parentMetadata = parentClass[Symbol.metadata || Symbol.for("Symbol.metadata")];
358
+ }
359
+ var metadata = Object.create(parentMetadata === void 0 ? null : parentMetadata);
360
+ var e = applyMemberDecs(targetClass, memberDecs, metadata);
361
+ if (!classDecs.length) defineMetadata(targetClass, metadata);
362
+ return {
363
+ e: e,
364
+ get c () {
365
+ return applyClassDecs(targetClass, classDecs, metadata);
366
+ }
367
+ };
368
+ };
369
+ }
370
+ function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
371
+ return (_apply_decs_2203_r = applyDecs2203RFactory())(targetClass, memberDecs, classDecs, parentClass);
372
+ }
373
+ var _dec, _dec1, _initProto;
374
+ import { Blob, getBlobsPerL1Block, getPrefixedEthBlobCommitments } from '@aztec/blob-lib';
375
+ import { FeeAssetPriceOracle, MULTI_CALL_3_ADDRESS, Multicall3, MulticallForwarderRevertedError, buildSimulationOverridesStateOverride } from '@aztec/ethereum/contracts';
376
+ import { L1FeeAnalyzer } from '@aztec/ethereum/l1-fee-analysis';
377
+ import { MAX_L1_TX_LIMIT, WEI_CONST } from '@aztec/ethereum/l1-tx-utils';
378
+ import { FormattedViemError, formatViemError, mergeAbis, tryDecodeRevertReason, tryExtractEvent } from '@aztec/ethereum/utils';
379
+ import { CheckpointNumber, SlotNumber } from '@aztec/foundation/branded-types';
380
+ import { trimmedBytesLength } from '@aztec/foundation/buffer';
381
+ import { pick } from '@aztec/foundation/collection';
382
+ import { TimeoutError } from '@aztec/foundation/error';
5
383
  import { EthAddress } from '@aztec/foundation/eth-address';
384
+ import { Signature } from '@aztec/foundation/eth-signature';
6
385
  import { createLogger } from '@aztec/foundation/log';
386
+ import { InterruptibleSleep } from '@aztec/foundation/sleep';
387
+ import { bufferToHex } from '@aztec/foundation/string';
7
388
  import { Timer } from '@aztec/foundation/timer';
8
- import { ForwarderAbi, RollupAbi } from '@aztec/l1-artifacts';
9
- import { ConsensusPayload, SignatureDomainSeparator, getHashedSignaturePayload } from '@aztec/stdlib/p2p';
10
- import { getTelemetryClient } from '@aztec/telemetry-client';
11
- import pick from 'lodash.pick';
12
- import { encodeFunctionData } from 'viem';
389
+ import { EmpireBaseAbi, ErrorsAbi, RollupAbi, SlashingProposerAbi } from '@aztec/l1-artifacts';
390
+ import { encodeSlashConsensusVotes } from '@aztec/slasher';
391
+ import { CommitteeAttestationsAndSigners } from '@aztec/stdlib/block';
392
+ import { getLastL1SlotTimestampForL2Slot, getNextL1SlotTimestamp, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
393
+ import { getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
394
+ import { encodeFunctionData, keccak256, toHex } from 'viem';
395
+ import { createL1TxFailedStore } from './l1_tx_failed_store/index.js';
396
+ import { SequencerBundleSimulator } from './sequencer-bundle-simulator.js';
13
397
  import { SequencerPublisherMetrics } from './sequencer-publisher-metrics.js';
14
- export var VoteType = /*#__PURE__*/ function(VoteType) {
15
- VoteType[VoteType["GOVERNANCE"] = 0] = "GOVERNANCE";
16
- VoteType[VoteType["SLASHING"] = 1] = "SLASHING";
17
- return VoteType;
18
- }({});
398
+ /**
399
+ * Returns true if the receipt indicates a successful send AND the expected event was emitted
400
+ * by the target contract. Both pieces are required: an aggregate3 entry that reverted will
401
+ * have receipt.status === 'success' but no event log.
402
+ */ function extractEventSuccess(receipt, opts) {
403
+ if (!receipt || receipt.status !== 'success') {
404
+ return false;
405
+ }
406
+ return !!tryExtractEvent(receipt.logs, opts.address.toString(), opts.abi, opts.eventName);
407
+ }
408
+ export const Actions = [
409
+ 'invalidate-by-invalid-attestation',
410
+ 'invalidate-by-insufficient-attestations',
411
+ 'propose',
412
+ 'governance-signal',
413
+ 'vote-offenses',
414
+ 'execute-slash'
415
+ ];
416
+ // Sorting for actions such that invalidations go before proposals, and proposals go before votes
417
+ export const compareActions = (a, b)=>Actions.indexOf(a) - Actions.indexOf(b);
418
+ _dec = trackSpan('SequencerPublisher.sendRequests'), _dec1 = trackSpan('SequencerPublisher.validateBlockHeader');
19
419
  export class SequencerPublisher {
20
- interrupted = false;
420
+ config;
421
+ static{
422
+ ({ e: [_initProto] } = _apply_decs_2203_r(this, [
423
+ [
424
+ _dec,
425
+ 2,
426
+ "sendRequests"
427
+ ],
428
+ [
429
+ _dec1,
430
+ 2,
431
+ "validateBlockHeader"
432
+ ]
433
+ ], []));
434
+ }
435
+ interrupted;
21
436
  metrics;
437
+ bundleSimulator;
22
438
  epochCache;
23
- forwarderContract;
24
- governanceLog = createLogger('sequencer:publisher:governance');
25
- governanceProposerAddress;
26
- governancePayload = EthAddress.ZERO;
27
- slashingLog = createLogger('sequencer:publisher:slashing');
28
- slashingProposerAddress;
29
- getSlashPayload = undefined;
30
- myLastVotes = {
31
- [0]: 0n,
32
- [1]: 0n
33
- };
34
- log = createLogger('sequencer:publisher');
439
+ failedTxStore;
440
+ /**
441
+ * ABI used to decode raw revert payloads from dropped bundle entries when the original
442
+ * request did not carry an abi (e.g. the propose request). Merges every contract the
443
+ * publisher can route to so any of their custom errors decode against it.
444
+ */ revertDecoderAbi;
445
+ lastActions;
446
+ log;
35
447
  ethereumSlotDuration;
36
- blobSinkClient;
37
- // @note - with blobs, the below estimate seems too large.
38
- // Total used for full block from int_l1_pub e2e test: 1m (of which 86k is 1x blob)
39
- // Total used for emptier block from above test: 429k (of which 84k is 1x blob)
40
- static PROPOSE_GAS_GUESS = 12_000_000n;
448
+ aztecSlotDuration;
449
+ /** Date provider for wall-clock time. */ dateProvider;
450
+ blobClient;
451
+ /** Optional callback to obtain a replacement publisher when the current one fails to send. */ getNextPublisher;
452
+ /** L1 fee analyzer for fisherman mode */ l1FeeAnalyzer;
453
+ /** Fee asset price oracle for computing price modifiers from Uniswap V4 */ feeAssetPriceOracle;
454
+ /** Interruptible sleep used by sendRequestsAt to wait until a target timestamp. */ interruptibleSleep;
41
455
  l1TxUtils;
42
456
  rollupContract;
43
457
  govProposerContract;
44
458
  slashingProposerContract;
45
- requests = [];
459
+ tracer;
460
+ requests;
46
461
  constructor(config, deps){
462
+ this.config = config;
463
+ this.interrupted = (_initProto(this), false);
464
+ this.revertDecoderAbi = mergeAbis([
465
+ RollupAbi,
466
+ SlashingProposerAbi,
467
+ EmpireBaseAbi,
468
+ ErrorsAbi
469
+ ]);
470
+ this.lastActions = {};
471
+ this.interruptibleSleep = new InterruptibleSleep();
472
+ this.requests = [];
473
+ this.log = deps.log ?? createLogger('sequencer:publisher');
47
474
  this.ethereumSlotDuration = BigInt(config.ethereumSlotDuration);
475
+ this.aztecSlotDuration = BigInt(config.aztecSlotDuration);
476
+ this.dateProvider = deps.dateProvider;
48
477
  this.epochCache = deps.epochCache;
49
- this.blobSinkClient = deps.blobSinkClient ?? createBlobSinkClient(config);
478
+ this.lastActions = deps.lastActions;
479
+ this.blobClient = deps.blobClient;
480
+ this.dateProvider = deps.dateProvider;
50
481
  const telemetry = deps.telemetry ?? getTelemetryClient();
51
- this.metrics = new SequencerPublisherMetrics(telemetry, 'SequencerPublisher');
482
+ this.metrics = deps.metrics ?? new SequencerPublisherMetrics(telemetry, 'SequencerPublisher');
483
+ this.tracer = telemetry.getTracer('SequencerPublisher');
52
484
  this.l1TxUtils = deps.l1TxUtils;
485
+ this.getNextPublisher = deps.getNextPublisher;
53
486
  this.rollupContract = deps.rollupContract;
54
- this.forwarderContract = deps.forwarderContract;
55
487
  this.govProposerContract = deps.governanceProposerContract;
56
488
  this.slashingProposerContract = deps.slashingProposerContract;
489
+ this.rollupContract.listenToSlasherChanged(async ()=>{
490
+ this.log.info('Slashing proposer changed');
491
+ const newSlashingProposer = await this.rollupContract.getSlashingProposer();
492
+ this.slashingProposerContract = newSlashingProposer;
493
+ });
494
+ // Initialize L1 fee analyzer for fisherman mode
495
+ if (config.fishermanMode) {
496
+ this.l1FeeAnalyzer = new L1FeeAnalyzer(this.l1TxUtils.client, deps.dateProvider, this.log.createChild('fee-analyzer'));
497
+ }
498
+ // Initialize fee asset price oracle
499
+ this.feeAssetPriceOracle = new FeeAssetPriceOracle(this.l1TxUtils.client, this.rollupContract, this.log.createChild('price-oracle'));
500
+ // Initialize failed L1 tx store (optional, for test networks)
501
+ this.failedTxStore = createL1TxFailedStore(config.l1TxFailedStore, this.log);
502
+ this.bundleSimulator = new SequencerBundleSimulator({
503
+ getL1TxUtils: ()=>this.l1TxUtils,
504
+ rollupContract: this.rollupContract,
505
+ epochCache: this.epochCache,
506
+ log: this.log.createChild('bundle-simulator')
507
+ });
57
508
  }
58
- registerSlashPayloadGetter(callback) {
59
- this.getSlashPayload = callback;
509
+ /**
510
+ * Backs up a failed L1 transaction to the configured store for debugging.
511
+ * Does nothing if no store is configured.
512
+ */ backupFailedTx(failedTx) {
513
+ if (!this.failedTxStore) {
514
+ return;
515
+ }
516
+ const tx = {
517
+ ...failedTx,
518
+ timestamp: Date.now()
519
+ };
520
+ // Fire and forget - don't block on backup
521
+ void this.failedTxStore.then((store)=>store?.saveFailedTx(tx)).catch((err)=>{
522
+ this.log.warn(`Failed to backup failed L1 tx to store`, err);
523
+ });
60
524
  }
61
- getForwarderAddress() {
62
- return EthAddress.fromString(this.forwarderContract.getAddress());
525
+ getRollupContract() {
526
+ return this.rollupContract;
63
527
  }
64
- getSenderAddress() {
65
- return EthAddress.fromString(this.l1TxUtils.getSenderAddress());
528
+ /**
529
+ * Gets the fee asset price modifier from the oracle.
530
+ *
531
+ * @param predictedParentEthPerFeeAssetE12 - Optional predicted parent eth-per-fee-asset (E12).
532
+ * Pipelined proposers should pass the value from the predicted parent fee header so the
533
+ * modifier matches the parent L1 will use when applying it.
534
+ * @returns The fee asset price modifier in basis points, or 0n if the oracle query fails.
535
+ */ getFeeAssetPriceModifier(predictedParentEthPerFeeAssetE12) {
536
+ return this.feeAssetPriceOracle.computePriceModifier(predictedParentEthPerFeeAssetE12);
66
537
  }
67
- getGovernancePayload() {
68
- return this.governancePayload;
538
+ getSenderAddress() {
539
+ return this.l1TxUtils.getSenderAddress();
69
540
  }
70
- setGovernancePayload(payload) {
71
- this.governancePayload = payload;
541
+ /**
542
+ * Gets the L1 fee analyzer instance (only available in fisherman mode)
543
+ */ getL1FeeAnalyzer() {
544
+ return this.l1FeeAnalyzer;
72
545
  }
73
546
  addRequest(request) {
74
547
  this.requests.push(request);
75
548
  }
76
549
  getCurrentL2Slot() {
77
- return this.epochCache.getEpochAndSlotNow().slot;
550
+ return this.epochCache.getSlotNow();
551
+ }
552
+ /**
553
+ * Clears all pending requests without sending them.
554
+ */ clearPendingRequests() {
555
+ const count = this.requests.length;
556
+ this.requests = [];
557
+ if (count > 0) {
558
+ this.log.debug(`Cleared ${count} pending request(s)`);
559
+ }
560
+ }
561
+ /**
562
+ * Analyzes L1 fees for the pending requests without sending them.
563
+ * This is used in fisherman mode to validate fee calculations.
564
+ * @param l2SlotNumber - The L2 slot number for this analysis
565
+ * @param onComplete - Optional callback to invoke when analysis completes (after block is mined)
566
+ * @returns The analysis result (incomplete until block mines), or undefined if no requests
567
+ */ async analyzeL1Fees(l2SlotNumber, onComplete) {
568
+ if (!this.l1FeeAnalyzer) {
569
+ this.log.warn('L1 fee analyzer not available (not in fisherman mode)');
570
+ return undefined;
571
+ }
572
+ const requestsToAnalyze = [
573
+ ...this.requests
574
+ ];
575
+ if (requestsToAnalyze.length === 0) {
576
+ this.log.debug('No requests to analyze for L1 fees');
577
+ return undefined;
578
+ }
579
+ // Extract blob config from requests (if any)
580
+ const blobConfigs = requestsToAnalyze.filter((request)=>request.blobConfig).map((request)=>request.blobConfig);
581
+ const blobConfig = blobConfigs[0];
582
+ // Get gas configs
583
+ const gasConfigs = requestsToAnalyze.filter((request)=>request.gasConfig).map((request)=>request.gasConfig);
584
+ const gasLimits = gasConfigs.map((g)=>g?.gasLimit).filter((g)=>g !== undefined);
585
+ const gasLimit = gasLimits.length > 0 ? gasLimits.reduce((sum, g)=>sum + g, 0n) : 0n;
586
+ // Get the transaction requests
587
+ const l1Requests = requestsToAnalyze.map((r)=>r.request);
588
+ // Start the analysis
589
+ const analysisId = await this.l1FeeAnalyzer.startAnalysis(l2SlotNumber, gasLimit > 0n ? gasLimit : MAX_L1_TX_LIMIT, l1Requests, blobConfig, onComplete);
590
+ this.log.info('Started L1 fee analysis', {
591
+ analysisId,
592
+ l2SlotNumber: l2SlotNumber.toString(),
593
+ requestCount: requestsToAnalyze.length,
594
+ hasBlobConfig: !!blobConfig,
595
+ gasLimit: gasLimit.toString(),
596
+ actions: requestsToAnalyze.map((r)=>r.action)
597
+ });
598
+ // Return the analysis result (will be incomplete until block mines)
599
+ return this.l1FeeAnalyzer.getAnalysis(analysisId);
78
600
  }
79
601
  /**
80
602
  * Sends all requests that are still valid.
603
+ * @param targetSlot - The target L2 slot for this send. When provided (the production path, via
604
+ * sendRequestsAt), it is threaded into bundleSimulate so the block.timestamp override matches
605
+ * the slot the propose is built for. When omitted, falls back to getCurrentL2Slot() for the
606
+ * AutomineSequencer, which publishes synchronously within the current slot.
81
607
  * @returns one of:
82
608
  * - A receipt and stats if the tx succeeded
83
609
  * - a receipt and errorMsg if it failed on L1
84
610
  * - undefined if no valid requests are found OR the tx failed to send.
85
- */ async sendRequests() {
611
+ */ async sendRequests(targetSlot) {
86
612
  const requestsToProcess = [
87
613
  ...this.requests
88
614
  ];
89
615
  this.requests = [];
90
- if (this.interrupted) {
616
+ if (this.interrupted || requestsToProcess.length === 0) {
91
617
  return undefined;
92
618
  }
93
- const currentL2Slot = this.getCurrentL2Slot();
94
- this.log.debug(`Current L2 slot: ${currentL2Slot}`);
619
+ const currentL2Slot = targetSlot ?? this.getCurrentL2Slot();
620
+ this.log.debug(`Sending requests on L2 slot ${currentL2Slot}`);
95
621
  const validRequests = requestsToProcess.filter((request)=>request.lastValidL2Slot >= currentL2Slot);
622
+ const expiredActions = requestsToProcess.filter((request)=>request.lastValidL2Slot < currentL2Slot).map((x)=>x.action);
96
623
  if (validRequests.length !== requestsToProcess.length) {
97
624
  this.log.warn(`Some requests were expired for slot ${currentL2Slot}`, {
98
625
  validRequests: validRequests.map((request)=>({
@@ -109,56 +636,235 @@ export class SequencerPublisher {
109
636
  this.log.debug(`No valid requests to send`);
110
637
  return undefined;
111
638
  }
112
- // @note - we can only have one gas config and one blob config per bundle
113
- // find requests with gas and blob configs
114
- // See https://github.com/AztecProtocol/aztec-packages/issues/11513
115
- const gasConfigs = requestsToProcess.filter((request)=>request.gasConfig);
116
- const blobConfigs = requestsToProcess.filter((request)=>request.blobConfig);
117
- if (gasConfigs.length > 1 || blobConfigs.length > 1) {
118
- throw new Error('Multiple gas or blob configs found');
119
- }
120
- const gasConfig = gasConfigs[0]?.gasConfig;
121
- const blobConfig = blobConfigs[0]?.blobConfig;
639
+ // Collect earliest txTimeoutAt across all requests.
640
+ const gasConfigs = validRequests.filter((request)=>request.gasConfig).map((request)=>request.gasConfig);
641
+ const txTimeoutAts = gasConfigs.map((g)=>g?.txTimeoutAt).filter((g)=>g !== undefined);
642
+ const txTimeoutAt = txTimeoutAts.length > 0 ? new Date(Math.min(...txTimeoutAts.map((g)=>g.getTime()))) : undefined;
643
+ // Sort the requests so that proposals always go first
644
+ // This ensures the committee gets precomputed correctly
645
+ validRequests.sort((a, b)=>compareActions(a.action, b.action));
122
646
  try {
647
+ // Bundle-level eth_simulateV1: filters out entries that revert and derives the gasLimit.
648
+ const bundleResult = await this.bundleSimulator.simulate(validRequests, currentL2Slot);
649
+ if (bundleResult.kind === 'aborted') {
650
+ this.logDroppedInSim(bundleResult.droppedRequests);
651
+ void this.backupDroppedInSim(bundleResult.droppedRequests);
652
+ return undefined;
653
+ }
654
+ const { requests, droppedRequests, gasLimit } = bundleResult.kind === 'fallback' ? {
655
+ requests: bundleResult.requests,
656
+ droppedRequests: bundleResult.droppedRequests,
657
+ gasLimit: MAX_L1_TX_LIMIT
658
+ } : bundleResult;
659
+ this.logDroppedInSim(droppedRequests);
660
+ // Compute blobConfig from survivors (not original validRequests) so that if the propose
661
+ // entry was dropped by bundleSimulate we don't attach a blob-typed config to a non-blob tx.
662
+ const [blobConfig] = requests.filter((r)=>r.blobConfig).map((r)=>r.blobConfig);
663
+ const txConfig = {
664
+ gasLimit,
665
+ txTimeoutAt
666
+ };
123
667
  this.log.debug('Forwarding transactions', {
124
- validRequests: validRequests.map((request)=>request.action)
668
+ requests: requests.map((request)=>request.action),
669
+ txConfig
125
670
  });
126
- const result = await this.forwarderContract.forward(validRequests.map((request)=>request.request), this.l1TxUtils, gasConfig, blobConfig, this.log);
127
- this.callbackBundledTransactions(validRequests, result);
128
- return result;
671
+ const result = await this.forwardWithPublisherRotation(requests, txConfig, blobConfig);
672
+ if (result === undefined) {
673
+ return undefined;
674
+ }
675
+ const { successfulActions = [], failedActions = [] } = this.callbackBundledTransactions(requests, result);
676
+ const allFailedActions = [
677
+ ...failedActions,
678
+ ...droppedRequests.map((d)=>d.request.action)
679
+ ];
680
+ return {
681
+ result,
682
+ expiredActions,
683
+ sentActions: requests.map((x)=>x.action),
684
+ successfulActions,
685
+ failedActions: allFailedActions
686
+ };
129
687
  } catch (err) {
130
688
  const viemError = formatViemError(err);
131
689
  this.log.error(`Failed to publish bundled transactions`, viemError);
132
690
  return undefined;
133
691
  } finally{
134
692
  try {
135
- this.metrics.recordSenderBalance(await this.l1TxUtils.getSenderBalance(), this.l1TxUtils.getSenderAddress());
693
+ this.metrics.recordSenderBalance(await this.l1TxUtils.getSenderBalance(), this.l1TxUtils.getSenderAddress().toString());
136
694
  } catch (err) {
137
695
  this.log.warn(`Failed to record balance after sending tx: ${err}`);
138
696
  }
139
697
  }
140
698
  }
699
+ /** Logs entries dropped by bundle simulation as warnings on the publisher's logger. */ logDroppedInSim(dropped) {
700
+ for (const drop of dropped){
701
+ const revertReasonDecoded = drop.revertReason ?? tryDecodeRevertReason(drop.returnData, this.revertDecoderAbi);
702
+ this.log.warn('Bundle entry dropped: action reverted in sim', {
703
+ action: drop.request.action,
704
+ revertReason: revertReasonDecoded ?? drop.returnData,
705
+ revertReasonDecoded,
706
+ returnData: drop.returnData
707
+ });
708
+ }
709
+ }
710
+ /** Backs up entries dropped by bundle simulation, one record per dropped action. */ async backupDroppedInSim(dropped) {
711
+ if (dropped.length === 0) {
712
+ return;
713
+ }
714
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
715
+ for (const { request: req } of dropped){
716
+ this.backupFailedTx({
717
+ id: keccak256(req.request.data),
718
+ failureType: 'simulation',
719
+ request: {
720
+ to: req.request.to,
721
+ data: req.request.data
722
+ },
723
+ l1BlockNumber: l1BlockNumber.toString(),
724
+ error: {
725
+ message: 'Bundle entry dropped: action reverted in sim'
726
+ },
727
+ context: {
728
+ actions: [
729
+ req.action
730
+ ],
731
+ sender: this.getSenderAddress().toString()
732
+ }
733
+ });
734
+ }
735
+ }
736
+ /**
737
+ * Forwards transactions via Multicall3, rotating to the next available publisher if a send
738
+ * failure occurs (i.e. the tx never reached the chain).
739
+ * On-chain reverts and simulation errors are returned as-is without rotation.
740
+ */ async forwardWithPublisherRotation(validRequests, txConfig, blobConfig) {
741
+ if (!txConfig?.gasLimit) {
742
+ throw new Error('gasLimit is required for bundled transactions');
743
+ }
744
+ const txConfigWithGasLimit = txConfig;
745
+ const triedAddresses = [];
746
+ let currentPublisher = this.l1TxUtils;
747
+ while(true){
748
+ if (txConfig.txTimeoutAt && new Date() > txConfig.txTimeoutAt) {
749
+ this.log.warn(`Tx timeout (${txConfig.txTimeoutAt.toISOString()}) elapsed; stopping publisher rotation`, {
750
+ triedAddresses: triedAddresses.map((a)=>a.toString())
751
+ });
752
+ return undefined;
753
+ }
754
+ triedAddresses.push(currentPublisher.getSenderAddress());
755
+ try {
756
+ const result = await Multicall3.forward(validRequests.map((r)=>r.request), currentPublisher, txConfigWithGasLimit, blobConfig, {
757
+ gasLimitRequired: true
758
+ });
759
+ this.l1TxUtils = currentPublisher;
760
+ return result;
761
+ } catch (err) {
762
+ if (err instanceof TimeoutError) {
763
+ throw err;
764
+ }
765
+ if (err instanceof MulticallForwarderRevertedError) {
766
+ this.log.error('Forwarder transaction reverted on-chain; not rotating publisher', err, {
767
+ transactionHash: err.receipt.transactionHash
768
+ });
769
+ return undefined;
770
+ }
771
+ const viemError = formatViemError(err);
772
+ if (!this.getNextPublisher) {
773
+ this.log.error('Failed to publish bundled transactions', viemError);
774
+ return undefined;
775
+ }
776
+ this.log.warn(`Publisher ${currentPublisher.getSenderAddress()} failed to send, rotating to next publisher`, viemError);
777
+ const nextPublisher = await this.getNextPublisher([
778
+ ...triedAddresses
779
+ ]);
780
+ if (!nextPublisher) {
781
+ this.log.error(`All available publishers exhausted (tried ${triedAddresses.length}), failed to publish bundled transactions`, viemError, {
782
+ triedAddresses: triedAddresses.map((a)=>a.toString())
783
+ });
784
+ return undefined;
785
+ }
786
+ currentPublisher = nextPublisher;
787
+ }
788
+ }
789
+ }
790
+ /*
791
+ * Schedules sending all enqueued requests at (or after) the start of the given L2 slot.
792
+ * Sleeps until one L1 slot before the L2 slot boundary so the tx has a chance of being
793
+ * picked up by the first L1 block of the L2 slot.
794
+ * NB: there is a known correctness risk — being included in the L1 block right before the
795
+ * L2 slot starts would revert propose with HeaderLib__InvalidSlotNumber.
796
+ * Uses InterruptibleSleep so it can be cancelled via interrupt().
797
+ */ async sendRequestsAt(targetSlot) {
798
+ const l1Constants = this.epochCache.getL1Constants();
799
+ // Start of the target L2 slot, in ms (getTimestampForSlot returns seconds).
800
+ const startOfTargetSlotMs = Number(getTimestampForSlot(targetSlot, l1Constants)) * 1000;
801
+ // Aim to be in the mempool one L1 slot before the L2 slot starts, so we have a chance of
802
+ // being picked up by the first L1 block of the L2 slot.
803
+ const submitAfterMs = startOfTargetSlotMs - Number(this.ethereumSlotDuration) * 1000;
804
+ const sleepMs = submitAfterMs - this.dateProvider.now();
805
+ if (sleepMs > 0) {
806
+ this.log.debug(`Sleeping ${sleepMs}ms before sending requests`, {
807
+ targetSlot,
808
+ submitAfterMs
809
+ });
810
+ await this.interruptibleSleep.sleep(sleepMs);
811
+ }
812
+ if (this.interrupted) {
813
+ return undefined;
814
+ }
815
+ return this.sendRequests(targetSlot);
816
+ }
141
817
  callbackBundledTransactions(requests, result) {
142
- const success = result?.receipt.status === 'success';
143
- const logger = success ? this.log.info : this.log.error;
818
+ const actionsListStr = requests.map((r)=>r.action).join(', ');
819
+ this.log.verbose(`Published bundled transactions (${actionsListStr})`, {
820
+ result,
821
+ requests: requests.map((r)=>({
822
+ ...r,
823
+ // Avoid logging large blob data
824
+ blobConfig: r.blobConfig ? {
825
+ ...r.blobConfig,
826
+ blobs: r.blobConfig.blobs.map((b)=>({
827
+ size: trimmedBytesLength(b)
828
+ }))
829
+ } : undefined
830
+ }))
831
+ });
832
+ const successfulActions = [];
833
+ const failedActions = [];
144
834
  for (const request of requests){
145
- logger(`Bundled [${request.action}] transaction [${success ? 'succeeded' : 'failed'}]`);
146
- request.onResult?.(request.request, result);
835
+ if (request.checkSuccess(request.request, result)) {
836
+ successfulActions.push(request.action);
837
+ } else {
838
+ failedActions.push(request.action);
839
+ }
147
840
  }
841
+ return {
842
+ successfulActions,
843
+ failedActions
844
+ };
148
845
  }
149
846
  /**
150
- * @notice Will call `canProposeAtNextEthBlock` to make sure that it is possible to propose
847
+ * @notice Will call `canProposeAt` to make sure that it is possible to propose
151
848
  * @param tipArchive - The archive to check
152
849
  * @returns The slot and block number if it is possible to propose, undefined otherwise
153
- */ canProposeAtNextEthBlock(tipArchive) {
154
- const ignoredErrors = [
850
+ */ async canProposeAt(tipArchive, msgSender, simulationOverridesPlan) {
851
+ // TODO: #14291 - should loop through multiple keys to check if any of them can propose
852
+ // These errors are expected when we cannot actually propose right now — usually because our
853
+ // local view of the chain is ahead of L1 (proposed parent hasn't landed yet, or someone
854
+ // else has just landed the slot, or the archive override doesn't match). We log a warn and
855
+ // skip the proposal; we do NOT treat these as bugs.
856
+ const expectedErrors = [
155
857
  'SlotAlreadyInChain',
156
858
  'InvalidProposer',
157
859
  'InvalidArchive'
158
860
  ];
159
- return this.rollupContract.canProposeAtNextEthBlock(tipArchive, this.getForwarderAddress().toString(), this.ethereumSlotDuration).catch((err)=>{
160
- if (err instanceof FormattedViemError && ignoredErrors.find((e)=>err.message.includes(e))) {
161
- this.log.debug(err.message);
861
+ const slotOffset = this.aztecSlotDuration;
862
+ const nextL1SlotTs = this.getNextL1SlotTimestamp() + slotOffset;
863
+ return this.rollupContract.canProposeAt(tipArchive.toBuffer(), msgSender.toString(), nextL1SlotTs, await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan)).catch((err)=>{
864
+ if (err instanceof FormattedViemError && expectedErrors.find((e)=>err.message.includes(e))) {
865
+ this.log.warn(`Failed canProposeAtTime check with ${expectedErrors.find((e)=>err.message.includes(e))}`, {
866
+ error: err.message
867
+ });
162
868
  } else {
163
869
  this.log.error(err.name, err);
164
870
  }
@@ -166,135 +872,406 @@ export class SequencerPublisher {
166
872
  });
167
873
  }
168
874
  /**
169
- * @notice Will call `validateHeader` to make sure that it is possible to propose
170
- *
171
- * @dev Throws if unable to propose
172
- *
173
- * @param header - The header to propose
174
- * @param digest - The digest that attestations are signing over
175
- *
176
- */ async validateBlockForSubmission(header, attestationData = {
177
- digest: Buffer.alloc(32),
178
- signatures: []
179
- }) {
180
- const ts = BigInt((await this.l1TxUtils.getBlock()).timestamp + this.ethereumSlotDuration);
181
- const formattedSignatures = attestationData.signatures.map((attest)=>attest.toViemSignature());
875
+ * @notice Will simulate `validateHeader` to make sure that the block header is valid
876
+ * @dev This is a convenience function that can be used by the sequencer to validate a "partial" header.
877
+ * It will throw if the block header is invalid.
878
+ * @param header - The block header to validate
879
+ */ async validateBlockHeader(header, simulationOverridesPlan) {
182
880
  const flags = {
183
881
  ignoreDA: true,
184
- ignoreSignatures: formattedSignatures.length == 0
882
+ ignoreSignatures: true
185
883
  };
186
884
  const args = [
187
- `0x${header.toBuffer().toString('hex')}`,
188
- formattedSignatures,
189
- `0x${attestationData.digest.toString('hex')}`,
190
- ts,
191
- `0x${header.contentCommitment.blobsHash.toString('hex')}`,
885
+ header.toViem(),
886
+ CommitteeAttestationsAndSigners.packAttestations([]),
887
+ [],
888
+ Signature.empty().toViemSignature(),
889
+ `0x${'0'.repeat(64)}`,
890
+ header.blobsHash.toString(),
192
891
  flags
193
892
  ];
194
- await this.rollupContract.validateHeader(args, this.getForwarderAddress().toString());
195
- return ts;
893
+ const l1Constants = this.epochCache.getL1Constants();
894
+ const ts = getLastL1SlotTimestampForL2Slot(header.slotNumber, l1Constants);
895
+ const stateOverrides = await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan);
896
+ let balance = 0n;
897
+ if (this.config.fishermanMode) {
898
+ // In fisherman mode, we can't know where the proposer is publishing from
899
+ // so we just add sufficient balance to the multicall3 address
900
+ balance = 10n * WEI_CONST * WEI_CONST; // 10 ETH
901
+ } else {
902
+ balance = await this.l1TxUtils.getSenderBalance();
903
+ }
904
+ stateOverrides.push({
905
+ address: MULTI_CALL_3_ADDRESS,
906
+ balance
907
+ });
908
+ await this.l1TxUtils.simulate({
909
+ to: this.rollupContract.address,
910
+ data: encodeFunctionData({
911
+ abi: RollupAbi,
912
+ functionName: 'validateHeaderWithAttestations',
913
+ args
914
+ }),
915
+ from: MULTI_CALL_3_ADDRESS
916
+ }, {
917
+ time: ts
918
+ }, stateOverrides);
919
+ this.log.debug(`Simulated validateHeader`);
196
920
  }
197
- async getCurrentEpochCommittee() {
198
- const committee = await this.rollupContract.getCurrentEpochCommittee();
199
- return committee.map(EthAddress.fromString);
921
+ /**
922
+ * Simulate making a call to invalidate a checkpoint with invalid attestations. Returns undefined if no need to invalidate.
923
+ * @param validationResult - The validation result indicating which checkpoint to invalidate (as returned by the archiver)
924
+ */ async simulateInvalidateCheckpoint(validationResult) {
925
+ if (validationResult.valid) {
926
+ return undefined;
927
+ }
928
+ const { reason, checkpoint } = validationResult;
929
+ const checkpointNumber = checkpoint.checkpointNumber;
930
+ const logData = {
931
+ ...checkpoint,
932
+ reason
933
+ };
934
+ const currentCheckpointNumber = await this.rollupContract.getCheckpointNumber();
935
+ if (currentCheckpointNumber < checkpointNumber) {
936
+ this.log.verbose(`Skipping checkpoint ${checkpointNumber} invalidation since it has already been removed from the pending chain`, {
937
+ currentCheckpointNumber,
938
+ ...logData
939
+ });
940
+ return undefined;
941
+ }
942
+ const request = this.buildInvalidateCheckpointRequest(validationResult);
943
+ this.log.debug(`Simulating invalidate checkpoint ${checkpointNumber}`, {
944
+ ...logData,
945
+ request
946
+ });
947
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
948
+ try {
949
+ const { gasUsed } = await this.l1TxUtils.simulate(request, undefined, undefined, mergeAbis([
950
+ request.abi ?? [],
951
+ ErrorsAbi
952
+ ]));
953
+ this.log.verbose(`Simulation for invalidate checkpoint ${checkpointNumber} succeeded`, {
954
+ ...logData,
955
+ request,
956
+ gasUsed
957
+ });
958
+ return {
959
+ request,
960
+ gasUsed,
961
+ checkpointNumber,
962
+ forcePendingCheckpointNumber: CheckpointNumber(checkpointNumber - 1),
963
+ lastArchive: validationResult.checkpoint.lastArchive,
964
+ reason
965
+ };
966
+ } catch (err) {
967
+ const viemError = formatViemError(err);
968
+ // If the error is due to the checkpoint not being in the pending chain, and it was indeed removed by someone else,
969
+ // we can safely ignore it and return undefined so we go ahead with checkpoint building.
970
+ if (viemError.message?.includes('Rollup__CheckpointNotInPendingChain')) {
971
+ this.log.verbose(`Simulation for invalidate checkpoint ${checkpointNumber} failed due to checkpoint not being in pending chain`, {
972
+ ...logData,
973
+ request,
974
+ error: viemError.message
975
+ });
976
+ const latestProposedCheckpointNumber = await this.rollupContract.getCheckpointNumber();
977
+ if (latestProposedCheckpointNumber < checkpointNumber) {
978
+ this.log.verbose(`Checkpoint ${checkpointNumber} has already been invalidated`, {
979
+ ...logData
980
+ });
981
+ return undefined;
982
+ } else {
983
+ this.log.error(`Simulation for invalidate checkpoint ${checkpointNumber} failed and it is still in pending chain`, viemError, logData);
984
+ throw new Error(`Failed to simulate invalidate checkpoint ${checkpointNumber} while it is still in pending chain`, {
985
+ cause: viemError
986
+ });
987
+ }
988
+ }
989
+ // Otherwise, throw. We cannot build the next checkpoint if we cannot invalidate the previous one.
990
+ this.log.error(`Simulation for invalidate checkpoint ${checkpointNumber} failed`, viemError, logData);
991
+ this.backupFailedTx({
992
+ id: keccak256(request.data),
993
+ failureType: 'simulation',
994
+ request: {
995
+ to: request.to,
996
+ data: request.data,
997
+ value: request.value?.toString()
998
+ },
999
+ l1BlockNumber: l1BlockNumber.toString(),
1000
+ error: {
1001
+ message: viemError.message,
1002
+ name: viemError.name
1003
+ },
1004
+ context: {
1005
+ actions: [
1006
+ `invalidate-${reason}`
1007
+ ],
1008
+ checkpointNumber,
1009
+ sender: this.getSenderAddress().toString()
1010
+ }
1011
+ });
1012
+ throw new Error(`Failed to simulate invalidate checkpoint ${checkpointNumber}`, {
1013
+ cause: viemError
1014
+ });
1015
+ }
1016
+ }
1017
+ buildInvalidateCheckpointRequest(validationResult) {
1018
+ if (validationResult.valid) {
1019
+ throw new Error('Cannot invalidate a valid checkpoint');
1020
+ }
1021
+ const { checkpoint, committee, reason } = validationResult;
1022
+ const logData = {
1023
+ ...checkpoint,
1024
+ reason
1025
+ };
1026
+ this.log.debug(`Building invalidate checkpoint ${checkpoint.checkpointNumber} request`, logData);
1027
+ const attestationsAndSigners = CommitteeAttestationsAndSigners.packAttestations(validationResult.attestations);
1028
+ if (reason === 'invalid-attestation') {
1029
+ return this.rollupContract.buildInvalidateBadAttestationRequest(checkpoint.checkpointNumber, attestationsAndSigners, committee, validationResult.invalidIndex);
1030
+ } else if (reason === 'insufficient-attestations') {
1031
+ return this.rollupContract.buildInvalidateInsufficientAttestationsRequest(checkpoint.checkpointNumber, attestationsAndSigners, committee);
1032
+ } else {
1033
+ const _ = reason;
1034
+ throw new Error(`Unknown reason for invalidation`);
1035
+ }
200
1036
  }
201
- async enqueueCastVoteHelper(slotNumber, timestamp, voteType, payload, base) {
202
- if (this.myLastVotes[voteType] >= slotNumber) {
1037
+ async enqueueCastSignalHelper(slotNumber, signalType, payload, base, signerAddress, signer) {
1038
+ if (this.lastActions[signalType] && this.lastActions[signalType] === slotNumber) {
1039
+ this.log.debug(`Skipping duplicate vote cast signal ${signalType} for slot ${slotNumber}`);
203
1040
  return false;
204
1041
  }
205
1042
  if (payload.equals(EthAddress.ZERO)) {
206
1043
  return false;
207
1044
  }
1045
+ if (signerAddress.equals(EthAddress.ZERO)) {
1046
+ this.log.warn(`Cannot enqueue vote cast signal ${signalType} for address zero at slot ${slotNumber}`);
1047
+ return false;
1048
+ }
208
1049
  const round = await base.computeRound(slotNumber);
209
- const [proposer, roundInfo] = await Promise.all([
210
- this.rollupContract.getProposerAt(timestamp),
211
- base.getRoundInfo(this.rollupContract.address, round)
212
- ]);
213
- if (proposer.toLowerCase() !== this.getForwarderAddress().toString().toLowerCase()) {
1050
+ const roundInfo = await base.getRoundInfo(this.rollupContract.address, round);
1051
+ if (roundInfo.quorumReached) {
214
1052
  return false;
215
1053
  }
216
- if (roundInfo.lastVote >= slotNumber) {
1054
+ if (roundInfo.lastSignalSlot >= slotNumber) {
217
1055
  return false;
218
1056
  }
219
- const cachedLastVote = this.myLastVotes[voteType];
220
- this.myLastVotes[voteType] = slotNumber;
1057
+ if (await base.isPayloadEmpty(payload)) {
1058
+ this.log.warn(`Skipping vote cast for payload with empty code`);
1059
+ return false;
1060
+ }
1061
+ // Skip signaling if there is already a live (non-terminal) Governance proposal for this
1062
+ // payload. This is intentionally not cached: a previously-live proposal may transition to
1063
+ // a terminal state (Dropped/Rejected/Expired/Executed), at which point we may want to re-signal
1064
+ // the same payload in a future round.
1065
+ let proposed = false;
1066
+ try {
1067
+ proposed = await base.hasActiveProposalWithPayload(payload.toString());
1068
+ } catch (err) {
1069
+ // We deliberately swallow the error and proceed to signal. Failing closed (skipping the
1070
+ // signal) on transient RPC errors would let a flaky L1 endpoint silence governance
1071
+ // participation entirely; failing open at worst produces a duplicate signal that the
1072
+ // contract will simply count alongside others in the round.
1073
+ this.log.error(`Failed to check if payload ${payload} was already proposed (signalling anyway)`, err);
1074
+ }
1075
+ if (proposed) {
1076
+ this.log.info(`Payload ${payload} has a live governance proposal, stopping signals`);
1077
+ return false;
1078
+ }
1079
+ const cachedLastVote = this.lastActions[signalType];
1080
+ this.lastActions[signalType] = slotNumber;
1081
+ const action = signalType;
1082
+ const request = await base.createSignalRequestWithSignature(payload.toString(), slotNumber, this.config.l1ChainId, signerAddress.toString(), signer);
1083
+ this.log.debug(`Created ${action} request with signature`, {
1084
+ request,
1085
+ round,
1086
+ signer: this.l1TxUtils.client.account?.address,
1087
+ lastValidL2Slot: slotNumber
1088
+ });
1089
+ // TODO(palla/slash): All votes (governance and slashing) should txTimeoutAt at the end of the slot.
221
1090
  this.addRequest({
222
- action: voteType === 0 ? 'governance-vote' : 'slashing-vote',
223
- request: base.createVoteRequest(payload.toString()),
1091
+ action,
1092
+ request,
224
1093
  lastValidL2Slot: slotNumber,
225
- onResult: (_request, result)=>{
226
- if (!result || result.receipt.status !== 'success') {
227
- this.myLastVotes[voteType] = cachedLastVote;
1094
+ checkSuccess: (_request, result)=>{
1095
+ const success = result && extractEventSuccess(result.receipt, {
1096
+ address: base.address.toString(),
1097
+ abi: EmpireBaseAbi,
1098
+ eventName: 'SignalCast'
1099
+ });
1100
+ const logData = {
1101
+ ...result,
1102
+ slotNumber,
1103
+ round,
1104
+ payload: payload.toString()
1105
+ };
1106
+ if (!success) {
1107
+ this.log.error(`Signaling in ${action} for ${payload} at slot ${slotNumber} in round ${round} failed`, logData);
1108
+ this.lastActions[signalType] = cachedLastVote;
1109
+ return false;
228
1110
  } else {
229
- this.log.info(`Cast [${voteType}] vote for slot ${slotNumber}`);
1111
+ this.log.info(`Signaling in ${action} for ${payload} at slot ${slotNumber} in round ${round} succeeded`, logData);
1112
+ return true;
230
1113
  }
231
1114
  }
232
1115
  });
233
1116
  return true;
234
1117
  }
235
- async getVoteConfig(slotNumber, voteType) {
236
- if (voteType === 0) {
237
- return {
238
- payload: this.governancePayload,
239
- base: this.govProposerContract
240
- };
241
- } else if (voteType === 1) {
242
- if (!this.getSlashPayload) {
243
- return undefined;
244
- }
245
- const slashPayload = await this.getSlashPayload(slotNumber);
246
- if (!slashPayload) {
247
- return undefined;
248
- }
249
- return {
250
- payload: slashPayload,
251
- base: this.slashingProposerContract
252
- };
253
- }
254
- throw new Error('Unreachable: Invalid vote type');
255
- }
256
1118
  /**
257
- * Enqueues a castVote transaction to cast a vote for a given slot number.
258
- * @param slotNumber - The slot number to cast a vote for.
259
- * @param timestamp - The timestamp of the slot to cast a vote for.
260
- * @param voteType - The type of vote to cast.
261
- * @returns True if the vote was successfully enqueued, false otherwise.
262
- */ async enqueueCastVote(slotNumber, timestamp, voteType) {
263
- const voteConfig = await this.getVoteConfig(slotNumber, voteType);
264
- if (!voteConfig) {
1119
+ * Enqueues a governance castSignal transaction to cast a signal for a given slot number.
1120
+ * @param slotNumber - The slot number to cast a signal for.
1121
+ * @returns True if the signal was successfully enqueued, false otherwise.
1122
+ */ enqueueGovernanceCastSignal(governancePayload, slotNumber, signerAddress, signer) {
1123
+ return this.enqueueCastSignalHelper(slotNumber, 'governance-signal', governancePayload, this.govProposerContract, signerAddress, signer);
1124
+ }
1125
+ /** Enqueues all slashing actions as returned by the slasher client. */ async enqueueSlashingActions(actions, slotNumber, signerAddress, signer) {
1126
+ if (actions.length === 0) {
1127
+ this.log.debug(`No slashing actions to enqueue for slot ${slotNumber}`);
265
1128
  return false;
266
1129
  }
267
- const { payload, base } = voteConfig;
268
- return this.enqueueCastVoteHelper(slotNumber, timestamp, voteType, payload, base);
1130
+ for (const action of actions){
1131
+ switch(action.type){
1132
+ case 'vote-offenses':
1133
+ {
1134
+ this.log.debug(`Enqueuing slashing vote for ${action.votes.length} votes at slot ${slotNumber}`, {
1135
+ slotNumber,
1136
+ round: action.round,
1137
+ votesCount: action.votes.length,
1138
+ signerAddress
1139
+ });
1140
+ if (!this.slashingProposerContract) {
1141
+ this.log.error('No slashing proposer contract available');
1142
+ return false;
1143
+ }
1144
+ const votes = bufferToHex(encodeSlashConsensusVotes(action.votes));
1145
+ const request = await this.slashingProposerContract.buildVoteRequestFromSigner(votes, slotNumber, signer);
1146
+ this.enqueueRequest('vote-offenses', request, {
1147
+ address: this.slashingProposerContract.address.toString(),
1148
+ abi: SlashingProposerAbi,
1149
+ eventName: 'VoteCast'
1150
+ }, slotNumber);
1151
+ break;
1152
+ }
1153
+ case 'execute-slash':
1154
+ {
1155
+ this.log.debug(`Enqueuing slash execution for round ${action.round} at slot ${slotNumber}`, {
1156
+ slotNumber,
1157
+ round: action.round,
1158
+ signerAddress
1159
+ });
1160
+ if (!this.slashingProposerContract) {
1161
+ this.log.error('No slashing proposer contract available');
1162
+ return false;
1163
+ }
1164
+ const executeRequest = this.slashingProposerContract.buildExecuteRoundRequest(action.round, action.committees);
1165
+ this.enqueueRequest('execute-slash', executeRequest, {
1166
+ address: this.slashingProposerContract.address.toString(),
1167
+ abi: SlashingProposerAbi,
1168
+ eventName: 'RoundExecuted'
1169
+ }, slotNumber);
1170
+ break;
1171
+ }
1172
+ default:
1173
+ {
1174
+ const _ = action;
1175
+ throw new Error(`Unknown slashing action type: ${action.type}`);
1176
+ }
1177
+ }
1178
+ }
1179
+ return true;
269
1180
  }
270
- /**
271
- * Proposes a L2 block on L1.
272
- *
273
- * @param block - L2 block to propose.
274
- * @returns True if the tx has been enqueued, throws otherwise. See #9315
275
- */ async enqueueProposeL2Block(block, attestations, txHashes, opts = {}) {
276
- const consensusPayload = new ConsensusPayload(block.header, block.archive.root, txHashes ?? []);
277
- const digest = await getHashedSignaturePayload(consensusPayload, SignatureDomainSeparator.blockAttestation);
278
- const blobs = await Blob.getBlobs(block.body.toBlobFields());
1181
+ /** Enqueues a proposal for a checkpoint on L1 */ async enqueueProposeCheckpoint(checkpoint, attestationsAndSigners, attestationsAndSignersSignature, opts = {}) {
1182
+ const checkpointHeader = checkpoint.header;
1183
+ const blobFields = checkpoint.toBlobFields();
1184
+ const blobs = await getBlobsPerL1Block(blobFields);
279
1185
  const proposeTxArgs = {
280
- header: block.header.toBuffer(),
281
- archive: block.archive.root.toBuffer(),
282
- blockHash: (await block.header.hash()).toBuffer(),
283
- body: block.body.toBuffer(),
1186
+ header: checkpointHeader,
1187
+ archive: checkpoint.archive.root.toBuffer(),
284
1188
  blobs,
285
- attestations,
286
- txHashes: txHashes ?? []
1189
+ attestationsAndSigners,
1190
+ attestationsAndSignersSignature,
1191
+ feeAssetPriceModifier: checkpoint.feeAssetPriceModifier
1192
+ };
1193
+ this.log.verbose(`Enqueuing checkpoint propose transaction`, {
1194
+ ...checkpoint.toCheckpointInfo(),
1195
+ txTimeoutAt: opts.txTimeoutAt
1196
+ });
1197
+ await this.addProposeTx(checkpoint, proposeTxArgs, {
1198
+ txTimeoutAt: opts.txTimeoutAt
1199
+ });
1200
+ }
1201
+ enqueueInvalidateCheckpoint(request, opts = {}) {
1202
+ if (!request) {
1203
+ return;
1204
+ }
1205
+ const { gasUsed, checkpointNumber } = request;
1206
+ const logData = {
1207
+ gasUsed,
1208
+ checkpointNumber,
1209
+ opts
287
1210
  };
288
- // @note This will make sure that we are passing the checks for our header ASSUMING that the data is also made available
289
- // This means that we can avoid the simulation issues in later checks.
290
- // By simulation issue, I mean the fact that the block.timestamp is equal to the last block, not the next, which
291
- // make time consistency checks break.
292
- const ts = await this.validateBlockForSubmission(block.header, {
293
- digest: digest.toBuffer(),
294
- signatures: attestations ?? []
1211
+ this.log.verbose(`Enqueuing invalidate checkpoint request`, logData);
1212
+ this.addRequest({
1213
+ action: `invalidate-by-${request.reason}`,
1214
+ request: request.request,
1215
+ gasConfig: opts.txTimeoutAt ? {
1216
+ txTimeoutAt: opts.txTimeoutAt
1217
+ } : undefined,
1218
+ lastValidL2Slot: SlotNumber(this.getCurrentL2Slot() + 2),
1219
+ checkSuccess: (_req, result)=>{
1220
+ const success = result && extractEventSuccess(result.receipt, {
1221
+ address: this.rollupContract.address,
1222
+ abi: RollupAbi,
1223
+ eventName: 'CheckpointInvalidated'
1224
+ });
1225
+ if (!success) {
1226
+ this.log.warn(`Invalidate checkpoint ${request.checkpointNumber} failed`, {
1227
+ ...result,
1228
+ ...logData
1229
+ });
1230
+ } else {
1231
+ this.log.info(`Invalidate checkpoint ${request.checkpointNumber} succeeded`, {
1232
+ ...result,
1233
+ ...logData
1234
+ });
1235
+ }
1236
+ return !!success;
1237
+ }
1238
+ });
1239
+ }
1240
+ /**
1241
+ * Dedup-checked enqueue helper for actions that are simulated at bundle-send time rather
1242
+ * than at enqueue time. Validates the (action, slot) dedup key, sets `lastActions`, and
1243
+ * enqueues without a gasLimit so the bundle simulate sets the only gasLimit that matters.
1244
+ */ enqueueRequest(action, request, eventOpts, slotNumber) {
1245
+ if (this.lastActions[action] && this.lastActions[action] === slotNumber) {
1246
+ this.log.debug(`Skipping duplicate action ${action} for slot ${slotNumber}`);
1247
+ return false;
1248
+ }
1249
+ const cachedLastActionSlot = this.lastActions[action];
1250
+ this.lastActions[action] = slotNumber;
1251
+ this.log.debug(`Enqueuing ${action}`, {
1252
+ slotNumber
1253
+ });
1254
+ this.addRequest({
1255
+ action,
1256
+ request,
1257
+ lastValidL2Slot: slotNumber,
1258
+ checkSuccess: (_request, result)=>{
1259
+ const success = result && extractEventSuccess(result.receipt, eventOpts);
1260
+ if (!success) {
1261
+ this.log.warn(`Action ${action} at ${slotNumber} failed`, {
1262
+ ...result,
1263
+ slotNumber
1264
+ });
1265
+ this.lastActions[action] = cachedLastActionSlot;
1266
+ } else {
1267
+ this.log.info(`Action ${action} at ${slotNumber} succeeded`, {
1268
+ ...result,
1269
+ slotNumber
1270
+ });
1271
+ }
1272
+ return !!success;
1273
+ }
295
1274
  });
296
- this.log.debug(`Submitting propose transaction`);
297
- await this.addProposeTx(block, proposeTxArgs, opts, ts);
298
1275
  return true;
299
1276
  }
300
1277
  /**
@@ -304,51 +1281,92 @@ export class SequencerPublisher {
304
1281
  * A call to `restart` is required before you can continue publishing.
305
1282
  */ interrupt() {
306
1283
  this.interrupted = true;
1284
+ this.interruptibleSleep.interrupt();
307
1285
  this.l1TxUtils.interrupt();
308
1286
  }
309
1287
  /** Restarts the publisher after calling `interrupt`. */ restart() {
310
1288
  this.interrupted = false;
311
1289
  this.l1TxUtils.restart();
312
1290
  }
313
- async prepareProposeTx(encodedData, timestamp) {
1291
+ async prepareProposeTx(encodedData) {
314
1292
  const kzg = Blob.getViemKzgInstance();
315
- const blobInput = Blob.getEthBlobEvaluationInputs(encodedData.blobs);
1293
+ const blobInput = getPrefixedEthBlobCommitments(encodedData.blobs);
316
1294
  this.log.debug('Validating blob input', {
317
1295
  blobInput
318
1296
  });
319
- const blobEvaluationGas = await this.l1TxUtils.estimateGas(this.l1TxUtils.walletClient.account, {
320
- to: this.rollupContract.address,
321
- data: encodeFunctionData({
322
- abi: RollupAbi,
323
- functionName: 'validateBlobs',
324
- args: [
325
- blobInput
326
- ]
327
- })
328
- }, {}, {
329
- blobs: encodedData.blobs.map((b)=>b.data),
330
- kzg
331
- }).catch((err)=>{
332
- const { message, metaMessages } = formatViemError(err);
333
- this.log.error(`Failed to validate blobs`, message, {
334
- metaMessages
1297
+ // Get blob evaluation gas
1298
+ let blobEvaluationGas;
1299
+ if (this.config.fishermanMode) {
1300
+ // In fisherman mode, we can't estimate blob gas because estimateGas doesn't support state overrides
1301
+ // Use a fixed estimate.
1302
+ blobEvaluationGas = BigInt(encodedData.blobs.length) * 21_000n;
1303
+ this.log.debug(`Using fixed blob evaluation gas estimate in fisherman mode: ${blobEvaluationGas}`);
1304
+ } else {
1305
+ // We call validateBlobs via estimateGas with real blob+kzg sidecars as a consistency check
1306
+ // that our locally-built blob commitments match the blob data. The bundle simulate at send
1307
+ // time uses eth_simulateV1, which cannot carry blob inputs, so the rollup's on-chain blob
1308
+ // check is forced off there — making this the only pre-flight detector of a commitment/data
1309
+ // mismatch. The returned gas estimate is stashed on the request for the bundle path to read.
1310
+ blobEvaluationGas = await this.l1TxUtils.estimateGas(this.getSenderAddress().toString(), {
1311
+ to: this.rollupContract.address,
1312
+ data: encodeFunctionData({
1313
+ abi: RollupAbi,
1314
+ functionName: 'validateBlobs',
1315
+ args: [
1316
+ blobInput
1317
+ ]
1318
+ })
1319
+ }, {}, {
1320
+ blobs: encodedData.blobs.map((b)=>b.data),
1321
+ kzg
1322
+ }).catch(async (err)=>{
1323
+ const viemError = formatViemError(err);
1324
+ this.log.error(`Failed to validate blobs`, viemError.message, {
1325
+ metaMessages: viemError.metaMessages
1326
+ });
1327
+ const validateBlobsData = encodeFunctionData({
1328
+ abi: RollupAbi,
1329
+ functionName: 'validateBlobs',
1330
+ args: [
1331
+ blobInput
1332
+ ]
1333
+ });
1334
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
1335
+ this.backupFailedTx({
1336
+ id: keccak256(validateBlobsData),
1337
+ failureType: 'simulation',
1338
+ request: {
1339
+ to: this.rollupContract.address,
1340
+ data: validateBlobsData
1341
+ },
1342
+ blobData: encodedData.blobs.map((b)=>toHex(b.data)),
1343
+ l1BlockNumber: l1BlockNumber.toString(),
1344
+ error: {
1345
+ message: viemError.message,
1346
+ name: viemError.name
1347
+ },
1348
+ context: {
1349
+ actions: [
1350
+ 'validate-blobs'
1351
+ ],
1352
+ sender: this.getSenderAddress().toString()
1353
+ }
1354
+ });
1355
+ throw new Error('Failed to validate blobs');
335
1356
  });
336
- throw new Error('Failed to validate blobs');
337
- });
338
- const attestations = encodedData.attestations ? encodedData.attestations.map((attest)=>attest.toViemSignature()) : [];
339
- const txHashes = encodedData.txHashes ? encodedData.txHashes.map((txHash)=>txHash.toString()) : [];
1357
+ }
1358
+ const signers = encodedData.attestationsAndSigners.getSigners().map((signer)=>signer.toString());
340
1359
  const args = [
341
1360
  {
342
- header: `0x${encodedData.header.toString('hex')}`,
343
- archive: `0x${encodedData.archive.toString('hex')}`,
1361
+ header: encodedData.header.toViem(),
1362
+ archive: toHex(encodedData.archive),
344
1363
  oracleInput: {
345
- // We are currently not modifying these. See #9963
346
- feeAssetPriceModifier: 0n
347
- },
348
- blockHash: `0x${encodedData.blockHash.toString('hex')}`,
349
- txHashes
1364
+ feeAssetPriceModifier: encodedData.feeAssetPriceModifier
1365
+ }
350
1366
  },
351
- attestations,
1367
+ encodedData.attestationsAndSigners.getPackedAttestations(),
1368
+ signers,
1369
+ encodedData.attestationsAndSignersSignature.toViemSignature(),
352
1370
  blobInput
353
1371
  ];
354
1372
  const rollupData = encodeFunctionData({
@@ -356,126 +1374,87 @@ export class SequencerPublisher {
356
1374
  functionName: 'propose',
357
1375
  args
358
1376
  });
359
- const forwarderData = encodeFunctionData({
360
- abi: ForwarderAbi,
361
- functionName: 'forward',
362
- args: [
363
- [
364
- this.rollupContract.address
365
- ],
366
- [
367
- rollupData
368
- ]
369
- ]
370
- });
371
- const simulationResult = await this.l1TxUtils.simulateGasUsed({
372
- to: this.getForwarderAddress().toString(),
373
- data: forwarderData,
374
- gas: SequencerPublisher.PROPOSE_GAS_GUESS
375
- }, {
376
- // @note we add 1n to the timestamp because geth implementation doesn't like simulation timestamp to be equal to the current block timestamp
377
- time: timestamp + 1n,
378
- // @note reth should have a 30m gas limit per block but throws errors that this tx is beyond limit
379
- gasLimit: SequencerPublisher.PROPOSE_GAS_GUESS * 2n
380
- }, [
381
- {
382
- address: this.rollupContract.address,
383
- // @note we override checkBlob to false since blobs are not part simulate()
384
- stateDiff: [
385
- {
386
- slot: toHex(RollupContract.checkBlobStorageSlot, true),
387
- value: toHex(0n, true)
388
- }
389
- ]
390
- }
391
- ], {
392
- // @note fallback gas estimate to use if the node doesn't support simulation API
393
- fallbackGasEstimate: SequencerPublisher.PROPOSE_GAS_GUESS
394
- }).catch((err)=>{
395
- const { message, metaMessages } = formatViemError(err);
396
- this.log.error(`Failed to simulate gas used`, message, {
397
- metaMessages
398
- });
399
- throw new Error('Failed to simulate gas used');
400
- });
401
1377
  return {
402
1378
  args,
403
1379
  blobEvaluationGas,
404
- rollupData,
405
- simulationResult
1380
+ rollupData
406
1381
  };
407
1382
  }
408
- async addProposeTx(block, encodedData, opts = {}, timestamp) {
1383
+ async addProposeTx(checkpoint, encodedData, opts = {}) {
1384
+ const slot = checkpoint.header.slotNumber;
409
1385
  const timer = new Timer();
410
1386
  const kzg = Blob.getViemKzgInstance();
411
- const { rollupData, simulationResult, blobEvaluationGas } = await this.prepareProposeTx(encodedData, timestamp);
1387
+ const { rollupData, blobEvaluationGas } = await this.prepareProposeTx(encodedData);
412
1388
  const startBlock = await this.l1TxUtils.getBlockNumber();
413
- const blockHash = await block.hash();
1389
+ // Send the blobs to the blob client preemptively. This helps in tests where the sequencer mistakingly thinks that the propose
1390
+ // tx fails but it does get mined. We make sure that the blobs are sent to the blob client regardless of the tx outcome.
1391
+ void Promise.resolve().then(()=>this.blobClient.sendBlobsToFilestore(encodedData.blobs).catch((_err)=>{
1392
+ this.log.error('Failed to send blobs to blob client');
1393
+ }));
414
1394
  return this.addRequest({
415
1395
  action: 'propose',
416
1396
  request: {
417
1397
  to: this.rollupContract.address,
418
1398
  data: rollupData
419
1399
  },
420
- lastValidL2Slot: block.header.globalVariables.slotNumber.toBigInt(),
1400
+ lastValidL2Slot: checkpoint.header.slotNumber,
421
1401
  gasConfig: {
422
- ...opts,
423
- gasLimit: this.l1TxUtils.bumpGasLimit(simulationResult + blobEvaluationGas)
1402
+ txTimeoutAt: opts.txTimeoutAt,
1403
+ gasLimit: undefined
424
1404
  },
1405
+ blobEvaluationGas,
425
1406
  blobConfig: {
426
1407
  blobs: encodedData.blobs.map((b)=>b.data),
427
1408
  kzg
428
1409
  },
429
- onResult: (request, result)=>{
1410
+ checkSuccess: (_request, result)=>{
430
1411
  if (!result) {
431
- return;
1412
+ return false;
432
1413
  }
433
1414
  const { receipt, stats, errorMsg } = result;
434
- if (receipt.status === 'success') {
1415
+ const success = extractEventSuccess(receipt, {
1416
+ address: this.rollupContract.address,
1417
+ abi: RollupAbi,
1418
+ eventName: 'CheckpointProposed'
1419
+ });
1420
+ if (success) {
435
1421
  const endBlock = receipt.blockNumber;
436
1422
  const inclusionBlocks = Number(endBlock - startBlock);
1423
+ const { calldataGas, calldataSize, sender } = stats;
437
1424
  const publishStats = {
438
1425
  gasPrice: receipt.effectiveGasPrice,
439
1426
  gasUsed: receipt.gasUsed,
440
1427
  blobGasUsed: receipt.blobGasUsed ?? 0n,
441
1428
  blobDataGas: receipt.blobGasPrice ?? 0n,
442
1429
  transactionHash: receipt.transactionHash,
443
- ...pick(stats, 'calldataGas', 'calldataSize', 'sender'),
444
- ...block.getStats(),
1430
+ calldataGas,
1431
+ calldataSize,
1432
+ sender,
1433
+ ...checkpoint.getStats(),
445
1434
  eventName: 'rollup-published-to-l1',
446
1435
  blobCount: encodedData.blobs.length,
447
1436
  inclusionBlocks
448
1437
  };
449
- this.log.verbose(`Published L2 block to L1 rollup contract`, {
1438
+ this.log.info(`Published checkpoint ${checkpoint.number} at slot ${slot} to rollup contract`, {
450
1439
  ...stats,
451
- ...block.getStats()
1440
+ ...checkpoint.getStats(),
1441
+ ...pick(receipt, 'transactionHash', 'blockHash')
452
1442
  });
453
1443
  this.metrics.recordProcessBlockTx(timer.ms(), publishStats);
454
- // Send the blobs to the blob sink
455
- this.sendBlobsToBlobSink(receipt.blockHash, encodedData.blobs).catch((_err)=>{
456
- this.log.error('Failed to send blobs to blob sink');
457
- });
458
1444
  return true;
459
1445
  } else {
460
1446
  this.metrics.recordFailedTx('process');
461
- this.log.error(`Rollup process tx reverted. ${errorMsg ?? 'No error message'}`, undefined, {
462
- ...block.getStats(),
463
- txHash: receipt.transactionHash,
464
- blockHash,
465
- slotNumber: block.header.globalVariables.slotNumber.toBigInt()
1447
+ this.log.error(`Publishing checkpoint at slot ${slot} failed with ${errorMsg ?? 'no error message'}`, undefined, {
1448
+ ...checkpoint.getStats(),
1449
+ ...receipt
466
1450
  });
1451
+ return false;
467
1452
  }
468
1453
  }
469
1454
  });
470
1455
  }
471
- /**
472
- * Send blobs to the blob sink
473
- *
474
- * If a blob sink url is configured, then we send blobs to the blob sink
475
- * - for now we use the blockHash as the identifier for the blobs;
476
- * In the future this will move to be the beacon block id - which takes a bit more work
477
- * to calculate and will need to be mocked in e2e tests
478
- */ sendBlobsToBlobSink(blockHash, blobs) {
479
- return this.blobSinkClient.sendBlobsToBlobSink(blockHash, blobs);
1456
+ /** Returns the timestamp of the next L1 slot boundary after now. */ getNextL1SlotTimestamp() {
1457
+ const l1Constants = this.epochCache.getL1Constants();
1458
+ return getNextL1SlotTimestamp(this.dateProvider.nowInSeconds(), l1Constants);
480
1459
  }
481
1460
  }