@xyo-network/chain-producer 1.19.7 → 1.19.8

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.
@@ -1,12 +1,10 @@
1
1
  import type { Attributes, Counter } from '@opentelemetry/api';
2
- import type { Address, Logger } from '@xylabs/sdk-js';
3
- import type { ActorParamsV2, ChainStakeIntent, HydratedBlockWithHashMeta, XL1BlockNumber } from '@xyo-network/xl1-sdk';
4
- import { AccountBalanceViewer, ActorV2, BlockRunner, BlockViewer, MempoolRunner, MempoolViewer, StakeTotalsViewer } from '@xyo-network/xl1-sdk';
5
- export type ProducerActorParams = ActorParamsV2<{
6
- logger: Logger;
7
- rewardAddress: Address;
2
+ import type { ActorParamsV3, ChainContractViewer, ChainStakeIntent, Config, HydratedBlockWithHashMeta, XL1BlockNumber } from '@xyo-network/xl1-sdk';
3
+ import { AccountBalanceViewer, ActorV3, BlockRunner, BlockViewer, MempoolRunner, MempoolViewer, StakeTotalsViewer } from '@xyo-network/xl1-sdk';
4
+ export type ProducerActorParams = ActorParamsV3<{
5
+ config: Config;
8
6
  }>;
9
- export declare class ProducerActor extends ActorV2<ProducerActorParams> {
7
+ export declare class ProducerActor extends ActorV3<ProducerActorParams> {
10
8
  /**
11
9
  * The interval time (in MS) between block production attempts.
12
10
  */
@@ -29,42 +27,453 @@ export declare class ProducerActor extends ActorV2<ProducerActorParams> {
29
27
  private _accountBalanceViewer?;
30
28
  private _blockRunner?;
31
29
  private _blockViewer?;
30
+ private _chainContractViewer?;
32
31
  private _chainId?;
33
32
  private _lastHeadChangeTime?;
34
33
  private _lastHeadHash?;
35
34
  private _mempoolRunner?;
36
35
  private _mempoolViewer?;
37
36
  private _produceBlockMutex;
37
+ private _rewardAddress;
38
38
  private _stakeTotalsViewer?;
39
- get logger(): Logger;
39
+ get logger(): import("@xylabs/sdk-js").Logger;
40
40
  protected get accountBalanceViewer(): AccountBalanceViewer;
41
41
  protected get blockRunner(): BlockRunner;
42
42
  protected get blockViewer(): BlockViewer<"BlockViewer">;
43
+ protected get chainContractViewer(): ChainContractViewer;
43
44
  protected get chainId(): import("@xylabs/sdk-js").BrandedHex;
45
+ protected get config(): {
46
+ chain: {
47
+ id?: import("@xylabs/sdk-js").BrandedHex | undefined;
48
+ genesisRewardAddress?: (Lowercase<string> & {
49
+ readonly __hex: true;
50
+ } & {
51
+ readonly __address: true;
52
+ }) | undefined;
53
+ };
54
+ evm: {
55
+ chainId?: string | undefined;
56
+ infura?: {
57
+ projectId?: string | undefined;
58
+ projectSecret?: string | undefined;
59
+ } | undefined;
60
+ jsonRpc?: {
61
+ url?: string | undefined;
62
+ } | undefined;
63
+ };
64
+ log: {
65
+ logLevel: "log" | "error" | "warn" | "info" | "debug" | "trace";
66
+ silent: boolean;
67
+ };
68
+ remote: {
69
+ rpc?: {
70
+ url: string;
71
+ } | undefined;
72
+ };
73
+ storage: {
74
+ mongo?: {
75
+ connectionString?: string | undefined;
76
+ database?: string | undefined;
77
+ domain?: string | undefined;
78
+ password?: string | undefined;
79
+ username?: string | undefined;
80
+ } | undefined;
81
+ root?: string | undefined;
82
+ };
83
+ telemetry: {
84
+ metrics?: {
85
+ scrape: {
86
+ path: string;
87
+ port?: number | undefined;
88
+ };
89
+ } | undefined;
90
+ otel?: {
91
+ otlpEndpoint?: string | undefined;
92
+ } | undefined;
93
+ };
94
+ validation: {
95
+ allowedRewardRedeemers?: (Lowercase<string> & {
96
+ readonly __hex: true;
97
+ } & {
98
+ readonly __address: true;
99
+ })[] | undefined;
100
+ allowedRewardEscrowAccountSigners?: (Lowercase<string> & {
101
+ readonly __hex: true;
102
+ } & {
103
+ readonly __address: true;
104
+ })[] | undefined;
105
+ };
106
+ actors: {
107
+ api: {
108
+ chain: {
109
+ id?: import("@xylabs/sdk-js").BrandedHex | undefined;
110
+ genesisRewardAddress?: (Lowercase<string> & {
111
+ readonly __hex: true;
112
+ } & {
113
+ readonly __address: true;
114
+ }) | undefined;
115
+ };
116
+ evm: {
117
+ chainId?: string | undefined;
118
+ infura?: {
119
+ projectId?: string | undefined;
120
+ projectSecret?: string | undefined;
121
+ } | undefined;
122
+ jsonRpc?: {
123
+ url?: string | undefined;
124
+ } | undefined;
125
+ };
126
+ log: {
127
+ logLevel: "log" | "error" | "warn" | "info" | "debug" | "trace";
128
+ silent: boolean;
129
+ };
130
+ remote: {
131
+ rpc?: {
132
+ url: string;
133
+ } | undefined;
134
+ };
135
+ storage: {
136
+ mongo?: {
137
+ connectionString?: string | undefined;
138
+ database?: string | undefined;
139
+ domain?: string | undefined;
140
+ password?: string | undefined;
141
+ username?: string | undefined;
142
+ } | undefined;
143
+ root?: string | undefined;
144
+ };
145
+ telemetry: {
146
+ metrics?: {
147
+ scrape: {
148
+ path: string;
149
+ port?: number | undefined;
150
+ };
151
+ } | undefined;
152
+ otel?: {
153
+ otlpEndpoint?: string | undefined;
154
+ } | undefined;
155
+ };
156
+ validation: {
157
+ allowedRewardRedeemers?: (Lowercase<string> & {
158
+ readonly __hex: true;
159
+ } & {
160
+ readonly __address: true;
161
+ })[] | undefined;
162
+ allowedRewardEscrowAccountSigners?: (Lowercase<string> & {
163
+ readonly __hex: true;
164
+ } & {
165
+ readonly __address: true;
166
+ })[] | undefined;
167
+ };
168
+ host: string;
169
+ initRewardsCache: boolean;
170
+ port: number;
171
+ mnemonic?: string | undefined;
172
+ };
173
+ bridge: {
174
+ chain: {
175
+ id?: import("@xylabs/sdk-js").BrandedHex | undefined;
176
+ genesisRewardAddress?: (Lowercase<string> & {
177
+ readonly __hex: true;
178
+ } & {
179
+ readonly __address: true;
180
+ }) | undefined;
181
+ };
182
+ evm: {
183
+ chainId?: string | undefined;
184
+ infura?: {
185
+ projectId?: string | undefined;
186
+ projectSecret?: string | undefined;
187
+ } | undefined;
188
+ jsonRpc?: {
189
+ url?: string | undefined;
190
+ } | undefined;
191
+ };
192
+ log: {
193
+ logLevel: "log" | "error" | "warn" | "info" | "debug" | "trace";
194
+ silent: boolean;
195
+ };
196
+ remote: {
197
+ rpc?: {
198
+ url: string;
199
+ } | undefined;
200
+ };
201
+ storage: {
202
+ mongo?: {
203
+ connectionString?: string | undefined;
204
+ database?: string | undefined;
205
+ domain?: string | undefined;
206
+ password?: string | undefined;
207
+ username?: string | undefined;
208
+ } | undefined;
209
+ root?: string | undefined;
210
+ };
211
+ telemetry: {
212
+ metrics?: {
213
+ scrape: {
214
+ path: string;
215
+ port?: number | undefined;
216
+ };
217
+ } | undefined;
218
+ otel?: {
219
+ otlpEndpoint?: string | undefined;
220
+ } | undefined;
221
+ };
222
+ validation: {
223
+ allowedRewardRedeemers?: (Lowercase<string> & {
224
+ readonly __hex: true;
225
+ } & {
226
+ readonly __address: true;
227
+ })[] | undefined;
228
+ allowedRewardEscrowAccountSigners?: (Lowercase<string> & {
229
+ readonly __hex: true;
230
+ } & {
231
+ readonly __address: true;
232
+ })[] | undefined;
233
+ };
234
+ chainRpcApiUrl: string;
235
+ feeFixed: import("@xylabs/sdk-js").BrandedHex;
236
+ feeRateBasisPoints: number;
237
+ host: string;
238
+ maxBridgeAmount: import("@xylabs/sdk-js").BrandedHex;
239
+ minBridgeAmount: import("@xylabs/sdk-js").BrandedHex;
240
+ port: number;
241
+ redisHost: string;
242
+ redisPort: number;
243
+ remoteBridgeContractAddress: Lowercase<string> & {
244
+ readonly __hex: true;
245
+ } & {
246
+ readonly __address: true;
247
+ };
248
+ remoteChainId: import("@xylabs/sdk-js").BrandedHex;
249
+ remoteTokenAddress: import("@xylabs/sdk-js").BrandedHex;
250
+ remoteChainWalletPrivateKey: import("@xylabs/sdk-js").BrandedHex;
251
+ escrowAddress?: (Lowercase<string> & {
252
+ readonly __hex: true;
253
+ } & {
254
+ readonly __address: true;
255
+ }) | undefined;
256
+ feesAddress?: (Lowercase<string> & {
257
+ readonly __hex: true;
258
+ } & {
259
+ readonly __address: true;
260
+ }) | undefined;
261
+ mnemonic?: string | undefined;
262
+ xl1ChainId?: import("@xylabs/sdk-js").BrandedHex | undefined;
263
+ xl1TokenAddress?: import("@xylabs/sdk-js").BrandedHex | undefined;
264
+ };
265
+ mempool: {
266
+ chain: {
267
+ id?: import("@xylabs/sdk-js").BrandedHex | undefined;
268
+ genesisRewardAddress?: (Lowercase<string> & {
269
+ readonly __hex: true;
270
+ } & {
271
+ readonly __address: true;
272
+ }) | undefined;
273
+ };
274
+ evm: {
275
+ chainId?: string | undefined;
276
+ infura?: {
277
+ projectId?: string | undefined;
278
+ projectSecret?: string | undefined;
279
+ } | undefined;
280
+ jsonRpc?: {
281
+ url?: string | undefined;
282
+ } | undefined;
283
+ };
284
+ log: {
285
+ logLevel: "log" | "error" | "warn" | "info" | "debug" | "trace";
286
+ silent: boolean;
287
+ };
288
+ remote: {
289
+ rpc?: {
290
+ url: string;
291
+ } | undefined;
292
+ };
293
+ storage: {
294
+ mongo?: {
295
+ connectionString?: string | undefined;
296
+ database?: string | undefined;
297
+ domain?: string | undefined;
298
+ password?: string | undefined;
299
+ username?: string | undefined;
300
+ } | undefined;
301
+ root?: string | undefined;
302
+ };
303
+ telemetry: {
304
+ metrics?: {
305
+ scrape: {
306
+ path: string;
307
+ port?: number | undefined;
308
+ };
309
+ } | undefined;
310
+ otel?: {
311
+ otlpEndpoint?: string | undefined;
312
+ } | undefined;
313
+ };
314
+ validation: {
315
+ allowedRewardRedeemers?: (Lowercase<string> & {
316
+ readonly __hex: true;
317
+ } & {
318
+ readonly __address: true;
319
+ })[] | undefined;
320
+ allowedRewardEscrowAccountSigners?: (Lowercase<string> & {
321
+ readonly __hex: true;
322
+ } & {
323
+ readonly __address: true;
324
+ })[] | undefined;
325
+ };
326
+ enabled: boolean;
327
+ host: string;
328
+ port: number;
329
+ mnemonic?: string | undefined;
330
+ };
331
+ producer: {
332
+ chain: {
333
+ id?: import("@xylabs/sdk-js").BrandedHex | undefined;
334
+ genesisRewardAddress?: (Lowercase<string> & {
335
+ readonly __hex: true;
336
+ } & {
337
+ readonly __address: true;
338
+ }) | undefined;
339
+ };
340
+ evm: {
341
+ chainId?: string | undefined;
342
+ infura?: {
343
+ projectId?: string | undefined;
344
+ projectSecret?: string | undefined;
345
+ } | undefined;
346
+ jsonRpc?: {
347
+ url?: string | undefined;
348
+ } | undefined;
349
+ };
350
+ log: {
351
+ logLevel: "log" | "error" | "warn" | "info" | "debug" | "trace";
352
+ silent: boolean;
353
+ };
354
+ remote: {
355
+ rpc?: {
356
+ url: string;
357
+ } | undefined;
358
+ };
359
+ storage: {
360
+ mongo?: {
361
+ connectionString?: string | undefined;
362
+ database?: string | undefined;
363
+ domain?: string | undefined;
364
+ password?: string | undefined;
365
+ username?: string | undefined;
366
+ } | undefined;
367
+ root?: string | undefined;
368
+ };
369
+ telemetry: {
370
+ metrics?: {
371
+ scrape: {
372
+ path: string;
373
+ port?: number | undefined;
374
+ };
375
+ } | undefined;
376
+ otel?: {
377
+ otlpEndpoint?: string | undefined;
378
+ } | undefined;
379
+ };
380
+ validation: {
381
+ allowedRewardRedeemers?: (Lowercase<string> & {
382
+ readonly __hex: true;
383
+ } & {
384
+ readonly __address: true;
385
+ })[] | undefined;
386
+ allowedRewardEscrowAccountSigners?: (Lowercase<string> & {
387
+ readonly __hex: true;
388
+ } & {
389
+ readonly __address: true;
390
+ })[] | undefined;
391
+ };
392
+ heartbeatInterval: number;
393
+ minStake: number;
394
+ port: number;
395
+ allowlist?: (Lowercase<string> & {
396
+ readonly __hex: true;
397
+ } & {
398
+ readonly __address: true;
399
+ })[] | undefined;
400
+ disableIntentRedeclaration?: boolean | undefined;
401
+ healthCheckPort?: number | undefined;
402
+ mnemonic?: string | undefined;
403
+ rewardAddress?: string | undefined;
404
+ };
405
+ rewardRedemption: {
406
+ chain: {
407
+ id?: import("@xylabs/sdk-js").BrandedHex | undefined;
408
+ genesisRewardAddress?: (Lowercase<string> & {
409
+ readonly __hex: true;
410
+ } & {
411
+ readonly __address: true;
412
+ }) | undefined;
413
+ };
414
+ evm: {
415
+ chainId?: string | undefined;
416
+ infura?: {
417
+ projectId?: string | undefined;
418
+ projectSecret?: string | undefined;
419
+ } | undefined;
420
+ jsonRpc?: {
421
+ url?: string | undefined;
422
+ } | undefined;
423
+ };
424
+ log: {
425
+ logLevel: "log" | "error" | "warn" | "info" | "debug" | "trace";
426
+ silent: boolean;
427
+ };
428
+ remote: {
429
+ rpc?: {
430
+ url: string;
431
+ } | undefined;
432
+ };
433
+ storage: {
434
+ mongo?: {
435
+ connectionString?: string | undefined;
436
+ database?: string | undefined;
437
+ domain?: string | undefined;
438
+ password?: string | undefined;
439
+ username?: string | undefined;
440
+ } | undefined;
441
+ root?: string | undefined;
442
+ };
443
+ telemetry: {
444
+ metrics?: {
445
+ scrape: {
446
+ path: string;
447
+ port?: number | undefined;
448
+ };
449
+ } | undefined;
450
+ otel?: {
451
+ otlpEndpoint?: string | undefined;
452
+ } | undefined;
453
+ };
454
+ validation: {
455
+ allowedRewardRedeemers?: (Lowercase<string> & {
456
+ readonly __hex: true;
457
+ } & {
458
+ readonly __address: true;
459
+ })[] | undefined;
460
+ allowedRewardEscrowAccountSigners?: (Lowercase<string> & {
461
+ readonly __hex: true;
462
+ } & {
463
+ readonly __address: true;
464
+ })[] | undefined;
465
+ };
466
+ chainRpcApiUrl: string;
467
+ host: string;
468
+ port: number;
469
+ mnemonic?: string | undefined;
470
+ };
471
+ };
472
+ };
44
473
  protected get mempoolRunner(): MempoolRunner;
45
474
  protected get mempoolViewer(): MempoolViewer;
46
- protected get rewardAddress(): Lowercase<string> & {
47
- readonly __hex: true;
48
- } & {
49
- readonly __address: true;
50
- };
51
475
  protected get stakeTotalsViewer(): StakeTotalsViewer;
52
- static paramsHandler<T extends ProducerActor>(params: Partial<T['params']>): Promise<{
53
- rewardAddress: Lowercase<string> & {
54
- readonly __hex: true;
55
- } & {
56
- readonly __address: true;
57
- };
58
- account: T["params"]["account"];
59
- logger: import("@xylabs/sdk-js").IdLogger | undefined;
60
- config: T["params"]["config"];
61
- name?: import("@xylabs/sdk-js").CreatableName;
62
- statusReporter?: import("@xylabs/sdk-js").CreatableStatusReporter<void> | undefined;
63
- meterProvider?: import("@opentelemetry/api").MeterProvider;
64
- traceProvider?: import("@opentelemetry/api").TracerProvider;
65
- }>;
66
476
  createHandler(): Promise<void>;
67
- initLocator(): Promise<import("@xyo-network/xl1-sdk").ProviderFactoryLocatorInstance<import("@xyo-network/xl1-sdk").CreatableProviderContextType>>;
68
477
  startHandler(): Promise<void>;
69
478
  protected calculateBlocksUntilProducerDeclarationExpiration(currentBlock: number): number;
70
479
  protected produceBlock(): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"ProducerActor.d.ts","sourceRoot":"","sources":["../../src/ProducerActor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAA;AAC7D,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAA;AAUrD,OAAO,KAAK,EACV,aAAa,EAC2B,gBAAgB,EAAE,yBAAyB,EAAE,cAAc,EACpG,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EACL,oBAAoB,EAA+B,OAAO,EAAoB,WAAW,EAAsB,WAAW,EACH,aAAa,EACpI,aAAa,EAA4F,iBAAiB,EAE3H,MAAM,sBAAsB,CAAA;AAG7B,MAAM,MAAM,mBAAmB,GAAG,aAAa,CAAC;IAC9C,MAAM,EAAE,MAAM,CAAA;IACd,aAAa,EAAE,OAAO,CAAA;CACvB,CAAC,CAAA;AAcF,qBACa,aAAc,SAAQ,OAAO,CAAC,mBAAmB,CAAC;IAC7D;;OAEG;IACH,MAAM,CAAC,QAAQ,CAAC,4BAA4B,QAAO;IAEnD;;OAEG;IACH,MAAM,CAAC,QAAQ,CAAC,yBAAyB,SAAkD;IAE3F;;OAEG;IACH,MAAM,CAAC,QAAQ,CAAC,mBAAmB,SAAS;IAE5C,SAAS,CAAC,kBAAkB,CAAC,EAAE,yBAAyB,CAAA;IACxD,SAAS,CAAC,wBAAwB,CAAC,EAAE,gBA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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;MAEnB;IAED,SAAS,KAAK,aAAa,kBAE1B;IAED,SAAS,KAAK,aAAa,kBAE1B;IAED,SAAS,KAAK,iBAAiB,sBAE9B;IAEc,aAAa;IAgFb,YAAY;IAe3B,SAAS,CAAC,iDAAiD,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM;cAIzE,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC;cAgF7B,eAAe,IAAI,OAAO,CAAC,IAAI,CAAC;cAiEhC,yBAAyB,CAAC,YAAY,EAAE,cAAc,EAAE,mBAAmB,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC;cAkB7G,sBAAsB,IAAI,OAAO,CAAC,OAAO,CAAC;cAe1C,oBAAoB,IAAI,OAAO,CAAC,OAAO,CAAC;CAWzD"}
@@ -3,12 +3,8 @@ var __name = (target, value) => __defProp(target, "name", { value, configurable:
3
3
 
4
4
  // src/ProducerActor.ts
5
5
  import { assertEx, creatable, isDefined, isUndefined, toHex } from "@xylabs/sdk-js";
6
- import { buildTelemetryConfig, initEvmProvidersIfAvailable } from "@xyo-network/chain-orchestration";
7
6
  import { SimpleBlockRunner } from "@xyo-network/chain-services";
8
- import { initTelemetry } from "@xyo-network/chain-telemetry";
9
- import { startupSpanAsync } from "@xyo-network/chain-utils";
10
- import { validateHydratedBlock, validateHydratedBlockState } from "@xyo-network/chain-validation";
11
- import { AccountBalanceViewerMoniker, ActorV2, asXL1BlockNumber, BlockRunnerMoniker, BlockViewerMoniker, buildJsonRpcProviderLocatorV2, buildTransaction, createDeclarationIntent, DefaultMetricsScrapePorts, HttpRpcTransport, MempoolRunnerMoniker, MempoolViewerMoniker, SimpleBlockRewardViewer, SimpleBlockValidationViewer, StakeTotalsViewerMoniker } from "@xyo-network/xl1-sdk";
7
+ import { AccountBalanceViewerMoniker, ActorV3, asXL1BlockNumber, BlockRunnerMoniker, BlockViewerMoniker, buildTransaction, ChainContractViewerMoniker, createDeclarationIntent, FinalizationViewerMoniker, MempoolRunnerMoniker, MempoolViewerMoniker, StakeTotalsViewerMoniker } from "@xyo-network/xl1-sdk";
12
8
  import { Mutex } from "async-mutex";
13
9
  function _ts_decorate(decorators, target, key, desc) {
14
10
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -24,7 +20,7 @@ var toFormattedBlockReference = /* @__PURE__ */ __name((blockBoundWitness) => {
24
20
  prefix: true
25
21
  })}]`;
26
22
  }, "toFormattedBlockReference");
27
- var ProducerActor = class _ProducerActor extends ActorV2 {
23
+ var ProducerActor = class _ProducerActor extends ActorV3 {
28
24
  static {
29
25
  __name(this, "ProducerActor");
30
26
  }
@@ -50,12 +46,14 @@ var ProducerActor = class _ProducerActor extends ActorV2 {
50
46
  _accountBalanceViewer;
51
47
  _blockRunner;
52
48
  _blockViewer;
49
+ _chainContractViewer;
53
50
  _chainId;
54
51
  _lastHeadChangeTime;
55
52
  _lastHeadHash;
56
53
  _mempoolRunner;
57
54
  _mempoolViewer;
58
55
  _produceBlockMutex = new Mutex();
56
+ _rewardAddress;
59
57
  _stakeTotalsViewer;
60
58
  get logger() {
61
59
  return assertEx(super.logger, () => "Logger is required for ProducerActor");
@@ -69,34 +67,24 @@ var ProducerActor = class _ProducerActor extends ActorV2 {
69
67
  get blockViewer() {
70
68
  return this._blockViewer;
71
69
  }
70
+ get chainContractViewer() {
71
+ return this._chainContractViewer;
72
+ }
72
73
  get chainId() {
73
74
  return this._chainId;
74
75
  }
76
+ get config() {
77
+ return this.params.config;
78
+ }
75
79
  get mempoolRunner() {
76
80
  return this._mempoolRunner;
77
81
  }
78
82
  get mempoolViewer() {
79
83
  return this._mempoolViewer;
80
84
  }
81
- get rewardAddress() {
82
- return this.params.rewardAddress;
83
- }
84
85
  get stakeTotalsViewer() {
85
86
  return this._stakeTotalsViewer;
86
87
  }
87
- static async paramsHandler(params) {
88
- const superParams = await super.paramsHandler(params);
89
- const { logger, account } = superParams;
90
- const rewardAddress = params.rewardAddress ?? account.address;
91
- logger?.info(`Using reward address ${rewardAddress}`);
92
- if (rewardAddress === account.address) {
93
- logger?.warn(`Using producer account address as reward address: ${account.address}`);
94
- }
95
- return {
96
- ...superParams,
97
- rewardAddress
98
- };
99
- }
100
88
  async createHandler() {
101
89
  await super.createHandler();
102
90
  this._metricAttributes = {
@@ -114,34 +102,38 @@ var ProducerActor = class _ProducerActor extends ActorV2 {
114
102
  this._producerActorBlocksPublished = this.meter?.createCounter("producer_actor_blocks_published", {
115
103
  description: "Number of blocks published"
116
104
  });
105
+ const final = await this.locator?.getInstance(FinalizationViewerMoniker);
106
+ await final.start();
117
107
  this._accountBalanceViewer = assertEx(await this.locator?.getInstance(AccountBalanceViewerMoniker), () => "Unable to locate AccountBalanceViewer");
118
108
  this._blockRunner = assertEx(await this.locator?.getInstance(BlockRunnerMoniker), () => "Unable to locate BlockRunner");
119
109
  this._blockViewer = assertEx(await this.locator?.getInstance(BlockViewerMoniker), () => "Unable to locate BlockViewer");
110
+ this._chainContractViewer = assertEx(await this.locator?.getInstance(ChainContractViewerMoniker), () => "Unable to locate ChainContractViewer");
120
111
  this._mempoolRunner = assertEx(await this.locator?.getInstance(MempoolRunnerMoniker), () => "Unable to locate MempoolRunner");
121
112
  this._mempoolViewer = assertEx(await this.locator?.getInstance(MempoolViewerMoniker), () => "Unable to locate MempoolViewer");
122
113
  this._stakeTotalsViewer = assertEx(await this.locator?.getInstance(StakeTotalsViewerMoniker), () => "Unable to locate StakeTotalsViewer");
114
+ this._chainId = await this.chainContractViewer.chainId();
123
115
  }
124
- async initLocator() {
125
- const config = this.config;
126
- const endpoint = assertEx(config.services.apiEndpoint, () => "API endpoint is required in config.services.apiEndpoint");
127
- const transportFactory = /* @__PURE__ */ __name((schemas) => new HttpRpcTransport(endpoint, schemas), "transportFactory");
128
- const locator = await buildJsonRpcProviderLocatorV2(config, transportFactory);
129
- const version = "1.0.0";
130
- const telemetryConfig = buildTelemetryConfig(config, this.name, version, DefaultMetricsScrapePorts.producer);
131
- const { traceProvider, meterProvider } = await startupSpanAsync("initTelemetry", () => initTelemetry(telemetryConfig));
132
- locator.context.traceProvider = traceProvider;
133
- locator.context.meterProvider = meterProvider;
134
- locator.register(SimpleBlockRewardViewer.factory(SimpleBlockRewardViewer.dependencies, {}));
135
- locator.register(SimpleBlockValidationViewer.factory(SimpleBlockValidationViewer.dependencies, {
136
- state: validateHydratedBlockState,
137
- protocol: validateHydratedBlock
138
- }));
139
- locator.register(SimpleBlockRunner.factory(SimpleBlockRunner.dependencies, {
140
- account: this.params.account,
141
- rewardAddress: this.params.rewardAddress
142
- }));
143
- return await initEvmProvidersIfAvailable(locator);
144
- }
116
+ // async initLocator() {
117
+ // const config = this.config
118
+ // const endpoint = assertEx(config.services.apiEndpoint, () => 'API endpoint is required in config.services.apiEndpoint')
119
+ // const transportFactory: TransportFactory = (schemas: RpcSchemaMap) => new HttpRpcTransport(endpoint, schemas)
120
+ // const locator = await buildJsonRpcProviderLocatorV2(config, transportFactory)
121
+ // const version = '1.0.0'
122
+ // const telemetryConfig = buildTelemetryConfig(config, this.name, version, DefaultMetricsScrapePorts.producer)
123
+ // const { traceProvider, meterProvider } = await startupSpanAsync('initTelemetry', () => initTelemetry(telemetryConfig))
124
+ // locator.context.traceProvider = traceProvider
125
+ // locator.context.meterProvider = meterProvider
126
+ // locator.register(SimpleBlockRewardViewer.factory<SimpleBlockRewardViewer>(SimpleBlockRewardViewer.dependencies, {}))
127
+ // locator.register(SimpleBlockValidationViewer.factory<SimpleBlockValidationViewer>(
128
+ // SimpleBlockValidationViewer.dependencies,
129
+ // { state: validateHydratedBlockState, protocol: validateHydratedBlock },
130
+ // ))
131
+ // locator.register(SimpleBlockRunner.factory<SimpleBlockRunner>(
132
+ // SimpleBlockRunner.dependencies,
133
+ // { account: this.params.account, rewardAddress: this.params.rewardAddress },
134
+ // ))
135
+ // return await initEvmProvidersIfAvailable(locator)
136
+ // }
145
137
  async startHandler() {
146
138
  await super.startHandler();
147
139
  this.registerTimer("BlockProductionTimer", async () => {
@@ -213,7 +205,7 @@ var ProducerActor = class _ProducerActor extends ActorV2 {
213
205
  }
214
206
  async redeclareIntent() {
215
207
  await this.spanAsync("redeclareIntent", async () => {
216
- if (this.config.producer.disableIntentRedeclaration) return;
208
+ if (this.config.actors.producer.disableIntentRedeclaration) return;
217
209
  const head = (await this.blockViewer.currentBlock())[0];
218
210
  if (isUndefined(head)) return;
219
211
  const currentBlock = head.block;
@@ -231,7 +223,7 @@ var ProducerActor = class _ProducerActor extends ActorV2 {
231
223
  return;
232
224
  }
233
225
  if (!await this.validateCurrentStake()) {
234
- this.logger?.error(`Add stake to contract address ${this.config.chain.id} for the producer to declare it's intent.`);
226
+ this.logger?.error(`Add stake to contract address ${this.chainId} for the producer to declare it's intent.`);
235
227
  return;
236
228
  }
237
229
  this.logger?.log("Creating redeclaration intent for producer:", this.account.address);
@@ -285,22 +277,18 @@ ProducerActor = _ts_decorate([
285
277
  ], ProducerActor);
286
278
 
287
279
  // src/runProducer.ts
288
- import { asAddress, exists, IdLogger } from "@xylabs/sdk-js";
280
+ import { exists } from "@xylabs/sdk-js";
289
281
  import { initProducerAccount } from "@xyo-network/chain-orchestration";
290
- var runProducer = /* @__PURE__ */ __name(async ({ config, logger = console, orchestrator }) => {
291
- const localLogger = logger ?? new IdLogger(logger ?? console, () => "ResolveHelper [runProducer]");
282
+ var runProducer = /* @__PURE__ */ __name(async (config, orchestrator, locator) => {
292
283
  const account = await initProducerAccount({
293
- config
284
+ config,
285
+ logger: locator.context.logger
294
286
  });
295
- localLogger.info(`Running producer for account ${account.address}`);
296
- const rewardAddress = asAddress(config.producer.rewardAddress, () => "rewardAddress is required in config.producer");
297
- localLogger.info(`Using reward address ${rewardAddress}`);
298
287
  const producer = await ProducerActor.create({
299
- account,
300
288
  config,
301
- logger,
302
- rewardAddress,
303
- name: "xl1-producer"
289
+ locator,
290
+ name: "xl1-producer",
291
+ account
304
292
  });
305
293
  const actors = [
306
294
  producer
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/ProducerActor.ts","../../src/runProducer.ts"],"sourcesContent":["import type { Attributes, Counter } from '@opentelemetry/api'\nimport type { Address, Logger } from '@xylabs/sdk-js'\nimport {\n assertEx, creatable, isDefined, isUndefined,\n toHex,\n} from '@xylabs/sdk-js'\nimport { buildTelemetryConfig, initEvmProvidersIfAvailable } from '@xyo-network/chain-orchestration'\nimport { SimpleBlockRunner } from '@xyo-network/chain-services'\nimport { initTelemetry } from '@xyo-network/chain-telemetry'\nimport { startupSpanAsync } from '@xyo-network/chain-utils'\nimport { validateHydratedBlock, validateHydratedBlockState } from '@xyo-network/chain-validation'\nimport type {\n ActorParamsV2,\n BlockBoundWitnessWithHashMeta, ChainId, ChainStakeIntent, HydratedBlockWithHashMeta, XL1BlockNumber,\n} from '@xyo-network/xl1-sdk'\nimport {\n AccountBalanceViewer, AccountBalanceViewerMoniker, ActorV2, asXL1BlockNumber, BlockRunner, BlockRunnerMoniker, BlockViewer, BlockViewerMoniker,\n buildJsonRpcProviderLocatorV2, buildTransaction, createDeclarationIntent, DefaultMetricsScrapePorts, HttpRpcTransport, MempoolRunner, MempoolRunnerMoniker,\n MempoolViewer, MempoolViewerMoniker, RpcSchemaMap, SimpleBlockRewardViewer, SimpleBlockValidationViewer, StakeTotalsViewer, StakeTotalsViewerMoniker,\n TransportFactory,\n} from '@xyo-network/xl1-sdk'\nimport { Mutex } from 'async-mutex'\n\nexport type ProducerActorParams = ActorParamsV2<{\n logger: Logger\n rewardAddress: Address\n}>\n\nconst SHOULD_REGISTER_REDECLARATION_INTENT_TIMER = true\nconst TEN_MINUTES = 10 * 60 * 1000 // 10 minutes in milliseconds\n\n/**\n * Formats a hydrated block with hash meta into a string representation of its hash and block number.\n * @param blockBoundWitness The hydrated block with hash meta to format\n * @returns The formatted block reference string\n */\nconst toFormattedBlockReference = (blockBoundWitness: BlockBoundWitnessWithHashMeta): string => {\n return `${blockBoundWitness.block} [${toHex(blockBoundWitness._hash, { prefix: true })}]`\n}\n\n@creatable()\nexport class ProducerActor extends ActorV2<ProducerActorParams> {\n /**\n * The interval time (in MS) between block production attempts.\n */\n static readonly BlockSubmissionCheckInterval = 1500 // 1.5 seconds\n\n /**\n * The threshold time (in MS) for resubmitting the same block number if the head has not changed.\n */\n static readonly HeadResubmissionThreshold = ProducerActor.BlockSubmissionCheckInterval * 30\n\n /**\n * The window (in blocks) before expiration to attempt redeclaration of producer intent.\n */\n static readonly RedeclarationWindow = 10_000\n\n protected _lastProducedBlock?: HydratedBlockWithHashMeta\n protected _lastRedeclarationIntent?: ChainStakeIntent\n protected _metricAttributes?: Attributes\n protected _producerActorBlockProductionAttempts?: Counter<Attributes>\n protected _producerActorBlockProductionChecks?: Counter<Attributes>\n protected _producerActorBlocksProduced?: Counter<Attributes>\n protected _producerActorBlocksPublished?: Counter<Attributes>\n\n private _accountBalanceViewer?: AccountBalanceViewer\n private _blockRunner?: BlockRunner\n private _blockViewer?: BlockViewer\n private _chainId?: ChainId\n private _lastHeadChangeTime?: number\n private _lastHeadHash?: string\n private _mempoolRunner?: MempoolRunner\n private _mempoolViewer?: MempoolViewer\n private _produceBlockMutex = new Mutex()\n private _stakeTotalsViewer?: StakeTotalsViewer\n\n override get logger() {\n return assertEx(super.logger, () => 'Logger is required for ProducerActor')\n }\n\n protected get accountBalanceViewer() {\n return this._accountBalanceViewer!\n }\n\n protected get blockRunner() {\n return this._blockRunner!\n }\n\n protected get blockViewer() {\n return this._blockViewer!\n }\n\n protected get chainId() {\n return this._chainId!\n }\n\n protected get mempoolRunner() {\n return this._mempoolRunner!\n }\n\n protected get mempoolViewer() {\n return this._mempoolViewer!\n }\n\n protected get rewardAddress() {\n return this.params.rewardAddress!\n }\n\n protected get stakeTotalsViewer() {\n return this._stakeTotalsViewer!\n }\n\n static override async paramsHandler<T extends ProducerActor>(params: Partial<T['params']>) {\n const superParams = await super.paramsHandler(params)\n const { logger, account } = superParams\n const rewardAddress = params.rewardAddress ?? account.address\n logger?.info(`Using reward address ${rewardAddress}`)\n if (rewardAddress === account.address) {\n logger?.warn(`Using producer account address as reward address: ${account.address}`)\n }\n\n return {\n ...superParams,\n rewardAddress,\n }\n }\n\n override async createHandler() {\n await super.createHandler()\n // Create the consistent meter attributes that will\n // be included with all metrics from this actor\n this._metricAttributes = { address: this.account.address.toString() }\n // Create the metrics\n this._producerActorBlockProductionChecks = this.meter?.createCounter(\n 'producer_actor_block_production_checks',\n { description: 'Number of block production checks' },\n )\n this._producerActorBlockProductionAttempts = this.meter?.createCounter(\n 'producer_actor_block_production_attempts',\n { description: 'Number of block production attempts' },\n )\n this._producerActorBlocksProduced = this.meter?.createCounter(\n 'producer_actor_blocks_produced',\n { description: 'Number of blocks produced' },\n )\n this._producerActorBlocksPublished = this.meter?.createCounter(\n 'producer_actor_blocks_published',\n { description: 'Number of blocks published' },\n )\n this._accountBalanceViewer = assertEx(\n await this.locator?.getInstance<AccountBalanceViewer>(AccountBalanceViewerMoniker),\n () => 'Unable to locate AccountBalanceViewer',\n )\n this._blockRunner = assertEx(\n await this.locator?.getInstance<BlockRunner>(BlockRunnerMoniker),\n () => 'Unable to locate BlockRunner',\n )\n this._blockViewer = assertEx(\n await this.locator?.getInstance<BlockViewer>(BlockViewerMoniker),\n () => 'Unable to locate BlockViewer',\n )\n this._mempoolRunner = assertEx(\n await this.locator?.getInstance<MempoolRunner>(MempoolRunnerMoniker),\n () => 'Unable to locate MempoolRunner',\n )\n this._mempoolViewer = assertEx(\n await this.locator?.getInstance<MempoolViewer>(MempoolViewerMoniker),\n () => 'Unable to locate MempoolViewer',\n )\n this._stakeTotalsViewer = assertEx(\n await this.locator?.getInstance<StakeTotalsViewer>(StakeTotalsViewerMoniker),\n () => 'Unable to locate StakeTotalsViewer',\n )\n }\n\n async initLocator() {\n const config = this.config\n const endpoint = assertEx(config.services.apiEndpoint, () => 'API endpoint is required in config.services.apiEndpoint')\n const transportFactory: TransportFactory = (schemas: RpcSchemaMap) => new HttpRpcTransport(endpoint, schemas)\n const locator = await buildJsonRpcProviderLocatorV2(config, transportFactory)\n\n const version = '1.0.0'\n const telemetryConfig = buildTelemetryConfig(config, this.name, version, DefaultMetricsScrapePorts.producer)\n const { traceProvider, meterProvider } = await startupSpanAsync('initTelemetry', () => initTelemetry(telemetryConfig))\n\n locator.context.traceProvider = traceProvider\n locator.context.meterProvider = meterProvider\n\n locator.register(SimpleBlockRewardViewer.factory<SimpleBlockRewardViewer>(SimpleBlockRewardViewer.dependencies, {}))\n locator.register(SimpleBlockValidationViewer.factory<SimpleBlockValidationViewer>(\n SimpleBlockValidationViewer.dependencies,\n { state: validateHydratedBlockState, protocol: validateHydratedBlock },\n ))\n locator.register(SimpleBlockRunner.factory<SimpleBlockRunner>(\n SimpleBlockRunner.dependencies,\n { account: this.params.account, rewardAddress: this.params.rewardAddress },\n ))\n return await initEvmProvidersIfAvailable(locator)\n }\n\n override async startHandler() {\n await super.startHandler()\n // Register a timer to check if we should produce a block\n this.registerTimer('BlockProductionTimer', async () => {\n await this.produceBlock()\n }, 2000, ProducerActor.BlockSubmissionCheckInterval)\n\n if (SHOULD_REGISTER_REDECLARATION_INTENT_TIMER) {\n // Register a timer to check if we should redeclare the producer\n this.registerTimer('ProducerRedeclarationTimer', async () => {\n await this.redeclareIntent()\n }, TEN_MINUTES, TEN_MINUTES)\n }\n }\n\n protected calculateBlocksUntilProducerDeclarationExpiration(currentBlock: number): number {\n return (this._lastRedeclarationIntent?.exp ?? currentBlock) - currentBlock\n }\n\n protected async produceBlock(): Promise<void> {\n this._producerActorBlockProductionChecks?.add(1, this._metricAttributes)\n await this.spanAsync('produceBlock', async () => {\n if (this._produceBlockMutex.isLocked()) {\n this.logger?.log('Skipping block production, previous production still in progress')\n return\n }\n\n // eslint-disable-next-line complexity\n await this._produceBlockMutex.runExclusive(async () => {\n // Get the updated head\n const head = (await this.blockViewer.currentBlock())[0]\n // Check if we've already produced the next block for this head\n const headHash = head._hash\n\n // Track head changes\n const currentTime = Date.now()\n if (this._lastHeadHash !== headHash) {\n // Log the head change\n const lastHeadHashHex = isDefined(this._lastHeadHash) ? `0x${this._lastHeadHash}` : 'undefined'\n const currentHeadHashHex = `0x${headHash}`\n this.logger?.log(`Found updated head ${lastHeadHashHex} -> ${currentHeadHashHex}`)\n\n // Update the head change info\n this._lastHeadHash = headHash\n this._lastHeadChangeTime = currentTime\n }\n\n // Check if we should resubmit due to stale head\n const timeSinceHeadChange = isDefined(this._lastHeadChangeTime) ? currentTime - this._lastHeadChangeTime : 0\n\n // If we have never produced a block or the last produced block was not built on the current head we\n // need to attempt to produce a new block\n const shouldSubmit = !this._lastProducedBlock || this._lastProducedBlock[0].previous !== headHash\n\n // If the head has not changed determine if we should resubmit again based on head staleness\n const shouldResubmit = timeSinceHeadChange > ProducerActor.HeadResubmissionThreshold\n\n // Determine if we should submit or resubmit\n const shouldSubmitBlock = shouldSubmit || shouldResubmit\n\n if (shouldSubmitBlock) {\n // If we are resubmitting due to stale head\n if (shouldResubmit) {\n // Log that we are resubmitting due to stale head\n this.logger?.log(`Resubmitting block due to stale head. Head ${toFormattedBlockReference(head)} unchanged for ${timeSinceHeadChange}ms`)\n // Reset timer since we're resubmitting\n this._lastHeadChangeTime = currentTime\n }\n this._producerActorBlockProductionAttempts?.add(1, this._metricAttributes)\n // Produce the next block\n const nextBlock = await this.blockRunner.next(head)\n // If it was produced\n if (nextBlock) {\n const displayBlockNumber = toFormattedBlockReference(nextBlock[0])\n this.logger?.log('Produced block:', displayBlockNumber)\n this._producerActorBlocksProduced?.add(1, this._metricAttributes)\n // Insert the block into the chain\n await this.mempoolRunner.submitBlocks([nextBlock])\n this.logger?.log('Published block:', displayBlockNumber)\n this._producerActorBlocksPublished?.add(1, this._metricAttributes)\n // Record that we have produced a block so we do not produce it again\n this._lastProducedBlock = nextBlock\n } else {\n this.logger?.log('No block produced for submission.')\n }\n } else {\n // Log that we are not submitting a block at this time\n let nonSubmissionMessage = 'No block submission required at this time'\n // If we have already produced a block\n if (isDefined(this._lastProducedBlock)) {\n // include that info in the log\n nonSubmissionMessage = nonSubmissionMessage + `, already produced: ${toFormattedBlockReference(this._lastProducedBlock[0])}`\n }\n this.logger?.log(`${nonSubmissionMessage}.`)\n }\n })\n }, { ...this.context, timeBudgetLimit: 1000 })\n }\n\n protected async redeclareIntent(): Promise<void> {\n await this.spanAsync('redeclareIntent', async () => {\n // Decide if we should redeclare intent\n if (this.config.producer.disableIntentRedeclaration) return\n\n // Get the current block\n const head = (await this.blockViewer.currentBlock())[0]\n if (isUndefined(head)) return\n const currentBlock = head.block\n\n // // Calculate the time until the producer's declaration expires\n const blocksUntilExpiration = this.calculateBlocksUntilProducerDeclarationExpiration(currentBlock)\n\n // Allow the producer time to redeclare itself via block production\n // (for free) before submitting a redeclaration intent transaction.\n if (blocksUntilExpiration > ProducerActor.RedeclarationWindow * 0.1) {\n // Clear any previous redeclaration intent\n this._lastRedeclarationIntent = undefined\n // No need to redeclare yet\n return\n }\n\n // If we already have a valid redeclaration intent, do not create another\n // unless it has expired.\n if (this._lastRedeclarationIntent) {\n // Check if the last redeclaration intent is still valid\n if (this._lastRedeclarationIntent.exp > currentBlock) return\n // If it has expired, clear the last redeclaration intent\n this._lastRedeclarationIntent = undefined\n }\n\n // Check if we have a valid balance before declaring intent\n if (!await this.validateCurrentBalance()) {\n this.logger?.error(\n `Add balance to address ${this.account.address} for the producer to declare it's intent.`,\n )\n return\n }\n\n // Check if we have a valid stake before declaring intent\n if (!(await this.validateCurrentStake())) {\n this.logger?.error(\n `Add stake to contract address ${this.config.chain.id}`\n + ' for the producer to declare it\\'s intent.',\n )\n return\n }\n\n // Create a redeclaration intent\n this.logger?.log('Creating redeclaration intent for producer:', this.account.address)\n const redeclarationIntent = createDeclarationIntent(\n this.account.address,\n 'producer',\n currentBlock,\n currentBlock + SimpleBlockRunner.RedeclarationDuration,\n )\n\n // Submit the redeclaration intent\n await this.submitRedeclarationIntent(currentBlock, redeclarationIntent)\n\n // On successful submission, save the redeclaration intent\n this._lastRedeclarationIntent = redeclarationIntent\n }, { ...this.context, timeBudgetLimit: 1000 })\n }\n\n protected async submitRedeclarationIntent(currentBlock: XL1BlockNumber, redeclarationIntent: ChainStakeIntent): Promise<void> {\n this.logger?.log('Submitting redeclaration intent for producer:', this.account.address)\n // Create a transaction to submit the redeclaration intent\n const tx = await buildTransaction(\n this.chainId,\n [redeclarationIntent],\n [],\n this.account,\n currentBlock,\n asXL1BlockNumber(currentBlock + 1000, true),\n )\n\n // Submit the redeclaration intent\n await this.mempoolRunner.submitTransactions([tx])\n\n this.logger?.log('Submitted redeclaration intent for producer:', this.account.address)\n }\n\n protected async validateCurrentBalance(): Promise<boolean> {\n // Check if we have a valid balance before declaring intent\n const head = (await this.blockViewer.currentBlock())?.[0]?._hash\n if (isDefined(head)) {\n const balances = await this.accountBalanceViewer.accountBalances([this.account.address], { head })\n const currentBalance = balances[this.account.address] ?? 0n\n if (currentBalance <= 0n) {\n this.logger?.error(`Producer ${this.account.address} has no balance.`)\n return false\n }\n return true\n }\n return true\n }\n\n protected async validateCurrentStake(): Promise<boolean> {\n // Use StakeIntentService to get the required minimum stake\n const requiredMinimumStake = 1n // this.stakeIntentService.getRequiredMinimumStakeForIntent('producer')\n // Check if we have a valid stake before declaring intent\n const currentStake = await this.stakeTotalsViewer.activeByStaked(this.account.address)\n if (currentStake < requiredMinimumStake) {\n this.logger?.error(`Producer ${this.account.address} has insufficient stake.`)\n return false\n }\n return true\n }\n}\n","import type { CreatableName } from '@xylabs/sdk-js'\nimport {\n asAddress, exists, IdLogger,\n} from '@xylabs/sdk-js'\nimport { initProducerAccount, type OrchestratorInstance } from '@xyo-network/chain-orchestration'\nimport { type BaseContext, type Config } from '@xyo-network/xl1-sdk'\n\nimport type { ProducerActorParams } from './ProducerActor.ts'\nimport { ProducerActor } from './ProducerActor.ts'\n\nexport interface RunProducerContext extends BaseContext {\n config: Config\n orchestrator: OrchestratorInstance\n}\n\nexport const runProducer = async ({\n config, logger = console, orchestrator,\n}: RunProducerContext) => {\n const localLogger = logger ?? new IdLogger(logger ?? console, () => 'ResolveHelper [runProducer]')\n const account = await initProducerAccount({ config })\n localLogger.info(`Running producer for account ${account.address}`)\n const rewardAddress = asAddress(config.producer.rewardAddress, () => 'rewardAddress is required in config.producer')\n localLogger.info(`Using reward address ${rewardAddress}`)\n\n // Create actors\n const producer = await ProducerActor.create({\n account, config, logger, rewardAddress, name: 'xl1-producer' as CreatableName,\n } satisfies ProducerActorParams)\n const actors = [producer].filter(exists)\n\n for (const actor of actors) {\n // Register the actor with the orchestrator\n await orchestrator.registerActor(actor)\n }\n // Start the orchestrator => automatically activates the actor\n await orchestrator.start()\n}\n"],"mappings":";;;;AAEA,SACEA,UAAUC,WAAWC,WAAWC,aAChCC,aACK;AACP,SAASC,sBAAsBC,mCAAmC;AAClE,SAASC,yBAAyB;AAClC,SAASC,qBAAqB;AAC9B,SAASC,wBAAwB;AACjC,SAASC,uBAAuBC,kCAAkC;AAKlE,SACwBC,6BAA6BC,SAASC,kBAA+BC,oBAAiCC,oBAC5HC,+BAA+BC,kBAAkBC,yBAAyBC,2BAA2BC,kBAAiCC,sBACvHC,sBAAoCC,yBAAyBC,6BAAgDC,gCAEvH;AACP,SAASC,aAAa;;;;;;;;AAOtB,IAAMC,6CAA6C;AACnD,IAAMC,cAAc,KAAK,KAAK;AAO9B,IAAMC,4BAA4B,wBAACC,sBAAAA;AACjC,SAAO,GAAGA,kBAAkBC,KAAK,KAAKC,MAAMF,kBAAkBG,OAAO;IAAEC,QAAQ;EAAK,CAAA,CAAA;AACtF,GAFkC;AAK3B,IAAMC,gBAAN,MAAMA,uBAAsBC,QAAAA;SAAAA;;;;;;EAIjC,OAAgBC,+BAA+B;;;;EAK/C,OAAgBC,4BAA4BH,eAAcE,+BAA+B;;;;EAKzF,OAAgBE,sBAAs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F,eAAe,MAAM,8CAAA;AACrEN,cAAYI,KAAK,wBAAwBE,aAAAA,EAAe;AAGxD,QAAME,WAAW,MAAMC,cAAcC,OAAO;IAC1CR;IAASN;IAAQC;IAAQS;IAAeK,MAAM;EAChD,CAAA;AACA,QAAMC,SAAS;IAACJ;IAAUK,OAAOC,MAAAA;AAEjC,aAAWC,SAASH,QAAQ;AAE1B,UAAMb,aAAaiB,cAAcD,KAAAA;EACnC;AAEA,QAAMhB,aAAakB,MAAK;AAC1B,GArB2B;","names":["assertEx","creatable","isDefined","isUndefined","toHex","buildTelemetryConfig","initEvmProvidersIfAvailable","SimpleBlockRunner","initTelemetry","startupSpanAsync","validateHydratedBlock","validateHydratedBlockState","AccountBalanceViewerMoniker","ActorV2","asXL1BlockNumber","BlockRunnerMoniker","BlockViewerMoniker","buildJsonRpcProviderLocatorV2","buildTransaction","createDeclarationIntent","DefaultMetricsScrapePorts","HttpRpcTransport","MempoolRunnerMoniker","MempoolViewerMoniker","SimpleBlockRewardViewer","SimpleBlockValidationViewer","StakeTotalsViewerMoniker","Mutex","SHOULD_REGISTER_REDECLARATION_INTENT_TIMER","TEN_MINUTES","toFormattedBlockReference","blockBoundWitness","block","toHex","_hash","prefix","ProducerActor","ActorV2","BlockSubmissionCheckInterval","HeadResubmissionThreshold","RedeclarationWindow","_lastProducedBlock","_lastRedeclarationIntent","_metricAttributes","_producerActorBlockProductionAttempts","_producerActorBlockProductionChecks","_producerActorBlocksProduced","_producerActorBlocksPublished","_accountBalanceViewer","_blockRunner","_blockViewer","_chainId","_lastHeadChangeTime","_lastHeadHash","_mempoolRunner","_mempoolViewer","_produceBlockMutex","Mutex","_stakeTotalsViewer","logger","assertEx","accountBalanceViewer","blockRunner","blockViewer","chainId","mempoolRunner","mempoolViewer","rewardAddress","params","stakeTotalsViewer","paramsHandler","superParams","account","address","info","warn","createHandler","toString","meter","createCounter","description","locator","getInstance","AccountBalanceViewerMoniker","BlockRunnerMoniker","BlockViewerMoniker","MempoolRunnerMoniker","MempoolViewerMoniker","StakeTotalsViewerMoniker","initLocator","config","endpoint","services","apiEndpoint","transportFactory","schemas","HttpRpcTransport","buildJsonRpcProviderLocatorV2","version","telemetryConfig","buildTelemetryConfig","name","DefaultMetricsScrapePorts","producer","traceProvider","meterProvider","startupSpanAsync","initTelemetry","context","register","SimpleBlockRewardViewer","factory","dependencies","SimpleBlockValidationViewer","state","validateHydratedBlockState","protocol","validateHydratedBlock","SimpleBlockRunner","initEvmProvidersIfAvailable","startHandler","registerTimer","produceBlock","redeclareIntent","calculateBlocksUntilProducerDeclarationExpiration","currentBlock","exp","add","spanAsync","isLocked","log","runExclusive","head","headHash","currentTime","Date","now","lastHeadHashHex","isDefined","currentHeadHashHex","timeSinceHeadChange","shouldSubmit","previous","shouldResubmit","shouldSubmitBlock","nextBlock","next","displayBlockNumber","submitBlocks","nonSubmissionMessage","timeBudgetLimit","disableIntentRedeclaration","isUndefined","blocksUntilExpiration","undefined","validateCurrentBalance","error","validateCurrentStake","chain","id","redeclarationIntent","createDeclarationIntent","RedeclarationDuration","submitRedeclarationIntent","tx","buildTransaction","asXL1BlockNumber","submitTransactions","balances","accountBalances","currentBalance","requiredMinimumStake","currentStake","activeByStaked","asAddress","exists","IdLogger","initProducerAccount","runProducer","config","logger","console","orchestrator","localLogger","IdLogger","account","initProducerAccount","info","address","rewardAddress","asAddress","producer","ProducerActor","create","name","actors","filter","exists","actor","registerActor","start"]}
1
+ {"version":3,"sources":["../../src/ProducerActor.ts","../../src/runProducer.ts"],"sourcesContent":["import type { Attributes, Counter } from '@opentelemetry/api'\nimport {\n Address,\n assertEx, creatable, isDefined, isUndefined,\n toHex,\n} from '@xylabs/sdk-js'\nimport { SimpleBlockRunner } from '@xyo-network/chain-services'\nimport type {\n ActorParamsV3,\n BlockBoundWitnessWithHashMeta, ChainContractViewer, ChainId, ChainStakeIntent, Config, HydratedBlockWithHashMeta, XL1BlockNumber,\n} from '@xyo-network/xl1-sdk'\nimport {\n AccountBalanceViewer, AccountBalanceViewerMoniker, ActorV3, asXL1BlockNumber, BlockRunner, BlockRunnerMoniker, BlockViewer, BlockViewerMoniker,\n buildTransaction, ChainContractViewerMoniker, createDeclarationIntent, FinalizationViewer, FinalizationViewerMoniker, MempoolRunner, MempoolRunnerMoniker,\n MempoolViewer, MempoolViewerMoniker, StakeTotalsViewer, StakeTotalsViewerMoniker,\n} from '@xyo-network/xl1-sdk'\nimport { Mutex } from 'async-mutex'\n\nexport type ProducerActorParams = ActorParamsV3<{\n config: Config\n}>\n\nconst SHOULD_REGISTER_REDECLARATION_INTENT_TIMER = true\nconst TEN_MINUTES = 10 * 60 * 1000 // 10 minutes in milliseconds\n\n/**\n * Formats a hydrated block with hash meta into a string representation of its hash and block number.\n * @param blockBoundWitness The hydrated block with hash meta to format\n * @returns The formatted block reference string\n */\nconst toFormattedBlockReference = (blockBoundWitness: BlockBoundWitnessWithHashMeta): string => {\n return `${blockBoundWitness.block} [${toHex(blockBoundWitness._hash, { prefix: true })}]`\n}\n\n@creatable()\nexport class ProducerActor extends ActorV3<ProducerActorParams> {\n /**\n * The interval time (in MS) between block production attempts.\n */\n static readonly BlockSubmissionCheckInterval = 1500 // 1.5 seconds\n\n /**\n * The threshold time (in MS) for resubmitting the same block number if the head has not changed.\n */\n static readonly HeadResubmissionThreshold = ProducerActor.BlockSubmissionCheckInterval * 30\n\n /**\n * The window (in blocks) before expiration to attempt redeclaration of producer intent.\n */\n static readonly RedeclarationWindow = 10_000\n\n protected _lastProducedBlock?: HydratedBlockWithHashMeta\n protected _lastRedeclarationIntent?: ChainStakeIntent\n protected _metricAttributes?: Attributes\n protected _producerActorBlockProductionAttempts?: Counter<Attributes>\n protected _producerActorBlockProductionChecks?: Counter<Attributes>\n protected _producerActorBlocksProduced?: Counter<Attributes>\n protected _producerActorBlocksPublished?: Counter<Attributes>\n\n private _accountBalanceViewer?: AccountBalanceViewer\n private _blockRunner?: BlockRunner\n private _blockViewer?: BlockViewer\n private _chainContractViewer?: ChainContractViewer\n private _chainId?: ChainId\n private _lastHeadChangeTime?: number\n private _lastHeadHash?: string\n private _mempoolRunner?: MempoolRunner\n private _mempoolViewer?: MempoolViewer\n private _produceBlockMutex = new Mutex()\n private _rewardAddress!: Address\n private _stakeTotalsViewer?: StakeTotalsViewer\n\n override get logger() {\n return assertEx(super.logger, () => 'Logger is required for ProducerActor')\n }\n\n protected get accountBalanceViewer() {\n return this._accountBalanceViewer!\n }\n\n protected get blockRunner() {\n return this._blockRunner!\n }\n\n protected get blockViewer() {\n return this._blockViewer!\n }\n\n protected get chainContractViewer() {\n return this._chainContractViewer!\n }\n\n protected get chainId() {\n return this._chainId!\n }\n\n protected get config() {\n return this.params.config\n }\n\n protected get mempoolRunner() {\n return this._mempoolRunner!\n }\n\n protected get mempoolViewer() {\n return this._mempoolViewer!\n }\n\n protected get stakeTotalsViewer() {\n return this._stakeTotalsViewer!\n }\n\n override async createHandler() {\n await super.createHandler()\n // Create the consistent meter attributes that will\n // be included with all metrics from this actor\n this._metricAttributes = { address: this.account.address.toString() }\n // Create the metrics\n this._producerActorBlockProductionChecks = this.meter?.createCounter(\n 'producer_actor_block_production_checks',\n { description: 'Number of block production checks' },\n )\n this._producerActorBlockProductionAttempts = this.meter?.createCounter(\n 'producer_actor_block_production_attempts',\n { description: 'Number of block production attempts' },\n )\n this._producerActorBlocksProduced = this.meter?.createCounter(\n 'producer_actor_blocks_produced',\n { description: 'Number of blocks produced' },\n )\n this._producerActorBlocksPublished = this.meter?.createCounter(\n 'producer_actor_blocks_published',\n { description: 'Number of blocks published' },\n )\n const final = await this.locator?.getInstance<FinalizationViewer>(FinalizationViewerMoniker)\n await final.start()\n this._accountBalanceViewer = assertEx(\n await this.locator?.getInstance<AccountBalanceViewer>(AccountBalanceViewerMoniker),\n () => 'Unable to locate AccountBalanceViewer',\n )\n this._blockRunner = assertEx(\n await this.locator?.getInstance<BlockRunner>(BlockRunnerMoniker),\n () => 'Unable to locate BlockRunner',\n )\n this._blockViewer = assertEx(\n await this.locator?.getInstance<BlockViewer>(BlockViewerMoniker),\n () => 'Unable to locate BlockViewer',\n )\n this._chainContractViewer = assertEx(\n await this.locator?.getInstance<ChainContractViewer>(ChainContractViewerMoniker),\n () => 'Unable to locate ChainContractViewer',\n )\n this._mempoolRunner = assertEx(\n await this.locator?.getInstance<MempoolRunner>(MempoolRunnerMoniker),\n () => 'Unable to locate MempoolRunner',\n )\n this._mempoolViewer = assertEx(\n await this.locator?.getInstance<MempoolViewer>(MempoolViewerMoniker),\n () => 'Unable to locate MempoolViewer',\n )\n this._stakeTotalsViewer = assertEx(\n await this.locator?.getInstance<StakeTotalsViewer>(StakeTotalsViewerMoniker),\n () => 'Unable to locate StakeTotalsViewer',\n )\n this._chainId = await this.chainContractViewer.chainId()\n }\n\n // async initLocator() {\n // const config = this.config\n // const endpoint = assertEx(config.services.apiEndpoint, () => 'API endpoint is required in config.services.apiEndpoint')\n // const transportFactory: TransportFactory = (schemas: RpcSchemaMap) => new HttpRpcTransport(endpoint, schemas)\n // const locator = await buildJsonRpcProviderLocatorV2(config, transportFactory)\n\n // const version = '1.0.0'\n // const telemetryConfig = buildTelemetryConfig(config, this.name, version, DefaultMetricsScrapePorts.producer)\n // const { traceProvider, meterProvider } = await startupSpanAsync('initTelemetry', () => initTelemetry(telemetryConfig))\n\n // locator.context.traceProvider = traceProvider\n // locator.context.meterProvider = meterProvider\n\n // locator.register(SimpleBlockRewardViewer.factory<SimpleBlockRewardViewer>(SimpleBlockRewardViewer.dependencies, {}))\n // locator.register(SimpleBlockValidationViewer.factory<SimpleBlockValidationViewer>(\n // SimpleBlockValidationViewer.dependencies,\n // { state: validateHydratedBlockState, protocol: validateHydratedBlock },\n // ))\n // locator.register(SimpleBlockRunner.factory<SimpleBlockRunner>(\n // SimpleBlockRunner.dependencies,\n // { account: this.params.account, rewardAddress: this.params.rewardAddress },\n // ))\n // return await initEvmProvidersIfAvailable(locator)\n // }\n\n override async startHandler() {\n await super.startHandler()\n // Register a timer to check if we should produce a block\n this.registerTimer('BlockProductionTimer', async () => {\n await this.produceBlock()\n }, 2000, ProducerActor.BlockSubmissionCheckInterval)\n\n if (SHOULD_REGISTER_REDECLARATION_INTENT_TIMER) {\n // Register a timer to check if we should redeclare the producer\n this.registerTimer('ProducerRedeclarationTimer', async () => {\n await this.redeclareIntent()\n }, TEN_MINUTES, TEN_MINUTES)\n }\n }\n\n protected calculateBlocksUntilProducerDeclarationExpiration(currentBlock: number): number {\n return (this._lastRedeclarationIntent?.exp ?? currentBlock) - currentBlock\n }\n\n protected async produceBlock(): Promise<void> {\n this._producerActorBlockProductionChecks?.add(1, this._metricAttributes)\n await this.spanAsync('produceBlock', async () => {\n if (this._produceBlockMutex.isLocked()) {\n this.logger?.log('Skipping block production, previous production still in progress')\n return\n }\n\n // eslint-disable-next-line complexity\n await this._produceBlockMutex.runExclusive(async () => {\n // Get the updated head\n const head = (await this.blockViewer.currentBlock())[0]\n // Check if we've already produced the next block for this head\n const headHash = head._hash\n\n // Track head changes\n const currentTime = Date.now()\n if (this._lastHeadHash !== headHash) {\n // Log the head change\n const lastHeadHashHex = isDefined(this._lastHeadHash) ? `0x${this._lastHeadHash}` : 'undefined'\n const currentHeadHashHex = `0x${headHash}`\n this.logger?.log(`Found updated head ${lastHeadHashHex} -> ${currentHeadHashHex}`)\n\n // Update the head change info\n this._lastHeadHash = headHash\n this._lastHeadChangeTime = currentTime\n }\n\n // Check if we should resubmit due to stale head\n const timeSinceHeadChange = isDefined(this._lastHeadChangeTime) ? currentTime - this._lastHeadChangeTime : 0\n\n // If we have never produced a block or the last produced block was not built on the current head we\n // need to attempt to produce a new block\n const shouldSubmit = !this._lastProducedBlock || this._lastProducedBlock[0].previous !== headHash\n\n // If the head has not changed determine if we should resubmit again based on head staleness\n const shouldResubmit = timeSinceHeadChange > ProducerActor.HeadResubmissionThreshold\n\n // Determine if we should submit or resubmit\n const shouldSubmitBlock = shouldSubmit || shouldResubmit\n\n if (shouldSubmitBlock) {\n // If we are resubmitting due to stale head\n if (shouldResubmit) {\n // Log that we are resubmitting due to stale head\n this.logger?.log(`Resubmitting block due to stale head. Head ${toFormattedBlockReference(head)} unchanged for ${timeSinceHeadChange}ms`)\n // Reset timer since we're resubmitting\n this._lastHeadChangeTime = currentTime\n }\n this._producerActorBlockProductionAttempts?.add(1, this._metricAttributes)\n // Produce the next block\n const nextBlock = await this.blockRunner.next(head)\n // If it was produced\n if (nextBlock) {\n const displayBlockNumber = toFormattedBlockReference(nextBlock[0])\n this.logger?.log('Produced block:', displayBlockNumber)\n this._producerActorBlocksProduced?.add(1, this._metricAttributes)\n // Insert the block into the chain\n await this.mempoolRunner.submitBlocks([nextBlock])\n this.logger?.log('Published block:', displayBlockNumber)\n this._producerActorBlocksPublished?.add(1, this._metricAttributes)\n // Record that we have produced a block so we do not produce it again\n this._lastProducedBlock = nextBlock\n } else {\n this.logger?.log('No block produced for submission.')\n }\n } else {\n // Log that we are not submitting a block at this time\n let nonSubmissionMessage = 'No block submission required at this time'\n // If we have already produced a block\n if (isDefined(this._lastProducedBlock)) {\n // include that info in the log\n nonSubmissionMessage = nonSubmissionMessage + `, already produced: ${toFormattedBlockReference(this._lastProducedBlock[0])}`\n }\n this.logger?.log(`${nonSubmissionMessage}.`)\n }\n })\n }, { ...this.context, timeBudgetLimit: 1000 })\n }\n\n protected async redeclareIntent(): Promise<void> {\n await this.spanAsync('redeclareIntent', async () => {\n // Decide if we should redeclare intent\n if (this.config.actors.producer.disableIntentRedeclaration) return\n\n // Get the current block\n const head = (await this.blockViewer.currentBlock())[0]\n if (isUndefined(head)) return\n const currentBlock = head.block\n\n // // Calculate the time until the producer's declaration expires\n const blocksUntilExpiration = this.calculateBlocksUntilProducerDeclarationExpiration(currentBlock)\n\n // Allow the producer time to redeclare itself via block production\n // (for free) before submitting a redeclaration intent transaction.\n if (blocksUntilExpiration > ProducerActor.RedeclarationWindow * 0.1) {\n // Clear any previous redeclaration intent\n this._lastRedeclarationIntent = undefined\n // No need to redeclare yet\n return\n }\n\n // If we already have a valid redeclaration intent, do not create another\n // unless it has expired.\n if (this._lastRedeclarationIntent) {\n // Check if the last redeclaration intent is still valid\n if (this._lastRedeclarationIntent.exp > currentBlock) return\n // If it has expired, clear the last redeclaration intent\n this._lastRedeclarationIntent = undefined\n }\n\n // Check if we have a valid balance before declaring intent\n if (!await this.validateCurrentBalance()) {\n this.logger?.error(\n `Add balance to address ${this.account.address} for the producer to declare it's intent.`,\n )\n return\n }\n\n // Check if we have a valid stake before declaring intent\n if (!(await this.validateCurrentStake())) {\n this.logger?.error(\n `Add stake to contract address ${this.chainId}`\n + ' for the producer to declare it\\'s intent.',\n )\n return\n }\n\n // Create a redeclaration intent\n this.logger?.log('Creating redeclaration intent for producer:', this.account.address)\n const redeclarationIntent = createDeclarationIntent(\n this.account.address,\n 'producer',\n currentBlock,\n currentBlock + SimpleBlockRunner.RedeclarationDuration,\n )\n\n // Submit the redeclaration intent\n await this.submitRedeclarationIntent(currentBlock, redeclarationIntent)\n\n // On successful submission, save the redeclaration intent\n this._lastRedeclarationIntent = redeclarationIntent\n }, { ...this.context, timeBudgetLimit: 1000 })\n }\n\n protected async submitRedeclarationIntent(currentBlock: XL1BlockNumber, redeclarationIntent: ChainStakeIntent): Promise<void> {\n this.logger?.log('Submitting redeclaration intent for producer:', this.account.address)\n // Create a transaction to submit the redeclaration intent\n const tx = await buildTransaction(\n this.chainId,\n [redeclarationIntent],\n [],\n this.account,\n currentBlock,\n asXL1BlockNumber(currentBlock + 1000, true),\n )\n\n // Submit the redeclaration intent\n await this.mempoolRunner.submitTransactions([tx])\n\n this.logger?.log('Submitted redeclaration intent for producer:', this.account.address)\n }\n\n protected async validateCurrentBalance(): Promise<boolean> {\n // Check if we have a valid balance before declaring intent\n const head = (await this.blockViewer.currentBlock())?.[0]?._hash\n if (isDefined(head)) {\n const balances = await this.accountBalanceViewer.accountBalances([this.account.address], { head })\n const currentBalance = balances[this.account.address] ?? 0n\n if (currentBalance <= 0n) {\n this.logger?.error(`Producer ${this.account.address} has no balance.`)\n return false\n }\n return true\n }\n return true\n }\n\n protected async validateCurrentStake(): Promise<boolean> {\n // Use StakeIntentService to get the required minimum stake\n const requiredMinimumStake = 1n // this.stakeIntentService.getRequiredMinimumStakeForIntent('producer')\n // Check if we have a valid stake before declaring intent\n const currentStake = await this.stakeTotalsViewer.activeByStaked(this.account.address)\n if (currentStake < requiredMinimumStake) {\n this.logger?.error(`Producer ${this.account.address} has insufficient stake.`)\n return false\n }\n return true\n }\n}\n","import type { CreatableName } from '@xylabs/sdk-js'\nimport { exists } from '@xylabs/sdk-js'\nimport { initProducerAccount, type OrchestratorInstance } from '@xyo-network/chain-orchestration'\nimport type {\n Config,\n ProviderFactoryLocatorInstance,\n} from '@xyo-network/xl1-sdk'\n\nimport type { ProducerActorParams } from './ProducerActor.ts'\nimport { ProducerActor } from './ProducerActor.ts'\n\nexport const runProducer = async (\n config: Config,\n orchestrator: OrchestratorInstance,\n locator: ProviderFactoryLocatorInstance,\n) => {\n const account = await initProducerAccount({ config, logger: locator.context.logger })\n // Create actors\n const producer = await ProducerActor.create({\n config, locator, name: 'xl1-producer' as CreatableName, account,\n } satisfies ProducerActorParams)\n const actors = [producer].filter(exists)\n\n for (const actor of actors) {\n // Register the actor with the orchestrator\n await orchestrator.registerActor(actor)\n }\n // Start the orchestrator => automatically activates the actor\n await orchestrator.start()\n}\n"],"mappings":";;;;AACA,SAEEA,UAAUC,WAAWC,WAAWC,aAChCC,aACK;AACP,SAASC,yBAAyB;AAKlC,SACwBC,6BAA6BC,SAASC,kBAA+BC,oBAAiCC,oBAC5HC,kBAAkBC,4BAA4BC,yBAA6CC,2BAA0CC,sBACtHC,sBAAyCC,gCACnD;AACP,SAASC,aAAa;;;;;;;;AAMtB,IAAMC,6CAA6C;AACnD,IAAMC,cAAc,KAAK,KAAK;AAO9B,IAAMC,4BAA4B,wBAACC,sBAAAA;AACjC,SAAO,GAAGA,kBAAkBC,KAAK,KAAKC,MAAMF,kBAAkBG,OAAO;I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AK1E,kBAAkB2E,eAAe,KAAKxE,QAAQD,OAAO;AACrF,QAAIwE,eAAeD,sBAAsB;AACvC,WAAKpF,QAAQsE,MAAM,YAAY,KAAKxD,QAAQD,OAAO,0BAA0B;AAC7E,aAAO;IACT;AACA,WAAO;EACT;AACF;;;;;;AC/YA,SAAS0E,cAAc;AACvB,SAASC,2BAAsD;AASxD,IAAMC,cAAc,8BACzBC,QACAC,cACAC,YAAAA;AAEA,QAAMC,UAAU,MAAMC,oBAAoB;IAAEJ;IAAQK,QAAQH,QAAQI,QAAQD;EAAO,CAAA;AAEnF,QAAME,WAAW,MAAMC,cAAcC,OAAO;IAC1CT;IAAQE;IAASQ,MAAM;IAAiCP;EAC1D,CAAA;AACA,QAAMQ,SAAS;IAACJ;IAAUK,OAAOC,MAAAA;AAEjC,aAAWC,SAASH,QAAQ;AAE1B,UAAMV,aAAac,cAAcD,KAAAA;EACnC;AAEA,QAAMb,aAAae,MAAK;AAC1B,GAlB2B;","names":["assertEx","creatable","isDefined","isUndefined","toHex","SimpleBlockRunner","AccountBalanceViewerMoniker","ActorV3","asXL1BlockNumber","BlockRunnerMoniker","BlockViewerMoniker","buildTransaction","ChainContractViewerMoniker","createDeclarationIntent","FinalizationViewerMoniker","MempoolRunnerMoniker","MempoolViewerMoniker","StakeTotalsViewerMoniker","Mutex","SHOULD_REGISTER_REDECLARATION_INTENT_TIMER","TEN_MINUTES","toFormattedBlockReference","blockBoundWitness","block","toHex","_hash","prefix","ProducerActor","ActorV3","BlockSubmissionCheckInterval","HeadResubmissionThreshold","RedeclarationWindow","_lastProducedBlock","_lastRedeclarationIntent","_metricAttributes","_producerActorBlockProductionAttempts","_producerActorBlockProductionChecks","_producerActorBlocksProduced","_producerActorBlocksPublished","_accountBalanceViewer","_blockRunner","_blockViewer","_chainContractViewer","_chainId","_lastHeadChangeTime","_lastHeadHash","_mempoolRunner","_mempoolViewer","_produceBlockMutex","Mutex","_rewardAddress","_stakeTotalsViewer","logger","assertEx","accountBalanceViewer","blockRunner","blockViewer","chainContractViewer","chainId","config","params","mempoolRunner","mempoolViewer","stakeTotalsViewer","createHandler","address","account","toString","meter","createCounter","description","final","locator","getInstance","FinalizationViewerMoniker","start","AccountBalanceViewerMoniker","BlockRunnerMoniker","BlockViewerMoniker","ChainContractViewerMoniker","MempoolRunnerMoniker","MempoolViewerMoniker","StakeTotalsViewerMoniker","startHandler","registerTimer","produceBlock","redeclareIntent","calculateBlocksUntilProducerDeclarationExpiration","currentBlock","exp","add","spanAsync","isLocked","log","runExclusive","head","headHash","currentTime","Date","now","lastHeadHashHex","isDefined","currentHeadHashHex","timeSinceHeadChange","shouldSubmit","previous","shouldResubmit","shouldSubmitBlock","nextBlock","next","displayBlockNumber","submitBlocks","nonSubmissionMessage","context","timeBudgetLimit","actors","producer","disableIntentRedeclaration","isUndefined","blocksUntilExpiration","undefined","validateCurrentBalance","error","validateCurrentStake","redeclarationIntent","createDeclarationIntent","SimpleBlockRunner","RedeclarationDuration","submitRedeclarationIntent","tx","buildTransaction","asXL1BlockNumber","submitTransactions","balances","accountBalances","currentBalance","requiredMinimumStake","currentStake","activeByStaked","exists","initProducerAccount","runProducer","config","orchestrator","locator","account","initProducerAccount","logger","context","producer","ProducerActor","create","name","actors","filter","exists","actor","registerActor","start"]}
@@ -1,8 +1,4 @@
1
1
  import { type OrchestratorInstance } from '@xyo-network/chain-orchestration';
2
- import { type BaseContext, type Config } from '@xyo-network/xl1-sdk';
3
- export interface RunProducerContext extends BaseContext {
4
- config: Config;
5
- orchestrator: OrchestratorInstance;
6
- }
7
- export declare const runProducer: ({ config, logger, orchestrator, }: RunProducerContext) => Promise<void>;
2
+ import type { Config, ProviderFactoryLocatorInstance } from '@xyo-network/xl1-sdk';
3
+ export declare const runProducer: (config: Config, orchestrator: OrchestratorInstance, locator: ProviderFactoryLocatorInstance) => Promise<void>;
8
4
  //# sourceMappingURL=runProducer.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"runProducer.d.ts","sourceRoot":"","sources":["../../src/runProducer.ts"],"names":[],"mappings":"AAIA,OAAO,EAAuB,KAAK,oBAAoB,EAAE,MAAM,kCAAkC,CAAA;AACjG,OAAO,EAAE,KAAK,WAAW,EAAE,KAAK,MAAM,EAAE,MAAM,sBAAsB,CAAA;AAKpE,MAAM,WAAW,kBAAmB,SAAQ,WAAW;IACrD,MAAM,EAAE,MAAM,CAAA;IACd,YAAY,EAAE,oBAAoB,CAAA;CACnC;AAED,eAAO,MAAM,WAAW,GAAU,mCAE/B,kBAAkB,kBAmBpB,CAAA"}
1
+ {"version":3,"file":"runProducer.d.ts","sourceRoot":"","sources":["../../src/runProducer.ts"],"names":[],"mappings":"AAEA,OAAO,EAAuB,KAAK,oBAAoB,EAAE,MAAM,kCAAkC,CAAA;AACjG,OAAO,KAAK,EACV,MAAM,EACN,8BAA8B,EAC/B,MAAM,sBAAsB,CAAA;AAK7B,eAAO,MAAM,WAAW,GACtB,QAAQ,MAAM,EACd,cAAc,oBAAoB,EAClC,SAAS,8BAA8B,kBAexC,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xyo-network/chain-producer",
3
- "version": "1.19.7",
3
+ "version": "1.19.8",
4
4
  "description": "XYO Layer One Producer",
5
5
  "homepage": "https://xylabs.com",
6
6
  "bugs": {
@@ -49,13 +49,13 @@
49
49
  "types": "tsc --noEmit -p tsconfig.test.json"
50
50
  },
51
51
  "dependencies": {
52
- "@xylabs/sdk-js": "~5.0.65",
53
- "@xyo-network/chain-orchestration": "~1.19.7",
54
- "@xyo-network/chain-services": "~1.19.7",
55
- "@xyo-network/chain-telemetry": "~1.19.7",
56
- "@xyo-network/chain-utils": "~1.19.7",
57
- "@xyo-network/chain-validation": "~1.19.7",
58
- "@xyo-network/xl1-sdk": "~1.22.30",
52
+ "@xylabs/sdk-js": "~5.0.78",
53
+ "@xyo-network/chain-orchestration": "~1.19.8",
54
+ "@xyo-network/chain-services": "~1.19.8",
55
+ "@xyo-network/chain-telemetry": "~1.19.8",
56
+ "@xyo-network/chain-utils": "~1.19.8",
57
+ "@xyo-network/chain-validation": "~1.19.8",
58
+ "@xyo-network/xl1-sdk": "~1.23.6",
59
59
  "async-mutex": "~0.5.0"
60
60
  },
61
61
  "devDependencies": {
@@ -64,8 +64,8 @@
64
64
  "@types/cors": "~2.8.19",
65
65
  "@types/express": "5.0.6",
66
66
  "@types/express-serve-static-core": "~5.1.1",
67
- "@types/node": "~25.2.1",
68
- "@xylabs/sdk-js": "~5.0.65",
67
+ "@types/node": "~25.2.3",
68
+ "@xylabs/sdk-js": "~5.0.78",
69
69
  "@xylabs/ts-scripts-yarn3": "~7.3.2",
70
70
  "@xylabs/tsconfig": "~7.3.2",
71
71
  "@xyo-network/account": "~5.3.2",
@@ -73,12 +73,12 @@
73
73
  "@xyo-network/archivist-abstract": "~5.3.2",
74
74
  "@xyo-network/bios-model": "~7.2.1",
75
75
  "@xyo-network/boundwitness-builder": "~5.3.2",
76
- "@xyo-network/chain-services": "~1.19.7",
77
- "@xyo-network/chain-validation": "~1.19.7",
76
+ "@xyo-network/chain-services": "~1.19.8",
77
+ "@xyo-network/chain-validation": "~1.19.8",
78
78
  "@xyo-network/module-abstract-mongodb": "~5.3.2",
79
79
  "@xyo-network/module-model-mongodb": "~5.3.2",
80
80
  "@xyo-network/node-memory": "~5.3.2",
81
- "@xyo-network/xl1-sdk": "~1.22.30",
81
+ "@xyo-network/xl1-sdk": "~1.23.6",
82
82
  "dotenv": "~17.2.4",
83
83
  "eslint": "^9.39.2",
84
84
  "nodemon": "~3.1.11",
@@ -1,29 +1,23 @@
1
1
  import type { Attributes, Counter } from '@opentelemetry/api'
2
- import type { Address, Logger } from '@xylabs/sdk-js'
3
2
  import {
3
+ Address,
4
4
  assertEx, creatable, isDefined, isUndefined,
5
5
  toHex,
6
6
  } from '@xylabs/sdk-js'
7
- import { buildTelemetryConfig, initEvmProvidersIfAvailable } from '@xyo-network/chain-orchestration'
8
7
  import { SimpleBlockRunner } from '@xyo-network/chain-services'
9
- import { initTelemetry } from '@xyo-network/chain-telemetry'
10
- import { startupSpanAsync } from '@xyo-network/chain-utils'
11
- import { validateHydratedBlock, validateHydratedBlockState } from '@xyo-network/chain-validation'
12
8
  import type {
13
- ActorParamsV2,
14
- BlockBoundWitnessWithHashMeta, ChainId, ChainStakeIntent, HydratedBlockWithHashMeta, XL1BlockNumber,
9
+ ActorParamsV3,
10
+ BlockBoundWitnessWithHashMeta, ChainContractViewer, ChainId, ChainStakeIntent, Config, HydratedBlockWithHashMeta, XL1BlockNumber,
15
11
  } from '@xyo-network/xl1-sdk'
16
12
  import {
17
- AccountBalanceViewer, AccountBalanceViewerMoniker, ActorV2, asXL1BlockNumber, BlockRunner, BlockRunnerMoniker, BlockViewer, BlockViewerMoniker,
18
- buildJsonRpcProviderLocatorV2, buildTransaction, createDeclarationIntent, DefaultMetricsScrapePorts, HttpRpcTransport, MempoolRunner, MempoolRunnerMoniker,
19
- MempoolViewer, MempoolViewerMoniker, RpcSchemaMap, SimpleBlockRewardViewer, SimpleBlockValidationViewer, StakeTotalsViewer, StakeTotalsViewerMoniker,
20
- TransportFactory,
13
+ AccountBalanceViewer, AccountBalanceViewerMoniker, ActorV3, asXL1BlockNumber, BlockRunner, BlockRunnerMoniker, BlockViewer, BlockViewerMoniker,
14
+ buildTransaction, ChainContractViewerMoniker, createDeclarationIntent, FinalizationViewer, FinalizationViewerMoniker, MempoolRunner, MempoolRunnerMoniker,
15
+ MempoolViewer, MempoolViewerMoniker, StakeTotalsViewer, StakeTotalsViewerMoniker,
21
16
  } from '@xyo-network/xl1-sdk'
22
17
  import { Mutex } from 'async-mutex'
23
18
 
24
- export type ProducerActorParams = ActorParamsV2<{
25
- logger: Logger
26
- rewardAddress: Address
19
+ export type ProducerActorParams = ActorParamsV3<{
20
+ config: Config
27
21
  }>
28
22
 
29
23
  const SHOULD_REGISTER_REDECLARATION_INTENT_TIMER = true
@@ -39,7 +33,7 @@ const toFormattedBlockReference = (blockBoundWitness: BlockBoundWitnessWithHashM
39
33
  }
40
34
 
41
35
  @creatable()
42
- export class ProducerActor extends ActorV2<ProducerActorParams> {
36
+ export class ProducerActor extends ActorV3<ProducerActorParams> {
43
37
  /**
44
38
  * The interval time (in MS) between block production attempts.
45
39
  */
@@ -66,12 +60,14 @@ export class ProducerActor extends ActorV2<ProducerActorParams> {
66
60
  private _accountBalanceViewer?: AccountBalanceViewer
67
61
  private _blockRunner?: BlockRunner
68
62
  private _blockViewer?: BlockViewer
63
+ private _chainContractViewer?: ChainContractViewer
69
64
  private _chainId?: ChainId
70
65
  private _lastHeadChangeTime?: number
71
66
  private _lastHeadHash?: string
72
67
  private _mempoolRunner?: MempoolRunner
73
68
  private _mempoolViewer?: MempoolViewer
74
69
  private _produceBlockMutex = new Mutex()
70
+ private _rewardAddress!: Address
75
71
  private _stakeTotalsViewer?: StakeTotalsViewer
76
72
 
77
73
  override get logger() {
@@ -90,10 +86,18 @@ export class ProducerActor extends ActorV2<ProducerActorParams> {
90
86
  return this._blockViewer!
91
87
  }
92
88
 
89
+ protected get chainContractViewer() {
90
+ return this._chainContractViewer!
91
+ }
92
+
93
93
  protected get chainId() {
94
94
  return this._chainId!
95
95
  }
96
96
 
97
+ protected get config() {
98
+ return this.params.config
99
+ }
100
+
97
101
  protected get mempoolRunner() {
98
102
  return this._mempoolRunner!
99
103
  }
@@ -102,29 +106,10 @@ export class ProducerActor extends ActorV2<ProducerActorParams> {
102
106
  return this._mempoolViewer!
103
107
  }
104
108
 
105
- protected get rewardAddress() {
106
- return this.params.rewardAddress!
107
- }
108
-
109
109
  protected get stakeTotalsViewer() {
110
110
  return this._stakeTotalsViewer!
111
111
  }
112
112
 
113
- static override async paramsHandler<T extends ProducerActor>(params: Partial<T['params']>) {
114
- const superParams = await super.paramsHandler(params)
115
- const { logger, account } = superParams
116
- const rewardAddress = params.rewardAddress ?? account.address
117
- logger?.info(`Using reward address ${rewardAddress}`)
118
- if (rewardAddress === account.address) {
119
- logger?.warn(`Using producer account address as reward address: ${account.address}`)
120
- }
121
-
122
- return {
123
- ...superParams,
124
- rewardAddress,
125
- }
126
- }
127
-
128
113
  override async createHandler() {
129
114
  await super.createHandler()
130
115
  // Create the consistent meter attributes that will
@@ -147,6 +132,8 @@ export class ProducerActor extends ActorV2<ProducerActorParams> {
147
132
  'producer_actor_blocks_published',
148
133
  { description: 'Number of blocks published' },
149
134
  )
135
+ const final = await this.locator?.getInstance<FinalizationViewer>(FinalizationViewerMoniker)
136
+ await final.start()
150
137
  this._accountBalanceViewer = assertEx(
151
138
  await this.locator?.getInstance<AccountBalanceViewer>(AccountBalanceViewerMoniker),
152
139
  () => 'Unable to locate AccountBalanceViewer',
@@ -159,6 +146,10 @@ export class ProducerActor extends ActorV2<ProducerActorParams> {
159
146
  await this.locator?.getInstance<BlockViewer>(BlockViewerMoniker),
160
147
  () => 'Unable to locate BlockViewer',
161
148
  )
149
+ this._chainContractViewer = assertEx(
150
+ await this.locator?.getInstance<ChainContractViewer>(ChainContractViewerMoniker),
151
+ () => 'Unable to locate ChainContractViewer',
152
+ )
162
153
  this._mempoolRunner = assertEx(
163
154
  await this.locator?.getInstance<MempoolRunner>(MempoolRunnerMoniker),
164
155
  () => 'Unable to locate MempoolRunner',
@@ -171,32 +162,33 @@ export class ProducerActor extends ActorV2<ProducerActorParams> {
171
162
  await this.locator?.getInstance<StakeTotalsViewer>(StakeTotalsViewerMoniker),
172
163
  () => 'Unable to locate StakeTotalsViewer',
173
164
  )
165
+ this._chainId = await this.chainContractViewer.chainId()
174
166
  }
175
167
 
176
- async initLocator() {
177
- const config = this.config
178
- const endpoint = assertEx(config.services.apiEndpoint, () => 'API endpoint is required in config.services.apiEndpoint')
179
- const transportFactory: TransportFactory = (schemas: RpcSchemaMap) => new HttpRpcTransport(endpoint, schemas)
180
- const locator = await buildJsonRpcProviderLocatorV2(config, transportFactory)
181
-
182
- const version = '1.0.0'
183
- const telemetryConfig = buildTelemetryConfig(config, this.name, version, DefaultMetricsScrapePorts.producer)
184
- const { traceProvider, meterProvider } = await startupSpanAsync('initTelemetry', () => initTelemetry(telemetryConfig))
185
-
186
- locator.context.traceProvider = traceProvider
187
- locator.context.meterProvider = meterProvider
188
-
189
- locator.register(SimpleBlockRewardViewer.factory<SimpleBlockRewardViewer>(SimpleBlockRewardViewer.dependencies, {}))
190
- locator.register(SimpleBlockValidationViewer.factory<SimpleBlockValidationViewer>(
191
- SimpleBlockValidationViewer.dependencies,
192
- { state: validateHydratedBlockState, protocol: validateHydratedBlock },
193
- ))
194
- locator.register(SimpleBlockRunner.factory<SimpleBlockRunner>(
195
- SimpleBlockRunner.dependencies,
196
- { account: this.params.account, rewardAddress: this.params.rewardAddress },
197
- ))
198
- return await initEvmProvidersIfAvailable(locator)
199
- }
168
+ // async initLocator() {
169
+ // const config = this.config
170
+ // const endpoint = assertEx(config.services.apiEndpoint, () => 'API endpoint is required in config.services.apiEndpoint')
171
+ // const transportFactory: TransportFactory = (schemas: RpcSchemaMap) => new HttpRpcTransport(endpoint, schemas)
172
+ // const locator = await buildJsonRpcProviderLocatorV2(config, transportFactory)
173
+
174
+ // const version = '1.0.0'
175
+ // const telemetryConfig = buildTelemetryConfig(config, this.name, version, DefaultMetricsScrapePorts.producer)
176
+ // const { traceProvider, meterProvider } = await startupSpanAsync('initTelemetry', () => initTelemetry(telemetryConfig))
177
+
178
+ // locator.context.traceProvider = traceProvider
179
+ // locator.context.meterProvider = meterProvider
180
+
181
+ // locator.register(SimpleBlockRewardViewer.factory<SimpleBlockRewardViewer>(SimpleBlockRewardViewer.dependencies, {}))
182
+ // locator.register(SimpleBlockValidationViewer.factory<SimpleBlockValidationViewer>(
183
+ // SimpleBlockValidationViewer.dependencies,
184
+ // { state: validateHydratedBlockState, protocol: validateHydratedBlock },
185
+ // ))
186
+ // locator.register(SimpleBlockRunner.factory<SimpleBlockRunner>(
187
+ // SimpleBlockRunner.dependencies,
188
+ // { account: this.params.account, rewardAddress: this.params.rewardAddress },
189
+ // ))
190
+ // return await initEvmProvidersIfAvailable(locator)
191
+ // }
200
192
 
201
193
  override async startHandler() {
202
194
  await super.startHandler()
@@ -300,7 +292,7 @@ export class ProducerActor extends ActorV2<ProducerActorParams> {
300
292
  protected async redeclareIntent(): Promise<void> {
301
293
  await this.spanAsync('redeclareIntent', async () => {
302
294
  // Decide if we should redeclare intent
303
- if (this.config.producer.disableIntentRedeclaration) return
295
+ if (this.config.actors.producer.disableIntentRedeclaration) return
304
296
 
305
297
  // Get the current block
306
298
  const head = (await this.blockViewer.currentBlock())[0]
@@ -339,7 +331,7 @@ export class ProducerActor extends ActorV2<ProducerActorParams> {
339
331
  // Check if we have a valid stake before declaring intent
340
332
  if (!(await this.validateCurrentStake())) {
341
333
  this.logger?.error(
342
- `Add stake to contract address ${this.config.chain.id}`
334
+ `Add stake to contract address ${this.chainId}`
343
335
  + ' for the producer to declare it\'s intent.',
344
336
  )
345
337
  return
@@ -1,30 +1,23 @@
1
1
  import type { CreatableName } from '@xylabs/sdk-js'
2
- import {
3
- asAddress, exists, IdLogger,
4
- } from '@xylabs/sdk-js'
2
+ import { exists } from '@xylabs/sdk-js'
5
3
  import { initProducerAccount, type OrchestratorInstance } from '@xyo-network/chain-orchestration'
6
- import { type BaseContext, type Config } from '@xyo-network/xl1-sdk'
4
+ import type {
5
+ Config,
6
+ ProviderFactoryLocatorInstance,
7
+ } from '@xyo-network/xl1-sdk'
7
8
 
8
9
  import type { ProducerActorParams } from './ProducerActor.ts'
9
10
  import { ProducerActor } from './ProducerActor.ts'
10
11
 
11
- export interface RunProducerContext extends BaseContext {
12
- config: Config
13
- orchestrator: OrchestratorInstance
14
- }
15
-
16
- export const runProducer = async ({
17
- config, logger = console, orchestrator,
18
- }: RunProducerContext) => {
19
- const localLogger = logger ?? new IdLogger(logger ?? console, () => 'ResolveHelper [runProducer]')
20
- const account = await initProducerAccount({ config })
21
- localLogger.info(`Running producer for account ${account.address}`)
22
- const rewardAddress = asAddress(config.producer.rewardAddress, () => 'rewardAddress is required in config.producer')
23
- localLogger.info(`Using reward address ${rewardAddress}`)
24
-
12
+ export const runProducer = async (
13
+ config: Config,
14
+ orchestrator: OrchestratorInstance,
15
+ locator: ProviderFactoryLocatorInstance,
16
+ ) => {
17
+ const account = await initProducerAccount({ config, logger: locator.context.logger })
25
18
  // Create actors
26
19
  const producer = await ProducerActor.create({
27
- account, config, logger, rewardAddress, name: 'xl1-producer' as CreatableName,
20
+ config, locator, name: 'xl1-producer' as CreatableName, account,
28
21
  } satisfies ProducerActorParams)
29
22
  const actors = [producer].filter(exists)
30
23