@ownables/adapter-viem 0.8.1 → 0.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.
Files changed (132) hide show
  1. package/dist/adapter-viem/src/index.d.ts.map +1 -0
  2. package/dist/adapter-viem/src/index.js.map +1 -0
  3. package/dist/{services → adapter-viem/src/services}/EQTY.service.d.ts +6 -5
  4. package/dist/adapter-viem/src/services/EQTY.service.d.ts.map +1 -0
  5. package/dist/{services → adapter-viem/src/services}/EQTY.service.js +133 -87
  6. package/dist/adapter-viem/src/services/EQTY.service.js.map +1 -0
  7. package/dist/{services → adapter-viem/src/services}/MockEQTY.service.d.ts +3 -1
  8. package/dist/adapter-viem/src/services/MockEQTY.service.d.ts.map +1 -0
  9. package/dist/{services → adapter-viem/src/services}/MockEQTY.service.js +3 -1
  10. package/dist/adapter-viem/src/services/MockEQTY.service.js.map +1 -0
  11. package/dist/{types → adapter-viem/src/types}/EQTY.d.ts +9 -0
  12. package/dist/adapter-viem/src/types/EQTY.d.ts.map +1 -0
  13. package/dist/{types → adapter-viem/src/types}/EQTY.js.map +1 -1
  14. package/dist/core/src/index.d.ts +26 -0
  15. package/dist/core/src/index.d.ts.map +1 -0
  16. package/dist/core/src/index.js +25 -0
  17. package/dist/core/src/index.js.map +1 -0
  18. package/dist/core/src/interfaces/core.d.ts +59 -0
  19. package/dist/core/src/interfaces/core.d.ts.map +1 -0
  20. package/dist/core/src/interfaces/core.js +2 -0
  21. package/dist/core/src/interfaces/core.js.map +1 -0
  22. package/dist/core/src/logger.d.ts +3 -0
  23. package/dist/core/src/logger.d.ts.map +1 -0
  24. package/dist/core/src/logger.js +2 -0
  25. package/dist/core/src/logger.js.map +1 -0
  26. package/dist/core/src/ownableErrorMessage.d.ts +2 -0
  27. package/dist/core/src/ownableErrorMessage.d.ts.map +1 -0
  28. package/dist/core/src/ownableErrorMessage.js +23 -0
  29. package/dist/core/src/ownableErrorMessage.js.map +1 -0
  30. package/dist/core/src/progress.d.ts +3 -0
  31. package/dist/core/src/progress.d.ts.map +1 -0
  32. package/dist/core/src/progress.js +8 -0
  33. package/dist/core/src/progress.js.map +1 -0
  34. package/dist/core/src/services/AnchorValidation.service.d.ts +22 -0
  35. package/dist/core/src/services/AnchorValidation.service.d.ts.map +1 -0
  36. package/dist/core/src/services/AnchorValidation.service.js +94 -0
  37. package/dist/core/src/services/AnchorValidation.service.js.map +1 -0
  38. package/dist/core/src/services/EventChain.service.d.ts +44 -0
  39. package/dist/core/src/services/EventChain.service.d.ts.map +1 -0
  40. package/dist/core/src/services/EventChain.service.js +117 -0
  41. package/dist/core/src/services/EventChain.service.js.map +1 -0
  42. package/dist/core/src/services/Ownable.service.d.ts +85 -0
  43. package/dist/core/src/services/Ownable.service.d.ts.map +1 -0
  44. package/dist/core/src/services/Ownable.service.js +692 -0
  45. package/dist/core/src/services/Ownable.service.js.map +1 -0
  46. package/dist/core/src/services/OwnablePackageCid.service.d.ts +6 -0
  47. package/dist/core/src/services/OwnablePackageCid.service.d.ts.map +1 -0
  48. package/dist/core/src/services/OwnablePackageCid.service.js +24 -0
  49. package/dist/core/src/services/OwnablePackageCid.service.js.map +1 -0
  50. package/dist/core/src/services/Polling.service.d.ts +31 -0
  51. package/dist/core/src/services/Polling.service.d.ts.map +1 -0
  52. package/dist/core/src/services/Polling.service.js +109 -0
  53. package/dist/core/src/services/Polling.service.js.map +1 -0
  54. package/dist/core/src/services/ReplayAuthority.service.d.ts +20 -0
  55. package/dist/core/src/services/ReplayAuthority.service.d.ts.map +1 -0
  56. package/dist/core/src/services/ReplayAuthority.service.js +171 -0
  57. package/dist/core/src/services/ReplayAuthority.service.js.map +1 -0
  58. package/dist/core/src/services/SIWE.service.d.ts +16 -0
  59. package/dist/core/src/services/SIWE.service.d.ts.map +1 -0
  60. package/dist/core/src/services/SIWE.service.js +123 -0
  61. package/dist/core/src/services/SIWE.service.js.map +1 -0
  62. package/dist/core/src/services/StateStoreRecordStore.service.d.ts +13 -0
  63. package/dist/core/src/services/StateStoreRecordStore.service.d.ts.map +1 -0
  64. package/dist/core/src/services/StateStoreRecordStore.service.js +76 -0
  65. package/dist/core/src/services/StateStoreRecordStore.service.js.map +1 -0
  66. package/dist/core/src/services/WorkerRPC.service.d.ts +45 -0
  67. package/dist/core/src/services/WorkerRPC.service.d.ts.map +1 -0
  68. package/dist/core/src/services/WorkerRPC.service.js +290 -0
  69. package/dist/core/src/services/WorkerRPC.service.js.map +1 -0
  70. package/dist/core/src/services/workerSource.d.ts +2 -0
  71. package/dist/core/src/services/workerSource.d.ts.map +1 -0
  72. package/dist/core/src/services/workerSource.js +74 -0
  73. package/dist/core/src/services/workerSource.js.map +1 -0
  74. package/dist/core/src/types/AnchorValidation.d.ts +45 -0
  75. package/dist/core/src/types/AnchorValidation.d.ts.map +1 -0
  76. package/dist/core/src/types/AnchorValidation.js +2 -0
  77. package/dist/core/src/types/AnchorValidation.js.map +1 -0
  78. package/dist/core/src/types/Authority.d.ts +40 -0
  79. package/dist/core/src/types/Authority.d.ts.map +1 -0
  80. package/dist/core/src/types/Authority.js +2 -0
  81. package/dist/core/src/types/Authority.js.map +1 -0
  82. package/dist/core/src/types/EventChainStore.d.ts +12 -0
  83. package/dist/core/src/types/EventChainStore.d.ts.map +1 -0
  84. package/dist/core/src/types/EventChainStore.js +2 -0
  85. package/dist/core/src/types/EventChainStore.js.map +1 -0
  86. package/dist/core/src/types/MessageInfo.d.ts +19 -0
  87. package/dist/core/src/types/MessageInfo.d.ts.map +1 -0
  88. package/dist/core/src/types/MessageInfo.js +2 -0
  89. package/dist/core/src/types/MessageInfo.js.map +1 -0
  90. package/dist/core/src/types/OwnableRuntime.d.ts +79 -0
  91. package/dist/core/src/types/OwnableRuntime.d.ts.map +1 -0
  92. package/dist/core/src/types/OwnableRuntime.js +2 -0
  93. package/dist/core/src/types/OwnableRuntime.js.map +1 -0
  94. package/dist/core/src/types/Polling.d.ts +14 -0
  95. package/dist/core/src/types/Polling.d.ts.map +1 -0
  96. package/dist/core/src/types/Polling.js +2 -0
  97. package/dist/core/src/types/Polling.js.map +1 -0
  98. package/dist/core/src/types/Replay.d.ts +100 -0
  99. package/dist/core/src/types/Replay.d.ts.map +1 -0
  100. package/dist/core/src/types/Replay.js +2 -0
  101. package/dist/core/src/types/Replay.js.map +1 -0
  102. package/dist/core/src/types/SIWE.d.ts +30 -0
  103. package/dist/core/src/types/SIWE.d.ts.map +1 -0
  104. package/dist/core/src/types/SIWE.js +2 -0
  105. package/dist/core/src/types/SIWE.js.map +1 -0
  106. package/dist/core/src/types/TypedCosmWasmMsg.d.ts +12 -0
  107. package/dist/core/src/types/TypedCosmWasmMsg.d.ts.map +1 -0
  108. package/dist/core/src/types/TypedCosmWasmMsg.js +2 -0
  109. package/dist/core/src/types/TypedCosmWasmMsg.js.map +1 -0
  110. package/dist/core/src/types/TypedDict.d.ts +4 -0
  111. package/dist/core/src/types/TypedDict.d.ts.map +1 -0
  112. package/dist/core/src/types/TypedDict.js +2 -0
  113. package/dist/core/src/types/TypedDict.js.map +1 -0
  114. package/dist/core/src/types/TypedOwnableInfo.d.ts +34 -0
  115. package/dist/core/src/types/TypedOwnableInfo.d.ts.map +1 -0
  116. package/dist/core/src/types/TypedOwnableInfo.js +2 -0
  117. package/dist/core/src/types/TypedOwnableInfo.js.map +1 -0
  118. package/dist/core/src/types/TypedPackage.d.ts +39 -0
  119. package/dist/core/src/types/TypedPackage.d.ts.map +1 -0
  120. package/dist/core/src/types/TypedPackage.js +2 -0
  121. package/dist/core/src/types/TypedPackage.js.map +1 -0
  122. package/package.json +7 -5
  123. package/dist/index.d.ts.map +0 -1
  124. package/dist/index.js.map +0 -1
  125. package/dist/services/EQTY.service.d.ts.map +0 -1
  126. package/dist/services/EQTY.service.js.map +0 -1
  127. package/dist/services/MockEQTY.service.d.ts.map +0 -1
  128. package/dist/services/MockEQTY.service.js.map +0 -1
  129. package/dist/types/EQTY.d.ts.map +0 -1
  130. /package/dist/{index.d.ts → adapter-viem/src/index.d.ts} +0 -0
  131. /package/dist/{index.js → adapter-viem/src/index.js} +0 -0
  132. /package/dist/{types → adapter-viem/src/types}/EQTY.js +0 -0
@@ -0,0 +1,692 @@
1
+ import { EventChain, Event, Binary } from "eqty-core";
2
+ import { encode } from "cbor-x";
3
+ import { withProgress } from "../progress.js";
4
+ import WorkerRPC from "./WorkerRPC.service.js";
5
+ import { DEFAULT_WORKER_SOURCE } from "./workerSource.js";
6
+ import { dedupeIndexedPublicEvents, publicEventReplayKey, selectReplayableIndexedPublicEvents } from "./ReplayAuthority.service.js";
7
+ export default class OwnableService {
8
+ stateStore;
9
+ eventChains;
10
+ eqty;
11
+ packages;
12
+ runtimeSource;
13
+ logger;
14
+ runtimeRpc;
15
+ SNAPSHOT_INTERVAL = 50;
16
+ PUBLIC_EVENT_REPLAY_STORE_SUFFIX = ".public-event-replays";
17
+ constructor(stateStore, eventChains, eqty, packages, runtimeSource = {
18
+ getWorkerSource: () => DEFAULT_WORKER_SOURCE,
19
+ }, logger = console, runtimeRpc = {
20
+ create: (id) => new WorkerRPC(id),
21
+ }) {
22
+ this.stateStore = stateStore;
23
+ this.eventChains = eventChains;
24
+ this.eqty = eqty;
25
+ this.packages = packages;
26
+ this.runtimeSource = runtimeSource;
27
+ this.logger = logger;
28
+ this.runtimeRpc = runtimeRpc;
29
+ }
30
+ _rpc = new Map();
31
+ get anchoring() {
32
+ return this.eventChains.anchoring;
33
+ }
34
+ async loadAll() {
35
+ return this.eventChains.loadAll();
36
+ }
37
+ isReady(id) {
38
+ return this._rpc.has(id);
39
+ }
40
+ rpc(id) {
41
+ const rpc = this._rpc.get(id);
42
+ if (!rpc)
43
+ throw new Error(`No RPC for ownable ${id}`);
44
+ return rpc;
45
+ }
46
+ clearRpc(id) {
47
+ const rpc = this._rpc.get(id);
48
+ if (!rpc)
49
+ return;
50
+ rpc.terminate();
51
+ this._rpc.delete(id);
52
+ }
53
+ setWidgetWindow(id, win) {
54
+ const rpc = this._rpc.get(id);
55
+ if (rpc)
56
+ rpc.setWidgetWindow(win);
57
+ }
58
+ async initWorker(id, cid) {
59
+ if (this._rpc.has(id))
60
+ return;
61
+ const js = this.runtimeSource.getWorkerSource();
62
+ const wasm = (await this.packages.getAsset(cid, "ownable_bg.wasm", (fr, file) => fr.readAsArrayBuffer(file)));
63
+ const rpc = this.runtimeRpc.create(id);
64
+ await rpc.initialize(js, new Uint8Array(wasm));
65
+ this._rpc.set(id, rpc);
66
+ }
67
+ async create(pkg, onProgress) {
68
+ const address = this.eqty.address;
69
+ const networkId = this.eqty.chainId;
70
+ const chain = EventChain.create(address, networkId);
71
+ const anchors = [];
72
+ if (pkg.isDynamic || this.anchoring) {
73
+ const msg = {
74
+ "@context": "instantiate_msg.json",
75
+ ownable_id: chain.id,
76
+ package: pkg.cid,
77
+ network_id: networkId,
78
+ keywords: pkg.keywords ?? [],
79
+ ...(pkg.title ? { name: pkg.title } : {}),
80
+ ...(pkg.description ? { description: pkg.description } : {}),
81
+ };
82
+ await withProgress(onProgress)("signEvent", () => this.eqty.sign(new Event(msg).addTo(chain)));
83
+ }
84
+ if (this.anchoring) {
85
+ const hash = chain.latestHash.hex;
86
+ anchors.push(...chain.startingWith(Binary.fromHex(hash)).anchorMap);
87
+ }
88
+ if (anchors.length > 0) {
89
+ // Queue anchors and submit as single tx
90
+ await this.eqty.anchor(...anchors);
91
+ const txHash = await withProgress(onProgress)("anchorEvent", () => this.eqty.submitAnchors());
92
+ return txHash ? { chain, txHash } : { chain };
93
+ }
94
+ return { chain };
95
+ }
96
+ async init(chain, cid, uniqueMessageHash) {
97
+ if (!this._rpc.has(chain.id)) {
98
+ await this.initWorker(chain.id, cid);
99
+ }
100
+ const stateDump = await this.apply(chain, []);
101
+ await this.initStore(chain, cid, uniqueMessageHash, stateDump);
102
+ }
103
+ async createSnapshot(chain, stateDump, eventIndex) {
104
+ const chainId = chain.id;
105
+ const storeId = `ownable:${chainId}`;
106
+ const snapshotStoreId = `${storeId}.snapshots`;
107
+ try {
108
+ const snapshot = {
109
+ eventIndex,
110
+ blockHash: chain.latestHash.hex,
111
+ stateDump,
112
+ timestamp: new Date(),
113
+ };
114
+ if (!(await this.stateStore.hasStore(snapshotStoreId))) {
115
+ await this.stateStore.createStore(snapshotStoreId);
116
+ }
117
+ await this.stateStore.set(snapshotStoreId, `snapshot_${eventIndex}`, snapshot);
118
+ // Cleanup old snapshots (keep only last 3)
119
+ const keys = await this.stateStore.keys(snapshotStoreId);
120
+ if (keys.length > 3) {
121
+ const sortedKeys = keys
122
+ .map((key) => parseInt(key.replace("snapshot_", "")))
123
+ .sort((a, b) => b - a);
124
+ // Delete oldest snapshots, keep the 3 most recent
125
+ const keysToDelete = sortedKeys
126
+ .slice(3)
127
+ .map((index) => `snapshot_${index}`);
128
+ for (const key of keysToDelete) {
129
+ await this.stateStore.delete(snapshotStoreId, key);
130
+ }
131
+ }
132
+ }
133
+ catch (error) {
134
+ this.logger.error("Error creating snapshot:", error);
135
+ }
136
+ }
137
+ async getLatestSnapshot(chainId) {
138
+ const storeId = `ownable:${chainId}`;
139
+ const snapshotStoreId = `${storeId}.snapshots`;
140
+ const exist = await this.stateStore.hasStore(snapshotStoreId);
141
+ if (!exist) {
142
+ return null;
143
+ }
144
+ const snapshots = await this.stateStore.keys(snapshotStoreId);
145
+ if (snapshots.length === 0)
146
+ return null;
147
+ const latestKey = snapshots
148
+ .map((key) => parseInt(key.replace("snapshot_", "")))
149
+ .sort((a, b) => b - a)[0];
150
+ return await this.stateStore.get(snapshotStoreId, `snapshot_${latestKey}`);
151
+ }
152
+ async listSnapshots(chainId) {
153
+ const storeId = `ownable:${chainId}`;
154
+ const snapshotStoreId = `${storeId}.snapshots`;
155
+ if (!(await this.stateStore.hasStore(snapshotStoreId))) {
156
+ return [];
157
+ }
158
+ const snapshots = await this.stateStore.keys(snapshotStoreId);
159
+ const sortedKeys = snapshots
160
+ .map((key) => parseInt(key.replace("snapshot_", "")))
161
+ .sort((a, b) => a - b);
162
+ return Promise.all(sortedKeys.map((index) => this.stateStore.get(snapshotStoreId, `snapshot_${index}`)));
163
+ }
164
+ async deleteSnapshots(chainId) {
165
+ const storeId = `ownable:${chainId}`;
166
+ const snapshotStoreId = `${storeId}.snapshots`;
167
+ if (await this.stateStore.hasStore(snapshotStoreId)) {
168
+ await this.stateStore.deleteStore(snapshotStoreId);
169
+ }
170
+ }
171
+ publicEventReplayStoreId(chainId) {
172
+ return `ownable:${chainId}${this.PUBLIC_EVENT_REPLAY_STORE_SUFFIX}`;
173
+ }
174
+ replayRecord(event, status, sources) {
175
+ return {
176
+ replayKey: publicEventReplayKey(event),
177
+ event,
178
+ status,
179
+ sources: [...new Set(sources)],
180
+ };
181
+ }
182
+ mergeReplayRecordSources(current, next) {
183
+ return current.includes(next) ? current : [...current, next];
184
+ }
185
+ async ensureReplayStore(chainId) {
186
+ const replayStoreId = this.publicEventReplayStoreId(chainId);
187
+ if (!(await this.stateStore.hasStore(replayStoreId))) {
188
+ await this.stateStore.createStore(replayStoreId);
189
+ }
190
+ return replayStoreId;
191
+ }
192
+ async listReplayRecords(chainId) {
193
+ const replayStoreId = this.publicEventReplayStoreId(chainId);
194
+ if (!(await this.stateStore.hasStore(replayStoreId))) {
195
+ return [];
196
+ }
197
+ const records = (await this.stateStore.getAll(replayStoreId));
198
+ return [...records].sort((left, right) => {
199
+ if (left.event.blockNumber !== right.event.blockNumber) {
200
+ return left.event.blockNumber - right.event.blockNumber;
201
+ }
202
+ if (left.event.transactionIndex !== right.event.transactionIndex) {
203
+ return left.event.transactionIndex - right.event.transactionIndex;
204
+ }
205
+ return left.event.logIndex - right.event.logIndex;
206
+ });
207
+ }
208
+ async listTrackedPublicEvents(chainId) {
209
+ return this.listReplayRecords(chainId);
210
+ }
211
+ emptyReplayAttemptResult(stateDump) {
212
+ return {
213
+ complete: true,
214
+ stateDump,
215
+ appliedEvents: [],
216
+ appliedReplayKeys: [],
217
+ duplicateReplayKeys: [],
218
+ appliedPublicEvents: [],
219
+ duplicatePublicEvents: [],
220
+ ignoredPublicEvents: [],
221
+ pendingPublicEvents: [],
222
+ confirmedPendingPublicEvents: [],
223
+ };
224
+ }
225
+ publicEventSubjectId(chain) {
226
+ return Binary.fromHex(chain.id).hash().hex;
227
+ }
228
+ provisionalPublicEventReplayKey(chain, eventType, data) {
229
+ return `pending:${this.publicEventSubjectId(chain)}:${eventType}:${new Binary(data).hash().hex}`;
230
+ }
231
+ provisionalPublicEventRecord(chain, eventType, data) {
232
+ const replayKey = this.provisionalPublicEventReplayKey(chain, eventType, data);
233
+ const payloadHex = new Binary(data).hex;
234
+ return {
235
+ replayKey,
236
+ event: {
237
+ source: this.eqty.address,
238
+ eventType,
239
+ data: payloadHex,
240
+ blockNumber: 0,
241
+ transactionHash: payloadHex,
242
+ transactionIndex: 0,
243
+ logIndex: 0,
244
+ },
245
+ status: "pending",
246
+ sources: ["local"],
247
+ };
248
+ }
249
+ toRegisterRuntimeEvent(event) {
250
+ const { subjectId: _subjectId, timestamp: _timestamp, ...publicEvent } = event;
251
+ return {
252
+ ...publicEvent,
253
+ data: typeof publicEvent.data === "string"
254
+ ? publicEvent.data
255
+ : new Binary(event.data).hex,
256
+ };
257
+ }
258
+ publicEventSubjectMatches(chain, event) {
259
+ return event.subjectId.toLowerCase() === this.publicEventSubjectId(chain).toLowerCase();
260
+ }
261
+ toRegisterRpcPayload(event) {
262
+ return {
263
+ ...event,
264
+ data: Binary.fromHex(event.data),
265
+ transactionHash: Binary.fromHex(event.transactionHash),
266
+ };
267
+ }
268
+ async applyEvent(rpc, event, stateDump, chain, eventIndex) {
269
+ const info = {
270
+ sender: event.signerAddress || this.eqty.address,
271
+ funds: [],
272
+ };
273
+ const { "@context": context, ...msg } = event.parsedData;
274
+ let result;
275
+ switch (context) {
276
+ case "instantiate_msg.json":
277
+ result = await rpc.instantiate(msg, info);
278
+ break;
279
+ case "execute_msg.json":
280
+ result = await rpc.execute(msg, info, stateDump);
281
+ break;
282
+ case "register_msg.json":
283
+ result = await rpc.register(this.toRegisterRpcPayload(msg), info, stateDump);
284
+ break;
285
+ case "ingest_msg.json":
286
+ result = await rpc.ingest(msg, info, stateDump);
287
+ break;
288
+ default:
289
+ throw new Error(`Unknown event type`);
290
+ }
291
+ if ((eventIndex + 1) % this.SNAPSHOT_INTERVAL === 0) {
292
+ await this.createSnapshot(chain, result.state, eventIndex);
293
+ }
294
+ return result;
295
+ }
296
+ async apply(partialChain, stateDump) {
297
+ const rpc = this.rpc(partialChain.id);
298
+ const snapshot = await this.getLatestSnapshot(partialChain.id);
299
+ let startIndex = 0;
300
+ if (snapshot) {
301
+ const snapshotEventIndex = partialChain.events.findIndex((e) => e.hash?.hex === snapshot.blockHash);
302
+ if (snapshotEventIndex !== -1) {
303
+ stateDump = snapshot.stateDump;
304
+ startIndex = snapshotEventIndex + 1;
305
+ }
306
+ }
307
+ const BATCH_SIZE = 10;
308
+ const totalEvents = partialChain.events.length;
309
+ for (let batchStart = startIndex; batchStart < totalEvents; batchStart += BATCH_SIZE) {
310
+ const batchEnd = Math.min(batchStart + BATCH_SIZE, totalEvents);
311
+ const batch = partialChain.events.slice(batchStart, batchEnd);
312
+ for (let i = 0; i < batch.length; i++) {
313
+ const globalIndex = batchStart + i;
314
+ const event = batch[i];
315
+ if (!event)
316
+ continue;
317
+ try {
318
+ const result = await this.applyEvent(rpc, event, stateDump, partialChain, globalIndex);
319
+ stateDump = result.state;
320
+ }
321
+ catch (error) {
322
+ this.logger.error(`Error applying event at index ${globalIndex}:`, error);
323
+ if (globalIndex > startIndex) {
324
+ await this.createSnapshot(partialChain, stateDump, globalIndex - 1);
325
+ }
326
+ throw error;
327
+ }
328
+ }
329
+ if (batchEnd < totalEvents) {
330
+ await new Promise((resolve) => setTimeout(resolve, 0));
331
+ }
332
+ }
333
+ return stateDump;
334
+ }
335
+ async replayIndexedPublicEvents(chainId, stateDump, indexedPublicEvents, options) {
336
+ return this.attemptReplayIndexedPublicEvents(chainId, stateDump, indexedPublicEvents, options);
337
+ }
338
+ async attemptReplayIndexedPublicEvents(chainId, stateDump, indexedPublicEvents, options) {
339
+ const info = {
340
+ sender: this.eqty.address,
341
+ funds: [],
342
+ };
343
+ const deduped = dedupeIndexedPublicEvents(indexedPublicEvents);
344
+ const selected = options
345
+ ? selectReplayableIndexedPublicEvents(indexedPublicEvents, options)
346
+ : { events: deduped.events, ignoredPublicEvents: [] };
347
+ const events = selected.events;
348
+ const duplicateReplayKeys = deduped.duplicateReplayKeys;
349
+ const appliedEvents = [];
350
+ const appliedReplayKeys = [];
351
+ const appliedPublicEvents = [];
352
+ const duplicatePublicEvents = deduped.duplicateEvents.map((event) => ({
353
+ replayKey: publicEventReplayKey(event),
354
+ event,
355
+ }));
356
+ const ignoredPublicEvents = [...selected.ignoredPublicEvents];
357
+ let nextState = stateDump;
358
+ for (const indexedEvent of events) {
359
+ const runtimeEvent = this.toRegisterRuntimeEvent(indexedEvent);
360
+ const replayKey = publicEventReplayKey(indexedEvent);
361
+ try {
362
+ const { state } = await this.rpc(chainId).register(this.toRegisterRpcPayload(runtimeEvent), info, nextState);
363
+ nextState = state;
364
+ appliedEvents.push(indexedEvent);
365
+ appliedReplayKeys.push(replayKey);
366
+ appliedPublicEvents.push({
367
+ replayKey,
368
+ event: indexedEvent,
369
+ });
370
+ }
371
+ catch (cause) {
372
+ ignoredPublicEvents.push({
373
+ replayKey,
374
+ event: indexedEvent,
375
+ reason: "register_failed",
376
+ cause,
377
+ });
378
+ }
379
+ }
380
+ return {
381
+ complete: ignoredPublicEvents.length === 0,
382
+ stateDump: nextState,
383
+ appliedEvents,
384
+ appliedReplayKeys,
385
+ duplicateReplayKeys,
386
+ appliedPublicEvents,
387
+ duplicatePublicEvents,
388
+ ignoredPublicEvents,
389
+ pendingPublicEvents: [],
390
+ confirmedPendingPublicEvents: [],
391
+ };
392
+ }
393
+ async applyIndexedPublicEventSnapshot(chain, indexedPublicEvents, onProgress) {
394
+ return this.reconcileIndexedPublicEvents(chain, indexedPublicEvents, "snapshot", onProgress);
395
+ }
396
+ async applyIndexedPublicEventStream(chain, indexedPublicEvents, onProgress) {
397
+ return this.reconcileIndexedPublicEvents(chain, indexedPublicEvents, "stream", onProgress);
398
+ }
399
+ async reconcileIndexedPublicEvents(chain, indexedPublicEvents, source, onProgress) {
400
+ const stateDump = await this.eventChains.getStateDump(chain.id, chain.state.hex);
401
+ if (!stateDump)
402
+ throw Error("State mismatch for register public event");
403
+ const replayStoreId = await this.ensureReplayStore(chain.id);
404
+ const base = this.emptyReplayAttemptResult(stateDump);
405
+ const deduped = dedupeIndexedPublicEvents(indexedPublicEvents);
406
+ const info = {
407
+ sender: this.eqty.address,
408
+ funds: [],
409
+ };
410
+ base.duplicateReplayKeys.push(...deduped.duplicateReplayKeys);
411
+ base.duplicatePublicEvents.push(...deduped.duplicateEvents.map((event) => this.replayRecord(event, "confirmed", [source])));
412
+ let nextState = stateDump;
413
+ for (const indexedEvent of deduped.events) {
414
+ const replayKey = publicEventReplayKey(indexedEvent);
415
+ const existing = (await this.stateStore.get(replayStoreId, replayKey).catch(() => undefined));
416
+ if (existing?.status === "confirmed") {
417
+ const updated = this.replayRecord(existing.event, "confirmed", this.mergeReplayRecordSources(existing.sources, source));
418
+ await this.stateStore.set(replayStoreId, replayKey, updated);
419
+ base.duplicateReplayKeys.push(replayKey);
420
+ base.duplicatePublicEvents.push(updated);
421
+ continue;
422
+ }
423
+ const runtimeEvent = this.toRegisterRuntimeEvent(indexedEvent);
424
+ try {
425
+ const { state } = await this.rpc(chain.id).register(this.toRegisterRpcPayload(runtimeEvent), info, nextState);
426
+ nextState = state;
427
+ await withProgress(onProgress)("signPublicEvent", () => this.eqty.sign(new Event({
428
+ "@context": "register_msg.json",
429
+ ...runtimeEvent,
430
+ }).addTo(chain)));
431
+ await this.store(chain, nextState);
432
+ const confirmedRecord = this.replayRecord(indexedEvent, "confirmed", existing?.status === "pending"
433
+ ? this.mergeReplayRecordSources(existing.sources, source)
434
+ : [source]);
435
+ await this.stateStore.set(replayStoreId, replayKey, confirmedRecord);
436
+ base.appliedEvents.push(indexedEvent);
437
+ base.appliedReplayKeys.push(replayKey);
438
+ base.appliedPublicEvents.push({ replayKey, event: indexedEvent });
439
+ if (existing?.status === "pending") {
440
+ base.confirmedPendingPublicEvents.push(confirmedRecord);
441
+ }
442
+ }
443
+ catch (cause) {
444
+ base.ignoredPublicEvents.push({
445
+ replayKey,
446
+ event: indexedEvent,
447
+ reason: "register_failed",
448
+ cause,
449
+ });
450
+ }
451
+ }
452
+ return {
453
+ ...base,
454
+ complete: base.ignoredPublicEvents.length === 0,
455
+ stateDump: nextState,
456
+ };
457
+ }
458
+ async execute(chain, msg, stateDump, onProgress, attachments = []) {
459
+ const info = { sender: this.eqty.address, funds: [] };
460
+ const { state: newStateDump } = await this.rpc(chain.id).execute(msg, info, stateDump);
461
+ delete msg["@context"]; // Shouldn't be set
462
+ const event = new Event({ "@context": "execute_msg.json", ...msg }).addTo(chain);
463
+ for (const attachment of attachments) {
464
+ event.addAttachment(attachment.name, new Uint8Array(await attachment.file.arrayBuffer()), attachment.file.type || "application/octet-stream");
465
+ }
466
+ await withProgress(onProgress)("signEvent", () => this.eqty.sign(event));
467
+ // Store without submitting anchors yet; submission is controlled by caller
468
+ await this.store(chain, newStateDump);
469
+ return newStateDump;
470
+ }
471
+ async registerPublicEvent(chain, event, onProgress) {
472
+ const publicEvent = this.toRegisterRuntimeEvent(event);
473
+ return this.applyIndexedPublicEventStream(chain, [publicEvent], onProgress);
474
+ }
475
+ async emitPublicEvent(chain, eventType, payload, onProgress) {
476
+ const stateDump = await this.eventChains.getStateDump(chain.id, chain.state.hex);
477
+ if (!stateDump)
478
+ throw Error("State mismatch for emit public event");
479
+ const encodedPayload = await withProgress(onProgress)("encodePublicEvent", () => this.rpc(chain.id).encodePublicEvent(eventType, encode(payload)));
480
+ const subjectId = this.publicEventSubjectId(chain);
481
+ const replayStoreId = await this.ensureReplayStore(chain.id);
482
+ const provisionalPendingRecord = this.provisionalPublicEventRecord(chain, eventType, encodedPayload);
483
+ await this.stateStore.set(replayStoreId, provisionalPendingRecord.replayKey, provisionalPendingRecord);
484
+ let publicEvent;
485
+ try {
486
+ publicEvent = await withProgress(onProgress)("emitPublicEvent", () => this.eqty.emitPublicEvent(subjectId, eventType, encodedPayload));
487
+ }
488
+ catch (cause) {
489
+ await this.stateStore.delete(replayStoreId, provisionalPendingRecord.replayKey);
490
+ throw cause;
491
+ }
492
+ if (!this.publicEventSubjectMatches(chain, publicEvent)) {
493
+ await this.stateStore.delete(replayStoreId, provisionalPendingRecord.replayKey);
494
+ const result = this.emptyReplayAttemptResult(stateDump);
495
+ result.complete = false;
496
+ result.ignoredPublicEvents.push({
497
+ replayKey: publicEventReplayKey(this.toRegisterRuntimeEvent(publicEvent)),
498
+ event: this.toRegisterRuntimeEvent(publicEvent),
499
+ reason: "invalid_subject_id",
500
+ cause: {
501
+ expectedSubjectId: subjectId,
502
+ receivedSubjectId: publicEvent.subjectId,
503
+ },
504
+ });
505
+ return result;
506
+ }
507
+ const runtimeEvent = this.toRegisterRuntimeEvent(publicEvent);
508
+ const pendingRecord = this.replayRecord(runtimeEvent, "pending", ["local"]);
509
+ await this.stateStore.delete(replayStoreId, provisionalPendingRecord.replayKey);
510
+ await this.stateStore.set(replayStoreId, pendingRecord.replayKey, pendingRecord);
511
+ const result = this.emptyReplayAttemptResult(stateDump);
512
+ result.pendingPublicEvents.push(pendingRecord);
513
+ return result;
514
+ }
515
+ async submitAnchors(onProgress) {
516
+ if (!this.anchoring)
517
+ return undefined;
518
+ return await withProgress(onProgress)("anchor", () => this.eqty.submitAnchors());
519
+ }
520
+ async canConsume(consumer, info) {
521
+ if (!this.packages.info(consumer.package).isConsumer)
522
+ return false;
523
+ try {
524
+ const state = await this.eventChains.getStateDump(consumer.chain.id, consumer.chain.state.hex);
525
+ if (!state)
526
+ return false;
527
+ const result = await this.rpc(consumer.chain.id).query({
528
+ is_consumer_of: {
529
+ consumable_type: info.ownable_type,
530
+ issuer: info.issuer,
531
+ },
532
+ }, state);
533
+ return result === true;
534
+ }
535
+ catch (error) {
536
+ this.logger.warn("Error checking canConsume:", error);
537
+ return false;
538
+ }
539
+ }
540
+ async consume(consumer, consumable, onProgress) {
541
+ const info = {
542
+ sender: this.eqty.address,
543
+ funds: [],
544
+ };
545
+ const consumeMessage = { consume: {} };
546
+ const consumerState = await this.eventChains.getStateDump(consumer.id, consumer.state.hex);
547
+ const consumableState = await this.eventChains.getStateDump(consumable.id, consumable.state.hex);
548
+ if (!consumerState || !consumableState)
549
+ throw Error("State mismatch for consume");
550
+ const { events, state: consumableStateDump } = await this.rpc(consumable.id).execute(consumeMessage, info, consumableState);
551
+ const consumeEvent = events.find((event) => event.type === "consume");
552
+ if (!consumeEvent)
553
+ throw Error("No consume event emitted");
554
+ const consumableInfo = (await this.rpc(consumable.id).query({ get_info: {} }, consumableStateDump));
555
+ const ingestEvent = {
556
+ source: {
557
+ id: consumable.id,
558
+ owner: consumableInfo.owner,
559
+ issuer: consumableInfo.issuer,
560
+ },
561
+ attributes: consumeEvent.attributes,
562
+ eventType: consumeEvent.type,
563
+ };
564
+ const { state: consumerStateDump } = await this.rpc(consumer.id).ingest(ingestEvent, info, consumerState);
565
+ await withProgress(onProgress)("signConsumableEvent", () => this.eqty.sign(new Event({ "@context": "execute_msg.json", ...consumeMessage }).addTo(consumable)));
566
+ await withProgress(onProgress)("signConsumerEvent", () => this.eqty.sign(new Event({
567
+ "@context": "ingest_msg.json",
568
+ ...ingestEvent,
569
+ }).addTo(consumer)));
570
+ // Store both chains; emit anchor progress only once to represent anchoring both
571
+ // Queue anchors for both chains without submitting yet
572
+ await this.store(consumable, consumableStateDump);
573
+ await this.stateStore.set(`ownable:${consumable.id}`, "isConsumed", true);
574
+ await this.store(consumer, consumerStateDump);
575
+ // Submit a single anchor tx for both
576
+ await this.submitAnchors(onProgress);
577
+ }
578
+ async retryOperation(operation, maxRetries = 3, delay = 1000) {
579
+ for (let attempt = 1; attempt <= maxRetries; attempt++) {
580
+ try {
581
+ return await operation();
582
+ }
583
+ catch (error) {
584
+ this.logger.warn(`Attempt ${attempt} failed:`, error);
585
+ if (attempt < maxRetries) {
586
+ await new Promise((resolve) => setTimeout(resolve, delay * attempt));
587
+ }
588
+ }
589
+ }
590
+ throw new Error(`Operation failed after ${maxRetries} attempts. Last error: `);
591
+ }
592
+ async initStore(chain, pkg, uniqueMessageHash, stateDump) {
593
+ const storeId = `ownable:${chain.id}`;
594
+ const stateStoreId = `${storeId}.state`;
595
+ const chainData = {
596
+ chain: chain.toJSON(),
597
+ state: chain.state.hex,
598
+ package: pkg,
599
+ isConsumed: false,
600
+ created: new Date(),
601
+ latestHash: chain.latestHash.hex,
602
+ keywords: this.packages.info(pkg).keywords,
603
+ uniqueMessageHash: this.packages.info(pkg, uniqueMessageHash)
604
+ .uniqueMessageHash,
605
+ };
606
+ const stores = [storeId];
607
+ if (stateDump)
608
+ stores.push(stateStoreId);
609
+ await this.retryOperation(async () => {
610
+ const hasStore = await this.stateStore.hasStore(storeId);
611
+ if (hasStore) {
612
+ return;
613
+ }
614
+ await this.stateStore.createStore(...stores);
615
+ const data = {
616
+ [storeId]: chainData,
617
+ };
618
+ if (stateDump) {
619
+ data[stateStoreId] = new Map(stateDump);
620
+ }
621
+ try {
622
+ await this.stateStore.setAll(data);
623
+ }
624
+ catch (error) {
625
+ // If setAll fails, attempt to clean up
626
+ this.logger.error("Failed to set data, cleaning up stores...");
627
+ await Promise.all(stores.map((store) => this.stateStore.deleteStore(store).catch(() => { })));
628
+ throw error;
629
+ }
630
+ const verifyData = await Promise.all([
631
+ this.stateStore.get(storeId, "state"),
632
+ stateDump ? this.stateStore.getAll(stateStoreId) : Promise.resolve(null),
633
+ ]);
634
+ if (verifyData[0] !== chainData.state ||
635
+ (stateDump && !verifyData[1]?.length)) {
636
+ throw new Error("Data verification failed after write");
637
+ }
638
+ });
639
+ }
640
+ async store(chain, stateDump) {
641
+ const anchors = [];
642
+ const storeId = `ownable:${chain.id}`;
643
+ const stateStoreId = `${storeId}.state`;
644
+ await this.retryOperation(async () => {
645
+ const storedState = await this.stateStore.get(storeId, "state");
646
+ if (storedState === chain.state)
647
+ return;
648
+ const data = {
649
+ [storeId]: {
650
+ chain: chain.toJSON(),
651
+ state: chain.state.hex,
652
+ latestHash: chain.latestHash.hex,
653
+ },
654
+ [stateStoreId]: new Map(stateDump),
655
+ };
656
+ if (this.anchoring) {
657
+ const previousHash = await this.stateStore.get(`ownable:${chain.id}`, "latestHash");
658
+ anchors.push(...chain.startingAfter(Binary.fromHex(previousHash)).anchorMap);
659
+ }
660
+ if (anchors.length > 0) {
661
+ // Queue anchors only; submission handled separately to allow batching
662
+ await this.eqty.anchor(...anchors);
663
+ }
664
+ await this.stateStore.setAll(data);
665
+ const eventCount = chain.events.length;
666
+ if (eventCount % this.SNAPSHOT_INTERVAL === 0) {
667
+ await this.createSnapshot(chain, stateDump, eventCount - 1);
668
+ }
669
+ // Verify write
670
+ const verifyState = await this.stateStore.get(storeId, "state");
671
+ if (verifyState !== chain.state.hex) {
672
+ throw new Error("State verification failed after write");
673
+ }
674
+ });
675
+ }
676
+ async delete(id) {
677
+ await this.eventChains.delete(id);
678
+ }
679
+ async deleteAll() {
680
+ await this.eventChains.deleteAll();
681
+ }
682
+ async zip(chain) {
683
+ const firstEvent = chain.events[0];
684
+ if (!firstEvent)
685
+ throw new Error("Cannot zip an empty ownable chain");
686
+ const packageCid = firstEvent.parsedData.package;
687
+ const zip = await this.packages.zip(packageCid);
688
+ zip.file("chain.json", JSON.stringify(chain.toJSON()));
689
+ return zip;
690
+ }
691
+ }
692
+ //# sourceMappingURL=Ownable.service.js.map