@canton-network/core-splice-client 1.8.0 → 1.9.0

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/dist/index.js CHANGED
@@ -1,409 +1,412 @@
1
- import createClient from 'openapi-fetch';
2
-
3
- var __defProp = Object.defineProperty;
4
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
5
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
6
- var _ScanClient = class _ScanClient {
7
- constructor(baseUrl, logger, accessTokenProvider) {
8
- __publicField(this, "client");
9
- __publicField(this, "logger");
10
- __publicField(this, "accessTokenProvider");
11
- __publicField(this, "baseUrlHref");
12
- this.logger = logger;
13
- this.baseUrlHref = baseUrl.href;
14
- this.accessTokenProvider = accessTokenProvider;
15
- this.logger.debug({ baseUrl }, "ScanClient initialized");
16
- this.client = createClient({
17
- baseUrl: baseUrl.href,
18
- fetch: async (url, options = {}) => {
19
- const accessToken = await this.accessTokenProvider.getAccessToken();
20
- return fetch(url, {
21
- ...options,
22
- headers: {
23
- ...options.headers || {},
24
- ...accessToken ? { Authorization: `Bearer ${accessToken}` } : {},
25
- "Content-Type": "application/json"
26
- }
27
- });
28
- }
29
- });
30
- }
31
- async post(path, body, params) {
32
- const options = { body, params };
33
- this.logger.debug({ requestBody: body }, `POST ${path}`);
34
- const resp = await this.client.POST(path, options);
35
- this.logger.debug({ requestBody: body, response: resp }, `POST ${path}`);
36
- return this.valueOrError(resp);
37
- }
38
- async get(path, params) {
39
- const options = { params };
40
- const resp = await this.client.GET(path, options);
41
- this.logger.debug(
42
- { path, params, response: resp },
43
- `GET ${path}`
44
- );
45
- return this.valueOrError(resp);
46
- }
47
- async valueOrError(response) {
48
- if (response.data === void 0) {
49
- return Promise.reject(response.error);
50
- } else {
51
- return Promise.resolve(response.data);
52
- }
53
- }
54
- async getAmuletSynchronizerId() {
55
- const dsoInfo = await this.get("/v0/dso");
56
- const payloadObj = JSON.parse(
57
- JSON.stringify(dsoInfo.amulet_rules.contract.payload)
58
- );
59
- const initActiveSynchronizer = payloadObj?.configSchedule?.initialValue?.decentralizedSynchronizer?.activeSynchronizer;
60
- const futureValues = payloadObj?.configSchedule?.futureValues;
61
- if (futureValues.length > 0) {
62
- let updatedValue = void 0;
63
- for (const value of futureValues) {
64
- const parsed = JSON.parse(JSON.stringify(value));
65
- if (parsed?.decentralizedSynchronizer?.activeSynchronizer) {
66
- updatedValue = parsed.decentralizedSynchronizer.activeSynchronizer;
67
- }
68
- }
69
- return updatedValue ?? initActiveSynchronizer;
70
- } else return initActiveSynchronizer;
71
- }
72
- async fetchAmuletRulesOnce() {
73
- const resp = await this.post("/v0/amulet-rules", {});
74
- const contract = resp.amulet_rules_update.contract;
75
- if (!contract?.contract_id || !contract?.template_id) {
76
- throw new Error("Malformed AmuletRules response");
77
- }
78
- _ScanClient.amuletRulesCache.set(this.baseUrlHref, contract);
79
- return contract;
80
- }
81
- async getAmuletRules() {
82
- const key = this.baseUrlHref;
83
- const cached = _ScanClient.amuletRulesCache.get(key);
84
- if (cached) return structuredClone(cached);
85
- let inflight = _ScanClient.amuletRulesInflight.get(key);
86
- if (!inflight) {
87
- inflight = this.fetchAmuletRulesOnce().finally(() => {
88
- _ScanClient.amuletRulesInflight.delete(key);
89
- });
90
- _ScanClient.amuletRulesInflight.set(key, inflight);
91
- }
92
- const contract = await inflight;
93
- return structuredClone(contract);
94
- }
95
- static invalidateAmuletRulesCache(baseUrl) {
96
- const key = baseUrl.href;
97
- this.amuletRulesCache.delete(key);
98
- this.amuletRulesInflight.delete(key);
99
- }
100
- computeNextChangeAt(rounds) {
101
- const now = Date.now();
102
- let next = Number.POSITIVE_INFINITY;
103
- for (const round of rounds) {
104
- const { opensAt, targetClosesAt } = round.payload ?? {};
105
- const openMs = opensAt ? Number(new Date(opensAt)) : NaN;
106
- const closeMs = targetClosesAt ? Number(new Date(targetClosesAt)) : NaN;
107
- if (Number.isFinite(openMs) && openMs > now && openMs < next) {
108
- next = openMs;
109
- }
110
- if (Number.isFinite(closeMs) && closeMs > now && closeMs < next) {
111
- next = closeMs;
112
- }
113
- }
114
- return Number.isFinite(next) ? next : now;
115
- }
116
- async fetchOpenMiningRoundsOnce() {
117
- const resp = await this.post("/v0/open-and-issuing-mining-rounds", {
118
- cached_open_mining_round_contract_ids: [],
119
- cached_issuing_round_contract_ids: []
120
- });
121
- const rounds = Object.values(resp.open_mining_rounds).flatMap(
122
- (x) => x.contract ? [x.contract] : []
123
- );
124
- const key = this.baseUrlHref;
125
- _ScanClient.roundsCache.set(key, rounds);
126
- _ScanClient.roundsNextChangeAt.set(key, this.computeNextChangeAt(rounds));
127
- return rounds;
128
- }
129
- async refreshRounds(key) {
130
- let inflight = _ScanClient.roundsInflight.get(key);
131
- if (!inflight) {
132
- inflight = this.fetchOpenMiningRoundsOnce().finally(() => {
133
- _ScanClient.roundsInflight.delete(key);
134
- });
135
- _ScanClient.roundsInflight.set(key, inflight);
136
- }
137
- return inflight;
138
- }
139
- async getOpenMiningRounds() {
140
- const key = this.baseUrlHref;
141
- const now = Date.now();
142
- const cached = _ScanClient.roundsCache.get(key);
143
- const next = _ScanClient.roundsNextChangeAt.get(key);
144
- if (cached && next !== void 0 && now < next) {
145
- return structuredClone(cached);
146
- }
147
- const fresh = await this.refreshRounds(key);
148
- return structuredClone(fresh);
149
- }
150
- async getActiveOpenMiningRound() {
151
- const pickActive = (rounds2, timestamp) => rounds2.filter((round) => {
152
- const { opensAt, targetClosesAt } = round.payload;
153
- const openMs = opensAt ? Number(new Date(opensAt)) : NaN;
154
- const closeMs = targetClosesAt ? Number(new Date(targetClosesAt)) : NaN;
155
- return Number.isFinite(openMs) && Number.isFinite(closeMs) && openMs <= timestamp && timestamp < closeMs;
156
- }).sort((a, b) => a.payload.opensAt - b.payload.opensAt).at(-1) ?? null;
157
- const now = Date.now();
158
- const rounds = await this.getOpenMiningRounds();
159
- const active = pickActive(rounds, now);
160
- return active ? structuredClone(active) : null;
161
- }
162
- static invalidateOpenMiningRoundsCache(baseUrl) {
163
- const key = baseUrl.href;
164
- this.roundsCache.delete(key);
165
- this.roundsInflight.delete(key);
166
- this.roundsNextChangeAt.delete(key);
167
- }
168
- async isDevNet() {
169
- const amuletRules = await this.getAmuletRules();
170
- const payload = amuletRules.payload;
171
- return payload?.isDevNet ?? false;
172
- }
1
+ import createClient from "openapi-fetch";
2
+ //#region \0@oxc-project+runtime@0.142.0/helpers/esm/typeof.js
3
+ function _typeof(o) {
4
+ "@babel/helpers - typeof";
5
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
6
+ return typeof o;
7
+ } : function(o) {
8
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
9
+ }, _typeof(o);
10
+ }
11
+ //#endregion
12
+ //#region \0@oxc-project+runtime@0.142.0/helpers/esm/toPrimitive.js
13
+ function toPrimitive(t, r) {
14
+ if ("object" != _typeof(t) || !t) return t;
15
+ var e = t[Symbol.toPrimitive];
16
+ if (void 0 !== e) {
17
+ var i = e.call(t, r || "default");
18
+ if ("object" != _typeof(i)) return i;
19
+ throw new TypeError("@@toPrimitive must return a primitive value.");
20
+ }
21
+ return ("string" === r ? String : Number)(t);
22
+ }
23
+ //#endregion
24
+ //#region \0@oxc-project+runtime@0.142.0/helpers/esm/toPropertyKey.js
25
+ function toPropertyKey(t) {
26
+ var i = toPrimitive(t, "string");
27
+ return "symbol" == _typeof(i) ? i : i + "";
28
+ }
29
+ //#endregion
30
+ //#region \0@oxc-project+runtime@0.142.0/helpers/esm/defineProperty.js
31
+ function _defineProperty(e, r, t) {
32
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
33
+ value: t,
34
+ enumerable: !0,
35
+ configurable: !0,
36
+ writable: !0
37
+ }) : e[r] = t, e;
38
+ }
39
+ //#endregion
40
+ //#region src/scan-client.ts
41
+ var ScanClient = class ScanClient {
42
+ constructor(baseUrl, logger, accessTokenProvider) {
43
+ _defineProperty(this, "client", void 0);
44
+ _defineProperty(this, "logger", void 0);
45
+ _defineProperty(this, "accessTokenProvider", void 0);
46
+ _defineProperty(this, "baseUrlHref", void 0);
47
+ this.logger = logger;
48
+ this.baseUrlHref = baseUrl.href;
49
+ this.accessTokenProvider = accessTokenProvider;
50
+ this.logger.debug({ baseUrl }, "ScanClient initialized");
51
+ this.client = createClient({
52
+ baseUrl: baseUrl.href,
53
+ fetch: async (url, options = {}) => {
54
+ const accessToken = await this.accessTokenProvider.getAccessToken();
55
+ return fetch(url, {
56
+ ...options,
57
+ headers: {
58
+ ...options.headers || {},
59
+ ...accessToken ? { Authorization: `Bearer ${accessToken}` } : {},
60
+ "Content-Type": "application/json"
61
+ }
62
+ });
63
+ }
64
+ });
65
+ }
66
+ async post(path, body, params) {
67
+ const options = {
68
+ body,
69
+ params
70
+ };
71
+ this.logger.debug({ requestBody: body }, `POST ${path}`);
72
+ const resp = await this.client.POST(path, options);
73
+ this.logger.debug({
74
+ requestBody: body,
75
+ response: resp
76
+ }, `POST ${path}`);
77
+ return this.valueOrError(resp);
78
+ }
79
+ async get(path, params) {
80
+ const options = { params };
81
+ const resp = await this.client.GET(path, options);
82
+ this.logger.debug({
83
+ path,
84
+ params,
85
+ response: resp
86
+ }, `GET ${path}`);
87
+ return this.valueOrError(resp);
88
+ }
89
+ async valueOrError(response) {
90
+ if (response.data === void 0) return Promise.reject(response.error);
91
+ else return Promise.resolve(response.data);
92
+ }
93
+ async getAmuletSynchronizerId() {
94
+ const dsoInfo = await this.get("/v0/dso");
95
+ const payloadObj = JSON.parse(JSON.stringify(dsoInfo.amulet_rules.contract.payload));
96
+ const initActiveSynchronizer = payloadObj?.configSchedule?.initialValue?.decentralizedSynchronizer?.activeSynchronizer;
97
+ const futureValues = payloadObj?.configSchedule?.futureValues;
98
+ if (futureValues.length > 0) {
99
+ let updatedValue = void 0;
100
+ for (const value of futureValues) {
101
+ const parsed = JSON.parse(JSON.stringify(value));
102
+ if (parsed?.decentralizedSynchronizer?.activeSynchronizer) updatedValue = parsed.decentralizedSynchronizer.activeSynchronizer;
103
+ }
104
+ return updatedValue ?? initActiveSynchronizer;
105
+ } else return initActiveSynchronizer;
106
+ }
107
+ async fetchAmuletRulesOnce() {
108
+ const contract = (await this.post("/v0/amulet-rules", {})).amulet_rules_update.contract;
109
+ if (!contract?.contract_id || !contract?.template_id) throw new Error("Malformed AmuletRules response");
110
+ ScanClient.amuletRulesCache.set(this.baseUrlHref, contract);
111
+ return contract;
112
+ }
113
+ async getAmuletRules() {
114
+ const key = this.baseUrlHref;
115
+ const cached = ScanClient.amuletRulesCache.get(key);
116
+ if (cached) return structuredClone(cached);
117
+ let inflight = ScanClient.amuletRulesInflight.get(key);
118
+ if (!inflight) {
119
+ inflight = this.fetchAmuletRulesOnce().finally(() => {
120
+ ScanClient.amuletRulesInflight.delete(key);
121
+ });
122
+ ScanClient.amuletRulesInflight.set(key, inflight);
123
+ }
124
+ const contract = await inflight;
125
+ return structuredClone(contract);
126
+ }
127
+ static invalidateAmuletRulesCache(baseUrl) {
128
+ const key = baseUrl.href;
129
+ this.amuletRulesCache.delete(key);
130
+ this.amuletRulesInflight.delete(key);
131
+ }
132
+ computeNextChangeAt(rounds) {
133
+ const now = Date.now();
134
+ let next = Number.POSITIVE_INFINITY;
135
+ for (const round of rounds) {
136
+ const { opensAt, targetClosesAt } = round.payload ?? {};
137
+ const openMs = opensAt ? Number(new Date(opensAt)) : NaN;
138
+ const closeMs = targetClosesAt ? Number(new Date(targetClosesAt)) : NaN;
139
+ if (Number.isFinite(openMs) && openMs > now && openMs < next) next = openMs;
140
+ if (Number.isFinite(closeMs) && closeMs > now && closeMs < next) next = closeMs;
141
+ }
142
+ return Number.isFinite(next) ? next : now;
143
+ }
144
+ async fetchOpenMiningRoundsOnce() {
145
+ const resp = await this.post("/v0/open-and-issuing-mining-rounds", {
146
+ cached_open_mining_round_contract_ids: [],
147
+ cached_issuing_round_contract_ids: []
148
+ });
149
+ const rounds = Object.values(resp.open_mining_rounds).flatMap((x) => x.contract ? [x.contract] : []);
150
+ const key = this.baseUrlHref;
151
+ ScanClient.roundsCache.set(key, rounds);
152
+ ScanClient.roundsNextChangeAt.set(key, this.computeNextChangeAt(rounds));
153
+ return rounds;
154
+ }
155
+ async refreshRounds(key) {
156
+ let inflight = ScanClient.roundsInflight.get(key);
157
+ if (!inflight) {
158
+ inflight = this.fetchOpenMiningRoundsOnce().finally(() => {
159
+ ScanClient.roundsInflight.delete(key);
160
+ });
161
+ ScanClient.roundsInflight.set(key, inflight);
162
+ }
163
+ return inflight;
164
+ }
165
+ async getOpenMiningRounds() {
166
+ const key = this.baseUrlHref;
167
+ const now = Date.now();
168
+ const cached = ScanClient.roundsCache.get(key);
169
+ const next = ScanClient.roundsNextChangeAt.get(key);
170
+ if (cached && next !== void 0 && now < next) return structuredClone(cached);
171
+ const fresh = await this.refreshRounds(key);
172
+ return structuredClone(fresh);
173
+ }
174
+ async getActiveOpenMiningRound() {
175
+ const pickActive = (rounds, timestamp) => rounds.filter((round) => {
176
+ const { opensAt, targetClosesAt } = round.payload;
177
+ const openMs = opensAt ? Number(new Date(opensAt)) : NaN;
178
+ const closeMs = targetClosesAt ? Number(new Date(targetClosesAt)) : NaN;
179
+ return Number.isFinite(openMs) && Number.isFinite(closeMs) && openMs <= timestamp && timestamp < closeMs;
180
+ }).sort((a, b) => a.payload.opensAt - b.payload.opensAt).at(-1) ?? null;
181
+ const now = Date.now();
182
+ const active = pickActive(await this.getOpenMiningRounds(), now);
183
+ return active ? structuredClone(active) : null;
184
+ }
185
+ static invalidateOpenMiningRoundsCache(baseUrl) {
186
+ const key = baseUrl.href;
187
+ this.roundsCache.delete(key);
188
+ this.roundsInflight.delete(key);
189
+ this.roundsNextChangeAt.delete(key);
190
+ }
191
+ async isDevNet() {
192
+ return (await this.getAmuletRules()).payload?.isDevNet ?? false;
193
+ }
173
194
  };
174
- __publicField(_ScanClient, "amuletRulesCache", /* @__PURE__ */ new Map());
175
- __publicField(_ScanClient, "roundsCache", /* @__PURE__ */ new Map());
176
- // one in-flight fetch per baseUrl for rules/rounds
177
- __publicField(_ScanClient, "amuletRulesInflight", /* @__PURE__ */ new Map());
178
- __publicField(_ScanClient, "roundsInflight", /* @__PURE__ */ new Map());
179
- // time after surpassing which mining rounds should be refreshed
180
- __publicField(_ScanClient, "roundsNextChangeAt", /* @__PURE__ */ new Map());
181
- var ScanClient = _ScanClient;
182
- var _ScanProxyClient = class _ScanProxyClient {
183
- constructor(baseUrl, logger, accessTokenProvider) {
184
- __publicField(this, "client");
185
- __publicField(this, "logger");
186
- __publicField(this, "accessTokenProvider");
187
- __publicField(this, "baseUrlHref");
188
- this.baseUrlHref = baseUrl.href;
189
- this.accessTokenProvider = accessTokenProvider;
190
- this.logger = logger;
191
- this.logger.debug({ baseUrl }, "ScanProxyClient initialized");
192
- this.client = createClient({
193
- baseUrl: baseUrl.href,
194
- fetch: async (url, options = {}) => {
195
- const accessToken = await this.accessTokenProvider.getAccessToken();
196
- return fetch(url, {
197
- ...options,
198
- headers: {
199
- ...options.headers || {},
200
- ...accessToken ? { Authorization: `Bearer ${accessToken}` } : {},
201
- "Content-Type": "application/json"
202
- }
203
- });
204
- }
205
- });
206
- }
207
- async post(path, body, params) {
208
- const options = { body, params };
209
- this.logger.debug({ requestBody: body }, `POST ${path}`);
210
- const resp = await this.client.POST(path, options);
211
- this.logger.debug({ requestBody: body, response: resp }, `POST ${path}`);
212
- return this.valueOrError(resp);
213
- }
214
- async get(path, params) {
215
- const options = { params };
216
- const resp = await this.client.GET(path, options);
217
- this.logger.debug(
218
- { path, params, response: resp },
219
- `GET ${path}`
220
- );
221
- return this.valueOrError(resp);
222
- }
223
- async valueOrError(response) {
224
- if (response.data === void 0) {
225
- return Promise.reject(response.error);
226
- } else {
227
- return Promise.resolve(response.data);
228
- }
229
- }
230
- async fetchAmuletRulesOnce() {
231
- const resp = await this.get("/v0/scan-proxy/amulet-rules");
232
- const contract = resp?.amulet_rules?.contract;
233
- if (!contract?.contract_id || !contract?.template_id) {
234
- throw new Error("Malformed AmuletRules response");
235
- }
236
- _ScanProxyClient.amuletRulesCache.set(this.baseUrlHref, contract);
237
- return contract;
238
- }
239
- async getAmuletRules() {
240
- const key = this.baseUrlHref;
241
- const cached = _ScanProxyClient.amuletRulesCache.get(key);
242
- if (cached) return structuredClone(cached);
243
- let inflight = _ScanProxyClient.amuletRulesInflight.get(key);
244
- if (!inflight) {
245
- inflight = this.fetchAmuletRulesOnce().finally(() => {
246
- _ScanProxyClient.amuletRulesInflight.delete(key);
247
- });
248
- _ScanProxyClient.amuletRulesInflight.set(key, inflight);
249
- }
250
- const contract = await inflight;
251
- return structuredClone(contract);
252
- }
253
- static invalidateAmuletRulesCache(baseUrl) {
254
- const key = baseUrl.href;
255
- this.amuletRulesCache.delete(key);
256
- this.amuletRulesInflight.delete(key);
257
- }
258
- computeNextChangeAt(rounds) {
259
- const now = Date.now();
260
- let next = Number.POSITIVE_INFINITY;
261
- for (const round of rounds) {
262
- const { opensAt, targetClosesAt } = round.payload ?? {};
263
- const openMs = opensAt ? Number(new Date(opensAt)) : NaN;
264
- const closeMs = targetClosesAt ? Number(new Date(targetClosesAt)) : NaN;
265
- if (Number.isFinite(openMs) && openMs > now && openMs < next) {
266
- next = openMs;
267
- }
268
- if (Number.isFinite(closeMs) && closeMs > now && closeMs < next) {
269
- next = closeMs;
270
- }
271
- }
272
- return Number.isFinite(next) ? next : now;
273
- }
274
- async fetchOpenMiningRoundsOnce() {
275
- const resp = await this.get(
276
- "/v0/scan-proxy/open-and-issuing-mining-rounds"
277
- );
278
- const rounds = (resp.open_mining_rounds ?? []).map(
279
- (x) => x.contract
280
- );
281
- const key = this.baseUrlHref;
282
- _ScanProxyClient.roundsCache.set(key, rounds);
283
- _ScanProxyClient.roundsNextChangeAt.set(
284
- key,
285
- this.computeNextChangeAt(rounds)
286
- );
287
- return rounds;
288
- }
289
- async refreshRounds(key) {
290
- let inflight = _ScanProxyClient.roundsInflight.get(key);
291
- if (!inflight) {
292
- inflight = this.fetchOpenMiningRoundsOnce().finally(() => {
293
- _ScanProxyClient.roundsInflight.delete(key);
294
- });
295
- _ScanProxyClient.roundsInflight.set(key, inflight);
296
- }
297
- return inflight;
298
- }
299
- async getOpenMiningRounds() {
300
- const key = this.baseUrlHref;
301
- const now = Date.now();
302
- const cached = _ScanProxyClient.roundsCache.get(key);
303
- const next = _ScanProxyClient.roundsNextChangeAt.get(key);
304
- if (cached && next !== void 0 && now < next) {
305
- return structuredClone(cached);
306
- }
307
- const fresh = await this.refreshRounds(key);
308
- return structuredClone(fresh);
309
- }
310
- async getActiveOpenMiningRound() {
311
- const pickActive = (rounds2, timestamp) => rounds2.filter((round) => {
312
- const { opensAt, targetClosesAt } = round.payload;
313
- const openMs = opensAt ? Number(new Date(opensAt)) : NaN;
314
- const closeMs = targetClosesAt ? Number(new Date(targetClosesAt)) : NaN;
315
- return Number.isFinite(openMs) && Number.isFinite(closeMs) && openMs <= timestamp && timestamp < closeMs;
316
- }).sort((a, b) => a.payload.opensAt - b.payload.opensAt).at(-1) ?? null;
317
- const now = Date.now();
318
- const rounds = await this.getOpenMiningRounds();
319
- const active = pickActive(rounds, now);
320
- return active ? structuredClone(active) : null;
321
- }
322
- static invalidateOpenMiningRoundsCache(baseUrl) {
323
- const key = baseUrl.href;
324
- this.roundsCache.delete(key);
325
- this.roundsInflight.delete(key);
326
- this.roundsNextChangeAt.delete(key);
327
- }
328
- async getAmuletSynchronizerId() {
329
- const amuletRules = await this.getAmuletRules();
330
- const payloadObj = amuletRules.payload;
331
- const initActiveSynchronizer = payloadObj?.configSchedule?.initialValue?.decentralizedSynchronizer?.activeSynchronizer;
332
- const futureValues = payloadObj?.configSchedule?.futureValues;
333
- if (Array.isArray(futureValues) && futureValues.length > 0) {
334
- let updatedValue = void 0;
335
- for (const value of futureValues) {
336
- const parsed = JSON.parse(JSON.stringify(value));
337
- if (parsed?.decentralizedSynchronizer?.activeSynchronizer) {
338
- updatedValue = parsed.decentralizedSynchronizer.activeSynchronizer;
339
- }
340
- }
341
- return updatedValue ?? initActiveSynchronizer;
342
- } else return initActiveSynchronizer;
343
- }
344
- async isDevNet() {
345
- const amuletRules = await this.getAmuletRules();
346
- const payload = amuletRules.payload;
347
- return payload?.isDevNet ?? false;
348
- }
195
+ _defineProperty(ScanClient, "amuletRulesCache", /* @__PURE__ */ new Map());
196
+ _defineProperty(ScanClient, "roundsCache", /* @__PURE__ */ new Map());
197
+ _defineProperty(ScanClient, "amuletRulesInflight", /* @__PURE__ */ new Map());
198
+ _defineProperty(ScanClient, "roundsInflight", /* @__PURE__ */ new Map());
199
+ _defineProperty(ScanClient, "roundsNextChangeAt", /* @__PURE__ */ new Map());
200
+ //#endregion
201
+ //#region src/scan-proxy-client.ts
202
+ var ScanProxyClient = class ScanProxyClient {
203
+ constructor(baseUrl, logger, accessTokenProvider) {
204
+ _defineProperty(this, "client", void 0);
205
+ _defineProperty(this, "logger", void 0);
206
+ _defineProperty(this, "accessTokenProvider", void 0);
207
+ _defineProperty(this, "baseUrlHref", void 0);
208
+ this.baseUrlHref = baseUrl.href;
209
+ this.accessTokenProvider = accessTokenProvider;
210
+ this.logger = logger;
211
+ this.logger.debug({ baseUrl }, "ScanProxyClient initialized");
212
+ this.client = createClient({
213
+ baseUrl: baseUrl.href,
214
+ fetch: async (url, options = {}) => {
215
+ const accessToken = await this.accessTokenProvider.getAccessToken();
216
+ return fetch(url, {
217
+ ...options,
218
+ headers: {
219
+ ...options.headers || {},
220
+ ...accessToken ? { Authorization: `Bearer ${accessToken}` } : {},
221
+ "Content-Type": "application/json"
222
+ }
223
+ });
224
+ }
225
+ });
226
+ }
227
+ async post(path, body, params) {
228
+ const options = {
229
+ body,
230
+ params
231
+ };
232
+ this.logger.debug({ requestBody: body }, `POST ${path}`);
233
+ const resp = await this.client.POST(path, options);
234
+ this.logger.debug({
235
+ requestBody: body,
236
+ response: resp
237
+ }, `POST ${path}`);
238
+ return this.valueOrError(resp);
239
+ }
240
+ async get(path, params) {
241
+ const options = { params };
242
+ const resp = await this.client.GET(path, options);
243
+ this.logger.debug({
244
+ path,
245
+ params,
246
+ response: resp
247
+ }, `GET ${path}`);
248
+ return this.valueOrError(resp);
249
+ }
250
+ async valueOrError(response) {
251
+ if (response.data === void 0) return Promise.reject(response.error);
252
+ else return Promise.resolve(response.data);
253
+ }
254
+ async fetchAmuletRulesOnce() {
255
+ const contract = (await this.get("/v0/scan-proxy/amulet-rules"))?.amulet_rules?.contract;
256
+ if (!contract?.contract_id || !contract?.template_id) throw new Error("Malformed AmuletRules response");
257
+ ScanProxyClient.amuletRulesCache.set(this.baseUrlHref, contract);
258
+ return contract;
259
+ }
260
+ async getAmuletRules() {
261
+ const key = this.baseUrlHref;
262
+ const cached = ScanProxyClient.amuletRulesCache.get(key);
263
+ if (cached) return structuredClone(cached);
264
+ let inflight = ScanProxyClient.amuletRulesInflight.get(key);
265
+ if (!inflight) {
266
+ inflight = this.fetchAmuletRulesOnce().finally(() => {
267
+ ScanProxyClient.amuletRulesInflight.delete(key);
268
+ });
269
+ ScanProxyClient.amuletRulesInflight.set(key, inflight);
270
+ }
271
+ const contract = await inflight;
272
+ return structuredClone(contract);
273
+ }
274
+ static invalidateAmuletRulesCache(baseUrl) {
275
+ const key = baseUrl.href;
276
+ this.amuletRulesCache.delete(key);
277
+ this.amuletRulesInflight.delete(key);
278
+ }
279
+ computeNextChangeAt(rounds) {
280
+ const now = Date.now();
281
+ let next = Number.POSITIVE_INFINITY;
282
+ for (const round of rounds) {
283
+ const { opensAt, targetClosesAt } = round.payload ?? {};
284
+ const openMs = opensAt ? Number(new Date(opensAt)) : NaN;
285
+ const closeMs = targetClosesAt ? Number(new Date(targetClosesAt)) : NaN;
286
+ if (Number.isFinite(openMs) && openMs > now && openMs < next) next = openMs;
287
+ if (Number.isFinite(closeMs) && closeMs > now && closeMs < next) next = closeMs;
288
+ }
289
+ return Number.isFinite(next) ? next : now;
290
+ }
291
+ async fetchOpenMiningRoundsOnce() {
292
+ const rounds = ((await this.get("/v0/scan-proxy/open-and-issuing-mining-rounds")).open_mining_rounds ?? []).map((x) => x.contract);
293
+ const key = this.baseUrlHref;
294
+ ScanProxyClient.roundsCache.set(key, rounds);
295
+ ScanProxyClient.roundsNextChangeAt.set(key, this.computeNextChangeAt(rounds));
296
+ return rounds;
297
+ }
298
+ async refreshRounds(key) {
299
+ let inflight = ScanProxyClient.roundsInflight.get(key);
300
+ if (!inflight) {
301
+ inflight = this.fetchOpenMiningRoundsOnce().finally(() => {
302
+ ScanProxyClient.roundsInflight.delete(key);
303
+ });
304
+ ScanProxyClient.roundsInflight.set(key, inflight);
305
+ }
306
+ return inflight;
307
+ }
308
+ async getOpenMiningRounds() {
309
+ const key = this.baseUrlHref;
310
+ const now = Date.now();
311
+ const cached = ScanProxyClient.roundsCache.get(key);
312
+ const next = ScanProxyClient.roundsNextChangeAt.get(key);
313
+ if (cached && next !== void 0 && now < next) return structuredClone(cached);
314
+ const fresh = await this.refreshRounds(key);
315
+ return structuredClone(fresh);
316
+ }
317
+ async getActiveOpenMiningRound() {
318
+ const pickActive = (rounds, timestamp) => rounds.filter((round) => {
319
+ const { opensAt, targetClosesAt } = round.payload;
320
+ const openMs = opensAt ? Number(new Date(opensAt)) : NaN;
321
+ const closeMs = targetClosesAt ? Number(new Date(targetClosesAt)) : NaN;
322
+ return Number.isFinite(openMs) && Number.isFinite(closeMs) && openMs <= timestamp && timestamp < closeMs;
323
+ }).sort((a, b) => a.payload.opensAt - b.payload.opensAt).at(-1) ?? null;
324
+ const now = Date.now();
325
+ const active = pickActive(await this.getOpenMiningRounds(), now);
326
+ return active ? structuredClone(active) : null;
327
+ }
328
+ static invalidateOpenMiningRoundsCache(baseUrl) {
329
+ const key = baseUrl.href;
330
+ this.roundsCache.delete(key);
331
+ this.roundsInflight.delete(key);
332
+ this.roundsNextChangeAt.delete(key);
333
+ }
334
+ async getAmuletSynchronizerId() {
335
+ const payloadObj = (await this.getAmuletRules()).payload;
336
+ const initActiveSynchronizer = payloadObj?.configSchedule?.initialValue?.decentralizedSynchronizer?.activeSynchronizer;
337
+ const futureValues = payloadObj?.configSchedule?.futureValues;
338
+ if (Array.isArray(futureValues) && futureValues.length > 0) {
339
+ let updatedValue = void 0;
340
+ for (const value of futureValues) {
341
+ const parsed = JSON.parse(JSON.stringify(value));
342
+ if (parsed?.decentralizedSynchronizer?.activeSynchronizer) updatedValue = parsed.decentralizedSynchronizer.activeSynchronizer;
343
+ }
344
+ return updatedValue ?? initActiveSynchronizer;
345
+ } else return initActiveSynchronizer;
346
+ }
347
+ async isDevNet() {
348
+ return (await this.getAmuletRules()).payload?.isDevNet ?? false;
349
+ }
349
350
  };
350
- // shared caches for all instances of ScanProxyClient
351
- __publicField(_ScanProxyClient, "amuletRulesCache", /* @__PURE__ */ new Map());
352
- __publicField(_ScanProxyClient, "roundsCache", /* @__PURE__ */ new Map());
353
- // one in-flight fetch per baseUrl for rules/rounds
354
- __publicField(_ScanProxyClient, "amuletRulesInflight", /* @__PURE__ */ new Map());
355
- __publicField(_ScanProxyClient, "roundsInflight", /* @__PURE__ */ new Map());
356
- // time after surpassing which mining rounds should be refreshed
357
- __publicField(_ScanProxyClient, "roundsNextChangeAt", /* @__PURE__ */ new Map());
358
- var ScanProxyClient = _ScanProxyClient;
351
+ _defineProperty(ScanProxyClient, "amuletRulesCache", /* @__PURE__ */ new Map());
352
+ _defineProperty(ScanProxyClient, "roundsCache", /* @__PURE__ */ new Map());
353
+ _defineProperty(ScanProxyClient, "amuletRulesInflight", /* @__PURE__ */ new Map());
354
+ _defineProperty(ScanProxyClient, "roundsInflight", /* @__PURE__ */ new Map());
355
+ _defineProperty(ScanProxyClient, "roundsNextChangeAt", /* @__PURE__ */ new Map());
356
+ //#endregion
357
+ //#region src/validator-internal-client.ts
359
358
  var ValidatorInternalClient = class {
360
- constructor(baseUrl, logger, accessTokenProvider) {
361
- __publicField(this, "client");
362
- __publicField(this, "logger");
363
- __publicField(this, "accessTokenProvider");
364
- this.accessTokenProvider = accessTokenProvider;
365
- this.logger = logger;
366
- this.logger.debug({ baseUrl }, "ValidatorInternalClient initialized");
367
- this.client = createClient({
368
- baseUrl: baseUrl.href,
369
- fetch: async (url, options = {}) => {
370
- const accessToken = await this.accessTokenProvider.getAccessToken();
371
- return fetch(url, {
372
- ...options,
373
- headers: {
374
- ...options.headers || {},
375
- ...accessToken ? { Authorization: `Bearer ${accessToken}` } : {},
376
- "Content-Type": "application/json"
377
- }
378
- });
379
- }
380
- });
381
- }
382
- async post(path, body, params) {
383
- const options = { body, params };
384
- this.logger.debug({ requestBody: body }, `POST ${path}`);
385
- const resp = await this.client.POST(path, options);
386
- this.logger.debug({ requestBody: body, response: resp }, `POST ${path}`);
387
- return this.valueOrError(resp);
388
- }
389
- async get(path, params) {
390
- const options = { params };
391
- const resp = await this.client.GET(path, options);
392
- this.logger.debug(
393
- { path, params, response: resp },
394
- `GET ${path}`
395
- );
396
- return this.valueOrError(resp);
397
- }
398
- async valueOrError(response) {
399
- if (response.data === void 0) {
400
- return Promise.reject(response.error);
401
- } else {
402
- return Promise.resolve(response.data);
403
- }
404
- }
359
+ constructor(baseUrl, logger, accessTokenProvider) {
360
+ _defineProperty(this, "client", void 0);
361
+ _defineProperty(this, "logger", void 0);
362
+ _defineProperty(this, "accessTokenProvider", void 0);
363
+ this.accessTokenProvider = accessTokenProvider;
364
+ this.logger = logger;
365
+ this.logger.debug({ baseUrl }, "ValidatorInternalClient initialized");
366
+ this.client = createClient({
367
+ baseUrl: baseUrl.href,
368
+ fetch: async (url, options = {}) => {
369
+ const accessToken = await this.accessTokenProvider.getAccessToken();
370
+ return fetch(url, {
371
+ ...options,
372
+ headers: {
373
+ ...options.headers || {},
374
+ ...accessToken ? { Authorization: `Bearer ${accessToken}` } : {},
375
+ "Content-Type": "application/json"
376
+ }
377
+ });
378
+ }
379
+ });
380
+ }
381
+ async post(path, body, params) {
382
+ const options = {
383
+ body,
384
+ params
385
+ };
386
+ this.logger.debug({ requestBody: body }, `POST ${path}`);
387
+ const resp = await this.client.POST(path, options);
388
+ this.logger.debug({
389
+ requestBody: body,
390
+ response: resp
391
+ }, `POST ${path}`);
392
+ return this.valueOrError(resp);
393
+ }
394
+ async get(path, params) {
395
+ const options = { params };
396
+ const resp = await this.client.GET(path, options);
397
+ this.logger.debug({
398
+ path,
399
+ params,
400
+ response: resp
401
+ }, `GET ${path}`);
402
+ return this.valueOrError(resp);
403
+ }
404
+ async valueOrError(response) {
405
+ if (response.data === void 0) return Promise.reject(response.error);
406
+ else return Promise.resolve(response.data);
407
+ }
405
408
  };
406
-
409
+ //#endregion
407
410
  export { ScanClient, ScanProxyClient, ValidatorInternalClient };
408
- //# sourceMappingURL=index.js.map
411
+
409
412
  //# sourceMappingURL=index.js.map