@aztec-labs/sequencer-client 6.0.0-nightly.20260829

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 (165) hide show
  1. package/README.md +307 -0
  2. package/dest/client/index.d.ts +2 -0
  3. package/dest/client/index.d.ts.map +1 -0
  4. package/dest/client/index.js +1 -0
  5. package/dest/client/sequencer-client.d.ts +94 -0
  6. package/dest/client/sequencer-client.d.ts.map +1 -0
  7. package/dest/client/sequencer-client.js +177 -0
  8. package/dest/config.d.ts +56 -0
  9. package/dest/config.d.ts.map +1 -0
  10. package/dest/config.js +251 -0
  11. package/dest/global_variable_builder/fee_predictor.d.ts +49 -0
  12. package/dest/global_variable_builder/fee_predictor.d.ts.map +1 -0
  13. package/dest/global_variable_builder/fee_predictor.js +127 -0
  14. package/dest/global_variable_builder/fee_provider.d.ts +28 -0
  15. package/dest/global_variable_builder/fee_provider.d.ts.map +1 -0
  16. package/dest/global_variable_builder/fee_provider.js +87 -0
  17. package/dest/global_variable_builder/global_builder.d.ts +28 -0
  18. package/dest/global_variable_builder/global_builder.d.ts.map +1 -0
  19. package/dest/global_variable_builder/global_builder.js +40 -0
  20. package/dest/global_variable_builder/index.d.ts +4 -0
  21. package/dest/global_variable_builder/index.d.ts.map +1 -0
  22. package/dest/global_variable_builder/index.js +3 -0
  23. package/dest/index.d.ts +7 -0
  24. package/dest/index.d.ts.map +1 -0
  25. package/dest/index.js +8 -0
  26. package/dest/publisher/config.d.ts +68 -0
  27. package/dest/publisher/config.d.ts.map +1 -0
  28. package/dest/publisher/config.js +137 -0
  29. package/dest/publisher/index.d.ts +5 -0
  30. package/dest/publisher/index.d.ts.map +1 -0
  31. package/dest/publisher/index.js +4 -0
  32. package/dest/publisher/l1_to_l2_messaging.d.ts +21 -0
  33. package/dest/publisher/l1_to_l2_messaging.d.ts.map +1 -0
  34. package/dest/publisher/l1_to_l2_messaging.js +70 -0
  35. package/dest/publisher/l1_tx_failed_store/factory.d.ts +11 -0
  36. package/dest/publisher/l1_tx_failed_store/factory.d.ts.map +1 -0
  37. package/dest/publisher/l1_tx_failed_store/factory.js +22 -0
  38. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +101 -0
  39. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -0
  40. package/dest/publisher/l1_tx_failed_store/failed_tx_store.js +68 -0
  41. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts +15 -0
  42. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts.map +1 -0
  43. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.js +36 -0
  44. package/dest/publisher/l1_tx_failed_store/index.d.ts +4 -0
  45. package/dest/publisher/l1_tx_failed_store/index.d.ts.map +1 -0
  46. package/dest/publisher/l1_tx_failed_store/index.js +3 -0
  47. package/dest/publisher/sequencer-bundle-simulator.d.ts +96 -0
  48. package/dest/publisher/sequencer-bundle-simulator.d.ts.map +1 -0
  49. package/dest/publisher/sequencer-bundle-simulator.js +198 -0
  50. package/dest/publisher/sequencer-publisher-factory.d.ts +50 -0
  51. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -0
  52. package/dest/publisher/sequencer-publisher-factory.js +75 -0
  53. package/dest/publisher/sequencer-publisher-metrics.d.ts +26 -0
  54. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -0
  55. package/dest/publisher/sequencer-publisher-metrics.js +101 -0
  56. package/dest/publisher/sequencer-publisher.d.ts +254 -0
  57. package/dest/publisher/sequencer-publisher.d.ts.map +1 -0
  58. package/dest/publisher/sequencer-publisher.js +1784 -0
  59. package/dest/publisher/write_json.d.ts +11 -0
  60. package/dest/publisher/write_json.d.ts.map +1 -0
  61. package/dest/publisher/write_json.js +57 -0
  62. package/dest/sequencer/automine/automine_factory.d.ts +56 -0
  63. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -0
  64. package/dest/sequencer/automine/automine_factory.js +85 -0
  65. package/dest/sequencer/automine/automine_sequencer.d.ts +189 -0
  66. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
  67. package/dest/sequencer/automine/automine_sequencer.js +732 -0
  68. package/dest/sequencer/automine/index.d.ts +3 -0
  69. package/dest/sequencer/automine/index.d.ts.map +1 -0
  70. package/dest/sequencer/automine/index.js +2 -0
  71. package/dest/sequencer/checkpoint_proposal_job.d.ts +169 -0
  72. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -0
  73. package/dest/sequencer/checkpoint_proposal_job.js +1961 -0
  74. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  75. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  76. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  77. package/dest/sequencer/checkpoint_voter.d.ts +34 -0
  78. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -0
  79. package/dest/sequencer/checkpoint_voter.js +106 -0
  80. package/dest/sequencer/config.d.ts +8 -0
  81. package/dest/sequencer/config.d.ts.map +1 -0
  82. package/dest/sequencer/config.js +1 -0
  83. package/dest/sequencer/errors.d.ts +11 -0
  84. package/dest/sequencer/errors.d.ts.map +1 -0
  85. package/dest/sequencer/errors.js +15 -0
  86. package/dest/sequencer/events.d.ts +103 -0
  87. package/dest/sequencer/events.d.ts.map +1 -0
  88. package/dest/sequencer/events.js +1 -0
  89. package/dest/sequencer/inbox_bucket_selector.d.ts +88 -0
  90. package/dest/sequencer/inbox_bucket_selector.d.ts.map +1 -0
  91. package/dest/sequencer/inbox_bucket_selector.js +80 -0
  92. package/dest/sequencer/index.d.ts +6 -0
  93. package/dest/sequencer/index.d.ts.map +1 -0
  94. package/dest/sequencer/index.js +5 -0
  95. package/dest/sequencer/metrics.d.ts +75 -0
  96. package/dest/sequencer/metrics.d.ts.map +1 -0
  97. package/dest/sequencer/metrics.js +343 -0
  98. package/dest/sequencer/missing_committee.d.ts +72 -0
  99. package/dest/sequencer/missing_committee.d.ts.map +1 -0
  100. package/dest/sequencer/missing_committee.js +139 -0
  101. package/dest/sequencer/requests_tracker.d.ts +22 -0
  102. package/dest/sequencer/requests_tracker.d.ts.map +1 -0
  103. package/dest/sequencer/requests_tracker.js +33 -0
  104. package/dest/sequencer/sequencer.d.ts +326 -0
  105. package/dest/sequencer/sequencer.d.ts.map +1 -0
  106. package/dest/sequencer/sequencer.js +1495 -0
  107. package/dest/sequencer/types.d.ts +3 -0
  108. package/dest/sequencer/types.d.ts.map +1 -0
  109. package/dest/sequencer/types.js +1 -0
  110. package/dest/sequencer/utils.d.ts +30 -0
  111. package/dest/sequencer/utils.d.ts.map +1 -0
  112. package/dest/sequencer/utils.js +18 -0
  113. package/dest/test/index.d.ts +23 -0
  114. package/dest/test/index.d.ts.map +1 -0
  115. package/dest/test/index.js +6 -0
  116. package/dest/test/mock_checkpoint_builder.d.ts +95 -0
  117. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -0
  118. package/dest/test/mock_checkpoint_builder.js +230 -0
  119. package/dest/test/utils.d.ts +67 -0
  120. package/dest/test/utils.d.ts.map +1 -0
  121. package/dest/test/utils.js +121 -0
  122. package/package.json +118 -0
  123. package/src/client/index.ts +1 -0
  124. package/src/client/sequencer-client.ts +281 -0
  125. package/src/config.ts +309 -0
  126. package/src/global_variable_builder/README.md +44 -0
  127. package/src/global_variable_builder/fee_predictor.ts +176 -0
  128. package/src/global_variable_builder/fee_provider.ts +104 -0
  129. package/src/global_variable_builder/global_builder.ts +68 -0
  130. package/src/global_variable_builder/index.ts +3 -0
  131. package/src/index.ts +15 -0
  132. package/src/publisher/config.ts +220 -0
  133. package/src/publisher/index.ts +8 -0
  134. package/src/publisher/l1_to_l2_messaging.ts +85 -0
  135. package/src/publisher/l1_tx_failed_store/factory.ts +32 -0
  136. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +166 -0
  137. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +47 -0
  138. package/src/publisher/l1_tx_failed_store/index.ts +3 -0
  139. package/src/publisher/sequencer-bundle-simulator.ts +253 -0
  140. package/src/publisher/sequencer-publisher-factory.ts +121 -0
  141. package/src/publisher/sequencer-publisher-metrics.ts +145 -0
  142. package/src/publisher/sequencer-publisher.ts +1719 -0
  143. package/src/publisher/write_json.ts +77 -0
  144. package/src/sequencer/README.md +243 -0
  145. package/src/sequencer/automine/README.md +60 -0
  146. package/src/sequencer/automine/automine_factory.ts +156 -0
  147. package/src/sequencer/automine/automine_sequencer.ts +841 -0
  148. package/src/sequencer/automine/index.ts +6 -0
  149. package/src/sequencer/checkpoint_proposal_job.ts +1889 -0
  150. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  151. package/src/sequencer/checkpoint_voter.ts +118 -0
  152. package/src/sequencer/config.ts +9 -0
  153. package/src/sequencer/errors.ts +21 -0
  154. package/src/sequencer/events.ts +93 -0
  155. package/src/sequencer/inbox_bucket_selector.ts +160 -0
  156. package/src/sequencer/index.ts +5 -0
  157. package/src/sequencer/metrics.ts +463 -0
  158. package/src/sequencer/missing_committee.ts +192 -0
  159. package/src/sequencer/requests_tracker.ts +43 -0
  160. package/src/sequencer/sequencer.ts +1401 -0
  161. package/src/sequencer/types.ts +6 -0
  162. package/src/sequencer/utils.ts +42 -0
  163. package/src/test/index.ts +26 -0
  164. package/src/test/mock_checkpoint_builder.ts +324 -0
  165. package/src/test/utils.ts +215 -0
@@ -0,0 +1,1495 @@
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, _dec2, _dec3, _initProto;
374
+ import { getKzg } from '@aztec-labs/blob-lib';
375
+ import { PROPOSER_PIPELINING_SLOT_OFFSET } from '@aztec-labs/epoch-cache';
376
+ import { NoCommitteeError } from '@aztec-labs/ethereum/contracts';
377
+ import { CheckpointNumber, SlotNumber } from '@aztec-labs/foundation/branded-types';
378
+ import { merge, omit, pick } from '@aztec-labs/foundation/collection';
379
+ import { EthAddress } from '@aztec-labs/foundation/eth-address';
380
+ import { createLogger } from '@aztec-labs/foundation/log';
381
+ import { RunningPromise } from '@aztec-labs/foundation/running-promise';
382
+ import { buildCheckpointSimulationOverridesPlan } from '@aztec-labs/stdlib/checkpoint';
383
+ import { getEpochAtSlot } from '@aztec-labs/stdlib/epoch-helpers';
384
+ import { MIN_PER_BLOCK_ALLOCATION_MULTIPLIER, MIN_PER_BLOCK_DA_ALLOCATION_MULTIPLIER, computeNetworkTxGasLimits } from '@aztec-labs/stdlib/gas';
385
+ import { SequencerConfigSchema } from '@aztec-labs/stdlib/interfaces/server';
386
+ import { pickFromSchema } from '@aztec-labs/stdlib/schemas';
387
+ import { buildProposerTimetable } from '@aztec-labs/stdlib/timetable';
388
+ import { Attributes, getTelemetryClient, trackSpan } from '@aztec-labs/telemetry-client';
389
+ import EventEmitter from 'node:events';
390
+ import { DefaultSequencerConfig } from '../config.js';
391
+ import { CheckpointProposalJob } from './checkpoint_proposal_job.js';
392
+ import { CheckpointProposalJobMetrics } from './checkpoint_proposal_job_metrics.js';
393
+ import { CheckpointVoter } from './checkpoint_voter.js';
394
+ import { SequencerInterruptedError } from './errors.js';
395
+ import { SequencerMetrics } from './metrics.js';
396
+ import { logMissingCommittee } from './missing_committee.js';
397
+ import { RequestsTracker } from './requests_tracker.js';
398
+ import { SequencerState } from './utils.js';
399
+ export { SequencerState };
400
+ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpointProposal'), _dec2 = trackSpan('Sequencer.tryVoteAndPruneWhenCannotBuild', ({ slot })=>({
401
+ [Attributes.SLOT_NUMBER]: slot
402
+ })), _dec3 = trackSpan('Sequencer.tryVoteWhenEscapeHatchOpen', ({ slot })=>({
403
+ [Attributes.SLOT_NUMBER]: slot
404
+ }));
405
+ /**
406
+ * Sequencer client
407
+ * - Checks whether it is elected as proposer for the next slot
408
+ * - Builds multiple blocks and broadcasts them
409
+ * - Collects attestations for the checkpoint
410
+ * - Publishes the checkpoint to L1
411
+ * - Votes for proposals and slashes on L1
412
+ */ export class Sequencer extends EventEmitter {
413
+ publisherFactory;
414
+ validatorClient;
415
+ globalsBuilder;
416
+ p2pClient;
417
+ worldState;
418
+ slasherClient;
419
+ l2BlockSource;
420
+ l1ToL2MessageSource;
421
+ checkpointsBuilder;
422
+ l1Constants;
423
+ dateProvider;
424
+ epochCache;
425
+ rollupContract;
426
+ telemetry;
427
+ log;
428
+ static{
429
+ ({ e: [_initProto] } = _apply_decs_2203_r(this, [
430
+ [
431
+ _dec,
432
+ 2,
433
+ "work"
434
+ ],
435
+ [
436
+ _dec1,
437
+ 2,
438
+ "prepareCheckpointProposal"
439
+ ],
440
+ [
441
+ _dec2,
442
+ 2,
443
+ "tryVoteAndPruneWhenCannotBuild"
444
+ ],
445
+ [
446
+ _dec3,
447
+ 2,
448
+ "tryVoteWhenEscapeHatchOpen"
449
+ ]
450
+ ], []));
451
+ }
452
+ runningPromise;
453
+ state;
454
+ stateSlotNumber;
455
+ /** Wall-clock time (ms, via the date provider) at which the current state was entered. */ stateEnteredAtMs;
456
+ metrics;
457
+ checkpointProposalJobMetrics;
458
+ stateLog;
459
+ /** The last slot for which we attempted to perform our fallback duties (votes and/or prune) with degraded block production */ lastSlotForFallbackAction;
460
+ /** The (checkpoint, slot) of the last invalidation request we successfully simulated, to prevent
461
+ * re-simulating and re-submitting the same invalidation across the many ticks within a single slot. */ lastInvalidationAttempt;
462
+ /** The last epoch for which we logged a "no committee" diagnostic, to avoid per-slot log spam. */ lastEpochForNoCommitteeLog;
463
+ /** The last slot for which we triggered a checkpoint proposal job, to prevent duplicate attempts. */ lastSlotForCheckpointProposalJob;
464
+ /** Last successful checkpoint proposed */ lastCheckpointProposed;
465
+ /** The last epoch for which we logged strategy comparison in fisherman mode. */ lastEpochForStrategyComparison;
466
+ /** The last checkpoint proposal job, tracked so we can await its pending L1 submission during shutdown. */ lastCheckpointProposalJob;
467
+ /**
468
+ * In-flight fire-and-forget requests that {@link stop} interrupts and drains, and {@link pause} awaits
469
+ * untouched: the checkpoint proposal jobs' backgrounded L1 submissions (each job is handed this shared
470
+ * tracker) plus the sequencer's own fallback submissions (votes/prune when we cannot build, or
471
+ * escape-hatch votes). Each fallback send is gated by its wrapper publisher's interruptible target-slot
472
+ * sleep; the tracked interrupt wakes that sleep so the send short-circuits without publishing. A wrapper
473
+ * is created for a single send and is never restarted, so once interrupted its sleeper can never publish
474
+ * a stale-slot tx, even after the pooled publishers are restarted by a later {@link start}.
475
+ */ pendingRequests;
476
+ /** Proposer schedule and block sub-slot timetable for the sequencer, rebuilt on every config update. */ timetable;
477
+ /** Config for the sequencer */ config;
478
+ signatureContext;
479
+ constructor(publisherFactory, validatorClient, globalsBuilder, p2pClient, worldState, slasherClient, l2BlockSource, l1ToL2MessageSource, checkpointsBuilder, l1Constants, dateProvider, epochCache, rollupContract, config, telemetry = getTelemetryClient(), log = createLogger('sequencer')){
480
+ super(), this.publisherFactory = publisherFactory, this.validatorClient = validatorClient, this.globalsBuilder = globalsBuilder, this.p2pClient = p2pClient, this.worldState = worldState, this.slasherClient = slasherClient, this.l2BlockSource = l2BlockSource, this.l1ToL2MessageSource = l1ToL2MessageSource, this.checkpointsBuilder = checkpointsBuilder, this.l1Constants = l1Constants, this.dateProvider = dateProvider, this.epochCache = epochCache, this.rollupContract = rollupContract, this.telemetry = telemetry, this.log = log, this.state = (_initProto(this), SequencerState.STOPPED), this.pendingRequests = new RequestsTracker(), this.config = DefaultSequencerConfig;
481
+ this.stateLog = log.createChild('state');
482
+ this.stateEnteredAtMs = this.dateProvider.now();
483
+ // Add [FISHERMAN] prefix to logger if in fisherman mode
484
+ if (config.fishermanMode) {
485
+ this.log = log.createChild('[FISHERMAN]');
486
+ }
487
+ this.signatureContext = {
488
+ chainId: config.l1ChainId,
489
+ rollupAddress: config.rollupAddress
490
+ };
491
+ this.metrics = new SequencerMetrics(telemetry, this.rollupContract, 'Sequencer');
492
+ this.checkpointProposalJobMetrics = new CheckpointProposalJobMetrics(telemetry);
493
+ this.updateConfig(config);
494
+ }
495
+ /**
496
+ * Updates sequencer config by the defined values and rebuilds the timetable.
497
+ *
498
+ * The merged config is validated against a candidate before being committed: {@link buildTimetable} may
499
+ * reject the candidate (invalid timing geometry, or per-block allocation multipliers below the network
500
+ * minimums). On rejection we leave `this.config` and `this.timetable` untouched and rethrow, so a bad update
501
+ * never leaves the sequencer running with a rejected config and a stale timetable.
502
+ */ updateConfig(config) {
503
+ const filteredConfig = pickFromSchema(config, SequencerConfigSchema);
504
+ const candidate = merge(this.config, filteredConfig);
505
+ let timetable;
506
+ try {
507
+ timetable = this.buildTimetable(candidate);
508
+ } catch (err) {
509
+ this.log.warn(`Rejecting sequencer config update: ${err.message}`, {
510
+ rejectedConfig: omit(filteredConfig, 'txPublicSetupAllowListExtend')
511
+ });
512
+ throw err;
513
+ }
514
+ this.config = candidate;
515
+ this.timetable = timetable;
516
+ this.log.info(`Updated sequencer config`, omit(filteredConfig, 'txPublicSetupAllowListExtend'));
517
+ }
518
+ /**
519
+ * Builds the proposer timetable from the given config and L1 constants via the shared
520
+ * {@link buildProposerTimetable} helper, so the sequencer derives the same blocks-per-checkpoint as the p2p
521
+ * layer and `getNodeInfo`. The fast local/e2e profile and budget clamping happen inside
522
+ * {@link ProposerTimetable}.
523
+ *
524
+ * Throws if the timing geometry is invalid or the per-block allocation multipliers are below the network
525
+ * minimums; callers must treat a throw as a rejected config and not commit it.
526
+ */ buildTimetable(config) {
527
+ const timetable = buildProposerTimetable(config, this.l1Constants);
528
+ const maxNumberOfBlocks = timetable.getMaxBlocksPerCheckpoint();
529
+ this.log.info(`Sequencer timetable initialized with ${maxNumberOfBlocks} blocks per slot`, {
530
+ aztecSlotDuration: timetable.aztecSlotDuration,
531
+ ethereumSlotDuration: timetable.ethereumSlotDuration,
532
+ blockDuration: timetable.blockDuration,
533
+ minBlockDuration: timetable.minBlockDuration,
534
+ p2pPropagationTime: timetable.p2pPropagationTime,
535
+ checkpointProposalPrepareTime: timetable.checkpointProposalPrepareTime,
536
+ maxNumberOfBlocks
537
+ });
538
+ this.assertConfigMeetsNetworkTxLimits(config, maxNumberOfBlocks);
539
+ return timetable;
540
+ }
541
+ /**
542
+ * Checks this node's configured per-block allocation against the network admission limit. A node
543
+ * advertises and admits txs up to the limit derived from the network-minimum multipliers (see
544
+ * {@link computeNetworkTxGasLimits}).
545
+ *
546
+ * Fails startup (and runtime config updates) only when the configured per-block allocation *multipliers*
547
+ * (`perBlockAllocationMultiplier` / `perBlockDAAllocationMultiplier`) are below the network minimums: such
548
+ * a node would accept txs over RPC/gossip that its builder can never pack into a block regardless of block
549
+ * size. Operators may configure a higher (more generous) multiplier, but not a lower one.
550
+ *
551
+ * When the multipliers meet the floor but an absolute per-block gas cap (`maxDABlockGas` / `maxL2BlockGas`)
552
+ * shrinks the builder's effective grant below the network limit, this is legitimate operator
553
+ * restrictiveness — the node simply builds smaller blocks and such txs stay in the pool for other
554
+ * proposers — so we only log a warning rather than failing startup. Restrictive tx-count caps
555
+ * (`maxTxsPerBlock` / `maxTxsPerCheckpoint`) can likewise make the builder skip admitted txs; they are
556
+ * intentionally not modeled here for the same reason.
557
+ */ assertConfigMeetsNetworkTxLimits(config, maxBlocksPerCheckpoint) {
558
+ // Mirror CheckpointBuilder.capLimitsByCheckpointBudgets: DA falls back to the general multiplier.
559
+ const l2Multiplier = config.perBlockAllocationMultiplier;
560
+ const daMultiplier = config.perBlockDAAllocationMultiplier ?? l2Multiplier;
561
+ // The allocation is monotonic in the multiplier, so a multiplier at or above the network minimum
562
+ // guarantees the builder grants at least the network admission limit. Checking the multipliers directly
563
+ // is sufficient (and strictly more conservative than modeling the resulting gas grant).
564
+ if (daMultiplier < MIN_PER_BLOCK_DA_ALLOCATION_MULTIPLIER) {
565
+ throw new Error(`perBlockDAAllocationMultiplier (${daMultiplier}) is below the network minimum ` + `${MIN_PER_BLOCK_DA_ALLOCATION_MULTIPLIER}; the node would admit txs its own builder can never include.`);
566
+ }
567
+ if (l2Multiplier < MIN_PER_BLOCK_ALLOCATION_MULTIPLIER) {
568
+ throw new Error(`perBlockAllocationMultiplier (${l2Multiplier}) is below the network minimum ` + `${MIN_PER_BLOCK_ALLOCATION_MULTIPLIER}; the node would admit txs its own builder can never include.`);
569
+ }
570
+ // Absolute per-block gas caps below the network admission limit are legitimate operator restrictiveness:
571
+ // the node simply builds smaller blocks and such txs stay in the pool for other proposers. Warn only.
572
+ const networkLimit = computeNetworkTxGasLimits({
573
+ maxBlocksPerCheckpoint,
574
+ manaCheckpointBudget: this.l1Constants.rollupManaLimit
575
+ });
576
+ if (config.maxDABlockGas !== undefined && config.maxDABlockGas < networkLimit.daGas) {
577
+ this.log.warn(`Sequencer maxDABlockGas (${config.maxDABlockGas}) is below the network DA admission limit ` + `(${networkLimit.daGas}): txs declaring more DA gas are admitted over RPC/gossip but will be skipped ` + `by this proposer's own blocks and left in the pool for other proposers.`, {
578
+ maxDABlockGas: config.maxDABlockGas,
579
+ networkDaGas: networkLimit.daGas,
580
+ maxBlocksPerCheckpoint
581
+ });
582
+ }
583
+ if (config.maxL2BlockGas !== undefined && config.maxL2BlockGas < networkLimit.l2Gas) {
584
+ this.log.warn(`Sequencer maxL2BlockGas (${config.maxL2BlockGas}) is below the network L2 admission limit ` + `(${networkLimit.l2Gas}): txs declaring more L2 gas are admitted over RPC/gossip but will be skipped ` + `by this proposer's own blocks and left in the pool for other proposers.`, {
585
+ maxL2BlockGas: config.maxL2BlockGas,
586
+ networkL2Gas: networkLimit.l2Gas,
587
+ maxBlocksPerCheckpoint
588
+ });
589
+ }
590
+ }
591
+ /** Initializes the sequencer (precomputes tables). Takes about 3s. */ init() {
592
+ getKzg();
593
+ }
594
+ /**
595
+ * Starts (or restarts) the sequencer and moves it to the IDLE state. Idempotent: a start while already
596
+ * running is a no-op, so it never orphans the previous poll loop. A start while STOPPING throws, since the
597
+ * in-flight stop would mark the fresh loop's state STOPPED and orphan it — silently doing nothing would
598
+ * leave the caller believing the sequencer is running when it is on its way to STOPPED. Safe to call after
599
+ * a previous {@link stop} has resolved; the caller must also restart the publishers (see
600
+ * {@link SequencerClient.start}) so L1 publishing is re-enabled.
601
+ */ start() {
602
+ if (this.state === SequencerState.STOPPING) {
603
+ throw new Error('Cannot start sequencer while it is stopping');
604
+ }
605
+ if (this.runningPromise?.isRunning()) {
606
+ this.log.warn('Attempted to start sequencer that is already running');
607
+ return;
608
+ }
609
+ this.runningPromise = new RunningPromise(this.safeWork.bind(this), this.log, this.config.sequencerPollingIntervalMS);
610
+ this.setState(SequencerState.IDLE, undefined, {
611
+ force: true
612
+ });
613
+ this.runningPromise.start();
614
+ this.log.info('Started sequencer');
615
+ }
616
+ /** Triggers an immediate run of the sequencer, bypassing the polling interval. */ trigger() {
617
+ return this.runningPromise?.trigger();
618
+ }
619
+ /**
620
+ * Stops the sequencer from building blocks and moves it to STOPPED state, interrupting the in-flight
621
+ * work() iteration and its pending L1 submissions for a fast shutdown, then draining before returning.
622
+ * Idempotent: a second call while already stopped or stopping is a no-op. Lifecycle calls are expected
623
+ * to be serialized by the caller. For a restartable pause that lets in-flight work finish untouched
624
+ * (e.g. around a test clock warp), use {@link pause} instead.
625
+ */ async stop() {
626
+ if (this.state === SequencerState.STOPPED || this.state === SequencerState.STOPPING) {
627
+ this.log.debug(`Sequencer already ${this.state.toLowerCase()}, ignoring stop`);
628
+ return;
629
+ }
630
+ this.log.info(`Stopping sequencer`);
631
+ this.setState(SequencerState.STOPPING, undefined, {
632
+ force: true
633
+ });
634
+ this.lastCheckpointProposalJob?.interrupt();
635
+ await this.publisherFactory.stopAll();
636
+ // Stop the poll loop and await the in-flight work() iteration. work() registers its fire-and-forget
637
+ // requests synchronously before returning, so once the loop has stopped, pendingRequests holds every
638
+ // request that will ever exist. Interrupting any earlier could miss a request registered by the last
639
+ // in-flight iteration.
640
+ await this.runningPromise?.stop();
641
+ this.pendingRequests.interruptRequests();
642
+ await this.pendingRequests.awaitRequests();
643
+ this.setState(SequencerState.STOPPED, undefined, {
644
+ force: true
645
+ });
646
+ this.log.info('Stopped sequencer');
647
+ }
648
+ /**
649
+ * Gracefully pauses block production so the sequencer can later be resumed with {@link start}: halts the
650
+ * poll loop and waits for the in-flight work() iteration and every pending L1 submission / fallback send
651
+ * to finish, without interrupting them. No interrupt lands mid-build, so no spurious checkpoint-error is
652
+ * emitted and no enqueued checkpoint is dropped. Deliberately does not stop inner services (validator/HA
653
+ * signer, publishers), so the slashing-protection store stays open and the sequencer stays restartable.
654
+ * Used by tests that pause sequencers around an L1 clock warp. Idempotent.
655
+ */ async pause() {
656
+ if (!this.runningPromise?.isRunning()) {
657
+ this.log.debug('Sequencer not running, ignoring pause');
658
+ return;
659
+ }
660
+ this.log.info('Pausing sequencer');
661
+ // Halt the poll loop and let the in-flight iteration finish naturally — no interrupt, and no STOPPING
662
+ // state, since entering STOPPING would make the iteration's own setState calls throw and fail it.
663
+ // work() registers its fire-and-forget requests synchronously before returning, so once the loop has
664
+ // stopped pendingRequests holds every request that will ever exist; awaiting it lets them all finish.
665
+ await this.runningPromise.stop();
666
+ await this.pendingRequests.awaitRequests();
667
+ this.log.info('Paused sequencer');
668
+ }
669
+ /** Main sequencer loop with a try/catch */ async safeWork() {
670
+ try {
671
+ await this.work();
672
+ } catch (err) {
673
+ this.emit('checkpoint-error', {
674
+ error: err
675
+ });
676
+ throw err;
677
+ } finally{
678
+ this.setState(SequencerState.IDLE, undefined);
679
+ }
680
+ }
681
+ /** Returns the current state of the sequencer. */ status() {
682
+ return {
683
+ state: this.state
684
+ };
685
+ }
686
+ /**
687
+ * Main sequencer loop:
688
+ * - Checks if we are up to date
689
+ * - If we are and we are the sequencer, collect txs and build blocks
690
+ * - Build multiple blocks per slot when configured
691
+ * - Collect attestations for the final block
692
+ * - Submit checkpoint
693
+ */ async work() {
694
+ this.setState(SequencerState.SYNCHRONIZING, undefined);
695
+ const { slot, targetSlot, epoch, targetEpoch, ts, nowSeconds } = this.getSlotContextInNextL1Slot();
696
+ // Check if we are synced and it's our slot, grab a publisher, check previous block invalidation, etc
697
+ const checkpointProposalJob = await this.prepareCheckpointProposal(slot, targetSlot, epoch, targetEpoch, ts, nowSeconds);
698
+ if (!checkpointProposalJob) {
699
+ return;
700
+ }
701
+ // Track the job so we can await its pending L1 submission during shutdown
702
+ this.lastCheckpointProposalJob = checkpointProposalJob;
703
+ // Execute the checkpoint proposal job
704
+ const checkpoint = await checkpointProposalJob.execute();
705
+ // Update last checkpoint proposed (currently unused)
706
+ if (checkpoint) {
707
+ this.lastCheckpointProposed = checkpoint;
708
+ }
709
+ // Log fee strategy comparison if on fisherman (uses target epoch since we mirror the proposer's perspective)
710
+ if (this.config.fishermanMode && (this.lastEpochForStrategyComparison === undefined || targetEpoch > this.lastEpochForStrategyComparison)) {
711
+ this.logStrategyComparison(targetEpoch, checkpointProposalJob.getPublisher());
712
+ this.lastEpochForStrategyComparison = targetEpoch;
713
+ }
714
+ return checkpoint;
715
+ }
716
+ /** Returns slot and target slot from a single clock snapshot. */ getSlotContextInNextL1Slot() {
717
+ const { slot, ts, nowSeconds, epoch } = this.epochCache.getEpochAndSlotInNextL1Slot();
718
+ const targetSlot = SlotNumber(slot + PROPOSER_PIPELINING_SLOT_OFFSET);
719
+ return {
720
+ slot,
721
+ targetSlot,
722
+ epoch,
723
+ targetEpoch: getEpochAtSlot(targetSlot, this.l1Constants),
724
+ ts,
725
+ nowSeconds
726
+ };
727
+ }
728
+ /**
729
+ * Prepares the checkpoint proposal by performing all necessary checks and setup.
730
+ * This is the initial step in the main loop.
731
+ * @returns CheckpointProposalJob if successful, undefined if we are not yet synced or are not the proposer.
732
+ */ async prepareCheckpointProposal(slot, targetSlot, epoch, targetEpoch, ts, nowSeconds) {
733
+ // Check we have not already processed this target slot (cheapest check).
734
+ if (this.lastSlotForCheckpointProposalJob && this.lastSlotForCheckpointProposalJob >= targetSlot) {
735
+ this.log.trace(`Target slot ${targetSlot} has already been processed`);
736
+ return undefined;
737
+ }
738
+ // But if we have already proposed for this slot, then we definitely have to skip it, automining or not
739
+ if (this.lastCheckpointProposed && this.lastCheckpointProposed.header.slotNumber >= targetSlot) {
740
+ this.log.trace(`Slot ${targetSlot} has already been published as checkpoint ${this.lastCheckpointProposed.number}`);
741
+ return undefined;
742
+ }
743
+ // Test-only: skip proposing for explicitly paused slots. Attestation paths run in the validator
744
+ // client and are not gated by this hook, so paused proposers still attest to others' proposals.
745
+ if (this.config.pauseProposingForSlots?.some((s)=>s === targetSlot)) {
746
+ this.log.warn(`Skipping proposal for paused slot ${targetSlot} (test-only pauseProposingForSlots hook)`, {
747
+ targetSlot
748
+ });
749
+ return undefined;
750
+ }
751
+ // Cheap proposer check first: most nodes are not the proposer for most slots, so gate the
752
+ // expensive multi-subsystem checkSync (and the rest of the build path) behind it. Computed once
753
+ // here and reused for the escape-hatch voting path below. No setState/timing gate on this path:
754
+ // the build-start deadline gate runs only on the proposer build path after a successful checkSync.
755
+ const [canPropose, proposer] = await this.checkCanPropose(targetSlot);
756
+ // If escape hatch is open for the target epoch, do not start checkpoint proposal work and do not attempt invalidations.
757
+ // Still perform governance/slashing voting (as proposer) once per slot.
758
+ // When pipelining, we check the target epoch (slot+1's epoch) since that's the epoch we're building for.
759
+ const isEscapeHatchOpen = await this.epochCache.isEscapeHatchOpen(targetEpoch);
760
+ if (isEscapeHatchOpen) {
761
+ if (canPropose) {
762
+ await this.tryVoteWhenEscapeHatchOpen({
763
+ slot,
764
+ targetSlot,
765
+ proposer
766
+ });
767
+ } else {
768
+ this.log.trace(`Escape hatch open but we are not proposer, skipping vote-only actions`, {
769
+ slot,
770
+ epoch,
771
+ proposer
772
+ });
773
+ }
774
+ return undefined;
775
+ }
776
+ // If we are not the proposer, check whether we should invalidate an invalid pending chain (a
777
+ // liveness backstop) and bail before any sync work or build-timing gate. This reads only the
778
+ // archiver's pending-chain validation status, which is authoritative on its own, instead of
779
+ // running the full sync check. Wrapped in try/catch because this leaner path skips the broader
780
+ // proposed-checkpoint/tip coherence screen that checkSync applied, so transient archiver
781
+ // incoherence surfaces as a quiet skip rather than a work-loop error.
782
+ if (!canPropose) {
783
+ try {
784
+ const pendingChainValidationStatus = await this.l2BlockSource.getPendingChainValidationStatus();
785
+ await this.considerInvalidatingCheckpoint(pendingChainValidationStatus, slot);
786
+ } catch (err) {
787
+ this.log.warn(`Failed to consider invalidating checkpoint`, {
788
+ err,
789
+ slot,
790
+ targetSlot
791
+ });
792
+ }
793
+ return undefined;
794
+ }
795
+ // Explicit build-loop entry gate: if we are past the latest useful block-building start for the
796
+ // target slot, abandon building for this slot. The proposer prioritizes the ideal L1-publish path
797
+ // and does not plan around the late consensus-handoff path. This is the proposer build path's
798
+ // timing gate; it runs only after we know we are the synced proposer, so non-proposer invalidation
799
+ // and escape-hatch voting (which returned above) are never gated by build timing. Vote-only paths
800
+ // still run when block building is abandoned.
801
+ const startDeadline = this.timetable.getBuildStartDeadline(targetSlot);
802
+ const nowForStartGate = this.dateProvider.now() / 1000;
803
+ if (nowForStartGate > startDeadline) {
804
+ this.log.debug(`Past start deadline for slot ${targetSlot}, abandoning block building`, {
805
+ targetSlot,
806
+ nowForStartGate,
807
+ startDeadline
808
+ });
809
+ // Mark the slot as attempted so a deadline abort is not retried within the same slot. Vote-only actions
810
+ // still need to run because sync can succeed even when it is too late to start building a checkpoint.
811
+ await this.tryVoteAndPruneWhenCannotBuild({
812
+ slot,
813
+ targetSlot
814
+ });
815
+ this.lastSlotForCheckpointProposalJob = targetSlot;
816
+ return undefined;
817
+ }
818
+ // A proposal that cannot reach the committee is worse than not proposing: the slot is burned, and a
819
+ // node holding enough committee seats to reach quorum on its own would publish a checkpoint whose tx
820
+ // data was never gossiped to anyone, which is indistinguishable from data withholding. Skip building
821
+ // while peerless, but keep the vote/prune duties below. Only applies when p2p is enabled: setups that
822
+ // disable it (sandbox, single node, automine) legitimately propose with no peers.
823
+ const connectivity = await this.p2pClient.getP2PConnectivity();
824
+ const minPeersToPropose = this.config.minPeersToPropose;
825
+ if (connectivity.enabled && connectivity.connectedPeers < minPeersToPropose) {
826
+ this.log.warn(`Skipping checkpoint proposal for slot ${targetSlot} since we have too few connected peers`, {
827
+ targetSlot,
828
+ connectedPeers: connectivity.connectedPeers,
829
+ minPeersToPropose
830
+ });
831
+ this.metrics.recordCheckpointPrecheckFailed('no_peers');
832
+ // Mark the slot as attempted so the gate is not re-evaluated on every tick within the slot. Vote-only
833
+ // actions still run: L1 duties (governance/slashing votes, prune) do not depend on gossip.
834
+ await this.tryVoteAndPruneWhenCannotBuild({
835
+ slot,
836
+ targetSlot
837
+ });
838
+ this.lastSlotForCheckpointProposalJob = targetSlot;
839
+ return undefined;
840
+ }
841
+ // We are the proposer, the escape hatch is closed, and we have time before the build start deadline.
842
+ // Now run the full sync check before building.
843
+ const syncedTo = await this.checkSync({
844
+ ts,
845
+ slot
846
+ });
847
+ if (!syncedTo) {
848
+ return undefined;
849
+ }
850
+ // Next checkpoint follows from the last synced one
851
+ const checkpointNumber = CheckpointNumber(syncedTo.checkpointNumber + 1);
852
+ const logCtx = {
853
+ nowSeconds,
854
+ syncedToL2Slot: syncedTo.syncedL2Slot,
855
+ slot,
856
+ targetSlot,
857
+ slotTs: ts,
858
+ checkpointNumber,
859
+ isPendingChainValid: pick(syncedTo.pendingChainValidationStatus, 'valid', 'reason', 'invalidIndex')
860
+ };
861
+ // We are the synced proposer within the build window; enter the proposer-check state and build.
862
+ this.setState(SequencerState.PROPOSER_CHECK, targetSlot);
863
+ // Guard: don't exceed 1-deep pipeline. Without a proposed checkpoint, we can only build
864
+ // confirmed + 1. With a proposed checkpoint, we can build confirmed + 2.
865
+ const confirmedCkpt = syncedTo.checkpointedCheckpointNumber;
866
+ if (checkpointNumber > confirmedCkpt + 2) {
867
+ this.log.verbose(`Skipping slot ${targetSlot}: checkpoint ${checkpointNumber} exceeds max pipeline depth (confirmed=${confirmedCkpt})`);
868
+ return undefined;
869
+ }
870
+ // Check that the target slot is not taken by a block already (should never happen, since only us can propose for this slot)
871
+ if (syncedTo.blockData && syncedTo.blockData.header.getSlot() >= targetSlot) {
872
+ this.log.warn(`Cannot propose block at target slot ${targetSlot} since that slot was taken by block ${syncedTo.blockNumber}`, {
873
+ ...logCtx,
874
+ block: syncedTo.blockData.header.toInspect()
875
+ });
876
+ this.metrics.recordCheckpointPrecheckFailed('slot_already_taken');
877
+ return undefined;
878
+ }
879
+ // We now need to get ourselves a publisher.
880
+ // The returned attestor will be the one we provided if we provided one.
881
+ // Otherwise it will be a valid attestor for the returned publisher.
882
+ // In fisherman mode, pass undefined to use the fisherman's own keystore instead of the actual proposer's
883
+ const proposerForPublisher = this.config.fishermanMode ? undefined : proposer;
884
+ const { attestorAddress, publisher } = await this.publisherFactory.create(proposerForPublisher);
885
+ this.log.verbose(`Created publisher at address ${publisher.getSenderAddress()} for attestor ${attestorAddress}`);
886
+ // Prepare invalidation request if the pending chain is invalid (returns undefined if no need).
887
+ // Only simulate invalidation when there's no proposed parent, since we assume the proposed parent
888
+ // will invalidate the currently invalid checkpoint on L1.
889
+ const invalidateCheckpoint = syncedTo.hasProposedCheckpoint || syncedTo.pendingChainValidationStatus.valid ? undefined : await publisher.simulateInvalidateCheckpoint(syncedTo.pendingChainValidationStatus);
890
+ // Determine the correct archive and L1 state overrides for the canProposeAt check.
891
+ // The L1 contract reads archives[proposedCheckpointNumber] and compares it with the provided archive.
892
+ // When invalidating or pipelining, the local archive may differ from L1's, so we adjust accordingly.
893
+ let archiveForCheck = syncedTo.archive;
894
+ if (syncedTo.hasProposedCheckpoint) {
895
+ this.metrics.recordPipelineDepth(syncedTo.checkpointNumber - syncedTo.checkpointedCheckpointNumber);
896
+ this.log.verbose(`Building on top of proposed checkpoint (pending=${syncedTo.proposedCheckpointData?.checkpointNumber}) for target slot ${targetSlot}`, {
897
+ targetSlot,
898
+ parentCheckpointNumber: CheckpointNumber(checkpointNumber - 1)
899
+ });
900
+ // Match what L1 will see at archives[pending] once the proposed parent lands: the parent's
901
+ // own archive root from the gossiped proposal. `syncedTo.archive` is the world-state-local
902
+ // view and can transiently diverge from the proposed parent (e.g. before the proposed
903
+ // parent's blocks have been applied locally); diverging here would cause the canProposeAt
904
+ // override to set archives[pending] to one value while we present another for comparison.
905
+ archiveForCheck = syncedTo.proposedCheckpointData.archive.root;
906
+ } else if (invalidateCheckpoint) {
907
+ // After invalidation, L1 will roll back to checkpoint N-1. The archive at N-1 already
908
+ // exists on L1, so we just pass the matching archive (the lastArchive of the invalid checkpoint).
909
+ archiveForCheck = invalidateCheckpoint.lastArchive;
910
+ this.metrics.recordPipelineDepth(0);
911
+ } else {
912
+ this.metrics.recordPipelineDepth(0);
913
+ }
914
+ // Build the simulation plan: pending/proven override from pipelining or invalidation (or the
915
+ // current snapshot when neither applies, to short-circuit any pending prune in simulation),
916
+ // plus the parent checkpoint cell and fee header when pipelining.
917
+ const simulationOverridesPlan = await buildCheckpointSimulationOverridesPlan({
918
+ checkpointNumber,
919
+ proposedCheckpointData: syncedTo.hasProposedCheckpoint ? syncedTo.proposedCheckpointData : undefined,
920
+ invalidateToPendingCheckpointNumber: invalidateCheckpoint?.forcePendingCheckpointNumber,
921
+ checkpointedCheckpointNumber: syncedTo.checkpointedCheckpointNumber,
922
+ rollup: this.rollupContract,
923
+ signatureContext: this.signatureContext,
924
+ log: this.log
925
+ });
926
+ // The plan always pins both pending/proven (to short-circuit `canPruneAtTime` in simulation),
927
+ // so `provenOverride` always reflects the assumed proven checkpoint we are pinning the
928
+ // simulation to. We additionally warn when the pin is load-bearing — i.e. when a prune would
929
+ // actually fire at the target slot without it — so observers can spot "we are building
930
+ // optimistically across a pruning boundary" in the logs.
931
+ const provenOverride = simulationOverridesPlan?.chainTipsOverride?.proven;
932
+ if (provenOverride !== undefined && await this.l2BlockSource.isPruneDueAtSlot(targetSlot)) {
933
+ this.log.warn(`Assuming proof for epoch ending at checkpoint ${provenOverride} lands by target slot ${targetSlot}`, {
934
+ checkpointNumber,
935
+ slot,
936
+ targetSlot,
937
+ provenOverride
938
+ });
939
+ }
940
+ this.emit('preparing-checkpoint', {
941
+ targetSlot,
942
+ checkpointNumber,
943
+ hadProposedParent: syncedTo.hasProposedCheckpoint,
944
+ provenOverride,
945
+ simulatedPending: simulationOverridesPlan?.chainTipsOverride?.pending
946
+ });
947
+ const canProposeCheck = await publisher.canProposeAt(archiveForCheck, proposer ?? EthAddress.ZERO, simulationOverridesPlan);
948
+ const proposeContext = {
949
+ hasProposedCheckpoint: syncedTo.hasProposedCheckpoint,
950
+ proposedCheckpointNumber: syncedTo.proposedCheckpointData?.checkpointNumber,
951
+ checkpointedCheckpointNumber: syncedTo.checkpointedCheckpointNumber,
952
+ isInvalidating: !!invalidateCheckpoint,
953
+ invalidatingCheckpointNumber: invalidateCheckpoint?.checkpointNumber,
954
+ archiveForCheck: archiveForCheck.toString(),
955
+ overridePendingCheckpointNumber: simulationOverridesPlan?.chainTipsOverride?.pending,
956
+ overrideArchive: simulationOverridesPlan?.pendingCheckpointState?.archive,
957
+ overrideFeeHeader: simulationOverridesPlan?.pendingCheckpointState?.feeHeader
958
+ };
959
+ if (canProposeCheck === undefined) {
960
+ this.log.warn(`Cannot propose checkpoint ${checkpointNumber} at slot ${slot} due to failed rollup contract check`, {
961
+ ...logCtx,
962
+ ...proposeContext
963
+ });
964
+ this.emit('proposer-rollup-check-failed', {
965
+ reason: 'Rollup contract check failed',
966
+ slot
967
+ });
968
+ this.metrics.recordCheckpointPrecheckFailed('rollup_contract_check_failed');
969
+ return undefined;
970
+ }
971
+ if (canProposeCheck.slot !== targetSlot) {
972
+ this.log.warn(`Cannot propose block due to slot mismatch with rollup contract (this can be caused by a clock out of sync). Expected slot ${targetSlot} but got ${canProposeCheck.slot}.`, {
973
+ ...logCtx,
974
+ ...proposeContext,
975
+ rollup: canProposeCheck,
976
+ expectedSlot: targetSlot
977
+ });
978
+ this.emit('proposer-rollup-check-failed', {
979
+ reason: 'Slot mismatch',
980
+ slot
981
+ });
982
+ this.metrics.recordCheckpointPrecheckFailed('slot_mismatch');
983
+ return undefined;
984
+ }
985
+ if (canProposeCheck.checkpointNumber !== checkpointNumber) {
986
+ this.log.warn(`Cannot propose due to block mismatch with rollup contract (this can be caused by a pending archiver sync). Expected checkpoint ${checkpointNumber} but got ${canProposeCheck.checkpointNumber}.`, {
987
+ ...logCtx,
988
+ ...proposeContext,
989
+ rollup: canProposeCheck,
990
+ expectedSlot: slot
991
+ });
992
+ this.emit('proposer-rollup-check-failed', {
993
+ reason: 'Block mismatch',
994
+ slot
995
+ });
996
+ this.metrics.recordCheckpointPrecheckFailed('block_number_mismatch');
997
+ return undefined;
998
+ }
999
+ this.lastSlotForCheckpointProposalJob = targetSlot;
1000
+ await this.p2pClient.prepareForSlot(targetSlot);
1001
+ this.log.info(`Preparing checkpoint proposal ${checkpointNumber} for target slot ${targetSlot} during wall-clock slot ${slot}`, {
1002
+ ...logCtx,
1003
+ ...proposeContext,
1004
+ proposer
1005
+ });
1006
+ // Create and return the checkpoint proposal job
1007
+ return this.createCheckpointProposalJob(targetSlot, targetEpoch, checkpointNumber, syncedTo.blockNumber, syncedTo.checkpointedCheckpointNumber, proposer, publisher, attestorAddress, invalidateCheckpoint, syncedTo.proposedCheckpointData);
1008
+ }
1009
+ createCheckpointProposalJob(targetSlot, targetEpoch, checkpointNumber, syncedToBlockNumber, checkpointedCheckpointNumber, proposer, publisher, attestorAddress, invalidateCheckpoint, proposedCheckpointData) {
1010
+ return new CheckpointProposalJob(targetSlot, targetEpoch, checkpointNumber, syncedToBlockNumber, checkpointedCheckpointNumber, proposer, publisher, attestorAddress, invalidateCheckpoint, this.validatorClient, this.globalsBuilder, this.p2pClient, this.worldState, this.l1ToL2MessageSource, this.l2BlockSource, this.checkpointsBuilder, this.l2BlockSource, this.l1Constants, this.signatureContext, this.config, this.timetable, this.slasherClient, this.epochCache, this.dateProvider, this.metrics, this.checkpointProposalJobMetrics.createRecorder(), this, this.pendingRequests, this.setState.bind(this), this.tracer, this.log.getBindings(), proposedCheckpointData);
1011
+ }
1012
+ /**
1013
+ * Returns the current sequencer state.
1014
+ */ getState() {
1015
+ return this.state;
1016
+ }
1017
+ /**
1018
+ * Internal helper for setting the sequencer state. Pure: sets the state, emits `state-changed`, and
1019
+ * records metrics. Timing deadlines are queried explicitly at the relevant call sites, not gated here.
1020
+ * @param proposedState - The new state to transition to.
1021
+ * @param slotNumber - The target slot being proposed for, emitted as `targetSlot` on the event payload
1022
+ * and used to anchor `secondsIntoBuildFrame`. Undefined for lifecycle states with no associated slot.
1023
+ * @param force - Whether to force the transition even if the sequencer is stopped.
1024
+ */ setState(proposedState, slotNumber, opts = {}) {
1025
+ if (this.state === SequencerState.STOPPING && proposedState !== SequencerState.STOPPED && !opts.force) {
1026
+ this.log.warn(`Cannot set sequencer to ${proposedState} as it is stopping.`);
1027
+ throw new SequencerInterruptedError();
1028
+ }
1029
+ if (this.state === SequencerState.STOPPED && !opts.force) {
1030
+ this.log.warn(`Cannot set sequencer from ${this.state} to ${proposedState} as it is stopped.`);
1031
+ return;
1032
+ }
1033
+ const secondsIntoBuildFrame = slotNumber !== undefined ? this.getSecondsIntoBuildFrame(slotNumber) : undefined;
1034
+ const oldState = this.state;
1035
+ const oldStateSlotNumber = this.stateSlotNumber;
1036
+ const stateChanged = proposedState !== oldState;
1037
+ // Wall-clock time spent in the previous state: the delta between consecutive state-changing setState
1038
+ // calls, read from the date provider so it tracks simulated time under a test/manual clock.
1039
+ const transitionAtMs = this.dateProvider.now();
1040
+ const stateDurationMs = transitionAtMs - this.stateEnteredAtMs;
1041
+ const boringStates = [
1042
+ SequencerState.IDLE,
1043
+ SequencerState.SYNCHRONIZING
1044
+ ];
1045
+ const logLevel = boringStates.includes(proposedState) && boringStates.includes(oldState) ? 'trace' : 'debug';
1046
+ this.stateLog[logLevel](`Transitioning from ${oldState} to ${proposedState}`, {
1047
+ oldState,
1048
+ newState: proposedState,
1049
+ slotNumber,
1050
+ stateSlotNumber: oldStateSlotNumber,
1051
+ secondsIntoBuildFrame,
1052
+ ...stateChanged && {
1053
+ stateDurationMs: Math.ceil(stateDurationMs)
1054
+ }
1055
+ });
1056
+ this.emit('state-changed', {
1057
+ oldState,
1058
+ newState: proposedState,
1059
+ secondsIntoBuildFrame,
1060
+ targetSlot: slotNumber
1061
+ });
1062
+ if (stateChanged) {
1063
+ this.metrics.recordStateDuration(stateDurationMs, oldState);
1064
+ this.stateEnteredAtMs = transitionAtMs;
1065
+ this.stateSlotNumber = slotNumber;
1066
+ }
1067
+ this.state = proposedState;
1068
+ }
1069
+ /**
1070
+ * Returns whether all dependencies have caught up.
1071
+ * We don't check against the previous block submitted since it may have been reorg'd out.
1072
+ */ async checkSync(args) {
1073
+ // Check that the archiver has fully synced the L2 slot before the one we want to propose in.
1074
+ // The archiver reports sync progress via L1 block timestamps and synced checkpoint slots.
1075
+ // See getSyncedL2SlotNumber for how missed L1 blocks are handled.
1076
+ const syncedL2Slot = await this.l2BlockSource.getSyncedL2SlotNumber();
1077
+ const { slot } = args;
1078
+ if (syncedL2Slot === undefined || syncedL2Slot + 1 < slot) {
1079
+ this.log.debug(`Cannot propose block at next L2 slot ${slot} due to pending sync from L1`, {
1080
+ slot,
1081
+ syncedL2Slot
1082
+ });
1083
+ return undefined;
1084
+ }
1085
+ const syncedBlocks = await Promise.all([
1086
+ this.worldState.status().then(({ syncSummary })=>({
1087
+ number: syncSummary.latestBlockNumber,
1088
+ hash: syncSummary.latestBlockHash
1089
+ })),
1090
+ this.l2BlockSource.getL2Tips().then((t)=>({
1091
+ proposed: t.proposed,
1092
+ checkpointed: t.checkpointed
1093
+ })),
1094
+ this.p2pClient.getStatus().then((p2p)=>p2p.syncedToL2Block),
1095
+ this.l1ToL2MessageSource.getL2Tips().then((t)=>({
1096
+ proposed: t.proposed,
1097
+ checkpointed: t.checkpointed
1098
+ })),
1099
+ this.l2BlockSource.getPendingChainValidationStatus(),
1100
+ this.l2BlockSource.getProposedCheckpointData()
1101
+ ]);
1102
+ const [worldState, l2Tips, p2p, l1ToL2MessageSourceTips, pendingChainValidationStatus, proposedCheckpointData] = syncedBlocks;
1103
+ const result = worldState.hash === l2Tips.proposed.hash && p2p.hash === l2Tips.proposed.hash && l1ToL2MessageSourceTips.proposed.hash === l2Tips.proposed.hash && l1ToL2MessageSourceTips.checkpointed.block.hash === l2Tips.checkpointed.block.hash && l1ToL2MessageSourceTips.checkpointed.checkpoint.hash === l2Tips.checkpointed.checkpoint.hash;
1104
+ if (!result) {
1105
+ this.log.debug(`Sequencer sync check failed`, {
1106
+ worldState,
1107
+ l2BlockSource: l2Tips.proposed,
1108
+ p2p,
1109
+ l1ToL2MessageSourceTips
1110
+ });
1111
+ return undefined;
1112
+ }
1113
+ const blockNumber = worldState.number;
1114
+ const blockData = await this.l2BlockSource.getBlockData({
1115
+ number: blockNumber
1116
+ });
1117
+ if (!blockData) {
1118
+ this.log.warn(`Sequencer sync check failed: failed to get L2 block data ${blockNumber} from the archiver`, {
1119
+ blockNumber,
1120
+ l2Tips,
1121
+ syncedL2Slot,
1122
+ ...args
1123
+ });
1124
+ return undefined;
1125
+ }
1126
+ // Refuse to build a checkpoint on top of a proposed block whose enclosing checkpoint was never
1127
+ // proposed. Under pipelining we may have received and reexecuted such a block locally — advancing
1128
+ // our world-state tip past the checkpointed tip — while the proposing node never published the
1129
+ // matching proposed checkpoint (e.g. it crashed before assembling it). Building on this orphan block
1130
+ // would fork the chain off a tip no other node can follow. The archiver prunes these orphan blocks
1131
+ // once their build slot ends; this guard is the correctness barrier during the grace window before.
1132
+ // `getProposedCheckpointData()` returns the latest proposed checkpoint payload, which is always
1133
+ // the leading one (a proposed entry is only stored beyond the confirmed frontier and is deleted
1134
+ // on confirmation). It carries no tip, so there is no tip-vs-payload split read to reconcile.
1135
+ if (blockData.checkpointNumber > l2Tips.checkpointed.checkpoint.number && proposedCheckpointData?.checkpointNumber !== blockData.checkpointNumber) {
1136
+ const logCtx = {
1137
+ blockCheckpointNumber: blockData.checkpointNumber,
1138
+ checkpointedCheckpointNumber: l2Tips.checkpointed.checkpoint.number,
1139
+ proposedCheckpointTipNumber: proposedCheckpointData?.checkpointNumber,
1140
+ blockNumber: blockData.header.getBlockNumber(),
1141
+ blockSlot: blockData.header.getSlot(),
1142
+ syncedL2Slot,
1143
+ ...args
1144
+ };
1145
+ this.log.debug(`Waiting for proposed checkpoint to catch up with reexecuted block`, logCtx);
1146
+ return undefined;
1147
+ }
1148
+ const hasProposedCheckpoint = proposedCheckpointData !== undefined;
1149
+ // Check that the proposed checkpoint is indeed the parent of the checkpoint we'll be building
1150
+ // The checkpoint number to build is derived as blockData.checkpointNumber + 1
1151
+ if (proposedCheckpointData && proposedCheckpointData.checkpointNumber !== blockData.checkpointNumber) {
1152
+ this.log.warn(`Sequencer sync check failed: proposed checkpoint number mismatch`, {
1153
+ proposedCheckpointNumber: proposedCheckpointData.checkpointNumber,
1154
+ blockCheckpointNumber: blockData.checkpointNumber,
1155
+ syncedL2Slot,
1156
+ ...args
1157
+ });
1158
+ return undefined;
1159
+ }
1160
+ return {
1161
+ blockData,
1162
+ blockNumber: blockData.header.getBlockNumber(),
1163
+ checkpointNumber: blockData.checkpointNumber,
1164
+ checkpointedCheckpointNumber: l2Tips.checkpointed.checkpoint.number,
1165
+ archive: blockData.archive.root,
1166
+ hasProposedCheckpoint,
1167
+ proposedCheckpointData,
1168
+ syncedL2Slot,
1169
+ pendingChainValidationStatus
1170
+ };
1171
+ }
1172
+ /**
1173
+ * Checks if we are the proposer for the next slot.
1174
+ * @returns True if we can propose, and the proposer address (undefined if anyone can propose)
1175
+ */ async checkCanPropose(targetSlot) {
1176
+ let proposer;
1177
+ try {
1178
+ proposer = await this.epochCache.getProposerAttesterAddressInSlot(targetSlot);
1179
+ } catch (e) {
1180
+ if (e instanceof NoCommitteeError) {
1181
+ const targetEpoch = getEpochAtSlot(targetSlot, this.l1Constants);
1182
+ if (this.lastEpochForNoCommitteeLog !== targetEpoch) {
1183
+ this.lastEpochForNoCommitteeLog = targetEpoch;
1184
+ await logMissingCommittee(targetSlot, targetEpoch, {
1185
+ epochCache: this.epochCache,
1186
+ rollupContract: this.rollupContract,
1187
+ l2BlockSource: this.l2BlockSource,
1188
+ l1Constants: this.l1Constants,
1189
+ dateProvider: this.dateProvider,
1190
+ logger: this.log
1191
+ });
1192
+ }
1193
+ return [
1194
+ false,
1195
+ undefined
1196
+ ];
1197
+ }
1198
+ this.log.error(`Error getting proposer for target slot ${targetSlot}`, e);
1199
+ return [
1200
+ false,
1201
+ undefined
1202
+ ];
1203
+ }
1204
+ // If proposer is undefined, then the committee is empty and anyone may propose
1205
+ if (proposer === undefined) {
1206
+ return [
1207
+ true,
1208
+ undefined
1209
+ ];
1210
+ }
1211
+ // In fisherman mode, just return the current proposer
1212
+ if (this.config.fishermanMode) {
1213
+ return [
1214
+ true,
1215
+ proposer
1216
+ ];
1217
+ }
1218
+ const validatorAddresses = this.validatorClient.getValidatorAddresses();
1219
+ const weAreProposer = validatorAddresses.some((addr)=>addr.equals(proposer));
1220
+ if (!weAreProposer) {
1221
+ this.log.debug(`Cannot propose at target slot ${targetSlot} since we are not a proposer`, {
1222
+ targetSlot,
1223
+ validatorAddresses,
1224
+ proposer
1225
+ });
1226
+ return [
1227
+ false,
1228
+ proposer
1229
+ ];
1230
+ }
1231
+ this.log.info(`We are the proposer for pipeline slot ${targetSlot}`, {
1232
+ targetSlot,
1233
+ proposer
1234
+ });
1235
+ return [
1236
+ true,
1237
+ proposer
1238
+ ];
1239
+ }
1240
+ /**
1241
+ * Tries to vote on slashing actions and governance and to prune when we cannot build and are past the
1242
+ * block-building window. This allows the sequencer to participate in governance/slashing votes even when it
1243
+ * cannot build blocks, and to prune the pending chain so it can recover from bad data that is blocking sync.
1244
+ */ async tryVoteAndPruneWhenCannotBuild(args) {
1245
+ const { slot, targetSlot } = args;
1246
+ // Prevent duplicate attempts in the same slot
1247
+ if (this.lastSlotForFallbackAction === slot) {
1248
+ this.log.trace(`Already attempted fallback actions in slot ${slot} (skipping)`);
1249
+ return;
1250
+ }
1251
+ // Vote-only actions do not give up the slot: if sync recovers, a later work-loop iteration can still build.
1252
+ // Under proposer pipelining the work loop reasons about the next L1 slot, so waiting for the target slot's
1253
+ // build-start deadline can miss the whole fallback window when the target advances with the clock.
1254
+ const nowSeconds = this.dateProvider.now() / 1000;
1255
+ const startDeadline = this.timetable.getBuildStartDeadline(targetSlot);
1256
+ this.log.trace(`Cannot build for slot ${slot}, checking for voting opportunities`, {
1257
+ nowSeconds,
1258
+ startDeadline
1259
+ });
1260
+ // Check if we're a proposer or proposal is open
1261
+ const [canPropose, proposer] = await this.checkCanPropose(targetSlot);
1262
+ if (!canPropose) {
1263
+ this.log.trace(`Cannot vote in slot ${slot} since we are not a proposer`, {
1264
+ slot,
1265
+ proposer
1266
+ });
1267
+ return;
1268
+ }
1269
+ // Mark this slot as attempted
1270
+ this.lastSlotForFallbackAction = slot;
1271
+ // Get a publisher for voting
1272
+ const { attestorAddress, publisher } = await this.publisherFactory.create(proposer);
1273
+ this.log.debug(`Attempting to vote despite sync failure at slot ${slot}`, {
1274
+ attestorAddress,
1275
+ slot
1276
+ });
1277
+ // Enqueue governance and slashing votes (voter uses the target slot for L1 submission)
1278
+ const voter = new CheckpointVoter(targetSlot, publisher, attestorAddress, this.validatorClient, this.slasherClient, this.l1Constants, this.config, this.metrics, this.log);
1279
+ const votesPromises = voter.enqueueVotes();
1280
+ const votes = await Promise.all(votesPromises);
1281
+ // Even if we cannot build, try to prune so a stuck pending chain (e.g. bad data blocking sync) can
1282
+ // recover. prune() is permissionless, so it rides the same fallback multicall as the votes.
1283
+ const pruneEnqueued = await this.tryEnqueuePruneIfPrunable(targetSlot, publisher);
1284
+ // Bail if nothing to do
1285
+ if (votes.every((p)=>!p) && !pruneEnqueued) {
1286
+ this.log.debug(`Nothing to enqueue for slot ${slot} (no votes, not prunable)`);
1287
+ return;
1288
+ }
1289
+ const [governanceVoteEnqueued, slashingVoteEnqueued] = votes;
1290
+ this.log.info(`Submitting fallback requests in slot ${slot} despite sync failure`, {
1291
+ slot,
1292
+ pruneEnqueued,
1293
+ governanceVoteEnqueued: !!governanceVoteEnqueued,
1294
+ slashingVoteEnqueued: !!slashingVoteEnqueued
1295
+ });
1296
+ // Votes are EIP-712-signed for `targetSlot` (the pipelined slot in which the multicall is
1297
+ // expected to mine). Delay submission to the start of `targetSlot` so the tx mines in the
1298
+ // slot the votes were signed for. We fire-and-forget so we don't block the sequencer's
1299
+ // work loop while waiting for the target slot to start, but track it so stop() can drain it.
1300
+ const send = publisher.sendRequestsAt(targetSlot).catch((err)=>{
1301
+ this.log.error(`Failed to publish fallback requests despite sync failure for slot ${slot}`, err, {
1302
+ slot
1303
+ });
1304
+ });
1305
+ this.pendingRequests.trackRequest(send, ()=>publisher.interrupt());
1306
+ }
1307
+ async tryEnqueuePruneIfPrunable(targetSlot, publisher) {
1308
+ try {
1309
+ return await publisher.enqueuePruneIfPrunable(targetSlot);
1310
+ } catch (err) {
1311
+ this.log.error(`Failed to enqueue rollup prune for slot ${targetSlot}`, err, {
1312
+ targetSlot
1313
+ });
1314
+ return false;
1315
+ }
1316
+ }
1317
+ /**
1318
+ * Tries to vote on slashing actions and governance proposals when escape hatch is open.
1319
+ * This allows the sequencer to participate in voting without performing checkpoint proposal work.
1320
+ */ async tryVoteWhenEscapeHatchOpen(args) {
1321
+ const { slot, targetSlot, proposer } = args;
1322
+ // Prevent duplicate attempts in the same slot
1323
+ if (this.lastSlotForFallbackAction === slot) {
1324
+ this.log.trace(`Already attempted to vote in slot ${slot} (escape hatch open, skipping)`);
1325
+ return;
1326
+ }
1327
+ // Mark this slot as attempted
1328
+ this.lastSlotForFallbackAction = slot;
1329
+ const { attestorAddress, publisher } = await this.publisherFactory.create(proposer);
1330
+ this.log.debug(`Escape hatch open for slot ${slot}, attempting vote-only actions`, {
1331
+ slot,
1332
+ targetSlot,
1333
+ attestorAddress
1334
+ });
1335
+ // Under proposer pipelining, the multicall is expected to mine in `targetSlot` (slot + 1).
1336
+ // Governance and slashing votes are EIP-712-signed against the slot they will mine in, and the
1337
+ // L1 contract checks `msg.sender == getCurrentProposer()` using the mining slot. So we must
1338
+ // sign for `targetSlot` and delay submission to the start of `targetSlot`.
1339
+ const voter = new CheckpointVoter(targetSlot, publisher, attestorAddress, this.validatorClient, this.slasherClient, this.l1Constants, this.config, this.metrics, this.log);
1340
+ const votesPromises = voter.enqueueVotes();
1341
+ const votes = await Promise.all(votesPromises);
1342
+ if (votes.every((p)=>!p)) {
1343
+ this.log.debug(`No votes to enqueue for slot ${slot} (escape hatch open)`);
1344
+ return;
1345
+ }
1346
+ this.log.info(`Voting in slot ${slot} (escape hatch open)`, {
1347
+ slot,
1348
+ targetSlot
1349
+ });
1350
+ // Votes are EIP-712-signed for `targetSlot`. Delay submission to the start of `targetSlot` so
1351
+ // the multicall mines in the slot the votes were signed for; otherwise the L1 contract reads
1352
+ // `signaler = getCurrentProposer()` against the wrong slot and signature verification fails
1353
+ // silently inside Multicall3. Fire-and-forget so we don't block the sequencer's work loop while
1354
+ // waiting for the target slot to start, mirroring tryVoteAndPruneWhenCannotBuild, but tracked so
1355
+ // stop() can drain it.
1356
+ const send = publisher.sendRequestsAt(targetSlot).catch((err)=>{
1357
+ this.log.error(`Failed to publish escape-hatch votes for slot ${slot}`, err, {
1358
+ slot,
1359
+ targetSlot
1360
+ });
1361
+ });
1362
+ this.pendingRequests.trackRequest(send, ()=>publisher.interrupt());
1363
+ }
1364
+ /**
1365
+ * Considers invalidating a block if the pending chain is invalid. Depends on how long the invalid block
1366
+ * has been there without being invalidated and whether the sequencer is in the committee or not. We always
1367
+ * have the proposer try to invalidate, but if they fail, the sequencers in the committee are expected to try,
1368
+ * and if they fail, any sequencer will try as well.
1369
+ * @param pendingChainValidationStatus - The archiver's pending-chain validation status, authoritative on its own.
1370
+ * @param currentSlot - The wall-clock slot, used for committee lookup, the per-(checkpoint, slot) dedup guard, and logging.
1371
+ */ async considerInvalidatingCheckpoint(pendingChainValidationStatus, currentSlot) {
1372
+ if (pendingChainValidationStatus.valid) {
1373
+ return;
1374
+ }
1375
+ const invalidCheckpointNumber = pendingChainValidationStatus.checkpoint.checkpointNumber;
1376
+ // Avoid re-running the committee lookup, simulation, and submission on every tick within a slot.
1377
+ // The guard is keyed by (checkpoint, slot) — so a different invalid checkpoint surfacing later in
1378
+ // the same slot is not suppressed — and is set only after a request is successfully simulated below,
1379
+ // so a transient simulation failure (or thresholds not yet met) still retries on the next tick.
1380
+ if (this.lastInvalidationAttempt?.slot === currentSlot && this.lastInvalidationAttempt.checkpointNumber === invalidCheckpointNumber) {
1381
+ this.log.trace(`Already attempted to invalidate checkpoint ${invalidCheckpointNumber} in slot ${currentSlot}`, {
1382
+ currentSlot,
1383
+ invalidCheckpointNumber
1384
+ });
1385
+ return;
1386
+ }
1387
+ const invalidCheckpointTimestamp = pendingChainValidationStatus.checkpoint.timestamp;
1388
+ const timeSinceChainInvalid = this.dateProvider.nowInSeconds() - Number(invalidCheckpointTimestamp);
1389
+ const ourValidatorAddresses = this.validatorClient.getValidatorAddresses();
1390
+ const { secondsBeforeInvalidatingBlockAsCommitteeMember, secondsBeforeInvalidatingBlockAsNonCommitteeMember } = this.config;
1391
+ const logData = {
1392
+ invalidL1Timestamp: invalidCheckpointTimestamp,
1393
+ invalidCheckpoint: pendingChainValidationStatus.checkpoint,
1394
+ secondsBeforeInvalidatingBlockAsCommitteeMember,
1395
+ secondsBeforeInvalidatingBlockAsNonCommitteeMember,
1396
+ ourValidatorAddresses,
1397
+ currentSlot
1398
+ };
1399
+ const inCurrentCommittee = ()=>this.epochCache.getCommittee(currentSlot).then((c)=>c?.committee?.some((member)=>ourValidatorAddresses.some((addr)=>addr.equals(member))));
1400
+ const invalidateAsCommitteeMember = secondsBeforeInvalidatingBlockAsCommitteeMember !== undefined && secondsBeforeInvalidatingBlockAsCommitteeMember > 0 && timeSinceChainInvalid > secondsBeforeInvalidatingBlockAsCommitteeMember && await inCurrentCommittee();
1401
+ const invalidateAsNonCommitteeMember = secondsBeforeInvalidatingBlockAsNonCommitteeMember !== undefined && secondsBeforeInvalidatingBlockAsNonCommitteeMember > 0 && timeSinceChainInvalid > secondsBeforeInvalidatingBlockAsNonCommitteeMember;
1402
+ if (!invalidateAsCommitteeMember && !invalidateAsNonCommitteeMember) {
1403
+ this.log.debug(`Not invalidating pending chain`, logData);
1404
+ return;
1405
+ }
1406
+ let validatorToUse;
1407
+ if (invalidateAsCommitteeMember) {
1408
+ // When invalidating as a committee member, use first validator that's actually in the committee
1409
+ const { committee } = await this.epochCache.getCommittee(currentSlot);
1410
+ if (committee) {
1411
+ const committeeSet = new Set(committee.map((addr)=>addr.toString()));
1412
+ validatorToUse = ourValidatorAddresses.find((addr)=>committeeSet.has(addr.toString())) ?? ourValidatorAddresses[0];
1413
+ } else {
1414
+ validatorToUse = ourValidatorAddresses[0];
1415
+ }
1416
+ } else {
1417
+ // When invalidating as a non-committee member, use the first validator
1418
+ validatorToUse = ourValidatorAddresses[0];
1419
+ }
1420
+ const { publisher } = await this.publisherFactory.create(validatorToUse);
1421
+ const invalidateCheckpoint = await publisher.simulateInvalidateCheckpoint(pendingChainValidationStatus);
1422
+ if (!invalidateCheckpoint) {
1423
+ this.log.warn(`Failed to simulate invalidate checkpoint`, logData);
1424
+ return;
1425
+ }
1426
+ // We produced a valid invalidation request; record it so further ticks within this slot skip the
1427
+ // committee lookup, simulation, and submission above for this same invalid checkpoint.
1428
+ this.lastInvalidationAttempt = {
1429
+ slot: currentSlot,
1430
+ checkpointNumber: invalidCheckpointNumber
1431
+ };
1432
+ this.log.info(invalidateAsCommitteeMember ? `Invalidating checkpoint ${invalidCheckpointNumber} as committee member` : `Invalidating checkpoint ${invalidCheckpointNumber} as non-committee member`, logData);
1433
+ publisher.enqueueInvalidateCheckpoint(invalidateCheckpoint);
1434
+ if (!this.config.fishermanMode) {
1435
+ await publisher.sendRequests();
1436
+ } else {
1437
+ this.log.info('Invalidating checkpoint in fisherman mode, clearing pending requests');
1438
+ publisher.clearPendingRequests();
1439
+ }
1440
+ }
1441
+ logStrategyComparison(epoch, publisher) {
1442
+ const feeAnalyzer = publisher.getL1FeeAnalyzer();
1443
+ if (!feeAnalyzer) {
1444
+ return;
1445
+ }
1446
+ const comparison = feeAnalyzer.getStrategyComparison();
1447
+ if (comparison.length === 0) {
1448
+ this.log.debug(`No strategy data available yet for epoch ${epoch}`);
1449
+ return;
1450
+ }
1451
+ this.log.info(`L1 Fee Strategy Performance Report - End of Epoch ${epoch}`, {
1452
+ epoch: Number(epoch),
1453
+ totalAnalyses: comparison[0]?.totalAnalyses,
1454
+ strategies: comparison.map((s)=>({
1455
+ id: s.strategyId,
1456
+ name: s.strategyName,
1457
+ inclusionRate: `${(s.inclusionRate * 100).toFixed(1)}%`,
1458
+ inclusionCount: `${s.inclusionCount}/${s.totalAnalyses}`,
1459
+ avgCostEth: s.avgEstimatedCostEth.toFixed(6),
1460
+ totalCostEth: s.totalEstimatedCostEth.toFixed(6),
1461
+ avgOverpaymentEth: s.avgOverpaymentEth.toFixed(6),
1462
+ totalOverpaymentEth: s.totalOverpaymentEth.toFixed(6),
1463
+ avgPriorityFeeDeltaGwei: s.avgPriorityFeeDeltaGwei.toFixed(2)
1464
+ }))
1465
+ });
1466
+ }
1467
+ /**
1468
+ * Wall-clock seconds elapsed since the build-frame start of the given target slot
1469
+ * (`now − getBuildFrameStart(targetSlot)`). May be negative if called before the build frame opens.
1470
+ */ getSecondsIntoBuildFrame(targetSlot) {
1471
+ const buildFrameStart = this.timetable.getBuildFrameStart(targetSlot);
1472
+ return Number((this.dateProvider.now() / 1000 - buildFrameStart).toFixed(3));
1473
+ }
1474
+ get aztecSlotDuration() {
1475
+ return this.l1Constants.slotDuration;
1476
+ }
1477
+ get maxL2BlockGas() {
1478
+ return this.config.maxL2BlockGas;
1479
+ }
1480
+ getSlasherClient() {
1481
+ return this.slasherClient;
1482
+ }
1483
+ get tracer() {
1484
+ return this.metrics.tracer;
1485
+ }
1486
+ getValidatorAddresses() {
1487
+ return this.validatorClient?.getValidatorAddresses();
1488
+ }
1489
+ /** Updates the publisher factory's node keystore adapter after a keystore reload. */ updatePublisherNodeKeyStore(adapter) {
1490
+ this.publisherFactory.updateNodeKeyStore(adapter);
1491
+ }
1492
+ getConfig() {
1493
+ return this.config;
1494
+ }
1495
+ }