@xyo-network/chain-producer 1.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
package/README.md ADDED
@@ -0,0 +1,112 @@
1
+ # @xyo-network/chain-api
2
+
3
+ [![logo][]](https://xyo.network)
4
+
5
+ [![npm-badge][]][npm-link]
6
+ [![npm-downloads-badge][]][npm-link]
7
+ [![jsdelivr-badge][]][jsdelivr-link]
8
+ [![npm-license-badge][]](LICENSE)
9
+ [![socket-badge][]][socket-link]
10
+
11
+ XYO Layer One API
12
+
13
+
14
+
15
+ ## Reference
16
+
17
+ **@xyo-network/chain-api**
18
+
19
+ ***
20
+
21
+ ## Functions
22
+
23
+ - [getApp](#functions/getApp)
24
+ - [getServer](#functions/getServer)
25
+
26
+ ### functions
27
+
28
+ ### <a id="getApp"></a>getApp
29
+
30
+ [**@xyo-network/chain-api**](#../README)
31
+
32
+ ***
33
+
34
+ ```ts
35
+ function getApp(
36
+ node,
37
+ transferSummaryMap,
38
+ stakedChainContext,
39
+ initRewardsCache?): Promise<Express>;
40
+ ```
41
+
42
+ ## Parameters
43
+
44
+ ### node
45
+
46
+ `NodeInstance`
47
+
48
+ ### transferSummaryMap
49
+
50
+ `MapType`\<`string`, `WithStorageMeta`\<`TransfersStepSummary`\>\>
51
+
52
+ ### stakedChainContext
53
+
54
+ `StakedChainContextRead`
55
+
56
+ ### initRewardsCache?
57
+
58
+ `boolean`
59
+
60
+ ## Returns
61
+
62
+ `Promise`\<`Express`\>
63
+
64
+ ### <a id="getServer"></a>getServer
65
+
66
+ [**@xyo-network/chain-api**](#../README)
67
+
68
+ ***
69
+
70
+ ```ts
71
+ function getServer(context): Promise<Server<typeof IncomingMessage, typeof ServerResponse>>;
72
+ ```
73
+
74
+ ## Parameters
75
+
76
+ ### context
77
+
78
+ `GetServerContext`
79
+
80
+ ## Returns
81
+
82
+ `Promise`\<`Server`\<*typeof* `IncomingMessage`, *typeof* `ServerResponse`\>\>
83
+
84
+
85
+ ## Maintainers
86
+
87
+ - [Arie Trouw](https://github.com/arietrouw) ([arietrouw.com](https://arietrouw.com))
88
+ - [Matt Jones](https://github.com/jonesmac)
89
+ - [Joel Carter](https://github.com/JoelBCarter)
90
+ - [Jordan Trouw](https://github.com/jordantrouw)
91
+
92
+ ## License
93
+
94
+ > See the [LICENSE](LICENSE) file for license details
95
+
96
+ ## Credits
97
+
98
+ [Made with 🔥 and ❄️ by XYO](https://xyo.network)
99
+
100
+ [logo]: https://cdn.xy.company/img/brand/XYO_full_colored.png
101
+
102
+ [npm-badge]: https://img.shields.io/npm/v/@xyo-network/chain-api.svg
103
+ [npm-link]: https://www.npmjs.com/package/@xyo-network/chain-api
104
+
105
+ [npm-downloads-badge]: https://img.shields.io/npm/dw/@xyo-network/chain-api
106
+ [npm-license-badge]: https://img.shields.io/npm/l/@xyo-network/chain-api
107
+
108
+ [jsdelivr-badge]: https://data.jsdelivr.com/v1/package/npm/@xyo-network/chain-api/badge
109
+ [jsdelivr-link]: https://www.jsdelivr.com/package/npm/@xyo-network/chain-api
110
+
111
+ [socket-badge]: https://socket.dev/api/badge/npm/package/@xyo-network/chain-api
112
+ [socket-link]: https://socket.dev/npm/package/@xyo-network/chain-api
@@ -0,0 +1,138 @@
1
+ import type { Attributes, Counter } from '@opentelemetry/api';
2
+ import type { CreatableName } from '@xylabs/sdk-js';
3
+ import { AccountInstance } from '@xyo-network/account-model';
4
+ import { Actor, type ActorParams } from '@xyo-network/chain-orchestration';
5
+ import type { ChainId, ChainStakeIntent, HydratedBlockWithHashMeta, XL1BlockNumber } from '@xyo-network/xl1-protocol';
6
+ import { AccountBalanceViewer, BlockProducerService, BlockRewardViewer, BlockViewer, Config, MempoolRunner, MempoolViewer, StakeTotalsViewer, TimeSyncViewer } from '@xyo-network/xl1-protocol-sdk';
7
+ export type ProducerActorParams = ActorParams<{
8
+ account: AccountInstance;
9
+ blockRewardViewer: BlockRewardViewer;
10
+ chainId: ChainId;
11
+ config: Config;
12
+ runners: {
13
+ mempoolRunner: MempoolRunner;
14
+ };
15
+ viewers: {
16
+ accountBalanceViewer: AccountBalanceViewer;
17
+ blockViewer: BlockViewer;
18
+ mempoolViewer: MempoolViewer;
19
+ stakeTotalsViewer: StakeTotalsViewer;
20
+ time: TimeSyncViewer;
21
+ };
22
+ }>;
23
+ export declare class ProducerActor extends Actor<ProducerActorParams> {
24
+ protected _lastProducedBlock: HydratedBlockWithHashMeta | undefined;
25
+ protected _lastRedeclarationIntent: ChainStakeIntent | undefined;
26
+ protected _metricAttributes: Attributes | undefined;
27
+ protected _producerActorBlockProductionAttempts: Counter<Attributes> | undefined;
28
+ protected _producerActorBlockProductionChecks: Counter<Attributes> | undefined;
29
+ protected _producerActorBlocksProduced: Counter<Attributes> | undefined;
30
+ protected _producerActorBlocksPublished: Counter<Attributes> | undefined;
31
+ private _produceBlockMutex;
32
+ private _producer;
33
+ protected get account(): AccountInstance;
34
+ protected get accountBalanceViewer(): AccountBalanceViewer;
35
+ protected get blockViewer(): BlockViewer;
36
+ protected get chainId(): import("@xylabs/sdk-js").Hex;
37
+ protected get config(): {
38
+ api: {
39
+ host: string;
40
+ initRewardsCache: boolean;
41
+ port: number;
42
+ mnemonic?: string | undefined;
43
+ };
44
+ bridge: {
45
+ host: string;
46
+ port: number;
47
+ mnemonic?: string | undefined;
48
+ };
49
+ chain: {
50
+ id?: string | undefined;
51
+ genesisRewardAddress?: import("@xylabs/sdk-js").Address | undefined;
52
+ };
53
+ evm: {
54
+ chainId?: string | undefined;
55
+ infura?: {
56
+ projectId?: string | undefined;
57
+ projectSecret?: string | undefined;
58
+ } | undefined;
59
+ jsonRpc?: {
60
+ url?: string | undefined;
61
+ } | undefined;
62
+ };
63
+ mempool: {
64
+ enabled: boolean;
65
+ host: string;
66
+ port: number;
67
+ mnemonic?: string | undefined;
68
+ };
69
+ producer: {
70
+ heartbeatInterval: number;
71
+ minStake: number;
72
+ port: number;
73
+ allowlist?: import("@xylabs/sdk-js").Address[] | undefined;
74
+ disableIntentRedeclaration?: boolean | undefined;
75
+ healthCheckPort?: number | undefined;
76
+ mnemonic?: string | undefined;
77
+ rewardAddress?: string | undefined;
78
+ };
79
+ rewardRedemptionApi: {
80
+ chainRpcApiUrl: string;
81
+ host: string;
82
+ port: number;
83
+ mnemonic?: string | undefined;
84
+ };
85
+ services: {
86
+ accountBalanceViewerEndpoint?: string | undefined;
87
+ apiEndpoint?: string | undefined;
88
+ };
89
+ storage: {
90
+ mongo?: {
91
+ connectionString?: string | undefined;
92
+ database?: string | undefined;
93
+ domain?: string | undefined;
94
+ password?: string | undefined;
95
+ username?: string | undefined;
96
+ } | undefined;
97
+ root?: string | undefined;
98
+ };
99
+ telemetry: {
100
+ metrics?: {
101
+ scrape: {
102
+ path: string;
103
+ port: number;
104
+ };
105
+ } | undefined;
106
+ otel?: {
107
+ otlpEndpoint?: string | undefined;
108
+ } | undefined;
109
+ };
110
+ validation: {
111
+ allowedRewardRedeemers?: import("@xylabs/sdk-js").Address[] | undefined;
112
+ allowedRewardEscrowAccountSigners?: import("@xylabs/sdk-js").Address[] | undefined;
113
+ };
114
+ logLevel: "info" | "warn" | "error" | "log" | "debug" | "trace";
115
+ silent: boolean;
116
+ };
117
+ protected get mempoolRunner(): MempoolRunner;
118
+ protected get mempoolViewer(): MempoolViewer;
119
+ protected get producer(): BlockProducerService;
120
+ protected get stakeTotalsViewer(): StakeTotalsViewer;
121
+ static paramsHandler<T extends ActorParams>(params?: Partial<T>): Promise<{
122
+ displayName: CreatableName | NonNullable<T["displayName"]> | undefined;
123
+ id: CreatableName | T["id"] | undefined;
124
+ logger: import("@xylabs/sdk-js").Logger;
125
+ name?: import("@xylabs/sdk-js").CreatableName;
126
+ statusReporter?: import("@xylabs/sdk-js").CreatableStatusReporter<void> | undefined;
127
+ meterProvider?: import("@opentelemetry/api").MeterProvider;
128
+ traceProvider?: import("@opentelemetry/api").TracerProvider;
129
+ }>;
130
+ createHandler(): Promise<void>;
131
+ startHandler(): Promise<void>;
132
+ protected produceBlock(): Promise<void>;
133
+ protected redeclareIntent(): Promise<void>;
134
+ protected submitRedeclarationIntent(currentBlock: XL1BlockNumber, redeclarationIntent: ChainStakeIntent): Promise<void>;
135
+ protected validateCurrentBalance(): Promise<boolean>;
136
+ protected validateCurrentStake(): Promise<boolean>;
137
+ }
138
+ //# sourceMappingURL=ProducerActor.d.ts.map
@@ -0,0 +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,aAAa,EAAE,MAAM,gBAAgB,CAAA;AAMnD,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAA;AAC5D,OAAO,EAAE,KAAK,EAAE,KAAK,WAAW,EAAE,MAAM,kCAAkC,CAAA;AAG1E,OAAO,KAAK,EACV,OAAO,EACP,gBAAgB,EAAE,yBAAyB,EAC3C,cAAc,EACf,MAAM,2BAA2B,CAAA;AAElC,OAAO,EACL,oBAAoB,EACpB,oBAAoB,EAAE,iBAAiB,EAAE,WAAW,EACpD,MAAM,EACN,aAAa,EACb,aAAa,EACb,iBAAiB,EACjB,cAAc,EACf,MAAM,+BAA+B,CAAA;AAGtC,MAAM,MAAM,mBAAmB,GAAG,WAAW,CAAC;IAC5C,OAAO,EAAE,eAAe,CAAA;IACxB,iBAAiB,EAAE,iBAAiB,CAAA;IACpC,OAAO,EAAE,OAAO,CAAA;IAChB,MAAM,EAAE,MAAM,CAAA;IACd,OAAO,EAAE;QACP,aAAa,EAAE,aAAa,CAAA;KAC7B,CAAA;IACD,OAAO,EAAE;QACP,oBAAoB,EAAE,oBAAoB,CAAA;QAC1C,WAAW,EAAE,WAAW,CAAA;QACxB,aAAa,EAAE,aAAa,CAAA;QAC5B,iBAAiB,EAAE,iBAAiB,CAAA;QACpC,IAAI,EAAE,cAAc,CAAA;KACrB,CAAA;CACF,CAAC,CAAA;AAKF,qBACa,aAAc,SAAQ,KAAK,CAAC,mBAAmB,CAAC;IAC3D,SAAS,CAAC,kBAAkB,EAAE,yBAAyB,GAAG,SAAS,CAAA;IACnE,SAAS,CA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C,OAAO,CAAC;CAWzD"}
@@ -0,0 +1,3 @@
1
+ export * from './ProducerActor.ts';
2
+ export * from './runProducer.ts';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,oBAAoB,CAAA;AAClC,cAAc,kBAAkB,CAAA"}
@@ -0,0 +1,302 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/ProducerActor.ts
5
+ import { asAddress, creatable, isDefined, isUndefined, toHex, ZERO_ADDRESS } from "@xylabs/sdk-js";
6
+ import { Actor } from "@xyo-network/chain-orchestration";
7
+ import { createDeclarationIntent } from "@xyo-network/chain-protocol";
8
+ import { SimpleBlockRunner } from "@xyo-network/chain-services";
9
+ import { asXL1BlockNumber } from "@xyo-network/xl1-protocol";
10
+ import { buildTransaction } from "@xyo-network/xl1-protocol-sdk";
11
+ import { Mutex } from "async-mutex";
12
+ function _ts_decorate(decorators, target, key, desc) {
13
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
15
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
16
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
17
+ }
18
+ __name(_ts_decorate, "_ts_decorate");
19
+ var SHOULD_REGISTER_REDECLARATION_INTENT_TIMER = true;
20
+ var TEN_MINUTES = 10 * 60 * 1e3;
21
+ var ProducerActor = class extends Actor {
22
+ static {
23
+ __name(this, "ProducerActor");
24
+ }
25
+ _lastProducedBlock;
26
+ _lastRedeclarationIntent;
27
+ _metricAttributes;
28
+ _producerActorBlockProductionAttempts;
29
+ _producerActorBlockProductionChecks;
30
+ _producerActorBlocksProduced;
31
+ _producerActorBlocksPublished;
32
+ _produceBlockMutex = new Mutex();
33
+ _producer;
34
+ get account() {
35
+ return this.params.account;
36
+ }
37
+ get accountBalanceViewer() {
38
+ return this.params.viewers.accountBalanceViewer;
39
+ }
40
+ get blockViewer() {
41
+ return this.params.viewers.blockViewer;
42
+ }
43
+ get chainId() {
44
+ return this.params.chainId;
45
+ }
46
+ get config() {
47
+ return this.params.config;
48
+ }
49
+ get mempoolRunner() {
50
+ return this.params.runners.mempoolRunner;
51
+ }
52
+ get mempoolViewer() {
53
+ return this.params.viewers.mempoolViewer;
54
+ }
55
+ get producer() {
56
+ return this._producer;
57
+ }
58
+ get stakeTotalsViewer() {
59
+ return this.params.viewers.stakeTotalsViewer;
60
+ }
61
+ static async paramsHandler(params) {
62
+ return await super.paramsHandler({
63
+ ...params,
64
+ name: params?.name ?? "Producer"
65
+ });
66
+ }
67
+ async createHandler() {
68
+ await super.createHandler();
69
+ this._metricAttributes = {
70
+ address: this.account.address.toString()
71
+ };
72
+ this._producerActorBlockProductionChecks = this.meter?.createCounter("producer_actor_block_production_checks", {
73
+ description: "Number of block production checks"
74
+ });
75
+ this._producerActorBlockProductionAttempts = this.meter?.createCounter("producer_actor_block_production_attempts", {
76
+ description: "Number of block production attempts"
77
+ });
78
+ this._producerActorBlocksProduced = this.meter?.createCounter("producer_actor_blocks_produced", {
79
+ description: "Number of blocks produced"
80
+ });
81
+ this._producerActorBlocksPublished = this.meter?.createCounter("producer_actor_blocks_published", {
82
+ description: "Number of blocks published"
83
+ });
84
+ const params = {
85
+ account: this.account,
86
+ balanceViewer: this.accountBalanceViewer,
87
+ config: this.config,
88
+ chainId: this.chainId,
89
+ mempoolRunner: this.mempoolRunner,
90
+ mempoolViewer: this.mempoolViewer,
91
+ blockRewardViewer: this.params.blockRewardViewer,
92
+ rewardAddress: asAddress(this.config.producer.rewardAddress ?? ZERO_ADDRESS, () => `Producer config must have a valid reward address configured [${this.params.config.producer.rewardAddress}]`),
93
+ time: this.params.viewers.time
94
+ };
95
+ this._producer = await SimpleBlockRunner.create(params);
96
+ }
97
+ async startHandler() {
98
+ await super.startHandler();
99
+ this.registerTimer(
100
+ "BlockProductionTimer",
101
+ async () => {
102
+ await this.produceBlock();
103
+ },
104
+ 2e3,
105
+ 1500
106
+ /* 500 */
107
+ );
108
+ if (SHOULD_REGISTER_REDECLARATION_INTENT_TIMER) {
109
+ this.registerTimer("ProducerRedeclarationTimer", async () => {
110
+ await this.redeclareIntent();
111
+ }, TEN_MINUTES, TEN_MINUTES);
112
+ }
113
+ }
114
+ // protected async calculateBlocksUntilProducerDeclarationExpiration(currentBlock: number): Promise<number> {
115
+ // // Decide if we need to redeclare intent
116
+ // const ranges = await this.stakeIntentService.getDeclaredCandidateRanges(this.account.address, 'producer')
117
+ // // TODO: This doesn't handle the case where the producer had declared a range for the future
118
+ // // but we're in a range that's not the future
119
+ // // Sort in ascending order based on ending range to get range with highest ending block
120
+ // const lastRange = ranges.toSorted((a, b) => a[1] > b[1] ? 1 : -1).at(-1)
121
+ // // Use the most recent range's end block as the current declaration end OR
122
+ // const [, currentDeclarationEnd] = lastRange
123
+ // // If we have no ranges, we need to declare intent, so use the current block
124
+ // ?? [undefined, currentBlock]
125
+ // // Calculate the time until the producer's declaration expires
126
+ // const timeToProducerExpiration = currentDeclarationEnd - currentBlock
127
+ // return timeToProducerExpiration
128
+ // }
129
+ async produceBlock() {
130
+ this._producerActorBlockProductionChecks?.add(1, this._metricAttributes);
131
+ await this.spanAsync("produceBlock", async () => {
132
+ if (this._produceBlockMutex.isLocked()) {
133
+ this.logger?.log("Skipping block production, previous production still in progress");
134
+ return;
135
+ }
136
+ await this._produceBlockMutex.runExclusive(async () => {
137
+ const headStart = Date.now();
138
+ const head = (await this.blockViewer.currentBlock())[0];
139
+ const headDuration = Date.now() - headStart;
140
+ if (headDuration > 500) this.logger?.warn(`[Slow] Fetched head in ${headDuration}ms: 0x${toHex(head._hash)}`);
141
+ const headHash = head._hash;
142
+ if (this._lastProducedBlock && this._lastProducedBlock[0].previous === headHash) {
143
+ this.logger?.log("Block already produced:", `0x${toHex(this._lastProducedBlock[0].block)}`, this._lastProducedBlock[0].block);
144
+ } else {
145
+ this._producerActorBlockProductionAttempts?.add(1, this._metricAttributes);
146
+ const nextStart = Date.now();
147
+ const nextBlock = await this.producer.next(head);
148
+ const nextDuration = Date.now() - nextStart;
149
+ if (nextDuration > 1e3) this.logger?.warn(`[Slow] Generated next block in ${nextDuration}ms, block: ${nextBlock?.[0]._hash}`);
150
+ if (nextBlock) {
151
+ const displayBlockNumber = `0x${toHex(nextBlock[0].block)}`;
152
+ this.logger?.log("Produced block:", displayBlockNumber);
153
+ this._producerActorBlocksProduced?.add(1, this._metricAttributes);
154
+ await this.mempoolRunner.submitBlocks([
155
+ nextBlock
156
+ ]);
157
+ this.logger?.log("Published block:", displayBlockNumber, nextBlock[0].block);
158
+ this._producerActorBlocksPublished?.add(1, this._metricAttributes);
159
+ this._lastProducedBlock = nextBlock;
160
+ }
161
+ }
162
+ });
163
+ });
164
+ }
165
+ async redeclareIntent() {
166
+ await this.spanAsync("redeclareIntent", async () => {
167
+ if (this.params.config.producer.disableIntentRedeclaration) return;
168
+ const head = (await this.blockViewer.currentBlock())[0];
169
+ if (isUndefined(head)) return;
170
+ const currentBlock = head.block;
171
+ if (this._lastRedeclarationIntent) {
172
+ if (this._lastRedeclarationIntent.exp > currentBlock) return;
173
+ this._lastRedeclarationIntent = void 0;
174
+ }
175
+ if (!await this.validateCurrentBalance()) {
176
+ this.logger?.error(`Add balance to address ${this.account.address} for the producer to declare it's intent.`);
177
+ return;
178
+ }
179
+ if (!await this.validateCurrentStake()) {
180
+ this.logger?.error(`Add stake to contract address ${this.params.config.chain.id} for the producer to declare it's intent.`);
181
+ return;
182
+ }
183
+ this.logger?.log("Creating redeclaration intent for producer:", this.account.address);
184
+ const redeclarationIntent = createDeclarationIntent(this.account.address, "producer", currentBlock, currentBlock + SimpleBlockRunner.RedeclarationDuration);
185
+ await this.submitRedeclarationIntent(currentBlock, redeclarationIntent);
186
+ this._lastRedeclarationIntent = redeclarationIntent;
187
+ });
188
+ }
189
+ async submitRedeclarationIntent(currentBlock, redeclarationIntent) {
190
+ this.logger?.log("Submitting redeclaration intent for producer:", this.account.address);
191
+ const tx = await buildTransaction(this.chainId, [
192
+ redeclarationIntent
193
+ ], [], this.account, currentBlock, asXL1BlockNumber(currentBlock + 1e3, true));
194
+ await this.mempoolRunner.submitTransactions([
195
+ tx
196
+ ]);
197
+ this.logger?.log("Submitted redeclaration intent for producer:", this.account.address);
198
+ }
199
+ async validateCurrentBalance() {
200
+ const head = this._lastProducedBlock?.[0]._hash;
201
+ if (isDefined(head)) {
202
+ const balances = await this.accountBalanceViewer.accountBalances([
203
+ this.account.address
204
+ ], head);
205
+ const currentBalance = balances[this.account.address] ?? 0n;
206
+ if (currentBalance <= 0n) {
207
+ this.logger?.error(`Producer ${this.account.address} has no balance.`);
208
+ return false;
209
+ }
210
+ return true;
211
+ }
212
+ return true;
213
+ }
214
+ async validateCurrentStake() {
215
+ const requiredMinimumStake = 1n;
216
+ const currentStake = await this.stakeTotalsViewer.activeByStaked(this.account.address);
217
+ if (currentStake < requiredMinimumStake) {
218
+ this.logger?.error(`Producer ${this.account.address} has insufficient stake.`);
219
+ return false;
220
+ }
221
+ return true;
222
+ }
223
+ };
224
+ ProducerActor = _ts_decorate([
225
+ creatable()
226
+ ], ProducerActor);
227
+
228
+ // src/runProducer.ts
229
+ import { assertEx, exists } from "@xylabs/sdk-js";
230
+ import { initProducerAccount } from "@xyo-network/chain-orchestration";
231
+ import { initBlockRewardViewer, initChainService, initTimeService } from "@xyo-network/chain-services";
232
+ import { AccountBalanceViewerRpcSchemas, BlockViewerRpcSchemas, HttpRpcTransport, JsonRpcAccountBalanceViewer, JsonRpcBlockViewer, JsonRpcMempoolRunner, JsonRpcMempoolViewer, JsonRpcStakeTotalsViewer, MempoolRunnerRpcSchemas, MempoolViewerRpcSchemas, StakeTotalsViewerRpcSchemas } from "@xyo-network/xl1-rpc";
233
+ var runProducer = /* @__PURE__ */ __name(async (context) => {
234
+ const { config, logger, orchestrator } = context;
235
+ const endpoint = assertEx(config.services?.apiEndpoint, () => "No API endpoint configured");
236
+ const account = await initProducerAccount({
237
+ config,
238
+ logger
239
+ });
240
+ const accountBalanceViewer = new JsonRpcAccountBalanceViewer(new HttpRpcTransport(endpoint, {
241
+ ...AccountBalanceViewerRpcSchemas
242
+ }));
243
+ const blockViewer = new JsonRpcBlockViewer(new HttpRpcTransport(endpoint, {
244
+ ...BlockViewerRpcSchemas
245
+ }));
246
+ const stakeTotalsViewer = new JsonRpcStakeTotalsViewer(new HttpRpcTransport(endpoint, {
247
+ ...StakeTotalsViewerRpcSchemas
248
+ }));
249
+ const chainId = (await blockViewer.currentBlock())[0].chain;
250
+ const mempoolViewer = new JsonRpcMempoolViewer(new HttpRpcTransport(endpoint, {
251
+ ...MempoolViewerRpcSchemas
252
+ }));
253
+ const mempoolRunner = new JsonRpcMempoolRunner(new HttpRpcTransport(endpoint, {
254
+ ...MempoolRunnerRpcSchemas
255
+ }));
256
+ const chainContractViewer = await initChainService({
257
+ account,
258
+ config,
259
+ logger
260
+ });
261
+ const blockRewardViewer = await initBlockRewardViewer({
262
+ config,
263
+ logger,
264
+ chainContractViewer
265
+ });
266
+ const timeSyncViewer = await initTimeService({
267
+ config,
268
+ logger,
269
+ blockViewer
270
+ });
271
+ const params = {
272
+ account,
273
+ id: "ProducerActor",
274
+ chainId,
275
+ config,
276
+ viewers: {
277
+ accountBalanceViewer,
278
+ blockViewer,
279
+ stakeTotalsViewer,
280
+ mempoolViewer,
281
+ time: timeSyncViewer
282
+ },
283
+ blockRewardViewer,
284
+ runners: {
285
+ mempoolRunner
286
+ },
287
+ logger
288
+ };
289
+ const producer = await ProducerActor.create(params);
290
+ const actors = [
291
+ producer
292
+ ].filter(exists);
293
+ for (const actor of actors) {
294
+ await orchestrator.registerActor(actor);
295
+ }
296
+ await orchestrator.start();
297
+ }, "runProducer");
298
+ export {
299
+ ProducerActor,
300
+ runProducer
301
+ };
302
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/ProducerActor.ts","../../src/runProducer.ts"],"sourcesContent":["import type { Attributes, Counter } from '@opentelemetry/api'\nimport type { CreatableName } from '@xylabs/sdk-js'\nimport {\n asAddress,\n creatable, isDefined, isUndefined, toHex,\n ZERO_ADDRESS,\n} from '@xylabs/sdk-js'\nimport { AccountInstance } from '@xyo-network/account-model'\nimport { Actor, type ActorParams } from '@xyo-network/chain-orchestration'\nimport { createDeclarationIntent } from '@xyo-network/chain-protocol'\nimport { SimpleBlockRunner, SimpleBlockRunnerParams } from '@xyo-network/chain-services'\nimport type {\n ChainId,\n ChainStakeIntent, HydratedBlockWithHashMeta,\n XL1BlockNumber,\n} from '@xyo-network/xl1-protocol'\nimport { asXL1BlockNumber } from '@xyo-network/xl1-protocol'\nimport {\n AccountBalanceViewer,\n BlockProducerService, BlockRewardViewer, BlockViewer, buildTransaction,\n Config,\n MempoolRunner,\n MempoolViewer,\n StakeTotalsViewer,\n TimeSyncViewer,\n} from '@xyo-network/xl1-protocol-sdk'\nimport { Mutex } from 'async-mutex'\n\nexport type ProducerActorParams = ActorParams<{\n account: AccountInstance\n blockRewardViewer: BlockRewardViewer\n chainId: ChainId\n config: Config\n runners: {\n mempoolRunner: MempoolRunner\n }\n viewers: {\n accountBalanceViewer: AccountBalanceViewer\n blockViewer: BlockViewer\n mempoolViewer: MempoolViewer\n stakeTotalsViewer: StakeTotalsViewer\n time: TimeSyncViewer\n }\n}>\n\nconst SHOULD_REGISTER_REDECLARATION_INTENT_TIMER = true\nconst TEN_MINUTES = 10 * 60 * 1000 // 10 minutes in milliseconds\n\n@creatable()\nexport class ProducerActor extends Actor<ProducerActorParams> {\n protected _lastProducedBlock: HydratedBlockWithHashMeta | undefined\n protected _lastRedeclarationIntent: ChainStakeIntent | undefined\n protected _metricAttributes: Attributes | undefined\n protected _producerActorBlockProductionAttempts: Counter<Attributes> | undefined\n protected _producerActorBlockProductionChecks: Counter<Attributes> | undefined\n protected _producerActorBlocksProduced: Counter<Attributes> | undefined\n protected _producerActorBlocksPublished: Counter<Attributes> | undefined\n\n private _produceBlockMutex = new Mutex()\n private _producer: BlockProducerService | undefined\n\n protected get account() {\n return this.params.account!\n }\n\n protected get accountBalanceViewer() {\n return this.params.viewers.accountBalanceViewer!\n }\n\n protected get blockViewer() {\n return this.params.viewers.blockViewer!\n }\n\n protected get chainId() {\n return this.params.chainId!\n }\n\n protected get config() {\n return this.params.config!\n }\n\n protected get mempoolRunner() {\n return this.params.runners.mempoolRunner!\n }\n\n protected get mempoolViewer() {\n return this.params.viewers.mempoolViewer!\n }\n\n protected get producer() {\n return this._producer!\n }\n\n protected get stakeTotalsViewer() {\n return this.params.viewers.stakeTotalsViewer!\n }\n\n static override async paramsHandler<T extends ActorParams>(params?: Partial<T>) {\n return await super.paramsHandler({ ...params, name: (params?.name ?? 'Producer') as CreatableName })\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 params = {\n account: this.account,\n balanceViewer: this.accountBalanceViewer,\n config: this.config,\n chainId: this.chainId,\n mempoolRunner: this.mempoolRunner,\n mempoolViewer: this.mempoolViewer,\n blockRewardViewer: this.params.blockRewardViewer!,\n rewardAddress: asAddress(\n this.config.producer.rewardAddress ?? ZERO_ADDRESS,\n () => `Producer config must have a valid reward address configured [${this.params.config.producer.rewardAddress}]`,\n ),\n time: this.params.viewers.time!,\n } satisfies SimpleBlockRunnerParams\n this._producer = await SimpleBlockRunner.create(params)\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, 1500/* 500 */)\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 async calculateBlocksUntilProducerDeclarationExpiration(currentBlock: number): Promise<number> {\n // // Decide if we need to redeclare intent\n // const ranges = await this.stakeIntentService.getDeclaredCandidateRanges(this.account.address, 'producer')\n // // TODO: This doesn't handle the case where the producer had declared a range for the future\n // // but we're in a range that's not the future\n // // Sort in ascending order based on ending range to get range with highest ending block\n // const lastRange = ranges.toSorted((a, b) => a[1] > b[1] ? 1 : -1).at(-1)\n\n // // Use the most recent range's end block as the current declaration end OR\n // const [, currentDeclarationEnd] = lastRange\n // // If we have no ranges, we need to declare intent, so use the current block\n // ?? [undefined, currentBlock]\n\n // // Calculate the time until the producer's declaration expires\n // const timeToProducerExpiration = currentDeclarationEnd - currentBlock\n // return timeToProducerExpiration\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 await this._produceBlockMutex.runExclusive(async () => {\n // Get the updated head\n const headStart = Date.now()\n const head = (await this.blockViewer.currentBlock())[0]\n const headDuration = Date.now() - headStart\n if (headDuration > 500) this.logger?.warn(`[Slow] Fetched head in ${headDuration}ms: 0x${toHex(head._hash)}`)\n // Check if we've already produced the next block for this head\n const headHash = head._hash\n // If our last produced block was the next block for the current head, we do not\n // need to produce another. This prevents duplicate blocks from being produced\n if (this._lastProducedBlock && this._lastProducedBlock[0].previous === headHash) {\n this.logger?.log('Block already produced:', `0x${toHex(this._lastProducedBlock[0].block)}`, this._lastProducedBlock[0].block)\n } else {\n this._producerActorBlockProductionAttempts?.add(1, this._metricAttributes)\n // Produce the next block\n const nextStart = Date.now()\n const nextBlock = await this.producer.next(head)\n const nextDuration = Date.now() - nextStart\n if (nextDuration > 1000) this.logger?.warn(`[Slow] Generated next block in ${nextDuration}ms, block: ${nextBlock?.[0]._hash}`)\n // If it was produced\n if (nextBlock) {\n const displayBlockNumber = `0x${toHex(nextBlock[0].block)}`\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, nextBlock[0].block)\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 }\n }\n })\n })\n }\n\n protected async redeclareIntent(): Promise<void> {\n await this.spanAsync('redeclareIntent', async () => {\n // Decide if we should redeclare intent\n if (this.params.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 = await 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 > BaseBlockProducerService.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.params.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 })\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 = this._lastProducedBlock?.[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 assertEx, exists, type Logger,\n} from '@xylabs/sdk-js'\nimport {\n initProducerAccount, initStakeViewer, type OrchestratorInstance,\n} from '@xyo-network/chain-orchestration'\nimport {\n initBlockRewardViewer, initChainService, initTimeService,\n} from '@xyo-network/chain-services'\nimport { type Config } from '@xyo-network/xl1-protocol-sdk'\nimport {\n AccountBalanceViewerRpcSchemas, BlockViewerRpcSchemas, HttpRpcTransport, JsonRpcAccountBalanceViewer,\n JsonRpcBlockViewer,\n JsonRpcMempoolRunner,\n JsonRpcMempoolViewer,\n JsonRpcStakeTotalsViewer,\n MempoolRunnerRpcSchemas,\n MempoolViewerRpcSchemas,\n StakeTotalsViewerRpcSchemas,\n} from '@xyo-network/xl1-rpc'\n\nimport { ProducerActor, type ProducerActorParams } from './ProducerActor.ts'\n\ninterface RunProducerContext {\n config: Config\n logger: Logger\n orchestrator: OrchestratorInstance\n}\n\nexport const runProducer = async (context: RunProducerContext) => {\n const {\n config, logger, orchestrator,\n } = context\n\n const endpoint = assertEx(config.services?.apiEndpoint, () => 'No API endpoint configured')\n const account = await initProducerAccount({ config, logger })\n const accountBalanceViewer = new JsonRpcAccountBalanceViewer(new HttpRpcTransport(endpoint, { ...AccountBalanceViewerRpcSchemas }))\n const blockViewer = new JsonRpcBlockViewer(new HttpRpcTransport(endpoint, { ...BlockViewerRpcSchemas }))\n const stakeTotalsViewer = new JsonRpcStakeTotalsViewer(new HttpRpcTransport(endpoint, { ...StakeTotalsViewerRpcSchemas }))\n const chainId = (await blockViewer.currentBlock())[0].chain\n const mempoolViewer = new JsonRpcMempoolViewer(new HttpRpcTransport(endpoint, { ...MempoolViewerRpcSchemas }))\n const mempoolRunner = new JsonRpcMempoolRunner(new HttpRpcTransport(endpoint, { ...MempoolRunnerRpcSchemas }))\n const chainContractViewer = await initChainService({\n account, config, logger,\n })\n const blockRewardViewer = await initBlockRewardViewer({\n config, logger, chainContractViewer,\n })\n const timeSyncViewer = await initTimeService({\n config, logger, blockViewer,\n })\n\n // Create actors\n const params = {\n account,\n id: 'ProducerActor',\n chainId,\n config,\n viewers: {\n accountBalanceViewer,\n blockViewer,\n stakeTotalsViewer,\n mempoolViewer,\n time: timeSyncViewer,\n },\n blockRewardViewer,\n runners: { mempoolRunner },\n logger,\n } satisfies ProducerActorParams\n // const apiEndpoint = config.services.apiEndpoint\n // const balances = isDefined(apiEndpoint) ? undefined : await BalanceActor.create(params)\n const producer = await ProducerActor.create(params)\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,WACAC,WAAWC,WAAWC,aAAaC,OACnCC,oBACK;AAEP,SAASC,aAA+B;AACxC,SAASC,+BAA+B;AACxC,SAASC,yBAAkD;AAM3D,SAASC,wBAAwB;AACjC,SAEwDC,wBAMjD;AACP,SAASC,aAAa;;;;;;;;AAmBtB,IAAMC,6CAA6C;AACnD,IAAMC,cAAc,KAAK,KAAK;AAGvB,IAAMC,gBAAN,cAA4BC,MAAAA;SAAAA;;;EACvBC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EAEFC,qBAAqB,IAAIC,MAAAA;EACzBC;EAER,IAAcC,UAAU;AACtB,WAAO,KAAKC,OAAOD;EACrB;EAEA,IAAcE,uBAAuB;AACnC,WAAO,KAAKD,OAAOE,QAAQD;EAC7B;EAEA,IAAcE,cAAc;AAC1B,WAAO,KAAKH,OAAOE,QAAQC;EAC7B;EAEA,IAAcC,UAAU;AACtB,WAAO,KAAKJ,OAAOI;EACrB;EAEA,IAAcC,SAAS;AACrB,WAAO,KAAKL,OAAOK;EACr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AA;AAC5C,QAAMQ,SAAS;IAACH;IAAUI,OAAOC,MAAAA;AAEjC,aAAWC,SAASH,QAAQ;AAE1B,UAAMxC,aAAa4C,cAAcD,KAAAA;EACnC;AAEA,QAAM3C,aAAa6C,MAAK;AAC1B,GAnD2B;","names":["asAddress","creatable","isDefined","isUndefined","toHex","ZERO_ADDRESS","Actor","createDeclarationIntent","SimpleBlockRunner","asXL1BlockNumber","buildTransaction","Mutex","SHOULD_REGISTER_REDECLARATION_INTENT_TIMER","TEN_MINUTES","ProducerActor","Actor","_lastProducedBlock","_lastRedeclarationIntent","_metricAttributes","_producerActorBlockProductionAttempts","_producerActorBlockProductionChecks","_producerActorBlocksProduced","_producerActorBlocksPublished","_produceBlockMutex","Mutex","_producer","account","params","accountBalanceViewer","viewers","blockViewer","chainId","config","mempoolRunner","runners","mempoolViewer","producer","stakeTotalsViewer","paramsHandler","name","createHandler","address","toString","meter","createCounter","description","balanceViewer","blockRewardViewer","rewardAddress","asAddress","ZERO_ADDRESS","time","SimpleBlockRunner","create","startHandler","registerTimer","produceBlock","redeclareIntent","add","spanAsync","isLocked","logger","log","runExclusive","headStart","Date","now","head","currentBlock","headDuration","warn","toHex","_hash","headHash","previous","block","nextStart","nextBlock","next","nextDuration","displayBlockNumber","submitBlocks","disableIntentRedeclaration","isUndefined","exp","undefined","validateCurrentBalance","error","validateCurrentStake","chain","id","redeclarationIntent","createDeclarationIntent","RedeclarationDuration","submitRedeclarationIntent","tx","buildTransaction","asXL1BlockNumber","submitTransactions","isDefined","balances","accountBalances","currentBalance","requiredMinimumStake","currentStake","activeByStaked","assertEx","exists","initProducerAccount","initBlockRewardViewer","initChainService","initTimeService","AccountBalanceViewerRpcSchemas","BlockViewerRpcSchemas","HttpRpcTransport","JsonRpcAccountBalanceViewer","JsonRpcBlockViewer","JsonRpcMempoolRunner","JsonRpcMempoolViewer","JsonRpcStakeTotalsViewer","MempoolRunnerRpcSchemas","MempoolViewerRpcSchemas","StakeTotalsViewerRpcSchemas","runProducer","context","config","logger","orchestrator","endpoint","assertEx","services","apiEndpoint","account","initProducerAccount","accountBalanceViewer","JsonRpcAccountBalanceViewer","HttpRpcTransport","AccountBalanceViewerRpcSchemas","blockViewer","JsonRpcBlockViewer","BlockViewerRpcSchemas","stakeTotalsViewer","JsonRpcStakeTotalsViewer","StakeTotalsViewerRpcSchemas","chainId","currentBlock","chain","mempoolViewer","JsonRpcMempoolViewer","MempoolViewerRpcSchemas","mempoolRunner","JsonRpcMempoolRunner","MempoolRunnerRpcSchemas","chainContractViewer","initChainService","blockRewardViewer","initBlockRewardViewer","timeSyncViewer","initTimeService","params","id","viewers","time","runners","producer","ProducerActor","create","actors","filter","exists","actor","registerActor","start"]}
@@ -0,0 +1,11 @@
1
+ import { type Logger } from '@xylabs/sdk-js';
2
+ import { type OrchestratorInstance } from '@xyo-network/chain-orchestration';
3
+ import { type Config } from '@xyo-network/xl1-protocol-sdk';
4
+ interface RunProducerContext {
5
+ config: Config;
6
+ logger: Logger;
7
+ orchestrator: OrchestratorInstance;
8
+ }
9
+ export declare const runProducer: (context: RunProducerContext) => Promise<void>;
10
+ export {};
11
+ //# sourceMappingURL=runProducer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runProducer.d.ts","sourceRoot":"","sources":["../../src/runProducer.ts"],"names":[],"mappings":"AAAA,OAAO,EACa,KAAK,MAAM,EAC9B,MAAM,gBAAgB,CAAA;AACvB,OAAO,EACiC,KAAK,oBAAoB,EAChE,MAAM,kCAAkC,CAAA;AAIzC,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,+BAA+B,CAAA;AAc3D,UAAU,kBAAkB;IAC1B,MAAM,EAAE,MAAM,CAAA;IACd,MAAM,EAAE,MAAM,CAAA;IACd,YAAY,EAAE,oBAAoB,CAAA;CACnC;AAED,eAAO,MAAM,WAAW,GAAU,SAAS,kBAAkB,kBAmD5D,CAAA"}
package/package.json ADDED
@@ -0,0 +1,96 @@
1
+ {
2
+ "name": "@xyo-network/chain-producer",
3
+ "version": "1.17.1",
4
+ "description": "XYO Layer One Producer",
5
+ "homepage": "https://xylabs.com",
6
+ "bugs": {
7
+ "url": "git+https://github.com/xylabs/xyo-chain/issues",
8
+ "email": "support@xylabs.com"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/xylabs/xyo-chain.git"
13
+ },
14
+ "license": "LGPL-3.0-only",
15
+ "author": {
16
+ "name": "XY Labs Development Team",
17
+ "email": "support@xylabs.com",
18
+ "url": "https://xylabs.com"
19
+ },
20
+ "sideEffects": false,
21
+ "type": "module",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/node/index.d.ts",
25
+ "source": "./src/index.ts",
26
+ "default": "./dist/node/index.mjs"
27
+ },
28
+ "./package.json": "./package.json",
29
+ "./README.md": "./README.md"
30
+ },
31
+ "module": "./dist/node/index.mjs",
32
+ "source": "./src/index.ts",
33
+ "types": "./dist/node/index.d.ts",
34
+ "files": [
35
+ "dist",
36
+ "src",
37
+ "!**/*.bench.*",
38
+ "!**/*.spec.*",
39
+ "!**/*.test.*"
40
+ ],
41
+ "scripts": {
42
+ "build-tests": "tsc --noEmit --lib dom,esnext",
43
+ "deploy": "echo Deploy not allowed!",
44
+ "deploy3": "echo Deploy3 not allowed!",
45
+ "start": "nodemon",
46
+ "start-esm": "node ./dist/node/index.mjs",
47
+ "test": "vitest run",
48
+ "test:ci": "vitest run",
49
+ "types": "tsc --noEmit -p tsconfig.test.json"
50
+ },
51
+ "dependencies": {
52
+ "@xylabs/sdk-js": "~5.0.48",
53
+ "@xyo-network/chain-orchestration": "~1.17.1",
54
+ "@xyo-network/chain-protocol": "~1.17.1",
55
+ "@xyo-network/chain-services": "~1.17.1",
56
+ "@xyo-network/xl1-protocol": "~1.14.16",
57
+ "@xyo-network/xl1-protocol-sdk": "~1.17.1",
58
+ "@xyo-network/xl1-rpc": "~1.17.1",
59
+ "async-mutex": "~0.5.0"
60
+ },
61
+ "devDependencies": {
62
+ "@opentelemetry/api": "~1.9.0",
63
+ "@types/compression": "~1.8.1",
64
+ "@types/cors": "~2.8.19",
65
+ "@types/express": "5.0.6",
66
+ "@types/express-serve-static-core": "~5.1.0",
67
+ "@types/node": "~24.10.1",
68
+ "@xylabs/sdk-js": "~5.0.48",
69
+ "@xylabs/ts-scripts-yarn3": "~7.2.8",
70
+ "@xylabs/tsconfig": "~7.2.8",
71
+ "@xyo-network/account": "~5.2.13",
72
+ "@xyo-network/account-model": "~5.2.13",
73
+ "@xyo-network/archivist-abstract": "~5.2.13",
74
+ "@xyo-network/bios-model": "~7.2.0",
75
+ "@xyo-network/boundwitness-builder": "~5.2.13",
76
+ "@xyo-network/chain-services": "~1.17.1",
77
+ "@xyo-network/module-abstract-mongodb": "~5.2.13",
78
+ "@xyo-network/module-model-mongodb": "~5.2.13",
79
+ "@xyo-network/node-memory": "~5.2.13",
80
+ "@xyo-network/xl1-protocol": "~1.14.16",
81
+ "dotenv": "~17.2.3",
82
+ "eslint": "^9.39.1",
83
+ "nodemon": "~3.1.11",
84
+ "tslib": "~2.8.1",
85
+ "typescript": "~5.9.3",
86
+ "vitest": "~4.0.15",
87
+ "vitest-mock-extended": "~3.1.0"
88
+ },
89
+ "engines": {
90
+ "node": ">=22.3 <23"
91
+ },
92
+ "engineStrict": true,
93
+ "publishConfig": {
94
+ "access": "restricted"
95
+ }
96
+ }
@@ -0,0 +1,327 @@
1
+ import type { Attributes, Counter } from '@opentelemetry/api'
2
+ import type { CreatableName } from '@xylabs/sdk-js'
3
+ import {
4
+ asAddress,
5
+ creatable, isDefined, isUndefined, toHex,
6
+ ZERO_ADDRESS,
7
+ } from '@xylabs/sdk-js'
8
+ import { AccountInstance } from '@xyo-network/account-model'
9
+ import { Actor, type ActorParams } from '@xyo-network/chain-orchestration'
10
+ import { createDeclarationIntent } from '@xyo-network/chain-protocol'
11
+ import { SimpleBlockRunner, SimpleBlockRunnerParams } from '@xyo-network/chain-services'
12
+ import type {
13
+ ChainId,
14
+ ChainStakeIntent, HydratedBlockWithHashMeta,
15
+ XL1BlockNumber,
16
+ } from '@xyo-network/xl1-protocol'
17
+ import { asXL1BlockNumber } from '@xyo-network/xl1-protocol'
18
+ import {
19
+ AccountBalanceViewer,
20
+ BlockProducerService, BlockRewardViewer, BlockViewer, buildTransaction,
21
+ Config,
22
+ MempoolRunner,
23
+ MempoolViewer,
24
+ StakeTotalsViewer,
25
+ TimeSyncViewer,
26
+ } from '@xyo-network/xl1-protocol-sdk'
27
+ import { Mutex } from 'async-mutex'
28
+
29
+ export type ProducerActorParams = ActorParams<{
30
+ account: AccountInstance
31
+ blockRewardViewer: BlockRewardViewer
32
+ chainId: ChainId
33
+ config: Config
34
+ runners: {
35
+ mempoolRunner: MempoolRunner
36
+ }
37
+ viewers: {
38
+ accountBalanceViewer: AccountBalanceViewer
39
+ blockViewer: BlockViewer
40
+ mempoolViewer: MempoolViewer
41
+ stakeTotalsViewer: StakeTotalsViewer
42
+ time: TimeSyncViewer
43
+ }
44
+ }>
45
+
46
+ const SHOULD_REGISTER_REDECLARATION_INTENT_TIMER = true
47
+ const TEN_MINUTES = 10 * 60 * 1000 // 10 minutes in milliseconds
48
+
49
+ @creatable()
50
+ export class ProducerActor extends Actor<ProducerActorParams> {
51
+ protected _lastProducedBlock: HydratedBlockWithHashMeta | undefined
52
+ protected _lastRedeclarationIntent: ChainStakeIntent | undefined
53
+ protected _metricAttributes: Attributes | undefined
54
+ protected _producerActorBlockProductionAttempts: Counter<Attributes> | undefined
55
+ protected _producerActorBlockProductionChecks: Counter<Attributes> | undefined
56
+ protected _producerActorBlocksProduced: Counter<Attributes> | undefined
57
+ protected _producerActorBlocksPublished: Counter<Attributes> | undefined
58
+
59
+ private _produceBlockMutex = new Mutex()
60
+ private _producer: BlockProducerService | undefined
61
+
62
+ protected get account() {
63
+ return this.params.account!
64
+ }
65
+
66
+ protected get accountBalanceViewer() {
67
+ return this.params.viewers.accountBalanceViewer!
68
+ }
69
+
70
+ protected get blockViewer() {
71
+ return this.params.viewers.blockViewer!
72
+ }
73
+
74
+ protected get chainId() {
75
+ return this.params.chainId!
76
+ }
77
+
78
+ protected get config() {
79
+ return this.params.config!
80
+ }
81
+
82
+ protected get mempoolRunner() {
83
+ return this.params.runners.mempoolRunner!
84
+ }
85
+
86
+ protected get mempoolViewer() {
87
+ return this.params.viewers.mempoolViewer!
88
+ }
89
+
90
+ protected get producer() {
91
+ return this._producer!
92
+ }
93
+
94
+ protected get stakeTotalsViewer() {
95
+ return this.params.viewers.stakeTotalsViewer!
96
+ }
97
+
98
+ static override async paramsHandler<T extends ActorParams>(params?: Partial<T>) {
99
+ return await super.paramsHandler({ ...params, name: (params?.name ?? 'Producer') as CreatableName })
100
+ }
101
+
102
+ override async createHandler() {
103
+ await super.createHandler()
104
+ // Create the consistent meter attributes that will
105
+ // be included with all metrics from this actor
106
+ this._metricAttributes = { address: this.account.address.toString() }
107
+ // Create the metrics
108
+ this._producerActorBlockProductionChecks = this.meter?.createCounter(
109
+ 'producer_actor_block_production_checks',
110
+ { description: 'Number of block production checks' },
111
+ )
112
+ this._producerActorBlockProductionAttempts = this.meter?.createCounter(
113
+ 'producer_actor_block_production_attempts',
114
+ { description: 'Number of block production attempts' },
115
+ )
116
+ this._producerActorBlocksProduced = this.meter?.createCounter(
117
+ 'producer_actor_blocks_produced',
118
+ { description: 'Number of blocks produced' },
119
+ )
120
+ this._producerActorBlocksPublished = this.meter?.createCounter(
121
+ 'producer_actor_blocks_published',
122
+ { description: 'Number of blocks published' },
123
+ )
124
+ const params = {
125
+ account: this.account,
126
+ balanceViewer: this.accountBalanceViewer,
127
+ config: this.config,
128
+ chainId: this.chainId,
129
+ mempoolRunner: this.mempoolRunner,
130
+ mempoolViewer: this.mempoolViewer,
131
+ blockRewardViewer: this.params.blockRewardViewer!,
132
+ rewardAddress: asAddress(
133
+ this.config.producer.rewardAddress ?? ZERO_ADDRESS,
134
+ () => `Producer config must have a valid reward address configured [${this.params.config.producer.rewardAddress}]`,
135
+ ),
136
+ time: this.params.viewers.time!,
137
+ } satisfies SimpleBlockRunnerParams
138
+ this._producer = await SimpleBlockRunner.create(params)
139
+ }
140
+
141
+ override async startHandler() {
142
+ await super.startHandler()
143
+ // Register a timer to check if we should produce a block
144
+ this.registerTimer('BlockProductionTimer', async () => {
145
+ await this.produceBlock()
146
+ }, 2000, 1500/* 500 */)
147
+
148
+ if (SHOULD_REGISTER_REDECLARATION_INTENT_TIMER) {
149
+ // Register a timer to check if we should redeclare the producer
150
+ this.registerTimer('ProducerRedeclarationTimer', async () => {
151
+ await this.redeclareIntent()
152
+ }, TEN_MINUTES, TEN_MINUTES)
153
+ }
154
+ }
155
+
156
+ // protected async calculateBlocksUntilProducerDeclarationExpiration(currentBlock: number): Promise<number> {
157
+ // // Decide if we need to redeclare intent
158
+ // const ranges = await this.stakeIntentService.getDeclaredCandidateRanges(this.account.address, 'producer')
159
+ // // TODO: This doesn't handle the case where the producer had declared a range for the future
160
+ // // but we're in a range that's not the future
161
+ // // Sort in ascending order based on ending range to get range with highest ending block
162
+ // const lastRange = ranges.toSorted((a, b) => a[1] > b[1] ? 1 : -1).at(-1)
163
+
164
+ // // Use the most recent range's end block as the current declaration end OR
165
+ // const [, currentDeclarationEnd] = lastRange
166
+ // // If we have no ranges, we need to declare intent, so use the current block
167
+ // ?? [undefined, currentBlock]
168
+
169
+ // // Calculate the time until the producer's declaration expires
170
+ // const timeToProducerExpiration = currentDeclarationEnd - currentBlock
171
+ // return timeToProducerExpiration
172
+ // }
173
+
174
+ protected async produceBlock(): Promise<void> {
175
+ this._producerActorBlockProductionChecks?.add(1, this._metricAttributes)
176
+ await this.spanAsync('produceBlock', async () => {
177
+ if (this._produceBlockMutex.isLocked()) {
178
+ this.logger?.log('Skipping block production, previous production still in progress')
179
+ return
180
+ }
181
+
182
+ await this._produceBlockMutex.runExclusive(async () => {
183
+ // Get the updated head
184
+ const headStart = Date.now()
185
+ const head = (await this.blockViewer.currentBlock())[0]
186
+ const headDuration = Date.now() - headStart
187
+ if (headDuration > 500) this.logger?.warn(`[Slow] Fetched head in ${headDuration}ms: 0x${toHex(head._hash)}`)
188
+ // Check if we've already produced the next block for this head
189
+ const headHash = head._hash
190
+ // If our last produced block was the next block for the current head, we do not
191
+ // need to produce another. This prevents duplicate blocks from being produced
192
+ if (this._lastProducedBlock && this._lastProducedBlock[0].previous === headHash) {
193
+ this.logger?.log('Block already produced:', `0x${toHex(this._lastProducedBlock[0].block)}`, this._lastProducedBlock[0].block)
194
+ } else {
195
+ this._producerActorBlockProductionAttempts?.add(1, this._metricAttributes)
196
+ // Produce the next block
197
+ const nextStart = Date.now()
198
+ const nextBlock = await this.producer.next(head)
199
+ const nextDuration = Date.now() - nextStart
200
+ if (nextDuration > 1000) this.logger?.warn(`[Slow] Generated next block in ${nextDuration}ms, block: ${nextBlock?.[0]._hash}`)
201
+ // If it was produced
202
+ if (nextBlock) {
203
+ const displayBlockNumber = `0x${toHex(nextBlock[0].block)}`
204
+ this.logger?.log('Produced block:', displayBlockNumber)
205
+ this._producerActorBlocksProduced?.add(1, this._metricAttributes)
206
+ // Insert the block into the chain
207
+ await this.mempoolRunner.submitBlocks([nextBlock])
208
+ this.logger?.log('Published block:', displayBlockNumber, nextBlock[0].block)
209
+ this._producerActorBlocksPublished?.add(1, this._metricAttributes)
210
+ // Record that we have produced a block so we do not produce it again
211
+ this._lastProducedBlock = nextBlock
212
+ }
213
+ }
214
+ })
215
+ })
216
+ }
217
+
218
+ protected async redeclareIntent(): Promise<void> {
219
+ await this.spanAsync('redeclareIntent', async () => {
220
+ // Decide if we should redeclare intent
221
+ if (this.params.config.producer.disableIntentRedeclaration) return
222
+
223
+ // Get the current block
224
+ const head = (await this.blockViewer.currentBlock())[0]
225
+ if (isUndefined(head)) return
226
+ const currentBlock = head.block
227
+
228
+ // // Calculate the time until the producer's declaration expires
229
+ // const blocksUntilExpiration = await this.calculateBlocksUntilProducerDeclarationExpiration(currentBlock)
230
+
231
+ // // Allow the producer time to redeclare itself via block production
232
+ // // (for free) before submitting a redeclaration intent transaction.
233
+ // if (blocksUntilExpiration > BaseBlockProducerService.RedeclarationWindow * 0.1) {
234
+ // // Clear any previous redeclaration intent
235
+ // this._lastRedeclarationIntent = undefined
236
+ // // No need to redeclare yet
237
+ // return
238
+ // }
239
+
240
+ // If we already have a valid redeclaration intent, do not create another
241
+ // unless it has expired.
242
+ if (this._lastRedeclarationIntent) {
243
+ // Check if the last redeclaration intent is still valid
244
+ if (this._lastRedeclarationIntent.exp > currentBlock) return
245
+ // If it has expired, clear the last redeclaration intent
246
+ this._lastRedeclarationIntent = undefined
247
+ }
248
+
249
+ // Check if we have a valid balance before declaring intent
250
+ if (!await this.validateCurrentBalance()) {
251
+ this.logger?.error(
252
+ `Add balance to address ${this.account.address} for the producer to declare it's intent.`,
253
+ )
254
+ return
255
+ }
256
+
257
+ // Check if we have a valid stake before declaring intent
258
+ if (!(await this.validateCurrentStake())) {
259
+ this.logger?.error(
260
+ `Add stake to contract address ${this.params.config.chain.id}`
261
+ + ' for the producer to declare it\'s intent.',
262
+ )
263
+ return
264
+ }
265
+
266
+ // Create a redeclaration intent
267
+ this.logger?.log('Creating redeclaration intent for producer:', this.account.address)
268
+ const redeclarationIntent = createDeclarationIntent(
269
+ this.account.address,
270
+ 'producer',
271
+ currentBlock,
272
+ currentBlock + SimpleBlockRunner.RedeclarationDuration,
273
+ )
274
+
275
+ // Submit the redeclaration intent
276
+ await this.submitRedeclarationIntent(currentBlock, redeclarationIntent)
277
+
278
+ // On successful submission, save the redeclaration intent
279
+ this._lastRedeclarationIntent = redeclarationIntent
280
+ })
281
+ }
282
+
283
+ protected async submitRedeclarationIntent(currentBlock: XL1BlockNumber, redeclarationIntent: ChainStakeIntent): Promise<void> {
284
+ this.logger?.log('Submitting redeclaration intent for producer:', this.account.address)
285
+ // Create a transaction to submit the redeclaration intent
286
+ const tx = await buildTransaction(
287
+ this.chainId,
288
+ [redeclarationIntent],
289
+ [],
290
+ this.account,
291
+ currentBlock,
292
+ asXL1BlockNumber(currentBlock + 1000, true),
293
+ )
294
+
295
+ // Submit the redeclaration intent
296
+ await this.mempoolRunner.submitTransactions([tx])
297
+
298
+ this.logger?.log('Submitted redeclaration intent for producer:', this.account.address)
299
+ }
300
+
301
+ protected async validateCurrentBalance(): Promise<boolean> {
302
+ // Check if we have a valid balance before declaring intent
303
+ const head = this._lastProducedBlock?.[0]._hash
304
+ if (isDefined(head)) {
305
+ const balances = await this.accountBalanceViewer.accountBalances([this.account.address], head)
306
+ const currentBalance = balances[this.account.address] ?? 0n
307
+ if (currentBalance <= 0n) {
308
+ this.logger?.error(`Producer ${this.account.address} has no balance.`)
309
+ return false
310
+ }
311
+ return true
312
+ }
313
+ return true
314
+ }
315
+
316
+ protected async validateCurrentStake(): Promise<boolean> {
317
+ // Use StakeIntentService to get the required minimum stake
318
+ const requiredMinimumStake = 1n // this.stakeIntentService.getRequiredMinimumStakeForIntent('producer')
319
+ // Check if we have a valid stake before declaring intent
320
+ const currentStake = await this.stakeTotalsViewer.activeByStaked(this.account.address)
321
+ if (currentStake < requiredMinimumStake) {
322
+ this.logger?.error(`Producer ${this.account.address} has insufficient stake.`)
323
+ return false
324
+ }
325
+ return true
326
+ }
327
+ }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './ProducerActor.ts'
2
+ export * from './runProducer.ts'
@@ -0,0 +1,81 @@
1
+ import {
2
+ assertEx, exists, type Logger,
3
+ } from '@xylabs/sdk-js'
4
+ import {
5
+ initProducerAccount, initStakeViewer, type OrchestratorInstance,
6
+ } from '@xyo-network/chain-orchestration'
7
+ import {
8
+ initBlockRewardViewer, initChainService, initTimeService,
9
+ } from '@xyo-network/chain-services'
10
+ import { type Config } from '@xyo-network/xl1-protocol-sdk'
11
+ import {
12
+ AccountBalanceViewerRpcSchemas, BlockViewerRpcSchemas, HttpRpcTransport, JsonRpcAccountBalanceViewer,
13
+ JsonRpcBlockViewer,
14
+ JsonRpcMempoolRunner,
15
+ JsonRpcMempoolViewer,
16
+ JsonRpcStakeTotalsViewer,
17
+ MempoolRunnerRpcSchemas,
18
+ MempoolViewerRpcSchemas,
19
+ StakeTotalsViewerRpcSchemas,
20
+ } from '@xyo-network/xl1-rpc'
21
+
22
+ import { ProducerActor, type ProducerActorParams } from './ProducerActor.ts'
23
+
24
+ interface RunProducerContext {
25
+ config: Config
26
+ logger: Logger
27
+ orchestrator: OrchestratorInstance
28
+ }
29
+
30
+ export const runProducer = async (context: RunProducerContext) => {
31
+ const {
32
+ config, logger, orchestrator,
33
+ } = context
34
+
35
+ const endpoint = assertEx(config.services?.apiEndpoint, () => 'No API endpoint configured')
36
+ const account = await initProducerAccount({ config, logger })
37
+ const accountBalanceViewer = new JsonRpcAccountBalanceViewer(new HttpRpcTransport(endpoint, { ...AccountBalanceViewerRpcSchemas }))
38
+ const blockViewer = new JsonRpcBlockViewer(new HttpRpcTransport(endpoint, { ...BlockViewerRpcSchemas }))
39
+ const stakeTotalsViewer = new JsonRpcStakeTotalsViewer(new HttpRpcTransport(endpoint, { ...StakeTotalsViewerRpcSchemas }))
40
+ const chainId = (await blockViewer.currentBlock())[0].chain
41
+ const mempoolViewer = new JsonRpcMempoolViewer(new HttpRpcTransport(endpoint, { ...MempoolViewerRpcSchemas }))
42
+ const mempoolRunner = new JsonRpcMempoolRunner(new HttpRpcTransport(endpoint, { ...MempoolRunnerRpcSchemas }))
43
+ const chainContractViewer = await initChainService({
44
+ account, config, logger,
45
+ })
46
+ const blockRewardViewer = await initBlockRewardViewer({
47
+ config, logger, chainContractViewer,
48
+ })
49
+ const timeSyncViewer = await initTimeService({
50
+ config, logger, blockViewer,
51
+ })
52
+
53
+ // Create actors
54
+ const params = {
55
+ account,
56
+ id: 'ProducerActor',
57
+ chainId,
58
+ config,
59
+ viewers: {
60
+ accountBalanceViewer,
61
+ blockViewer,
62
+ stakeTotalsViewer,
63
+ mempoolViewer,
64
+ time: timeSyncViewer,
65
+ },
66
+ blockRewardViewer,
67
+ runners: { mempoolRunner },
68
+ logger,
69
+ } satisfies ProducerActorParams
70
+ // const apiEndpoint = config.services.apiEndpoint
71
+ // const balances = isDefined(apiEndpoint) ? undefined : await BalanceActor.create(params)
72
+ const producer = await ProducerActor.create(params)
73
+ const actors = [producer].filter(exists)
74
+
75
+ for (const actor of actors) {
76
+ // Register the actor with the orchestrator
77
+ await orchestrator.registerActor(actor)
78
+ }
79
+ // Start the orchestrator => automatically activates the actor
80
+ await orchestrator.start()
81
+ }