@xyo-network/chain-producer 1.19.6 → 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,11 +1,10 @@
1
1
  import type { Attributes, Counter } from '@opentelemetry/api';
2
- import type { Address } from '@xylabs/sdk-js';
3
- import type { ChainStakeIntent, HydratedBlockWithHashMeta, XL1BlockNumber } from '@xyo-network/xl1-sdk';
4
- import { AccountBalanceViewer, Actor, ActorParams, BlockRunner, BlockViewer, MempoolRunner, MempoolViewer, StakeTotalsViewer } from '@xyo-network/xl1-sdk';
5
- export type ProducerActorParams = ActorParams<{
6
- 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;
7
6
  }>;
8
- export declare class ProducerActor extends Actor<ProducerActorParams> {
7
+ export declare class ProducerActor extends ActorV3<ProducerActorParams> {
9
8
  /**
10
9
  * The interval time (in MS) between block production attempts.
11
10
  */
@@ -28,46 +27,452 @@ export declare class ProducerActor extends Actor<ProducerActorParams> {
28
27
  private _accountBalanceViewer?;
29
28
  private _blockRunner?;
30
29
  private _blockViewer?;
30
+ private _chainContractViewer?;
31
31
  private _chainId?;
32
32
  private _lastHeadChangeTime?;
33
33
  private _lastHeadHash?;
34
34
  private _mempoolRunner?;
35
35
  private _mempoolViewer?;
36
36
  private _produceBlockMutex;
37
+ private _rewardAddress;
37
38
  private _stakeTotalsViewer?;
39
+ get logger(): import("@xylabs/sdk-js").Logger;
38
40
  protected get accountBalanceViewer(): AccountBalanceViewer;
39
41
  protected get blockRunner(): BlockRunner;
40
42
  protected get blockViewer(): BlockViewer<"BlockViewer">;
43
+ protected get chainContractViewer(): ChainContractViewer;
41
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
+ };
42
473
  protected get mempoolRunner(): MempoolRunner;
43
474
  protected get mempoolViewer(): MempoolViewer;
44
- protected get rewardAddress(): Lowercase<string> & {
45
- readonly __hex: true;
46
- } & {
47
- readonly __address: true;
48
- };
49
475
  protected get stakeTotalsViewer(): StakeTotalsViewer;
50
- static paramsHandler<T extends ProducerActor>(params?: Partial<T['params']>): Promise<{
51
- rewardAddress: Lowercase<string> & {
52
- readonly __hex: true;
53
- } & {
54
- readonly __address: true;
55
- };
56
- name?: import("@xylabs/sdk-js").CreatableName;
57
- statusReporter?: import("@xylabs/sdk-js").CreatableStatusReporter<void> | undefined;
58
- logger: import("@xylabs/sdk-js").Logger;
59
- meterProvider?: import("@opentelemetry/api").MeterProvider;
60
- traceProvider?: import("@opentelemetry/api").TracerProvider;
61
- account: import("@xyo-network/account-model").AccountInstance;
62
- context: import("@xyo-network/xl1-sdk").ActorContext;
63
- displayName: string | (string & {
64
- __baseClassName: true;
65
- }) | undefined;
66
- id: string | (string & {
67
- __baseClassName: true;
68
- });
69
- }>;
70
- protected static initContext(params: ProducerActorParams): Promise<import("@xyo-network/xl1-sdk").CreatableProviderContext>;
71
476
  createHandler(): Promise<void>;
72
477
  startHandler(): Promise<void>;
73
478
  protected calculateBlocksUntilProducerDeclarationExpiration(currentBlock: number): number;
@@ -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,gBAAgB,CAAA;AAS7C,OAAO,KAAK,EAC8B,gBAAgB,EAAE,yBAAyB,EAAE,cAAc,EACpG,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EACL,oBAAoB,EAA+B,KAAK,EAAE,WAAW,EAAoB,WAAW,EAAsB,WAAW,EACjB,aAAa,EACjI,aAAa,EAA4F,iBAAiB,EAE3H,MAAM,sBAAsB,CAAA;AAG7B,MAAM,MAAM,mBAAmB,GAAG,WAAW,CAAC;IAC5C,aAAa,EAAE,OAAO,CAAA;CACvB,CAAC,CAAA;AAcF,qBACa,aAAc,SAAQ,KAAK,CAAC,mBAAmB,CAAC;IAC3D;;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,gBAAgB,CAAA;IACrD,SAAS,CAAC,iBAAi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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"}
@@ -2,12 +2,9 @@ var __defProp = Object.defineProperty;
2
2
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
3
 
4
4
  // src/ProducerActor.ts
5
- import { asAddress, assertEx, creatable, isDefined, isUndefined, toHex } from "@xylabs/sdk-js";
6
- import { EvmChainContractViewer, EvmStakeTotalsViewer } from "@xyo-network/chain-ethereum";
7
- import { initEvmProvider, initProducerAccount } from "@xyo-network/chain-orchestration";
5
+ import { assertEx, creatable, isDefined, isUndefined, toHex } from "@xylabs/sdk-js";
8
6
  import { SimpleBlockRunner } from "@xyo-network/chain-services";
9
- import { validateHydratedBlock, validateHydratedBlockState } from "@xyo-network/chain-validation";
10
- import { AccountBalanceViewerMoniker, Actor, asXL1BlockNumber, BlockRunnerMoniker, BlockViewerMoniker, buildJsonRpcProviderLocator, buildTransaction, createDeclarationIntent, getDefaultConfig, 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";
11
8
  import { Mutex } from "async-mutex";
12
9
  function _ts_decorate(decorators, target, key, desc) {
13
10
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -23,7 +20,7 @@ var toFormattedBlockReference = /* @__PURE__ */ __name((blockBoundWitness) => {
23
20
  prefix: true
24
21
  })}]`;
25
22
  }, "toFormattedBlockReference");
26
- var ProducerActor = class _ProducerActor extends Actor {
23
+ var ProducerActor = class _ProducerActor extends ActorV3 {
27
24
  static {
28
25
  __name(this, "ProducerActor");
29
26
  }
@@ -49,13 +46,18 @@ var ProducerActor = class _ProducerActor extends Actor {
49
46
  _accountBalanceViewer;
50
47
  _blockRunner;
51
48
  _blockViewer;
49
+ _chainContractViewer;
52
50
  _chainId;
53
51
  _lastHeadChangeTime;
54
52
  _lastHeadHash;
55
53
  _mempoolRunner;
56
54
  _mempoolViewer;
57
55
  _produceBlockMutex = new Mutex();
56
+ _rewardAddress;
58
57
  _stakeTotalsViewer;
58
+ get logger() {
59
+ return assertEx(super.logger, () => "Logger is required for ProducerActor");
60
+ }
59
61
  get accountBalanceViewer() {
60
62
  return this._accountBalanceViewer;
61
63
  }
@@ -65,77 +67,24 @@ var ProducerActor = class _ProducerActor extends Actor {
65
67
  get blockViewer() {
66
68
  return this._blockViewer;
67
69
  }
70
+ get chainContractViewer() {
71
+ return this._chainContractViewer;
72
+ }
68
73
  get chainId() {
69
74
  return this._chainId;
70
75
  }
76
+ get config() {
77
+ return this.params.config;
78
+ }
71
79
  get mempoolRunner() {
72
80
  return this._mempoolRunner;
73
81
  }
74
82
  get mempoolViewer() {
75
83
  return this._mempoolViewer;
76
84
  }
77
- get rewardAddress() {
78
- return this.params.rewardAddress;
79
- }
80
85
  get stakeTotalsViewer() {
81
86
  return this._stakeTotalsViewer;
82
87
  }
83
- static async paramsHandler(params) {
84
- const logger = params?.context?.logger;
85
- const config = params?.context?.config ?? getDefaultConfig();
86
- const displayName = params?.displayName ?? "ProducerActor";
87
- const account = params?.account ?? await initProducerAccount({
88
- config
89
- });
90
- const id = account?.address.toString() ?? "unknown";
91
- logger?.info(`Running producer for account ${account.address}`);
92
- const rewardAddress = params?.rewardAddress ?? account.address;
93
- logger?.info(`Using reward address ${rewardAddress}`);
94
- if (rewardAddress === account.address) {
95
- logger?.warn(`Using producer account address as reward address: ${account.address}`);
96
- }
97
- return {
98
- ...await super.paramsHandler({
99
- ...params,
100
- account,
101
- displayName,
102
- id
103
- }),
104
- rewardAddress
105
- };
106
- }
107
- static async initContext(params) {
108
- const config = params?.context?.config ?? getDefaultConfig();
109
- const endpoint = assertEx(config.services.apiEndpoint, () => "API endpoint is required in config.services.apiEndpoint");
110
- const context = await super.initContext(params);
111
- const chainId = assertEx(config.chain.id, () => "Chain ID is required in config.chain.id");
112
- const transportFactory = /* @__PURE__ */ __name((schemas) => new HttpRpcTransport(endpoint, schemas), "transportFactory");
113
- const locator = await buildJsonRpcProviderLocator({
114
- context,
115
- transportFactory
116
- });
117
- const runner = await initEvmProvider({
118
- config
119
- });
120
- locator.register(EvmChainContractViewer.factory(EvmChainContractViewer.dependencies, {
121
- address: asAddress(chainId),
122
- runner
123
- }));
124
- locator.register(EvmStakeTotalsViewer.factory(EvmStakeTotalsViewer.dependencies, {
125
- address: asAddress(chainId),
126
- runner
127
- }));
128
- locator.register(SimpleBlockRewardViewer.factory(SimpleBlockRewardViewer.dependencies));
129
- locator.register(SimpleBlockValidationViewer.factory(SimpleBlockValidationViewer.dependencies, {
130
- state: validateHydratedBlockState,
131
- protocol: validateHydratedBlock
132
- }));
133
- locator.register(SimpleBlockRunner.factory(SimpleBlockRunner.dependencies, {
134
- account: params.account,
135
- rewardAddress: params.rewardAddress
136
- }));
137
- return locator.context;
138
- }
139
88
  async createHandler() {
140
89
  await super.createHandler();
141
90
  this._metricAttributes = {
@@ -153,13 +102,38 @@ var ProducerActor = class _ProducerActor extends Actor {
153
102
  this._producerActorBlocksPublished = this.meter?.createCounter("producer_actor_blocks_published", {
154
103
  description: "Number of blocks published"
155
104
  });
105
+ const final = await this.locator?.getInstance(FinalizationViewerMoniker);
106
+ await final.start();
156
107
  this._accountBalanceViewer = assertEx(await this.locator?.getInstance(AccountBalanceViewerMoniker), () => "Unable to locate AccountBalanceViewer");
157
108
  this._blockRunner = assertEx(await this.locator?.getInstance(BlockRunnerMoniker), () => "Unable to locate BlockRunner");
158
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");
159
111
  this._mempoolRunner = assertEx(await this.locator?.getInstance(MempoolRunnerMoniker), () => "Unable to locate MempoolRunner");
160
112
  this._mempoolViewer = assertEx(await this.locator?.getInstance(MempoolViewerMoniker), () => "Unable to locate MempoolViewer");
161
113
  this._stakeTotalsViewer = assertEx(await this.locator?.getInstance(StakeTotalsViewerMoniker), () => "Unable to locate StakeTotalsViewer");
114
+ this._chainId = await this.chainContractViewer.chainId();
162
115
  }
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
+ // }
163
137
  async startHandler() {
164
138
  await super.startHandler();
165
139
  this.registerTimer("BlockProductionTimer", async () => {
@@ -231,7 +205,7 @@ var ProducerActor = class _ProducerActor extends Actor {
231
205
  }
232
206
  async redeclareIntent() {
233
207
  await this.spanAsync("redeclareIntent", async () => {
234
- if (this.config.producer.disableIntentRedeclaration) return;
208
+ if (this.config.actors.producer.disableIntentRedeclaration) return;
235
209
  const head = (await this.blockViewer.currentBlock())[0];
236
210
  if (isUndefined(head)) return;
237
211
  const currentBlock = head.block;
@@ -249,7 +223,7 @@ var ProducerActor = class _ProducerActor extends Actor {
249
223
  return;
250
224
  }
251
225
  if (!await this.validateCurrentStake()) {
252
- 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.`);
253
227
  return;
254
228
  }
255
229
  this.logger?.log("Creating redeclaration intent for producer:", this.account.address);
@@ -303,24 +277,18 @@ ProducerActor = _ts_decorate([
303
277
  ], ProducerActor);
304
278
 
305
279
  // src/runProducer.ts
306
- import { asAddress as asAddress2, exists, IdLogger } from "@xylabs/sdk-js";
307
- import { initProducerAccount as initProducerAccount2 } from "@xyo-network/chain-orchestration";
308
- var runProducer = /* @__PURE__ */ __name(async ({ config, logger, orchestrator, locator }) => {
309
- const localLogger = logger ?? new IdLogger(logger ?? console, () => "ResolveHelper [runProducer]");
310
- const account = await initProducerAccount2({
311
- config
280
+ import { exists } from "@xylabs/sdk-js";
281
+ import { initProducerAccount } from "@xyo-network/chain-orchestration";
282
+ var runProducer = /* @__PURE__ */ __name(async (config, orchestrator, locator) => {
283
+ const account = await initProducerAccount({
284
+ config,
285
+ logger: locator.context.logger
312
286
  });
313
- localLogger.info(`Running producer for account ${account.address}`);
314
- const rewardAddress = asAddress2(config.producer.rewardAddress, () => "rewardAddress is required in config.producer");
315
- localLogger.info(`Using reward address ${rewardAddress}`);
316
287
  const producer = await ProducerActor.create({
317
- logger,
318
- context: {
319
- config,
320
- locator,
321
- singletons: {},
322
- caches: {}
323
- }
288
+ config,
289
+ locator,
290
+ name: "xl1-producer",
291
+ account
324
292
  });
325
293
  const actors = [
326
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 } from '@xylabs/sdk-js'\nimport {\n asAddress, assertEx, creatable, isDefined, isUndefined,\n toHex,\n} from '@xylabs/sdk-js'\nimport { EvmChainContractViewer, EvmStakeTotalsViewer } from '@xyo-network/chain-ethereum'\nimport { initEvmProvider, initProducerAccount } from '@xyo-network/chain-orchestration'\nimport { SimpleBlockRunner } from '@xyo-network/chain-services'\nimport { validateHydratedBlock, validateHydratedBlockState } from '@xyo-network/chain-validation'\nimport type {\n BlockBoundWitnessWithHashMeta, ChainId, ChainStakeIntent, HydratedBlockWithHashMeta, XL1BlockNumber,\n} from '@xyo-network/xl1-sdk'\nimport {\n AccountBalanceViewer, AccountBalanceViewerMoniker, Actor, ActorParams, asXL1BlockNumber, BlockRunner, BlockRunnerMoniker, BlockViewer, BlockViewerMoniker,\n buildJsonRpcProviderLocator, buildTransaction, Config, createDeclarationIntent, getDefaultConfig, 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 = ActorParams<{\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 Actor<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 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 logger = params?.context?.logger\n const config = params?.context?.config ?? getDefaultConfig()\n const displayName = params?.displayName ?? 'ProducerActor'\n const account = params?.account ?? await initProducerAccount({ config })\n const id = account?.address.toString() ?? 'unknown'\n logger?.info(`Running producer for account ${account.address}`)\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 ...await super.paramsHandler({\n ...params,\n account,\n displayName,\n id,\n }),\n rewardAddress,\n }\n }\n\n protected static override async initContext(\n params: ProducerActorParams,\n ) {\n const config: Config = params?.context?.config ?? getDefaultConfig()\n const endpoint = assertEx(config.services.apiEndpoint, () => 'API endpoint is required in config.services.apiEndpoint')\n\n const context = await super.initContext(params)\n\n const chainId = assertEx(config.chain.id, () => 'Chain ID is required in config.chain.id')\n\n const transportFactory: TransportFactory = (schemas: RpcSchemaMap) => new HttpRpcTransport(endpoint, schemas)\n const locator = await buildJsonRpcProviderLocator({ context, transportFactory })\n const runner = await initEvmProvider({ config })\n locator.register(EvmChainContractViewer.factory<EvmChainContractViewer>(EvmChainContractViewer.dependencies, { address: asAddress(chainId), runner }))\n locator.register(EvmStakeTotalsViewer.factory<EvmStakeTotalsViewer>(EvmStakeTotalsViewer.dependencies, { address: asAddress(chainId), runner }))\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: params.account, rewardAddress: params.rewardAddress },\n ))\n return locator.context\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 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 {\n asAddress, exists, IdLogger,\n} from '@xylabs/sdk-js'\nimport { initProducerAccount, type OrchestratorInstance } from '@xyo-network/chain-orchestration'\nimport type {\n BaseContext, Config, ProviderFactoryLocatorInstance,\n} from '@xyo-network/xl1-sdk'\n\nimport { ProducerActor } from './ProducerActor.ts'\n\nexport interface RunProducerContext extends BaseContext {\n config: Config\n locator?: ProviderFactoryLocatorInstance\n orchestrator: OrchestratorInstance\n}\n\nexport const runProducer = async ({\n config, logger, orchestrator, locator,\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 logger,\n context: {\n config, locator, singletons: {}, caches: {},\n },\n })\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,WAAWC,UAAUC,WAAWC,WAAWC,aAC3CC,aACK;AACP,SAASC,wBAAwBC,4BAA4B;AAC7D,SAASC,iBAAiBC,2BAA2B;AACrD,SAASC,yBAAyB;AAClC,SAASC,uBAAuBC,kCAAkC;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GAxB2B;","names":["asAddress","assertEx","creatable","isDefined","isUndefined","toHex","EvmChainContractViewer","EvmStakeTotalsViewer","initEvmProvider","initProducerAccount","SimpleBlockRunner","validateHydratedBlock","validateHydratedBlockState","AccountBalanceViewerMoniker","Actor","asXL1BlockNumber","BlockRunnerMoniker","BlockViewerMoniker","buildJsonRpcProviderLocator","buildTransaction","createDeclarationIntent","getDefaultConfig","HttpRpcTransport","MempoolRunnerMoniker","MempoolViewerMoniker","SimpleBlockRewardViewer","SimpleBlockValidationViewer","StakeTotalsViewerMoniker","Mutex","SHOULD_REGISTER_REDECLARATION_INTENT_TIMER","TEN_MINUTES","toFormattedBlockReference","blockBoundWitness","block","toHex","_hash","prefix","ProducerActor","Actor","BlockSubmissionCheckInterval","HeadResubmissionThreshold","RedeclarationWindow","_lastProducedBlock","_lastRedeclarationIntent","_metricAttributes","_producerActorBlockProductionAttempts","_producerActorBlockProductionChecks","_producerActorBlocksProduced","_producerActorBlocksPublished","_accountBalanceViewer","_blockRunner","_blockViewer","_chainId","_lastHeadChangeTime","_lastHeadHash","_mempoolRunner","_mempoolViewer","_produceBlockMutex","Mutex","_stakeTotalsViewer","accountBalanceViewer","blockRunner","blockViewer","chainId","mempoolRunner","mempoolViewer","rewardAddress","params","stakeTotalsViewer","paramsHandler","logger","context","config","getDefaultConfig","displayName","account","initProducerAccount","id","address","toString","info","warn","initContext","endpoint","assertEx","services","apiEndpoint","chain","transportFactory","schemas","HttpRpcTransport","locator","buildJsonRpcProviderLocator","runner","initEvmProvider","register","EvmChainContractViewer","factory","dependencies","asAddress","EvmStakeTotalsViewer","SimpleBlockRewardViewer","SimpleBlockValidationViewer","state","validateHydratedBlockState","protocol","validateHydratedBlock","SimpleBlockRunner","createHandler","meter","createCounter","description","getInstance","AccountBalanceViewerMoniker","BlockRunnerMoniker","BlockViewerMoniker","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","timeBudgetLimit","producer","disableIntentRedeclaration","isUndefined","blocksUntilExpiration","undefined","validateCurrentBalance","error","validateCurrentStake","redeclarationIntent","createDeclarationIntent","RedeclarationDuration","submitRedeclarationIntent","tx","buildTransaction","asXL1BlockNumber","submitTransactions","balances","accountBalances","currentBalance","requiredMinimumStake","currentStake","activeByStaked","asAddress","exists","IdLogger","initProducerAccount","runProducer","config","logger","orchestrator","locator","localLogger","IdLogger","console","account","initProducerAccount","info","address","rewardAddress","asAddress","producer","ProducerActor","create","context","singletons","caches","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;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,sBAAsB;EAE5BC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EAEFC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC,qBAAqB,IAAIC,MAAAA;EACzBC;EACAC;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QD;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,9 +1,4 @@
1
1
  import { type OrchestratorInstance } from '@xyo-network/chain-orchestration';
2
- import type { BaseContext, Config, ProviderFactoryLocatorInstance } from '@xyo-network/xl1-sdk';
3
- export interface RunProducerContext extends BaseContext {
4
- config: Config;
5
- locator?: ProviderFactoryLocatorInstance;
6
- orchestrator: OrchestratorInstance;
7
- }
8
- export declare const runProducer: ({ config, logger, orchestrator, locator, }: 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>;
9
4
  //# sourceMappingURL=runProducer.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"runProducer.d.ts","sourceRoot":"","sources":["../../src/runProducer.ts"],"names":[],"mappings":"AAGA,OAAO,EAAuB,KAAK,oBAAoB,EAAE,MAAM,kCAAkC,CAAA;AACjG,OAAO,KAAK,EACV,WAAW,EAAE,MAAM,EAAE,8BAA8B,EACpD,MAAM,sBAAsB,CAAA;AAI7B,MAAM,WAAW,kBAAmB,SAAQ,WAAW;IACrD,MAAM,EAAE,MAAM,CAAA;IACd,OAAO,CAAC,EAAE,8BAA8B,CAAA;IACxC,YAAY,EAAE,oBAAoB,CAAA;CACnC;AAED,eAAO,MAAM,WAAW,GAAU,4CAE/B,kBAAkB,kBAsBpB,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.6",
3
+ "version": "1.19.8",
4
4
  "description": "XYO Layer One Producer",
5
5
  "homepage": "https://xylabs.com",
6
6
  "bugs": {
@@ -49,12 +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-ethereum": "~1.19.6",
54
- "@xyo-network/chain-orchestration": "~1.19.6",
55
- "@xyo-network/chain-services": "~1.19.6",
56
- "@xyo-network/chain-validation": "~1.19.6",
57
- "@xyo-network/xl1-sdk": "~1.21.10",
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",
58
59
  "async-mutex": "~0.5.0"
59
60
  },
60
61
  "devDependencies": {
@@ -63,8 +64,8 @@
63
64
  "@types/cors": "~2.8.19",
64
65
  "@types/express": "5.0.6",
65
66
  "@types/express-serve-static-core": "~5.1.1",
66
- "@types/node": "~25.1.0",
67
- "@xylabs/sdk-js": "~5.0.65",
67
+ "@types/node": "~25.2.3",
68
+ "@xylabs/sdk-js": "~5.0.78",
68
69
  "@xylabs/ts-scripts-yarn3": "~7.3.2",
69
70
  "@xylabs/tsconfig": "~7.3.2",
70
71
  "@xyo-network/account": "~5.3.2",
@@ -72,13 +73,13 @@
72
73
  "@xyo-network/archivist-abstract": "~5.3.2",
73
74
  "@xyo-network/bios-model": "~7.2.1",
74
75
  "@xyo-network/boundwitness-builder": "~5.3.2",
75
- "@xyo-network/chain-services": "~1.19.6",
76
- "@xyo-network/chain-validation": "~1.19.6",
76
+ "@xyo-network/chain-services": "~1.19.8",
77
+ "@xyo-network/chain-validation": "~1.19.8",
77
78
  "@xyo-network/module-abstract-mongodb": "~5.3.2",
78
79
  "@xyo-network/module-model-mongodb": "~5.3.2",
79
80
  "@xyo-network/node-memory": "~5.3.2",
80
- "@xyo-network/xl1-sdk": "~1.21.10",
81
- "dotenv": "~17.2.3",
81
+ "@xyo-network/xl1-sdk": "~1.23.6",
82
+ "dotenv": "~17.2.4",
82
83
  "eslint": "^9.39.2",
83
84
  "nodemon": "~3.1.11",
84
85
  "tslib": "~2.8.1",
@@ -1,26 +1,23 @@
1
1
  import type { Attributes, Counter } from '@opentelemetry/api'
2
- import type { Address } from '@xylabs/sdk-js'
3
2
  import {
4
- asAddress, assertEx, creatable, isDefined, isUndefined,
3
+ Address,
4
+ assertEx, creatable, isDefined, isUndefined,
5
5
  toHex,
6
6
  } from '@xylabs/sdk-js'
7
- import { EvmChainContractViewer, EvmStakeTotalsViewer } from '@xyo-network/chain-ethereum'
8
- import { initEvmProvider, initProducerAccount } from '@xyo-network/chain-orchestration'
9
7
  import { SimpleBlockRunner } from '@xyo-network/chain-services'
10
- import { validateHydratedBlock, validateHydratedBlockState } from '@xyo-network/chain-validation'
11
8
  import type {
12
- BlockBoundWitnessWithHashMeta, ChainId, ChainStakeIntent, HydratedBlockWithHashMeta, XL1BlockNumber,
9
+ ActorParamsV3,
10
+ BlockBoundWitnessWithHashMeta, ChainContractViewer, ChainId, ChainStakeIntent, Config, HydratedBlockWithHashMeta, XL1BlockNumber,
13
11
  } from '@xyo-network/xl1-sdk'
14
12
  import {
15
- AccountBalanceViewer, AccountBalanceViewerMoniker, Actor, ActorParams, asXL1BlockNumber, BlockRunner, BlockRunnerMoniker, BlockViewer, BlockViewerMoniker,
16
- buildJsonRpcProviderLocator, buildTransaction, Config, createDeclarationIntent, getDefaultConfig, HttpRpcTransport, MempoolRunner, MempoolRunnerMoniker,
17
- MempoolViewer, MempoolViewerMoniker, RpcSchemaMap, SimpleBlockRewardViewer, SimpleBlockValidationViewer, StakeTotalsViewer, StakeTotalsViewerMoniker,
18
- TransportFactory,
13
+ AccountBalanceViewer, AccountBalanceViewerMoniker, ActorV3, asXL1BlockNumber, BlockRunner, BlockRunnerMoniker, BlockViewer, BlockViewerMoniker,
14
+ buildTransaction, ChainContractViewerMoniker, createDeclarationIntent, FinalizationViewer, FinalizationViewerMoniker, MempoolRunner, MempoolRunnerMoniker,
15
+ MempoolViewer, MempoolViewerMoniker, StakeTotalsViewer, StakeTotalsViewerMoniker,
19
16
  } from '@xyo-network/xl1-sdk'
20
17
  import { Mutex } from 'async-mutex'
21
18
 
22
- export type ProducerActorParams = ActorParams<{
23
- rewardAddress: Address
19
+ export type ProducerActorParams = ActorParamsV3<{
20
+ config: Config
24
21
  }>
25
22
 
26
23
  const SHOULD_REGISTER_REDECLARATION_INTENT_TIMER = true
@@ -36,7 +33,7 @@ const toFormattedBlockReference = (blockBoundWitness: BlockBoundWitnessWithHashM
36
33
  }
37
34
 
38
35
  @creatable()
39
- export class ProducerActor extends Actor<ProducerActorParams> {
36
+ export class ProducerActor extends ActorV3<ProducerActorParams> {
40
37
  /**
41
38
  * The interval time (in MS) between block production attempts.
42
39
  */
@@ -63,14 +60,20 @@ export class ProducerActor extends Actor<ProducerActorParams> {
63
60
  private _accountBalanceViewer?: AccountBalanceViewer
64
61
  private _blockRunner?: BlockRunner
65
62
  private _blockViewer?: BlockViewer
63
+ private _chainContractViewer?: ChainContractViewer
66
64
  private _chainId?: ChainId
67
65
  private _lastHeadChangeTime?: number
68
66
  private _lastHeadHash?: string
69
67
  private _mempoolRunner?: MempoolRunner
70
68
  private _mempoolViewer?: MempoolViewer
71
69
  private _produceBlockMutex = new Mutex()
70
+ private _rewardAddress!: Address
72
71
  private _stakeTotalsViewer?: StakeTotalsViewer
73
72
 
73
+ override get logger() {
74
+ return assertEx(super.logger, () => 'Logger is required for ProducerActor')
75
+ }
76
+
74
77
  protected get accountBalanceViewer() {
75
78
  return this._accountBalanceViewer!
76
79
  }
@@ -83,10 +86,18 @@ export class ProducerActor extends Actor<ProducerActorParams> {
83
86
  return this._blockViewer!
84
87
  }
85
88
 
89
+ protected get chainContractViewer() {
90
+ return this._chainContractViewer!
91
+ }
92
+
86
93
  protected get chainId() {
87
94
  return this._chainId!
88
95
  }
89
96
 
97
+ protected get config() {
98
+ return this.params.config
99
+ }
100
+
90
101
  protected get mempoolRunner() {
91
102
  return this._mempoolRunner!
92
103
  }
@@ -95,65 +106,10 @@ export class ProducerActor extends Actor<ProducerActorParams> {
95
106
  return this._mempoolViewer!
96
107
  }
97
108
 
98
- protected get rewardAddress() {
99
- return this.params.rewardAddress!
100
- }
101
-
102
109
  protected get stakeTotalsViewer() {
103
110
  return this._stakeTotalsViewer!
104
111
  }
105
112
 
106
- static override async paramsHandler<T extends ProducerActor>(params?: Partial<T['params']>) {
107
- const logger = params?.context?.logger
108
- const config = params?.context?.config ?? getDefaultConfig()
109
- const displayName = params?.displayName ?? 'ProducerActor'
110
- const account = params?.account ?? await initProducerAccount({ config })
111
- const id = account?.address.toString() ?? 'unknown'
112
- logger?.info(`Running producer for account ${account.address}`)
113
- const rewardAddress = params?.rewardAddress ?? account.address
114
- logger?.info(`Using reward address ${rewardAddress}`)
115
- if (rewardAddress === account.address) {
116
- logger?.warn(`Using producer account address as reward address: ${account.address}`)
117
- }
118
-
119
- return {
120
- ...await super.paramsHandler({
121
- ...params,
122
- account,
123
- displayName,
124
- id,
125
- }),
126
- rewardAddress,
127
- }
128
- }
129
-
130
- protected static override async initContext(
131
- params: ProducerActorParams,
132
- ) {
133
- const config: Config = params?.context?.config ?? getDefaultConfig()
134
- const endpoint = assertEx(config.services.apiEndpoint, () => 'API endpoint is required in config.services.apiEndpoint')
135
-
136
- const context = await super.initContext(params)
137
-
138
- const chainId = assertEx(config.chain.id, () => 'Chain ID is required in config.chain.id')
139
-
140
- const transportFactory: TransportFactory = (schemas: RpcSchemaMap) => new HttpRpcTransport(endpoint, schemas)
141
- const locator = await buildJsonRpcProviderLocator({ context, transportFactory })
142
- const runner = await initEvmProvider({ config })
143
- locator.register(EvmChainContractViewer.factory<EvmChainContractViewer>(EvmChainContractViewer.dependencies, { address: asAddress(chainId), runner }))
144
- locator.register(EvmStakeTotalsViewer.factory<EvmStakeTotalsViewer>(EvmStakeTotalsViewer.dependencies, { address: asAddress(chainId), runner }))
145
- locator.register(SimpleBlockRewardViewer.factory<SimpleBlockRewardViewer>(SimpleBlockRewardViewer.dependencies))
146
- locator.register(SimpleBlockValidationViewer.factory<SimpleBlockValidationViewer>(
147
- SimpleBlockValidationViewer.dependencies,
148
- { state: validateHydratedBlockState, protocol: validateHydratedBlock },
149
- ))
150
- locator.register(SimpleBlockRunner.factory<SimpleBlockRunner>(
151
- SimpleBlockRunner.dependencies,
152
- { account: params.account, rewardAddress: params.rewardAddress },
153
- ))
154
- return locator.context
155
- }
156
-
157
113
  override async createHandler() {
158
114
  await super.createHandler()
159
115
  // Create the consistent meter attributes that will
@@ -176,6 +132,8 @@ export class ProducerActor extends Actor<ProducerActorParams> {
176
132
  'producer_actor_blocks_published',
177
133
  { description: 'Number of blocks published' },
178
134
  )
135
+ const final = await this.locator?.getInstance<FinalizationViewer>(FinalizationViewerMoniker)
136
+ await final.start()
179
137
  this._accountBalanceViewer = assertEx(
180
138
  await this.locator?.getInstance<AccountBalanceViewer>(AccountBalanceViewerMoniker),
181
139
  () => 'Unable to locate AccountBalanceViewer',
@@ -188,6 +146,10 @@ export class ProducerActor extends Actor<ProducerActorParams> {
188
146
  await this.locator?.getInstance<BlockViewer>(BlockViewerMoniker),
189
147
  () => 'Unable to locate BlockViewer',
190
148
  )
149
+ this._chainContractViewer = assertEx(
150
+ await this.locator?.getInstance<ChainContractViewer>(ChainContractViewerMoniker),
151
+ () => 'Unable to locate ChainContractViewer',
152
+ )
191
153
  this._mempoolRunner = assertEx(
192
154
  await this.locator?.getInstance<MempoolRunner>(MempoolRunnerMoniker),
193
155
  () => 'Unable to locate MempoolRunner',
@@ -200,8 +162,34 @@ export class ProducerActor extends Actor<ProducerActorParams> {
200
162
  await this.locator?.getInstance<StakeTotalsViewer>(StakeTotalsViewerMoniker),
201
163
  () => 'Unable to locate StakeTotalsViewer',
202
164
  )
165
+ this._chainId = await this.chainContractViewer.chainId()
203
166
  }
204
167
 
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
+ // }
192
+
205
193
  override async startHandler() {
206
194
  await super.startHandler()
207
195
  // Register a timer to check if we should produce a block
@@ -304,7 +292,7 @@ export class ProducerActor extends Actor<ProducerActorParams> {
304
292
  protected async redeclareIntent(): Promise<void> {
305
293
  await this.spanAsync('redeclareIntent', async () => {
306
294
  // Decide if we should redeclare intent
307
- if (this.config.producer.disableIntentRedeclaration) return
295
+ if (this.config.actors.producer.disableIntentRedeclaration) return
308
296
 
309
297
  // Get the current block
310
298
  const head = (await this.blockViewer.currentBlock())[0]
@@ -343,7 +331,7 @@ export class ProducerActor extends Actor<ProducerActorParams> {
343
331
  // Check if we have a valid stake before declaring intent
344
332
  if (!(await this.validateCurrentStake())) {
345
333
  this.logger?.error(
346
- `Add stake to contract address ${this.config.chain.id}`
334
+ `Add stake to contract address ${this.chainId}`
347
335
  + ' for the producer to declare it\'s intent.',
348
336
  )
349
337
  return
@@ -1,35 +1,24 @@
1
- import {
2
- asAddress, exists, IdLogger,
3
- } from '@xylabs/sdk-js'
1
+ import type { CreatableName } from '@xylabs/sdk-js'
2
+ import { exists } from '@xylabs/sdk-js'
4
3
  import { initProducerAccount, type OrchestratorInstance } from '@xyo-network/chain-orchestration'
5
4
  import type {
6
- BaseContext, Config, ProviderFactoryLocatorInstance,
5
+ Config,
6
+ ProviderFactoryLocatorInstance,
7
7
  } from '@xyo-network/xl1-sdk'
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
- locator?: ProviderFactoryLocatorInstance
14
- orchestrator: OrchestratorInstance
15
- }
16
-
17
- export const runProducer = async ({
18
- config, logger, orchestrator, locator,
19
- }: RunProducerContext) => {
20
- const localLogger = logger ?? new IdLogger(logger ?? console, () => 'ResolveHelper [runProducer]')
21
- const account = await initProducerAccount({ config })
22
- localLogger.info(`Running producer for account ${account.address}`)
23
- const rewardAddress = asAddress(config.producer.rewardAddress, () => 'rewardAddress is required in config.producer')
24
- localLogger.info(`Using reward address ${rewardAddress}`)
25
-
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 })
26
18
  // Create actors
27
19
  const producer = await ProducerActor.create({
28
- logger,
29
- context: {
30
- config, locator, singletons: {}, caches: {},
31
- },
32
- })
20
+ config, locator, name: 'xl1-producer' as CreatableName, account,
21
+ } satisfies ProducerActorParams)
33
22
  const actors = [producer].filter(exists)
34
23
 
35
24
  for (const actor of actors) {