@seedprotocol/publish 0.7.3-next.613.g79a8dfd → 0.7.4-next.711.gce2b766

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 (44) hide show
  1. package/README.md +4 -2
  2. package/dist/chainConfig-RhKIuGtN.js +5289 -0
  3. package/dist/chainConfig-RhKIuGtN.js.map +1 -0
  4. package/dist/config.d.ts +3 -1
  5. package/dist/config.d.ts.map +1 -1
  6. package/dist/{ensureAutomationSessionKey-bw6knEyC.js → ensureAutomationSessionKey-CvUntLne.js} +25 -26
  7. package/dist/{ensureAutomationSessionKey-bw6knEyC.js.map → ensureAutomationSessionKey-CvUntLne.js.map} +1 -1
  8. package/dist/{ensureModularPublishBootstrap-Vc4Jz_B9.js → ensureModularPublishBootstrap-D9q246TT.js} +9 -11
  9. package/dist/{ensureModularPublishBootstrap-Vc4Jz_B9.js.map → ensureModularPublishBootstrap-D9q246TT.js.map} +1 -1
  10. package/dist/ensureSmartWalletThenPublish-C_iS5Wb-.js +52 -0
  11. package/dist/ensureSmartWalletThenPublish-C_iS5Wb-.js.map +1 -0
  12. package/dist/helpers/ensureSmartWalletThenPublish.d.ts +1 -0
  13. package/dist/helpers/ensureSmartWalletThenPublish.d.ts.map +1 -1
  14. package/dist/helpers/ensureWalletThenPublish.d.ts +7 -0
  15. package/dist/helpers/ensureWalletThenPublish.d.ts.map +1 -1
  16. package/dist/helpers/publishItem.d.ts +21 -0
  17. package/dist/helpers/publishItem.d.ts.map +1 -0
  18. package/dist/index.d.ts +2 -1
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +341 -476
  21. package/dist/index.js.map +1 -1
  22. package/dist/managedAccountAdmin-CLVRJEKI.js +26 -0
  23. package/dist/{managedAccountAdmin-B3DPMmhR.js.map → managedAccountAdmin-CLVRJEKI.js.map} +1 -1
  24. package/dist/publishAuthorization-DAarz1JK.js +176 -0
  25. package/dist/publishAuthorization-DAarz1JK.js.map +1 -0
  26. package/dist/{resolveRevokeAccount-CkbTpC27.js → resolveRevokeAccount-TRcqJtIO.js} +13 -15
  27. package/dist/{resolveRevokeAccount-CkbTpC27.js.map → resolveRevokeAccount-TRcqJtIO.js.map} +1 -1
  28. package/dist/services/publish/helpers/getPublishUploadData.d.ts +12 -23
  29. package/dist/services/publish/helpers/getPublishUploadData.d.ts.map +1 -1
  30. package/dist/services/upload/uploadMachine.d.ts +1 -1
  31. package/dist/thirdweb.js +144 -145
  32. package/dist/thirdweb.js.map +1 -1
  33. package/dist/{worker-CCQ7KBMm.js → worker-CyuMiBB-.js} +2 -2
  34. package/dist/{worker-CCQ7KBMm.js.map → worker-CyuMiBB-.js.map} +1 -1
  35. package/package.json +6 -6
  36. package/dist/chainConfig-BDMRU4m8.js +0 -1455
  37. package/dist/chainConfig-BDMRU4m8.js.map +0 -1
  38. package/dist/ensureSmartWalletThenPublish-42iEhiHG.js +0 -47
  39. package/dist/ensureSmartWalletThenPublish-42iEhiHG.js.map +0 -1
  40. package/dist/managedAccountAdmin-B3DPMmhR.js +0 -28
  41. package/dist/publishAuthorization-CAFF5jQ2.js +0 -4023
  42. package/dist/publishAuthorization-CAFF5jQ2.js.map +0 -1
  43. package/dist/publishThirdwebClient-CPzAjnmf.js +0 -18
  44. package/dist/publishThirdwebClient-CPzAjnmf.js.map +0 -1
@@ -1,4023 +0,0 @@
1
- import { t as e } from "./rolldown-runtime-Dy4uBu1J.js";
2
- import { At as t, B as n, Ct as r, D as i, Dt as a, Et as o, F as s, G as c, H as l, I as u, J as d, K as f, L as p, O as m, Ot as h, P as g, Q as _, R as v, St as y, V as b, X as x, Y as S, Z as ee, _ as C, _t as te, a as w, at as ne, b as re, bt as ie, c as ae, ct as oe, dt as T, et as se, f as ce, ft as le, h as ue, ht as de, it as fe, j as pe, jt as me, k as he, lt as ge, mt as E, o as D, ot as _e, q as ve, r as ye, rt as be, st as xe, t as O, u as Se, ut as Ce, v as k, wt as we, xt as Te, y as A, yt as Ee, z as De } from "./chainConfig-BDMRU4m8.js";
3
- import { t as j } from "./publishThirdwebClient-CPzAjnmf.js";
4
- import { BaseArweaveClient as Oe, BaseDb as ke, BaseFileManager as M, INTERNAL_DATA_TYPES as Ae, Item as N, ModelPropertyDataTypes as je, RelatedItemUnpublishedError as Me, applyPropertyAttestationUidsFromPublish as Ne, arweaveL1FinalizeJobs as Pe, assertLocalDbChain as Fe, getCorrectId as Ie, getEasSchemaForItemProperty as Le, getItemPropertiesFromEas as Re, getPublishDraftGraph as ze, getRelatedItemsForPublish as Be, getSegmentedItemProperties as Ve, getUnpublishedRelatedItems as He, getUploadPipelineTransactionStatus as Ue, htmlEmbeddedImageCoPublish as We, isItemOwned as Ge, isPublishedSeedRef as Ke, itemHasPublishUploadCandidates as qe, listRelationEasPropertyName as Je, normalizeDataType as Ye, normalizeRelationPropertyValue as Xe, prepareHtmlEmbeddedImagesForPublish as Ze, publishProcesses as P, resolvePublishPayloadValues as Qe, resolveSeedIdsFromRefString as $e, rewriteHtmlEmbeddedImagesOnDisk as et, setSchemaUidForModel as tt, setSchemaUidForSchemaDefinition as nt, updateVersionUid as rt, validateItemForPublish as it } from "@seedprotocol/sdk";
5
- import { BaseError as at, decodeAbiParameters as ot, decodeErrorResult as st, isAddressEqual as ct, parseEther as lt, parseEventLogs as ut, toFunctionSelector as dt, zeroAddress as ft } from "viem";
6
- import { deploySmartAccount as pt, getContract as mt } from "thirdweb";
7
- import { ethers as F, keccak256 as ht, toUtf8Bytes as gt } from "ethers";
8
- import { PUBLISH_AUTHORIZATION_DEFAULT_EXPIRATION_SECS as _t, PUBLISH_AUTHORIZATION_SCHEMA_DEF as vt, PUBLISH_AUTHORIZATION_SCHEMA_DEF as yt, PUBLISH_AUTHORIZATION_SCHEMA_NAME as bt, PUBLISH_AUTHORIZATION_SCHEMA_NAME as xt, PUBLISH_AUTHORIZATION_SCOPES as St, PUBLISH_AUTHORIZATION_SCOPES as Ct, assessPublishAuthorization as wt, decodePublishAuthorizationData as Tt, getPublishAuthorizationFromEas as Et, isValidEasAttestationUid as Dt, normalizeBytes32Hex as Ot } from "@seedprotocol/eas";
9
- import { createContext as kt, useContext as At, useEffect as jt, useRef as Mt, useState as Nt } from "react";
10
- import Pt from "arweave";
11
- import { NO_EXPIRATION as Ft, SchemaEncoder as It, SchemaRegistry as Lt, ZERO_ADDRESS as Rt, ZERO_BYTES32 as zt } from "@ethereum-attestation-service/eas-sdk";
12
- import { assign as I, createActor as Bt, enqueueActions as Vt, fromCallback as Ht, fromPromise as L, setup as Ut } from "xstate";
13
- import R from "debug";
14
- import { and as Wt, desc as Gt, eq as z } from "drizzle-orm";
15
- import { createWallet as Kt, inAppWallet as qt } from "thirdweb/wallets";
16
- import { useActiveAccount as Jt } from "thirdweb/react";
17
- import { estimateUserOpGas as Yt, getPaymasterAndData as Xt } from "thirdweb/wallets/smart";
18
- //#region src/react/PublishConfigContext.tsx
19
- var Zt = kt(null);
20
- function Qt() {
21
- let e = At(Zt);
22
- if (!e) throw Error("usePublishConfig: PublishConfig is missing. Pass config to PublishProvider or call initPublish() before render.");
23
- return e;
24
- }
25
- //#endregion
26
- //#region src/helpers/describeRevert.ts
27
- var $t = [
28
- {
29
- type: "error",
30
- name: "PublishIndexOutOfBounds",
31
- inputs: [{
32
- name: "targetIndex",
33
- type: "uint256"
34
- }, {
35
- name: "length",
36
- type: "uint256"
37
- }]
38
- },
39
- {
40
- type: "error",
41
- name: "UnknownPublishLocalId",
42
- inputs: [{
43
- name: "publishLocalId",
44
- type: "string"
45
- }]
46
- },
47
- {
48
- type: "error",
49
- name: "PublishTargetAlreadyAttested",
50
- inputs: [{
51
- name: "requestIndex",
52
- type: "uint256"
53
- }, {
54
- name: "targetIndex",
55
- type: "uint256"
56
- }]
57
- },
58
- {
59
- type: "error",
60
- name: "EmptyAttestationData",
61
- inputs: [{
62
- name: "targetIndex",
63
- type: "uint256"
64
- }, {
65
- name: "propertySchemaUid",
66
- type: "bytes32"
67
- }]
68
- },
69
- {
70
- type: "error",
71
- name: "PropertyToUpdateNotFound",
72
- inputs: [
73
- {
74
- name: "requestIndex",
75
- type: "uint256"
76
- },
77
- {
78
- name: "targetIndex",
79
- type: "uint256"
80
- },
81
- {
82
- name: "propertySchemaUid",
83
- type: "bytes32"
84
- }
85
- ]
86
- },
87
- {
88
- type: "error",
89
- name: "AmbiguousPropertyToUpdate",
90
- inputs: [{
91
- name: "targetIndex",
92
- type: "uint256"
93
- }, {
94
- name: "propertySchemaUid",
95
- type: "bytes32"
96
- }]
97
- },
98
- {
99
- type: "error",
100
- name: "InvalidEAS",
101
- inputs: [{
102
- name: "eas",
103
- type: "address"
104
- }]
105
- },
106
- {
107
- type: "error",
108
- name: "AttestationFailed",
109
- inputs: [{
110
- name: "schemaUid",
111
- type: "bytes32"
112
- }]
113
- },
114
- {
115
- type: "error",
116
- name: "Unauthorized",
117
- inputs: [{
118
- name: "caller",
119
- type: "address"
120
- }]
121
- },
122
- {
123
- type: "error",
124
- name: "InvalidAddress",
125
- inputs: [{
126
- name: "addr",
127
- type: "address"
128
- }]
129
- },
130
- {
131
- type: "error",
132
- name: "SeedExecutorAlreadyInstalled",
133
- inputs: []
134
- },
135
- {
136
- type: "error",
137
- name: "SeedExecutorNotInstalled",
138
- inputs: []
139
- },
140
- {
141
- type: "error",
142
- name: "NotSeedExecutor",
143
- inputs: [{
144
- name: "caller",
145
- type: "address"
146
- }]
147
- },
148
- {
149
- type: "error",
150
- name: "UnsupportedExecutionMode",
151
- inputs: [{
152
- name: "mode",
153
- type: "bytes32"
154
- }]
155
- },
156
- {
157
- type: "error",
158
- name: "TargetNotAllowed",
159
- inputs: [{
160
- name: "target",
161
- type: "address"
162
- }]
163
- },
164
- {
165
- type: "error",
166
- name: "SelectorNotAllowed",
167
- inputs: [{
168
- name: "selector",
169
- type: "bytes4"
170
- }]
171
- },
172
- {
173
- type: "error",
174
- name: "ValueMismatch",
175
- inputs: [{
176
- name: "encodedValue",
177
- type: "uint256"
178
- }, {
179
- name: "sentValue",
180
- type: "uint256"
181
- }]
182
- },
183
- ...y,
184
- ...we
185
- ];
186
- function en(e) {
187
- if (e instanceof at) return e.walk((e) => {
188
- let t = e.data;
189
- return typeof t == "string" && t.startsWith("0x") && t.length > 2;
190
- })?.data;
191
- }
192
- function tn(e) {
193
- if (en(e)) return !0;
194
- let t = e instanceof at ? `${e.shortMessage} ${e.details}` : String(e);
195
- return /revert/i.test(t);
196
- }
197
- var nn = "reverted with no data. The target likely has no matching function or the account cannot run executor calls";
198
- function rn(e, t = nn) {
199
- if (!e || e === "0x") return t;
200
- try {
201
- let t = st({
202
- abi: $t,
203
- data: e
204
- }), n = t.args?.length ? `(${t.args.map(String).join(", ")})` : "";
205
- return `reverted with ${t.errorName}${n}`;
206
- } catch {
207
- return `reverted with data ${e}`;
208
- }
209
- }
210
- function an(e, t) {
211
- return t && t !== "0x" ? `The publish UserOp in transaction ${e} ${rn(t)}.` : `The publish UserOp in transaction ${e} failed with no revert reason. That usually means it ran out of gas (the bundler's gas estimate was too low), not that the publish data is wrong. To confirm, run \`npx hardhat seed:explain-userop --network <network> --tx ${e}\` in seed-protocol.`;
212
- }
213
- function on(e) {
214
- let { txHash: t, revertData: n, sender: r, cause: i } = e, a = !!n && n !== "0x";
215
- return new E(an(t, n), a ? "USEROP_REVERTED" : "USEROP_FAILED_NO_REASON", r, i);
216
- }
217
- function sn(e) {
218
- let t = [];
219
- for (let n = e; n && t.length < 6; n = n.cause) t.push(n);
220
- return t;
221
- }
222
- var cn;
223
- function ln(e) {
224
- return cn ??= new Map($t.filter((e) => e.type === "error").map((e) => [dt(`${e.name}(${e.inputs.map((e) => e.type).join(",")})`), e.name])), cn.get(e.toLowerCase());
225
- }
226
- function un(e, t) {
227
- for (let n of sn(e)) {
228
- let r = String(n.message ?? "").match(/UserOp failed at txHash: (0x[0-9a-f]{64})/i);
229
- if (r) return on({
230
- txHash: r[1],
231
- sender: t,
232
- cause: e
233
- });
234
- let i = n.signature;
235
- if (n.name === "AbiErrorSignatureNotFoundError" && typeof i == "string") {
236
- let n = ln(i);
237
- if (n) return new E(`The publish transaction reverted with ${n} (its arguments were not decoded).`, "USEROP_REVERTED", t, e);
238
- }
239
- }
240
- return e;
241
- }
242
- //#endregion
243
- //#region src/helpers/blockchain.ts
244
- var B = () => {
245
- let e = Oe.getArweaveJsApiConfig(), t = Pt;
246
- return Object.keys(t).includes("default") && t.default ? t.default.init(e) : t.init(e);
247
- };
248
- //#endregion
249
- //#region src/helpers/schemaRegistry.ts
250
- async function V(e) {
251
- return be(e);
252
- }
253
- function dn(e) {
254
- return d(e);
255
- }
256
- //#endregion
257
- //#region src/helpers/nameSchemaAttestation.ts
258
- var fn = "0x0000000000000000000000000000000000000000";
259
- function pn(e) {
260
- let t = new It("bytes32 schemaId,string name").encodeData([{
261
- name: "schemaId",
262
- value: e.schemaUid,
263
- type: "bytes32"
264
- }, {
265
- name: "name",
266
- value: e.schemaName,
267
- type: "string"
268
- }]);
269
- return l({
270
- schema: o,
271
- data: {
272
- recipient: fn,
273
- expirationTime: BigInt(Ft),
274
- revocable: !0,
275
- refUID: zt,
276
- data: t,
277
- value: 0n
278
- }
279
- });
280
- }
281
- //#endregion
282
- //#region src/services/publish/helpers/ensureEasSchemas.ts
283
- var H = "0x0000000000000000000000000000000000000000", mn = !0, hn = "bytes32 schemaId,string name", gn = "bytes32 version", _n = /* @__PURE__ */ new Set();
284
- function vn(e) {
285
- return e.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
286
- }
287
- async function yn(e) {
288
- let { itemRelationProperties: t, itemImageProperties: n, itemListProperties: r } = await Ve(e), i = /* @__PURE__ */ new Set();
289
- e.modelName && i.add(e.modelName);
290
- for (let e of t) {
291
- let t = e.propertyDef?.ref;
292
- t && i.add(t);
293
- }
294
- for (let e of n) {
295
- let t = Ye(e.propertyDef?.dataType);
296
- t === je.File ? i.add("File") : t === je.Html ? i.add("Html") : i.add("Image");
297
- }
298
- for (let e of r) {
299
- let t = e.propertyDef?.ref;
300
- t && i.add(t);
301
- }
302
- return i;
303
- }
304
- async function bn(e, t) {
305
- let n = await e.sendTransaction(t);
306
- await T(n.transactionHash);
307
- }
308
- function xn(e) {
309
- let t = Ye(e);
310
- return Ae[t]?.eas ?? "string";
311
- }
312
- function Sn(e, t) {
313
- if (e) throw Error(`schema "${t}" is not registered; automation keys can't register schemas. Call ensureEasSchemasForItem with the owner wallet first.`);
314
- }
315
- async function Cn() {
316
- let e = ye().id;
317
- if (_n.has(e)) return;
318
- let t = Lt.getSchemaUID(gn, H, mn), n = [[hn, o], [gn, t]], r = [];
319
- for (let [e, t] of n) await V(t) || r.push(`"${e}" (${t})`);
320
- if (r.length > 0) throw Error(`Seed base schema${r.length > 1 ? "s" : ""} ${r.join(" and ")} not registered on chain ${e}. The protocol registers base schemas for each supported chain (seed-protocol: bun run seed:ensure-schemas).`);
321
- _n.add(e);
322
- }
323
- async function wn(e, t) {
324
- if (typeof t?.blockSchemaRegistration == "boolean") return t.blockSchemaRegistration;
325
- let n = t?.managedAddress?.trim();
326
- if (!n || !i(e)) return !1;
327
- let { isAutomationSessionActive: r } = await import("./ensureAutomationSessionKey-bw6knEyC.js").then((e) => e.n);
328
- return r(n, e.signer.address);
329
- }
330
- async function Tn(e, t, n) {
331
- await En(e, t, n);
332
- }
333
- async function En(e, t, n) {
334
- let r = await wn(t, n), a = i(t) ? t.txSender : he(t) ? t : (() => {
335
- throw Error("@seedprotocol/publish: ensureEasSchemasForItem requires a PublishWallet or SeedTxSender");
336
- })();
337
- await Cn();
338
- let { itemBasicProperties: o, itemRelationProperties: s, itemImageProperties: c, itemListProperties: l } = await Ve(e), u = [
339
- ...o,
340
- ...s,
341
- ...c,
342
- ...l
343
- ], d = /* @__PURE__ */ new Set(), f = await yn(e), p = /* @__PURE__ */ new Set();
344
- for (let e of f) {
345
- let t = `bytes32 ${vn(e)}`, n = Lt.getSchemaUID(t, H, mn);
346
- if (await V(n)) tt({
347
- modelName: e,
348
- schemaUid: n
349
- });
350
- else if (p.has(n)) tt({
351
- modelName: e,
352
- schemaUid: n
353
- });
354
- else {
355
- Sn(r, t);
356
- try {
357
- await bn(a, dn({
358
- schema: t,
359
- resolverAddress: H,
360
- revocable: mn
361
- }));
362
- } catch (t) {
363
- throw Error(`Failed to register EAS schema for model ${e}: ${t instanceof Error ? t.message : String(t)}`);
364
- }
365
- try {
366
- await bn(a, pn({
367
- schemaUid: n,
368
- schemaName: vn(e)
369
- }));
370
- } catch (t) {
371
- throw Error(`Failed to name EAS schema for model ${e}: ${t instanceof Error ? t.message : String(t)}`);
372
- }
373
- p.add(n), tt({
374
- modelName: e,
375
- schemaUid: n
376
- });
377
- }
378
- }
379
- let m = "string storage_transaction_id", h = Lt.getSchemaUID(m, H, mn);
380
- if (await V(h)) nt({
381
- text: m,
382
- schemaUid: h
383
- });
384
- else if (!d.has(h) && (f.has("Image") || f.has("File") || f.has("Html"))) {
385
- Sn(r, m);
386
- try {
387
- await bn(a, dn({
388
- schema: m,
389
- resolverAddress: H,
390
- revocable: mn
391
- })), await bn(a, pn({
392
- schemaUid: h,
393
- schemaName: "storage_transaction_id"
394
- }));
395
- } catch (e) {
396
- throw Error(`Failed to register EAS schema for storageTransactionId: ${e instanceof Error ? e.message : String(e)}`);
397
- }
398
- d.add(h), nt({
399
- text: m,
400
- schemaUid: h
401
- });
402
- }
403
- for (let e of u) {
404
- if (!e.propertyDef) continue;
405
- let t = xn(e.propertyDef.dataType), n = e, i = Je(e.propertyName, e.propertyDef), o = i ?? (n.storagePropertyName && n.storagePropertyName.length > 0 ? n.storagePropertyName : e.propertyName), s = vn(o), c = `${t} ${s}`;
406
- if (i && !s.endsWith("_ids")) throw Error(`Refusing to register "${c}" for list-relation property ${e.propertyName}: list relations attest as <singular>_<ref>_ids.`);
407
- let l = [
408
- "string",
409
- "address",
410
- "bool",
411
- "bytes",
412
- "bytes32",
413
- "uint8",
414
- "uint16",
415
- "uint32",
416
- "uint64",
417
- "uint128",
418
- "uint256"
419
- ].includes(t) ? t : void 0, u = await Le({
420
- schemaUid: i ? void 0 : e.schemaUid,
421
- propertyName: o,
422
- easDataType: l
423
- });
424
- if (u) {
425
- let e = await V(u.id);
426
- if (e && e.schema === c) {
427
- nt({
428
- text: c,
429
- schemaUid: u.id
430
- });
431
- continue;
432
- }
433
- }
434
- let f = Lt.getSchemaUID(c, H, mn);
435
- if (await V(f)) nt({
436
- text: c,
437
- schemaUid: f
438
- });
439
- else if (d.has(f)) nt({
440
- text: c,
441
- schemaUid: f
442
- });
443
- else {
444
- Sn(r, c);
445
- try {
446
- await bn(a, dn({
447
- schema: c,
448
- resolverAddress: H,
449
- revocable: mn
450
- }));
451
- } catch (t) {
452
- throw Error(`Failed to register EAS schema for property ${e.propertyName}: ${t instanceof Error ? t.message : String(t)}`);
453
- }
454
- try {
455
- await bn(a, pn({
456
- schemaUid: f,
457
- schemaName: s
458
- }));
459
- } catch (t) {
460
- throw Error(`Failed to name EAS schema for property ${e.propertyName}: ${t instanceof Error ? t.message : String(t)}`);
461
- }
462
- d.add(f), nt({
463
- text: c,
464
- schemaUid: f
465
- });
466
- }
467
- }
468
- let g = await Be(e);
469
- for (let e of g) await En(e, t, {
470
- managedAddress: n?.managedAddress,
471
- blockSchemaRegistration: r
472
- });
473
- }
474
- //#endregion
475
- //#region src/services/publish/actors/utils.ts
476
- var U = "0x" + "0".repeat(64), Dn = async (e) => {
477
- let t;
478
- try {
479
- t = await N.find({ seedLocalId: e });
480
- } catch {}
481
- return t || new Promise((t) => {
482
- let n = setInterval(() => {
483
- try {
484
- N.find({ seedLocalId: e }).then((e) => {
485
- e && (clearInterval(n), t(e));
486
- });
487
- } catch {}
488
- }, 200);
489
- });
490
- };
491
- function On(e) {
492
- if (!e || typeof e != "object") return;
493
- let t = e;
494
- if (Array.isArray(t.data_root)) return {
495
- data_root: new Uint8Array(t.data_root),
496
- chunks: (t.chunks ?? []).map((e) => ({
497
- ...e,
498
- dataHash: new Uint8Array(e.dataHash ?? [])
499
- })),
500
- proofs: (t.proofs ?? []).map((e) => ({
501
- ...e,
502
- proof: new Uint8Array(e.proof ?? [])
503
- }))
504
- };
505
- }
506
- function kn(e) {
507
- return {
508
- data_root: Array.from(e.data_root),
509
- chunks: e.chunks.map((e) => ({
510
- ...e,
511
- dataHash: Array.from(e.dataHash)
512
- })),
513
- proofs: e.proofs.map((e) => ({
514
- ...e,
515
- proof: Array.from(e.proof)
516
- }))
517
- };
518
- }
519
- //#endregion
520
- //#region src/services/publish/actors/createArweaveTransactions.ts
521
- var An = L(async ({ input: { context: e } }) => {
522
- let { item: t } = e;
523
- t.getPublishUploads || (t = await Dn(t.seedLocalId));
524
- let n = {};
525
- e.arweaveUploadTags?.length && (n.arweaveUploadTags = e.arweaveUploadTags);
526
- let r = e.htmlEmbeddedDeferredHtmlSeedLocalIds;
527
- r?.length && (n.deferHtmlStorageSeedLocalIds = r);
528
- let i = await t.getPublishUploads(Object.keys(n).length ? n : void 0), a = D(), o = e.signArweaveTransactions ?? a.signArweaveTransactions, s = e.arweaveJwk ?? a.arweaveJwk, c = i.map((e) => ({
529
- versionLocalId: e.versionLocalId,
530
- itemPropertyName: e.itemPropertyName,
531
- transactionJson: e.transactionToSign.toJSON()
532
- })), l;
533
- if (o) l = await o(c);
534
- else if (s) {
535
- let e = B(), t = s;
536
- l = [];
537
- for (let n of c) {
538
- let r = e.transactions.fromRaw(n.transactionJson);
539
- r.data && r.data.byteLength > 0 && !r.chunks && await r.prepareChunks(r.data), await e.transactions.sign(r, t);
540
- let i = r.toJSON();
541
- l.push({
542
- transaction: {
543
- ...i,
544
- chunks: r.chunks ? kn(r.chunks) : void 0
545
- },
546
- versionId: n.versionLocalId,
547
- modelName: n.itemPropertyName
548
- });
549
- }
550
- } else throw Error("Arweave signing not configured. Provide signArweaveTransactions or arweaveJwk at createPublish or in PublishProvider config.");
551
- let u = B();
552
- return {
553
- arweaveTransactions: l.map((e) => {
554
- let { chunks: t, ...n } = e.transaction, r = { ...n }, i = On(t);
555
- return i && (r.chunks = i), {
556
- transaction: u.transactions.fromRaw(r),
557
- versionId: e.versionId,
558
- modelName: e.modelName
559
- };
560
- }),
561
- publishUploads: i
562
- };
563
- }), jn = L(async ({ input: { context: e } }) => {
564
- let { item: t } = e;
565
- t.getPublishUploads || (t = await Dn(t.seedLocalId));
566
- let n = {};
567
- e.arweaveUploadTags?.length && (n.arweaveUploadTags = e.arweaveUploadTags);
568
- let r = e.htmlEmbeddedDeferredHtmlSeedLocalIds;
569
- r?.length && (n.onlyHtmlStorageSeedLocalIds = r);
570
- let i = await t.getPublishUploads(Object.keys(n).length ? n : void 0), a = D(), o = e.signArweaveTransactions ?? a.signArweaveTransactions, s = e.arweaveJwk ?? a.arweaveJwk, c = i.map((e) => ({
571
- versionLocalId: e.versionLocalId,
572
- itemPropertyName: e.itemPropertyName,
573
- transactionJson: e.transactionToSign.toJSON()
574
- })), l;
575
- if (o) l = await o(c);
576
- else if (s) {
577
- let e = B(), t = s;
578
- l = [];
579
- for (let n of c) {
580
- let r = e.transactions.fromRaw(n.transactionJson);
581
- r.data && r.data.byteLength > 0 && !r.chunks && await r.prepareChunks(r.data), await e.transactions.sign(r, t);
582
- let i = r.toJSON();
583
- l.push({
584
- transaction: {
585
- ...i,
586
- chunks: r.chunks ? kn(r.chunks) : void 0
587
- },
588
- versionId: n.versionLocalId,
589
- modelName: n.itemPropertyName
590
- });
591
- }
592
- } else throw Error("Arweave signing not configured. Provide signArweaveTransactions or arweaveJwk at createPublish or in PublishProvider config.");
593
- let u = B();
594
- return {
595
- arweaveTransactions: l.map((e) => {
596
- let { chunks: t, ...n } = e.transaction, r = { ...n }, i = On(t);
597
- return i && (r.chunks = i), {
598
- transaction: u.transactions.fromRaw(r),
599
- versionId: e.versionId,
600
- modelName: e.modelName
601
- };
602
- }),
603
- publishUploads: i
604
- };
605
- }), Mn = L(async ({ input: { context: e } }) => {
606
- let t = e.htmlEmbeddedDataUriPolicy ?? "materialize";
607
- return { deferredHtmlSeedLocalIds: (await Ze(e.item, t)).deferredHtmlSeedLocalIds };
608
- });
609
- //#endregion
610
- //#region src/services/publish/actors/rewritingHtmlEmbedded.ts
611
- function Nn(e, t) {
612
- let n = [], r = Math.min(e?.length ?? 0, t?.length ?? 0);
613
- for (let i = 0; i < r; i++) {
614
- let r = e[i], a = t[i], o = r.transaction?.id;
615
- typeof o == "string" && o.length > 0 && n.push({
616
- txId: o,
617
- seedLocalId: a.seedLocalId,
618
- versionLocalId: a.versionLocalId
619
- });
620
- }
621
- return n;
622
- }
623
- var Pn = L(async ({ input: { context: e } }) => {
624
- let t = Nn(e.htmlEmbeddedPhase1ArweaveTransactions, e.htmlEmbeddedPhase1PublishUploads);
625
- await et(e.item.seedLocalId, t, e.htmlEmbeddedDeferredHtmlSeedLocalIds);
626
- }), Fn = (e, t, n) => {
627
- let r = [];
628
- return e && r.push({
629
- name: "Content-SHA-256",
630
- value: e
631
- }), t && r.push({
632
- name: "Content-Type",
633
- value: t
634
- }), n?.length && r.push(...n), r;
635
- }, In = async (e) => {
636
- let t = (e instanceof Uint8Array, new Uint8Array(e)), n = await crypto.subtle.digest("SHA-256", t);
637
- return Array.from(new Uint8Array(n)).map((e) => e.toString(16).padStart(2, "0")).join("");
638
- }, Ln = {
639
- png: "image/png",
640
- jpg: "image/jpeg",
641
- jpeg: "image/jpeg",
642
- gif: "image/gif",
643
- webp: "image/webp",
644
- svg: "image/svg+xml",
645
- html: "text/html",
646
- htm: "text/html",
647
- json: "application/json",
648
- txt: "text/plain"
649
- }, Rn = (e) => {
650
- let t = e.split(".").pop()?.toLowerCase();
651
- return t ? Ln[t] : void 0;
652
- }, zn = async (e) => typeof Blob < "u" && e instanceof Blob ? new Uint8Array(await e.arrayBuffer()) : new Uint8Array(e), Bn = (e) => {
653
- switch (e) {
654
- case "Image": return M.getFilesPath("images");
655
- case "File": return M.getFilesPath("files");
656
- case "Html": return M.getFilesPath("html");
657
- case "Json": return M.getFilesPath("json");
658
- default: return M.getFilesPath("images");
659
- }
660
- }, Vn = /^data:(image\/[a-zA-Z0-9.+-]+);base64,([\s\S]*)$/i;
661
- function Hn(e) {
662
- let t = Vn.exec((e ?? "").trim());
663
- if (!t) return null;
664
- try {
665
- let e = t[1].toLowerCase().trim(), n = t[2].replace(/\s/g, "");
666
- return {
667
- mimeType: e,
668
- bytes: Uint8Array.from(atob(n), (e) => e.charCodeAt(0))
669
- };
670
- } catch {
671
- return null;
672
- }
673
- }
674
- var Un = async (e, t, n, r) => {
675
- let i = r?.arweaveUploadTags, a = e.itemProperty, o = [];
676
- for (let t of e.childProperties) {
677
- let e = t.localStoragePath;
678
- e && !e.endsWith("undefined") && await M.pathExists(e) && o.push({
679
- propertyName: t.propertyName,
680
- localStoragePath: e
681
- });
682
- }
683
- let s;
684
- if ((!o || o.length === 0) && n?.localStoragePath) {
685
- let e = n.localStoragePath;
686
- if (e && !e.endsWith("undefined") && await M.pathExists(e)) try {
687
- s = await zn(await M.readFileAsBuffer(e));
688
- } catch {
689
- s = await zn((await M.getFs()).readFileSync(e));
690
- }
691
- }
692
- if (o.length > 0) {
693
- let e = "===FILE_SEPARATOR===", t = "", n = await M.getFs();
694
- for (let r of o) {
695
- let i;
696
- try {
697
- i = await n.promises.readFile(r.localStoragePath);
698
- } catch {
699
- i = n.readFileSync(r.localStoragePath);
700
- }
701
- t += `${e}${r.propertyName}${e}${i}`;
702
- }
703
- s = typeof document < "u" ? new TextEncoder().encode(t) : new Uint8Array(Buffer.from(t));
704
- }
705
- if (!s) return t;
706
- let c = new Uint8Array(s), l = await In(c), u;
707
- o.length === 0 && n?.localStoragePath ? u = Rn(n.localStoragePath) : o.length > 0 && (u = "application/octet-stream");
708
- let d = n ? n.localId : a.localId, f = n ? n.propertyName : a.propertyName;
709
- return t.push({
710
- data: c,
711
- contentHash: l,
712
- contentType: u,
713
- tags: Fn(l, u, i),
714
- itemPropertyName: f,
715
- itemPropertyLocalId: d,
716
- seedLocalId: a.seedLocalId,
717
- versionLocalId: a.versionLocalId
718
- }), t;
719
- }, Wn = async (e, t) => {
720
- let n = [], r = t?.arweaveUploadTags;
721
- for (let i of e) {
722
- let e = i.getService().getSnapshot(), a = "context" in e ? e.context : null;
723
- if (!a) continue;
724
- let o = a.propertyValue, s = a.refResolvedValue;
725
- if (!s) continue;
726
- let { localId: c } = Ie(o ?? "");
727
- if (!c) continue;
728
- let l = i.propertyDef?.refValueType ?? i.propertyDef?.dataType ?? "Image";
729
- if (l === je.Html) {
730
- if (t?.deferHtmlStorageSeedLocalIds?.includes(c) || t?.onlyHtmlStorageSeedLocalIds?.length && !t.onlyHtmlStorageSeedLocalIds.includes(c)) continue;
731
- } else if (t?.onlyHtmlStorageSeedLocalIds?.length) continue;
732
- let u = `${Bn(l)}/${s}`;
733
- if (!await M.pathExists(u)) continue;
734
- let d = await zn(await M.readFileAsBuffer(u)), f = await In(d), p = Rn(s);
735
- n.push({
736
- data: d,
737
- contentHash: f,
738
- contentType: p,
739
- tags: Fn(f, p, r),
740
- itemPropertyName: i.propertyName,
741
- itemPropertyLocalId: i.localId,
742
- seedLocalId: c,
743
- versionLocalId: i.versionLocalId
744
- });
745
- }
746
- return n;
747
- };
748
- async function Gn(e, t, n) {
749
- let r = ke.getAppDb();
750
- if (!r || n?.onlyHtmlStorageSeedLocalIds?.length) return t;
751
- let i = await r.select().from(We).where(z(We.parentSeedLocalId, e.seedLocalId)), a = new Set(t.map((e) => e.seedLocalId));
752
- for (let e of i) {
753
- if (a.has(e.imageSeedLocalId)) continue;
754
- let r = await N.find({
755
- seedLocalId: e.imageSeedLocalId,
756
- modelName: "Image"
757
- });
758
- if (!r) continue;
759
- let i = r.internalProperties.storageTransactionId ?? r.allProperties.storageTransactionId, o = i?.getService().getSnapshot(), s = o && "context" in o ? o.context : void 0, c = Hn(typeof s?.propertyValue == "string" ? s.propertyValue ?? "" : ""), l = [];
760
- if (c && i && i.localId && i.versionLocalId) {
761
- let e = await In(c.bytes);
762
- l = [{
763
- data: c.bytes,
764
- contentHash: e,
765
- contentType: c.mimeType,
766
- tags: Fn(e, c.mimeType, n?.arweaveUploadTags),
767
- itemPropertyName: i.propertyName,
768
- itemPropertyLocalId: i.localId,
769
- seedLocalId: r.seedLocalId,
770
- versionLocalId: i.versionLocalId
771
- }];
772
- }
773
- for (let e of l) a.has(e.seedLocalId) || (t.push(e), a.add(e.seedLocalId));
774
- }
775
- return t;
776
- }
777
- var Kn = (e) => !e.seedUid || e.seedUid === "0x" + "0".repeat(64), qn = async (e, t, n, r) => {
778
- let { itemUploadProperties: i, itemRelationProperties: a, itemImageProperties: o } = await Ve(e);
779
- if (r?.onlyHtmlStorageSeedLocalIds?.length) {
780
- let e = await Wn(o, r);
781
- t.push(...e);
782
- } else {
783
- for (let e of i) t = await Un(e, t, n, r);
784
- let a = await Wn(o, r);
785
- t.push(...a), (!n || Kn(e)) && (t = await Gn(e, t, r));
786
- }
787
- if (r?.skipRelationRecursion) return t;
788
- let s = new Set(o);
789
- for (let e of a) {
790
- if (!s.has(e)) continue;
791
- let n = e.getService().getSnapshot(), i = "context" in n ? n.context : null;
792
- if (!i) continue;
793
- let a = i.propertyValue;
794
- if (!a || e.uid) continue;
795
- let { seedLocalId: o, seedUid: c } = $e(Xe(a) ?? "");
796
- if (!o && !c) throw Error(`Invalid relation value for ${e.propertyName}: expected local seed id or 0x uid`);
797
- let l = await N.find({
798
- seedLocalId: o,
799
- seedUid: c
800
- });
801
- if (!l) {
802
- if (Ke(a)) continue;
803
- throw Error(`No relatedItem found for ${e.propertyName}`);
804
- }
805
- t = await qn(l, t, e, {
806
- ...r,
807
- skipRelationRecursion: !0
808
- });
809
- }
810
- return t;
811
- }, Jn = async (e, t = [], n, r) => {
812
- if (t = await qn(e, t, n, r), r?.skipRelationRecursion) return t;
813
- let { drafts: i } = await ze(e, { strict: !0 });
814
- for (let { item: e, via: n, viaList: a } of i) t = await qn(e, t, a ? void 0 : n, r);
815
- return t;
816
- }, Yn = 3, Xn = new TextEncoder().encode("seed-recovery"), Zn = 32, Qn = 18446744073709551615n;
817
- function $n(e, t, n) {
818
- let r = F.solidityPackedKeccak256([
819
- "uint256",
820
- "address",
821
- "uint64"
822
- ], [
823
- BigInt(t),
824
- e,
825
- n & Qn
826
- ]);
827
- return F.getBytes(r);
828
- }
829
- function er(e) {
830
- if (e.length === 0) return new Uint8Array([0]);
831
- if (e.length !== Zn) throw Error(`ANS-104 target/anchor must be empty or ${Zn} bytes, got ${e.length}`);
832
- let t = /* @__PURE__ */ new Uint8Array(33);
833
- return t[0] = 1, t.set(e, 1), t;
834
- }
835
- function tr(e) {
836
- return typeof e == "object" && !!e && "privateKey" in e && typeof e.privateKey == "string";
837
- }
838
- function nr(e, t, n) {
839
- let r = e >= 0 ? e << 1 : ~e << 1 | 1, i = n;
840
- do {
841
- let e = r & 127;
842
- r >>>= 7, t[i++] = r ? e | 128 : e;
843
- } while (r);
844
- return i - n;
845
- }
846
- var rr = (e) => {
847
- if (!e?.length) return /* @__PURE__ */ new Uint8Array();
848
- let t = new TextEncoder(), n = /* @__PURE__ */ new Uint8Array(16), r = [], i = (e) => {
849
- let t = nr(e, n, 0);
850
- r.push(n.slice(0, t));
851
- };
852
- i(e.length);
853
- for (let n of e) {
854
- let e = t.encode(n.name), a = t.encode(n.value);
855
- i(e.length), r.push(e), i(a.length), r.push(a);
856
- }
857
- i(0);
858
- let a = r.reduce((e, t) => e + t.length, 0), o = new Uint8Array(a), s = 0;
859
- for (let e of r) o.set(e, s), s += e.length;
860
- return o;
861
- }, ir = (e) => {
862
- let t = /* @__PURE__ */ new Uint8Array(8), n = new DataView(t.buffer);
863
- return n.setUint32(0, e | 0, !0), n.setUint32(4, Math.floor(e / 4294967296), !0), t;
864
- };
865
- async function ar(e) {
866
- return new Uint8Array(await crypto.subtle.digest("SHA-384", e));
867
- }
868
- function or(e, t) {
869
- let n = new Uint8Array(e.length + t.length);
870
- return n.set(e, 0), n.set(t, e.length), n;
871
- }
872
- async function sr(e) {
873
- let t = new TextEncoder();
874
- if (Array.isArray(e)) {
875
- let n = await ar(or(t.encode("list"), t.encode(e.length.toString())));
876
- for (let t of e) {
877
- let e = await sr(t);
878
- n = await ar(or(n, e));
879
- }
880
- return n;
881
- }
882
- return ar(or(await ar(or(t.encode("blob"), t.encode(e.byteLength.toString()))), await ar(e)));
883
- }
884
- async function cr(e, t, n, r, i) {
885
- let a = new TextEncoder();
886
- return sr([
887
- a.encode("dataitem"),
888
- a.encode("1"),
889
- a.encode(Yn.toString()),
890
- e,
891
- t,
892
- n,
893
- r,
894
- i
895
- ]);
896
- }
897
- function lr(e, t, n, r, i) {
898
- let a = rr(t), o = ir(t.length), s = ir(a.length), c = [
899
- e,
900
- er(r),
901
- er(i),
902
- o,
903
- s,
904
- a,
905
- n
906
- ], l = c.reduce((e, t) => e + t.length, 0), u = new Uint8Array(l), d = 0;
907
- for (let e of c) u.set(e, d), d += e.length;
908
- return u;
909
- }
910
- async function ur(e, t) {
911
- let n = /* @__PURE__ */ new Uint8Array(2);
912
- new DataView(n.buffer).setUint16(0, Yn, !0);
913
- let r = 67 + t.length, i = new Uint8Array(r);
914
- i.set(n, 0), i.set(e, 2), i.set(t, 67);
915
- let a = await crypto.subtle.digest("SHA-256", new Uint8Array(e));
916
- return {
917
- id: gr(new Uint8Array(a)),
918
- raw: i
919
- };
920
- }
921
- var dr = async (e, t, n, r = /* @__PURE__ */ new Uint8Array()) => {
922
- let i = F.SigningKey.computePublicKey(t.privateKey, !1), a = F.getBytes(i), o = rr(n), s = /* @__PURE__ */ new Uint8Array(), c = await cr(a, s, r, o, e);
923
- return ur(F.getBytes(await t.signMessage(c)), lr(a, n, e, s, r));
924
- }, fr = async (e, t, n, r = /* @__PURE__ */ new Uint8Array()) => {
925
- let i = F.hexlify(Xn), a = await t.signMessage({ message: { raw: i } }), o = F.hashMessage(Xn), s = F.SigningKey.recoverPublicKey(o, a), c = F.getBytes(s), l = rr(n), u = /* @__PURE__ */ new Uint8Array(), d = await cr(c, u, r, l, e), f = F.hexlify(d), p = await t.signMessage({ message: { raw: f } });
926
- return ur(F.getBytes(p), lr(c, n, e, u, r));
927
- };
928
- function pr(e) {
929
- if (e.length < 133) return null;
930
- let t = e[132];
931
- if (t !== 0 && t !== 1) return null;
932
- let n = t === 1;
933
- if (n && e.length < 165) return null;
934
- let r = 132 + (n ? 33 : 1);
935
- if (e.length < r + 1) return null;
936
- let i = e[r];
937
- if (i !== 0 && i !== 1) return null;
938
- let a = i === 1;
939
- return a && e.length < r + 33 ? null : r + (a ? 33 : 1);
940
- }
941
- function mr(e) {
942
- let t = pr(e);
943
- if (t == null) return null;
944
- let n = e[132] === 1, r = n ? e.slice(133, 165) : /* @__PURE__ */ new Uint8Array(), i = 132 + (n ? 33 : 1);
945
- return {
946
- rawTarget: r,
947
- rawAnchor: e[i] === 1 ? e.slice(i + 1, i + 33) : /* @__PURE__ */ new Uint8Array(),
948
- tagsStart: t
949
- };
950
- }
951
- async function hr(e) {
952
- let t = mr(e);
953
- if (t == null) return !1;
954
- let { rawTarget: n, rawAnchor: r, tagsStart: i } = t, a = i + 16;
955
- if (e.length < a) return !1;
956
- let o = new DataView(e.buffer, e.byteOffset, e.byteLength);
957
- if (o.getUint16(0, !0) !== Yn) return !1;
958
- let s = e.slice(2, 67), c = e.slice(67, 132), l = Number(o.getUint32(i + 8, !0) + o.getUint32(i + 12, !0) * 4294967296), u = i + 16 + l;
959
- if (e.length < u) return !1;
960
- let d = e.slice(i + 16, u), f = e.slice(u);
961
- try {
962
- let e = await cr(c, n, r, d, f), t = F.hashMessage(e), i = F.hexlify(s), a = F.SigningKey.recoverPublicKey(t, i), o = F.getBytes(a);
963
- return o.length === c.length && o.every((e, t) => e === c[t]);
964
- } catch {
965
- return !1;
966
- }
967
- }
968
- var gr = (e) => {
969
- let t = "";
970
- for (let n of e) t += String.fromCharCode(n);
971
- return btoa(t).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
972
- }, _r = R("seedProtocol:createArweaveDataItems");
973
- async function vr(e, t, n) {
974
- let r, a;
975
- if (t) r = (await t(e)).map((e) => ({
976
- transaction: { id: e.transaction.id },
977
- versionId: e.versionId,
978
- modelName: e.modelName
979
- }));
980
- else if (n) {
981
- let t = [], o = Date.now();
982
- for (let r = 0; r < e.length; r++) {
983
- let a = e[r], s = a.tags, c = /* @__PURE__ */ new Uint8Array(8);
984
- crypto.getRandomValues(c);
985
- let l = (new DataView(c.buffer).getBigUint64(0, !1) ^ BigInt(r)) & 18446744073709551615n, u;
986
- if (tr(n)) {
987
- let e = $n(n.address, o, l);
988
- u = await dr(a.data, n, s, e);
989
- } else {
990
- let e = i(n) ? n.signer : n, t = $n(e.address, o, l);
991
- u = await fr(a.data, e, s, t);
992
- }
993
- if (!await hr(u.raw)) throw _r("DataItem verification failed: id=%s modelName=%s", u.id, a.itemPropertyName), Error(`DataItem signature verification failed for ${a.itemPropertyName}. The signing key may not match the owner, or the payload may have been modified.`);
994
- t.push(u);
995
- }
996
- a = t, r = t.map((t, n) => ({
997
- transaction: { id: t.id },
998
- versionId: e[n]?.versionLocalId,
999
- modelName: e[n]?.itemPropertyName
1000
- }));
1001
- } else throw Error("@seedprotocol/publish: useArweaveBundler requires signDataItems or dataItemSigner (pass at createPublish or in PublishProvider config)");
1002
- let o = e.map((e) => ({
1003
- itemPropertyName: e.itemPropertyName,
1004
- itemPropertyLocalId: e.itemPropertyLocalId,
1005
- seedLocalId: e.seedLocalId,
1006
- versionLocalId: e.versionLocalId,
1007
- transactionToSign: null
1008
- }));
1009
- return {
1010
- arweaveTransactions: r,
1011
- publishUploads: o,
1012
- signedDataItems: a
1013
- };
1014
- }
1015
- var yr = L(async ({ input: { context: e } }) => {
1016
- let { item: t } = e;
1017
- t.getPublishUploads || (t = await Dn(t.seedLocalId));
1018
- let n = {};
1019
- e.arweaveUploadTags?.length && (n.arweaveUploadTags = e.arweaveUploadTags);
1020
- let r = e.htmlEmbeddedDeferredHtmlSeedLocalIds;
1021
- r?.length && (n.deferHtmlStorageSeedLocalIds = r);
1022
- let i = await Jn(t, [], void 0, Object.keys(n).length ? n : void 0), a = D();
1023
- return vr(i, e.signDataItems ?? a.signDataItems, e.dataItemSigner ?? a.dataItemSigner);
1024
- });
1025
- //#endregion
1026
- //#region src/services/publish/actors/createArweaveDataItemsPhase2.ts
1027
- async function br(e) {
1028
- let { item: t } = e;
1029
- t.getPublishUploads || (t = await Dn(t.seedLocalId));
1030
- let n = {};
1031
- e.arweaveUploadTags?.length && (n.arweaveUploadTags = e.arweaveUploadTags);
1032
- let r = e.htmlEmbeddedDeferredHtmlSeedLocalIds;
1033
- r?.length && (n.onlyHtmlStorageSeedLocalIds = r);
1034
- let i = await Jn(t, [], void 0, Object.keys(n).length ? n : void 0), a = D(), o = e.signDataItems ?? a.signDataItems, s = e.dataItemSigner ?? a.dataItemSigner;
1035
- return i.length === 0 ? {
1036
- arweaveTransactions: [],
1037
- publishUploads: [],
1038
- signedDataItems: void 0
1039
- } : vr(i, o, s);
1040
- }
1041
- var xr = L(async ({ input: { context: e } }) => br(e)), Sr = 8192;
1042
- function Cr(e) {
1043
- let t = new Uint8Array(e), n = "";
1044
- for (let e = 0; e < t.length; e += Sr) {
1045
- let r = t.subarray(e, Math.min(e + Sr, t.length));
1046
- n += String.fromCharCode.apply(null, r);
1047
- }
1048
- return btoa(n);
1049
- }
1050
- async function wr(e) {
1051
- let t = [];
1052
- for (let [n, r] of e.entries()) {
1053
- let e = r;
1054
- if (typeof e == "object" && e && "arrayBuffer" in e) {
1055
- let r = Cr(await e.arrayBuffer()), i = e;
1056
- t.push({
1057
- name: n,
1058
- value: r,
1059
- encoding: "base64",
1060
- filename: i.name || void 0
1061
- });
1062
- } else t.push({
1063
- name: n,
1064
- value: String(r)
1065
- });
1066
- }
1067
- return t;
1068
- }
1069
- function Tr(e, t, n) {
1070
- let r = ["Upload server returned ", String(e)], i = t && typeof t == "object" && "message" in t ? String(t.message) : t && typeof t == "object" && "error" in t ? String(t.error) : null;
1071
- return i ? r.push(`: ${i}`) : n && r.push(` (${n})`), r.join("");
1072
- }
1073
- function Er(e) {
1074
- if (!e) return "Upload server unavailable. Please try again or check your connection.";
1075
- let t = e.toLowerCase();
1076
- return /other side closed|econnreset|socket hang up|connection closed/i.test(t) ? "Upload server closed the connection. It may be busy or the request may be too large—try again." : /etimedout|timeout/i.test(t) ? "Upload request timed out. Please try again." : /enotfound|getaddrinfo|dns/i.test(t) ? "Upload server could not be reached. Check the upload URL and your network." : "Upload failed. Please try again or check the upload server.";
1077
- }
1078
- async function Dr(e, t, n) {
1079
- let r = typeof window < "u" ? window.Main : void 0;
1080
- if (r?.uploadArweaveStart) {
1081
- let n = await wr(t);
1082
- return r.uploadArweaveStart(e, n);
1083
- }
1084
- let i = await fetch(e, {
1085
- method: "POST",
1086
- body: t
1087
- }), a = await i.json().catch(() => ({}));
1088
- return {
1089
- status: i.status,
1090
- body: a
1091
- };
1092
- }
1093
- //#endregion
1094
- //#region src/services/publish/actors/sendReimbursementRequest.ts
1095
- var Or = L(async ({ input: { context: e, event: t } }) => {
1096
- let { arweaveTransactions: n = [], transactionKeys: r, reimbursementTransactionId: i } = e;
1097
- if (i) return { transactionId: i };
1098
- let a = n.map(({ transaction: e }) => e), o = new FormData();
1099
- for (let e of a) {
1100
- let { data: t, chunks: n, ...r } = e, i = t instanceof Blob ? t : new Blob([t]);
1101
- o.append(`${e.id}-data`, i, `${e.id}-data`);
1102
- let a = new Blob([JSON.stringify(n)], { type: "application/json" });
1103
- o.append(`${e.id}-chunks`, a, `${e.id}-chunks`);
1104
- let s = new Blob([JSON.stringify(r)], { type: "application/json" });
1105
- o.append(`${e.id}-json`, s, `${e.id}-json`);
1106
- }
1107
- let { uploadApiBaseUrl: s } = D(), { status: c, body: l, message: u } = await Dr(`${s}/api/upload/arweave/start`, o, s);
1108
- if (c >= 300 || c < 200) {
1109
- let e = c === 0 ? u : null;
1110
- e && console.error("[upload]", e);
1111
- let t = c === 0 ? Er(e) : Tr(c, l, r);
1112
- throw Error(t);
1113
- }
1114
- return l;
1115
- }), kr = L(async ({ input: { context: e, event: t } }) => {
1116
- let { requestResponse: n, reimbursementTransactionId: r } = e;
1117
- if (!n) throw Error("No request response");
1118
- if (!r) throw Error("No reimbursement transaction id");
1119
- let i = B();
1120
- await new Promise((e, t) => {
1121
- let n = setInterval(async () => {
1122
- let t;
1123
- try {
1124
- t = await i.transactions.getStatus(r);
1125
- } catch {
1126
- return;
1127
- }
1128
- t && t.confirmed && (clearInterval(n), e());
1129
- }, 5e3);
1130
- });
1131
- }), W = R("seedProtocol:services:publish:actors");
1132
- function Ar(e) {
1133
- if (e instanceof Uint8Array) return e;
1134
- if (e instanceof ArrayBuffer) return new Uint8Array(e);
1135
- throw Error("Transaction data must be Uint8Array or ArrayBuffer for upload resume");
1136
- }
1137
- var jr = Ht(({ sendBack: e, input: t }) => {
1138
- let n = t.context, r = (n.arweaveTransactions ?? []).map(({ transaction: e }) => e), i = B(), a = n.uploaderState && typeof n.currentTransactionIndex == "number", o = a ? n.currentTransactionIndex : 0;
1139
- (async () => {
1140
- let t = r.length;
1141
- for (let s = o; s < t; s++) {
1142
- let c = r[s];
1143
- if (!c) continue;
1144
- let l = i.transactions.fromRaw(c);
1145
- if (!await i.transactions.verify(l)) throw Error("Transaction verification failed");
1146
- let u, d = n.uploaderState;
1147
- if (a && s === o && d) {
1148
- let e = l.data, t = e instanceof Uint8Array ? e : Ar(e);
1149
- u = await i.transactions.getUploader(d, t);
1150
- } else u = await i.transactions.getUploader(l, l.data);
1151
- for (; !u.isComplete;) {
1152
- W("uploading chunk"), W(`uploader.pctComplete: ${u.pctComplete}`), W(`uploader.uploadedChunks: ${u.uploadedChunks}`), W(`uploader.totalChunks: ${u.totalChunks}`), W(u.lastResponseError), W(u.lastResponseStatus);
1153
- try {
1154
- await u.uploadChunk(), e({
1155
- type: "updatePercentage",
1156
- completionPercentage: Math.trunc((s + u.pctComplete / 100) / t * 100),
1157
- uploaderState: u.toJSON(),
1158
- currentTransactionIndex: s
1159
- }), W(`${u.pctComplete}% complete, ${u.uploadedChunks}/${u.totalChunks}`);
1160
- } catch (e) {
1161
- W(e);
1162
- }
1163
- }
1164
- }
1165
- return "done";
1166
- })().then((t) => {
1167
- e({
1168
- type: "uploadComplete",
1169
- result: t
1170
- });
1171
- }).catch((t) => {
1172
- e({
1173
- type: "uploadError",
1174
- error: t
1175
- });
1176
- });
1177
- }), Mr = 12e4, Nr = Function("s", "return import(s)"), Pr = null, Fr = async () => {
1178
- if (Pr) return Pr;
1179
- if (typeof window < "u") return null;
1180
- try {
1181
- let e = await Nr(`node:${["fs", "promises"].join("/")}`);
1182
- return Pr = {
1183
- readFile: e.readFile,
1184
- stat: e.stat
1185
- }, Pr;
1186
- } catch {
1187
- return null;
1188
- }
1189
- }, Ir = Ht(({ sendBack: e, input: { context: t } }) => {
1190
- let { signedDataItems: n } = t, { uploadApiBaseUrl: r, useArweaveBundler: i } = D();
1191
- if (!i || !r) {
1192
- e({
1193
- type: "uploadError",
1194
- error: /* @__PURE__ */ Error("Arweave bundler not configured. Set useArweaveBundler and uploadApiBaseUrl.")
1195
- });
1196
- return;
1197
- }
1198
- let a = `${r.replace(/\/$/, "")}/api/upload/arweave/batch`;
1199
- !n || n.length === 0 ? e({
1200
- type: "uploadComplete",
1201
- result: "done"
1202
- }) : (async () => {
1203
- let e = n, t = e.length, r = Array(t).fill(null), i = async (e, t) => {
1204
- let n = e;
1205
- if (n.raw != null && (n.raw instanceof Uint8Array || Buffer.isBuffer(n.raw))) return n.raw.byteLength;
1206
- if (typeof n.getRaw == "function") {
1207
- let e = n.getRaw(), i = e instanceof Promise ? await e : e, a = Buffer.isBuffer(i) ? i : Buffer.from(i);
1208
- return r[t] = a, a.length;
1209
- }
1210
- if (n.filename != null) {
1211
- let e = await Fr();
1212
- if (!e) throw Error("DataItem.filename requires Node.js fs access. In browser runtime, provide DataItem.raw or DataItem.getRaw().");
1213
- return (await e.stat(n.filename)).size;
1214
- }
1215
- throw Error("Cannot get raw bytes from DataItem");
1216
- }, o = 4, s = [];
1217
- for (let n = 0; n < t; n++) {
1218
- let t = await i(e[n], n);
1219
- s.push(t), o += 4 + t;
1220
- }
1221
- let c = Buffer.alloc(o), l = 0;
1222
- c.writeUInt32BE(t, l), l += 4;
1223
- for (let n = 0; n < t; n++) {
1224
- let t = s[n], i = r[n];
1225
- if (i) {
1226
- c.writeUInt32BE(t, l), l += 4, i.copy(c, l), l += t;
1227
- continue;
1228
- }
1229
- let a = e[n];
1230
- if (a.raw != null && (a.raw instanceof Uint8Array || Buffer.isBuffer(a.raw))) c.writeUInt32BE(t, l), l += 4, c.set(a.raw, l), l += t;
1231
- else if (a.filename != null) {
1232
- let e = await Fr();
1233
- if (!e) throw Error("DataItem.filename requires Node.js fs access. In browser runtime, provide DataItem.raw or DataItem.getRaw().");
1234
- let t = await e.readFile(a.filename);
1235
- c.writeUInt32BE(t.length, l), l += 4, t.copy(c, l), l += t.length;
1236
- } else throw Error("Cannot get raw bytes from DataItem");
1237
- }
1238
- let u = new AbortController(), d = setTimeout(() => u.abort(), Mr), f;
1239
- try {
1240
- f = await fetch(a, {
1241
- method: "POST",
1242
- headers: { "Content-Type": "application/octet-stream" },
1243
- body: c,
1244
- signal: u.signal
1245
- });
1246
- } catch (e) {
1247
- throw clearTimeout(d), e instanceof Error && e.name === "AbortError" ? Error(`Arweave batch upload timed out after ${Mr / 1e3}s (upload API did not respond). Check uploadApiBaseUrl and network.`) : e;
1248
- }
1249
- if (clearTimeout(d), !f.ok) throw Error(`Batch upload failed: ${f.status}`);
1250
- let p = await f.json().catch(() => ({})), m = typeof p.failed == "number" ? p.failed : 0;
1251
- if (m > 0) {
1252
- let e = p.total ?? "?", t = p.succeeded ?? 0;
1253
- throw Error(`Arweave batch upload failed: ${m} of ${e} item(s) failed (${t} succeeded)`);
1254
- }
1255
- })().then(() => e({
1256
- type: "uploadComplete",
1257
- result: "done"
1258
- })).catch((t) => e({
1259
- type: "uploadError",
1260
- error: t
1261
- }));
1262
- });
1263
- //#endregion
1264
- //#region src/services/publish/helpers/receiptAttestationMs.ts
1265
- async function Lr(e) {
1266
- let t = e?.blockNumber;
1267
- return t == null ? Date.now() : await _e(t) ?? Date.now();
1268
- }
1269
- //#endregion
1270
- //#region src/services/publish/actors/seedUidHelpers.ts
1271
- function G(e) {
1272
- return e == null || e === "" ? U : ("0x" + (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0").padStart(64, "0").slice(-64)).toLowerCase();
1273
- }
1274
- function Rr(e, t) {
1275
- if (!e.logs?.length) return [];
1276
- let n = t ? Te : r;
1277
- try {
1278
- let t = ut({
1279
- abi: n,
1280
- eventName: "CreatedAttestation",
1281
- logs: e.logs,
1282
- strict: !1
1283
- }), r = [];
1284
- for (let e of t) {
1285
- let t = e.args?.result;
1286
- if (!t?.attestationUid) continue;
1287
- let n = t.attestationUid;
1288
- if (!n || G(n) === U) continue;
1289
- let i = t.schemaUid;
1290
- i && r.push({
1291
- schemaUid: i,
1292
- attestationUid: n
1293
- });
1294
- }
1295
- return r;
1296
- } catch {
1297
- return [];
1298
- }
1299
- }
1300
- //#endregion
1301
- //#region src/services/publish/actors/multiPublishReceipt.ts
1302
- var K = (e) => !e || G(e) === U, zr = (e, t) => !!e && !!t && G(e) === G(t);
1303
- function Br(e) {
1304
- let t = [];
1305
- for (let n of e.listOfAttestations ?? []) {
1306
- let e = Array.isArray(n?.data) ? n.data.length : 1, r = typeof n?._propertyName == "string" && n._propertyName !== "" ? n._propertyName : void 0;
1307
- for (let i = 0; i < e; i++) t.push({
1308
- schema: n?.schema,
1309
- propertyName: r
1310
- });
1311
- }
1312
- return t;
1313
- }
1314
- function Vr(e, t, n) {
1315
- let i = t.toLowerCase(), a = e.logs?.filter((e) => e.address && e.address.toLowerCase() === i);
1316
- if (!a?.length) return [];
1317
- try {
1318
- return n ? ut({
1319
- abi: Te,
1320
- eventName: "SeedPublished",
1321
- logs: a,
1322
- strict: !1
1323
- }).map((e) => {
1324
- let t = e.args;
1325
- return {
1326
- seedUid: K(t?.seedUid) ? void 0 : t.seedUid,
1327
- versionUid: K(t?.versionUid) ? void 0 : t.versionUid
1328
- };
1329
- }) : ut({
1330
- abi: r,
1331
- eventName: "SeedPublished",
1332
- logs: a,
1333
- strict: !1
1334
- }).map((e) => {
1335
- let t = e.args?.returnedDataFromEAS;
1336
- if (!t || t === "0x") return { uids: [] };
1337
- try {
1338
- return { uids: ot([{ type: "bytes32[]" }], t)[0] ?? [] };
1339
- } catch {
1340
- return { uids: [] };
1341
- }
1342
- });
1343
- } catch {
1344
- return [];
1345
- }
1346
- }
1347
- function Hr(e) {
1348
- let { receipt: t, requests: n, useModularExecutor: r, easContractAddress: i, contractAddressForEvents: a } = e, o = Rr(t, r), s = new Set(o.map((e) => G(e.attestationUid))), c = /* @__PURE__ */ new Set();
1349
- for (let e of n) K(e.seedUid) && e.seedSchemaUid && c.add(G(e.seedSchemaUid)), K(e.versionUid) && e.versionSchemaUid && c.add(G(e.versionSchemaUid));
1350
- let l = p(t, i).filter((e) => !s.has(G(e.uid)) && !c.has(G(e.schemaUid))).map((e) => ({
1351
- schemaUid: e.schemaUid,
1352
- attestationUid: e.uid
1353
- })), u = Vr(t, a, r), d = n.map(Br), f = n.reduce((e, t) => e + +!!K(t.seedUid) + +!!K(t.versionUid), 0), m = d.reduce((e, t) => e + t.length, 0), h = m > 0 && o.length >= f + m, g = 0, _ = 0, v = 0, y = (e) => {
1354
- let t = o[g];
1355
- if (t) return g += 1, zr(t.schemaUid, e) ? t.attestationUid : void 0;
1356
- };
1357
- return n.map((e, t) => {
1358
- let n = d[t], i = { propertyPairs: [] };
1359
- K(e.seedUid) && (i.seedUid = y(e.seedSchemaUid)), K(e.versionUid) && (i.versionUid = y(e.versionSchemaUid));
1360
- let a = [];
1361
- h ? (a = o.slice(g, g + n.length), g += n.length) : l.length && (a = l.slice(_, _ + n.length), _ += n.length);
1362
- let s = !r || n.length > 0 ? u[v++] : void 0;
1363
- if (s) {
1364
- if (r) K(e.seedUid) && !i.seedUid && (i.seedUid = s.seedUid), K(e.versionUid) && !i.versionUid && (i.versionUid = s.versionUid);
1365
- else if (s.uids?.length) {
1366
- !a.length && s.uids.length >= n.length && (a = s.uids.slice(0, n.length).map((e) => ({ attestationUid: e })));
1367
- let t = s.uids[n.length], r = s.uids[n.length + 1];
1368
- K(e.seedUid) && !i.seedUid && !K(t) && (i.seedUid = t), K(e.versionUid) && !i.versionUid && !K(r) && (i.versionUid = r);
1369
- }
1370
- }
1371
- return n.forEach((e, t) => {
1372
- let n = a[t];
1373
- if (!n || K(n.attestationUid) || n.schemaUid && !zr(n.schemaUid, e.schema)) return;
1374
- let r = n.schemaUid ?? e.schema;
1375
- r && i.propertyPairs.push({
1376
- schemaUid: r,
1377
- attestationUid: n.attestationUid,
1378
- ...e.propertyName ? { propertyName: e.propertyName } : {}
1379
- });
1380
- }), i;
1381
- });
1382
- }
1383
- //#endregion
1384
- //#region src/services/publish/actors/persistSeedUid.ts
1385
- var Ur = R("seedProtocol:services:publish:actors:persistSeedUid"), Wr = "0x" + "0".repeat(64), Gr = 15e3;
1386
- function Kr(e, t) {
1387
- let n = e.seedLocalId, r = n ? t.find((e) => e?.localId === n) : void 0, i = r ? r.seedUid : t[0]?.seedUid;
1388
- i && i !== Wr && (e.seedUid = i);
1389
- }
1390
- async function qr(e, t, n) {
1391
- let r = e.persistSeedUid;
1392
- if (typeof r != "function") return;
1393
- let i = new Promise((e, t) => setTimeout(() => t(/* @__PURE__ */ Error("persistSeedUid timed out")), Gr));
1394
- try {
1395
- await Promise.race([r.call(e, t, n), i]);
1396
- } catch (e) {
1397
- Ur("persistSeedUid failed (attestations already on-chain):", e);
1398
- }
1399
- }
1400
- //#endregion
1401
- //#region src/services/publish/actors/publishRequestNormalize.ts
1402
- var Jr = 64, q = (e) => {
1403
- if (e == null) return "0x" + "0".repeat(Jr);
1404
- if (typeof e == "string") return "0x" + (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0").padStart(Jr, "0").slice(-64);
1405
- if (e instanceof Uint8Array || typeof ArrayBuffer < "u" && e instanceof ArrayBuffer) {
1406
- let t = e instanceof Uint8Array ? e : new Uint8Array(e);
1407
- return "0x" + Array.from(t).map((e) => e.toString(16).padStart(2, "0")).join("").padStart(Jr, "0").slice(-64);
1408
- }
1409
- return "0x" + "0".repeat(Jr);
1410
- }, Yr = (e) => {
1411
- if (e == null || typeof e == "string" && (e === "" || e === "0x")) return "0x";
1412
- if (typeof e == "string") {
1413
- let t = (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0");
1414
- return "0x" + (t.length % 2 == 1 ? "0" + t : t);
1415
- }
1416
- if (e instanceof Uint8Array || typeof ArrayBuffer < "u" && e instanceof ArrayBuffer) {
1417
- let t = e instanceof Uint8Array ? e : new Uint8Array(e);
1418
- return "0x" + Array.from(t).map((e) => e.toString(16).padStart(2, "0")).join("");
1419
- }
1420
- return "0x";
1421
- };
1422
- function Xr(e) {
1423
- let t = new Set(e.map((e) => e?.localId).filter((e) => !!e));
1424
- return e.some((e) => (e?.listOfAttestations ?? []).some((e) => {
1425
- let n = e;
1426
- return n._unresolvedValue && t.has(n._unresolvedValue) ? !0 : Array.isArray(n._rawListIdsForResolve) ? n._rawListIdsForResolve.some((e) => e && t.has(String(e).trim())) : !1;
1427
- }));
1428
- }
1429
- function Zr(e, t) {
1430
- return (e ?? []).filter((e) => e.publishLocalId && t.has(e.publishLocalId));
1431
- }
1432
- var Qr = {
1433
- recipient: Rt,
1434
- expirationTime: BigInt(0),
1435
- revocable: !0,
1436
- refUID: U,
1437
- data: U,
1438
- value: BigInt(0)
1439
- };
1440
- function $r(e) {
1441
- let t = (e?.listOfAttestations ?? []).map((e) => {
1442
- let t = Array.isArray(e?.data) ? e.data : [];
1443
- return {
1444
- schema: q(e?.schema),
1445
- data: t.map((e) => ({
1446
- ...e,
1447
- refUID: q(e?.refUID),
1448
- data: Yr(e?.data),
1449
- expirationTime: e?.expirationTime == null ? BigInt(0) : BigInt(e.expirationTime),
1450
- value: e?.value == null ? BigInt(0) : BigInt(e.value)
1451
- })),
1452
- ...typeof e?._propertyName == "string" && e._propertyName !== "" ? { _propertyName: e._propertyName } : {},
1453
- ...typeof e?._propertyNameForSchema == "string" && e._propertyNameForSchema !== "" ? { _propertyNameForSchema: e._propertyNameForSchema } : {}
1454
- };
1455
- }), n = (e?.propertiesToUpdate ?? []).map((e) => ({
1456
- ...e,
1457
- propertySchemaUid: q(e?.propertySchemaUid)
1458
- }));
1459
- return {
1460
- ...e,
1461
- seedUid: q(e?.seedUid),
1462
- seedSchemaUid: q(e?.seedSchemaUid),
1463
- versionUid: q(e?.versionUid),
1464
- versionSchemaUid: q(e?.versionSchemaUid),
1465
- listOfAttestations: t,
1466
- propertiesToUpdate: n
1467
- };
1468
- }
1469
- function ei(e, t) {
1470
- for (let n of e) for (let e of n?.propertiesToUpdate ?? []) {
1471
- let n = e?.publishLocalId, r = q(e?.propertySchemaUid);
1472
- if (!n || !r) continue;
1473
- let i = t.get(n);
1474
- if (!i?.listOfAttestations) continue;
1475
- let a = i.listOfAttestations.find((e) => q(e?.schema)?.toLowerCase() === r?.toLowerCase());
1476
- a && (!Array.isArray(a.data) || a.data.length === 0) && (a.data = [{
1477
- ...Qr,
1478
- refUID: U
1479
- }]);
1480
- }
1481
- }
1482
- //#endregion
1483
- //#region src/services/publish/actors/recordMultiPublishReceipt.ts
1484
- var ti = R("seedProtocol:services:publish:actors:recordMultiPublishReceipt"), J = (e) => !e || q(e) === U, ni = (e) => J(e) ? void 0 : q(e);
1485
- async function ri(e) {
1486
- let { receipt: t, requests: n, rootSeedLocalId: r, useModularExecutor: i, contractAddressForEvents: a, publisherAddress: o } = e, { easContractAddress: s } = D(), c = Hr({
1487
- receipt: t,
1488
- requests: n,
1489
- useModularExecutor: i,
1490
- easContractAddress: s,
1491
- contractAddressForEvents: a
1492
- }), l = await Lr(t);
1493
- for (let e = 0; e < n.length; e++) {
1494
- let t = n[e], r = c[e].versionUid;
1495
- t.localId && J(t.versionUid) && !J(r) && await rt({
1496
- seedLocalId: t.localId,
1497
- versionUid: q(r),
1498
- publisher: o,
1499
- attestationCreatedAt: l
1500
- });
1501
- }
1502
- for (let e = 0; e < n.length; e++) {
1503
- let t = n[e], { propertyPairs: r, versionUid: i } = c[e];
1504
- t.localId && r.length && await Ne({
1505
- seedLocalId: t.localId,
1506
- attestationCreatedAtMs: l ?? null,
1507
- versionUid: ni(t.versionUid) ?? ni(i) ?? null,
1508
- pairs: r
1509
- });
1510
- }
1511
- for (let e = 0; e < n.length; e++) {
1512
- let t = n[e], i = c[e].seedUid;
1513
- t.localId && t.localId !== r && J(t.seedUid) && !J(i) && await ii({
1514
- seedLocalId: t.localId,
1515
- seedUid: i,
1516
- publisherAddress: o,
1517
- attestationCreatedAtMs: l
1518
- });
1519
- }
1520
- return {
1521
- attributed: c,
1522
- requests: n.map((e, t) => {
1523
- let { seedUid: n, versionUid: r } = c[t];
1524
- return {
1525
- ...e,
1526
- ...J(e.seedUid) && !J(n) ? { seedUid: n } : {},
1527
- ...J(e.versionUid) && !J(r) ? { versionUid: r } : {}
1528
- };
1529
- })
1530
- };
1531
- }
1532
- async function ii(e) {
1533
- let { seedLocalId: t, seedUid: n, publisherAddress: r, attestationCreatedAtMs: i } = e;
1534
- try {
1535
- let e = await N.find({ seedLocalId: t });
1536
- if (!e) {
1537
- ti("related item %s not found; its seed uid is not recorded", t);
1538
- return;
1539
- }
1540
- e.seedUid = n, await qr(e, r, i);
1541
- } catch (e) {
1542
- ti("recording seed uid of related item %s failed: %O", t, e);
1543
- }
1544
- }
1545
- //#endregion
1546
- //#region src/helpers/seedPaymaster.ts
1547
- var ai = 12000n;
1548
- function oi(e) {
1549
- return "paymasterAndData" in e && e.paymasterAndData ? e.paymasterAndData : "0x";
1550
- }
1551
- function si(e, t, n) {
1552
- return async (r) => {
1553
- if (k("paymaster hook called (userOp from thirdweb; callGasLimit is tx.gas or 0)", {
1554
- sender: r.sender,
1555
- chainId: t.id,
1556
- bundlerUrl: n ?? "(thirdweb default)",
1557
- entryPoint: "initCode" in r ? "v0.6" : "v0.7",
1558
- ...C(r)
1559
- }), !("initCode" in r)) throw Error("@seedprotocol/publish: the managed account sent an EntryPoint v0.7 UserOp; its sponsored gas handling only supports EntryPoint v0.6.");
1560
- let i = typeof e == "function" ? e() : e, a = await Xt({
1561
- userOp: r,
1562
- client: i,
1563
- chain: t
1564
- });
1565
- k("1/3 paymaster sponsored (limits here are ignored)", C(a));
1566
- let o = {
1567
- ...r,
1568
- paymasterAndData: oi(a)
1569
- }, s = await Yt({
1570
- userOp: o,
1571
- options: {
1572
- client: i,
1573
- chain: t,
1574
- bundlerUrl: n
1575
- }
1576
- });
1577
- k("2/3 bundler estimate (callGasLimit includes thirdweb's +50k)", C(s));
1578
- let c = s.callGasLimit * ai / 10000n;
1579
- o.callGasLimit = r.callGasLimit > c ? r.callGasLimit : c, o.verificationGasLimit = s.verificationGasLimit, o.preVerificationGas = s.preVerificationGas, k("raised limits sent to the paymaster for signing", {
1580
- ...C(o),
1581
- headroomBps: ai,
1582
- raisedEstimate: c,
1583
- txGas: r.callGasLimit
1584
- });
1585
- let l = await Xt({
1586
- userOp: o,
1587
- client: i,
1588
- chain: t
1589
- });
1590
- if (k("3/3 paymaster signed", C(l)), l.callGasLimit && l.verificationGasLimit && l.preVerificationGas) return k("returning to thirdweb: the PAYMASTER's own limits (its signature covers them)", {
1591
- ...C(l),
1592
- requestedCallGasLimit: o.callGasLimit
1593
- }), l;
1594
- let u = {
1595
- paymasterAndData: oi(l),
1596
- callGasLimit: o.callGasLimit,
1597
- verificationGasLimit: o.verificationGasLimit,
1598
- preVerificationGas: o.preVerificationGas
1599
- };
1600
- return k("returning to thirdweb: our raised limits (thirdweb should send exactly these)", C(u)), u;
1601
- };
1602
- }
1603
- //#endregion
1604
- //#region src/helpers/thirdweb.ts
1605
- var ci = /* @__PURE__ */ e({
1606
- ExternalWalletsForDeploy: () => Si,
1607
- appMetadata: () => Ti,
1608
- deployManagedAccountViaFactory: () => wi,
1609
- deploySmartWalletContract: () => Ci,
1610
- getConnectedAccount: () => Di,
1611
- getConnectedManagedAccountAddress: () => Ei,
1612
- getConnectedModularAccount: () => Oi,
1613
- getManagedAccountWallet: () => Mi,
1614
- getModularAccountWallet: () => Pi,
1615
- getSharedPublishInAppWalletStorage: () => fi,
1616
- getSmartWalletAddressForAdmin: () => vi,
1617
- getWalletsForConnectButton: () => Fi,
1618
- isSmartWalletDeployed: () => yi,
1619
- pollSmartWalletDeployed: () => bi,
1620
- resolveSmartWalletForPublish: () => xi,
1621
- syncPublishInAppAuthToken: () => pi,
1622
- useActiveSmartWalletContract: () => _i,
1623
- useLocalWalletAccount: () => gi,
1624
- wallets: () => hi
1625
- }), li = R("permaPress:helpers:thirdweb"), ui = "seedProtocol:inAppPublish:", di = null;
1626
- function fi() {
1627
- return di ||= {
1628
- getItem: async (e) => typeof window > "u" ? null : localStorage.getItem(ui + e),
1629
- setItem: async (e, t) => {
1630
- typeof window < "u" && localStorage.setItem(ui + e, t);
1631
- },
1632
- removeItem: async (e) => {
1633
- typeof window < "u" && localStorage.removeItem(ui + e);
1634
- }
1635
- }, di;
1636
- }
1637
- function pi() {
1638
- if (typeof window > "u") return {
1639
- syncedBareToPrefixed: !1,
1640
- syncedPrefixedToBare: !1
1641
- };
1642
- let { thirdwebClientId: e } = D();
1643
- if (!e) return {
1644
- syncedBareToPrefixed: !1,
1645
- syncedPrefixedToBare: !1
1646
- };
1647
- try {
1648
- let t = `walletToken-${e}`, n = `${ui}${t}`, r = localStorage.getItem(t), i = localStorage.getItem(n), a = !1, o = !1;
1649
- return r && !i && (localStorage.setItem(n, r), a = !0), i && !r && (localStorage.setItem(t, i), o = !0), i && r && r !== i && (localStorage.setItem(t, i), o = !0), {
1650
- syncedBareToPrefixed: a,
1651
- syncedPrefixedToBare: o
1652
- };
1653
- } catch {
1654
- return {
1655
- syncedBareToPrefixed: !1,
1656
- syncedPrefixedToBare: !1
1657
- };
1658
- }
1659
- }
1660
- async function mi(e = A()) {
1661
- pi();
1662
- let t = Mi();
1663
- return await t.autoConnect({
1664
- client: j(),
1665
- chain: e
1666
- }), t;
1667
- }
1668
- var hi = [Kt("io.metamask")], gi = () => {
1669
- let [e, t] = Nt(null);
1670
- return Kt("io.metamask"), Mt(!1), jt(() => {}, []), e;
1671
- }, _i = () => {
1672
- let e = Jt(), [t, n] = Nt(null);
1673
- return jt(() => {
1674
- e && e.address && n(mt({
1675
- client: j(),
1676
- chain: A(),
1677
- address: e.address
1678
- }));
1679
- }, [e]), t;
1680
- };
1681
- async function vi(e, t = "0x") {
1682
- return _(e, t);
1683
- }
1684
- async function yi(e) {
1685
- return oe(e);
1686
- }
1687
- async function bi(e, t, n) {
1688
- return ge(e, t, n);
1689
- }
1690
- async function xi(e) {
1691
- if (!e) return { needsDeploy: !0 };
1692
- if (await yi(e.address)) return {
1693
- address: e.address,
1694
- account: e
1695
- };
1696
- let t = await vi(e.address);
1697
- return await yi(t) ? {
1698
- address: t,
1699
- account: e
1700
- } : { needsDeploy: !0 };
1701
- }
1702
- var Si = [Kt("io.metamask"), Kt("me.rainbow")], Ci = async (e) => {
1703
- let t = mt({
1704
- client: j(),
1705
- chain: A(),
1706
- address: e.address
1707
- }), n = await pt({
1708
- smartAccount: e,
1709
- chain: A(),
1710
- client: j(),
1711
- accountContract: t
1712
- });
1713
- return li("deploySmartAccount result:", n), n;
1714
- };
1715
- async function wi(e) {
1716
- let { asThirdwebPublishWallet: t } = await import("./chainConfig-BDMRU4m8.js").then((e) => e.g), n = t(e.signingAccount), r = b(e.adminAddress, e.data ?? "0x");
1717
- await n.txSender.sendTransaction(r);
1718
- }
1719
- var Ti = {
1720
- name: "Seed Protocol",
1721
- description: "Seed Protocol",
1722
- url: "https://seedprotocol.io"
1723
- };
1724
- async function Ei(e = A()) {
1725
- let t = (await mi(e)).getAccount();
1726
- if (!t) throw Error("Failed to get managed account");
1727
- return t.address;
1728
- }
1729
- async function Di() {
1730
- try {
1731
- let e = Pi();
1732
- return await e.autoConnect({
1733
- client: j(),
1734
- chain: A()
1735
- }), e.getAccount() ?? null;
1736
- } catch {
1737
- return null;
1738
- }
1739
- }
1740
- async function Oi() {
1741
- return Di();
1742
- }
1743
- function ki(e) {
1744
- let t = A(e).id, n = e.managedAccountFactoryAddress ?? h[t];
1745
- if (!n) throw Error(`@seedprotocol/publish: no ManagedAccount factory is known for chain ${t}. Pass managedAccountFactoryAddress in publish config, or use the EOA / direct EAS path.`);
1746
- return n;
1747
- }
1748
- var Ai = [
1749
- "farcaster",
1750
- "email",
1751
- "passkey",
1752
- "phone"
1753
- ], ji = null, Mi = (e) => {
1754
- let t = e ?? w(), n = A(t ?? void 0), r = t ? ki(t) : ae(), { bundlerUrl: i, sponsorGas: a } = Se(t);
1755
- if (!i && re(n)) throw Error(`@seedprotocol/publish: chain ${n.id} is local, so Thirdweb's hosted bundler cannot reach it. Set PublishConfig.thirdweb.bundlerUrl to the chain's bundler (seedTwinConfig does this for the twin).`);
1756
- let o = [
1757
- n.id,
1758
- n.rpc,
1759
- r,
1760
- i ?? "",
1761
- a
1762
- ].join("|").toLowerCase();
1763
- return ji?.key !== o && (k("managed wallet built", {
1764
- chainId: n.id,
1765
- sponsorGas: a,
1766
- bundlerUrl: i ?? "(thirdweb default)",
1767
- paymasterHook: a ? "installed" : "none (thirdweb estimates callGasLimit itself)"
1768
- }), ji = {
1769
- key: o,
1770
- wallet: qt({
1771
- storage: fi(),
1772
- auth: { options: [...Ai] },
1773
- executionMode: {
1774
- mode: "EIP4337",
1775
- smartAccount: {
1776
- chain: n,
1777
- factoryAddress: r,
1778
- sponsorGas: a,
1779
- ...i || a ? { overrides: {
1780
- ...i ? { bundlerUrl: i } : {},
1781
- ...a ? { paymaster: si(j, n, i) } : {}
1782
- } } : {}
1783
- }
1784
- }
1785
- })
1786
- }), ji.wallet;
1787
- }, Ni = null, Pi = (e) => {
1788
- let t = e ?? w(), { modularWalletMode: n, sponsorGas: r } = Se(t);
1789
- if (n === "EIP7702") {
1790
- let e = A(t ?? void 0);
1791
- if (re(e)) throw Error(`@seedprotocol/publish: chain ${e.id} is local, and Thirdweb's EIP-7702 mode needs its hosted bundler, which cannot reach it. Set PublishConfig.thirdweb.modularWalletMode to 'EOA' and fund the in-app EOA (seedTwinConfig does this for the twin).`);
1792
- }
1793
- let i = `${n}|${r}`;
1794
- return Ni?.key !== i && (Ni = {
1795
- key: i,
1796
- wallet: qt({
1797
- storage: fi(),
1798
- auth: { options: [...Ai] },
1799
- executionMode: n === "EOA" ? { mode: "EOA" } : {
1800
- mode: "EIP7702",
1801
- sponsorGas: r
1802
- }
1803
- })
1804
- }), Ni.wallet;
1805
- }, Fi = (e) => {
1806
- let t = e ?? w() ?? void 0;
1807
- return t?.useModularExecutor ? [Pi(t)] : [Mi(t)];
1808
- }, Ii = "This ManagedAccount predates the Seed executor router extension, so the Seed executor cannot act for it and publish automation is not available for this account.", Li = "The Seed executor is not installed for this ManagedAccount, so automation session keys cannot publish through it. The account admin installs it (installSeedExecutor), which enrollPublishAutomation does.", Ri = "The Seed executor module is configured with a different EAS contract for this ManagedAccount than publish config. Automation session keys cannot change it.", zi = "Could not read the Seed executor module state for this ManagedAccount.";
1809
- function Bi() {
1810
- let e = D().modularAccountModuleContract?.trim();
1811
- if (!e || !/^0x[0-9a-fA-F]{40}$/.test(e)) throw Error("@seedprotocol/publish: publish automation requires PublishConfig.modularAccountModuleContract (executor module).");
1812
- return e;
1813
- }
1814
- async function Vi(e) {
1815
- return await ne(e) === null;
1816
- }
1817
- async function Hi(e, t = {}) {
1818
- let n = Bi(), r = e, i, a;
1819
- if (t.installedEas) i = !0, a = t.installedEas;
1820
- else try {
1821
- i = await Ce(() => ee(n, r), Boolean, { attempts: t.readAttempts ?? 1 }), a = i ? await x(n, r) : ft;
1822
- } catch (t) {
1823
- throw new E(zi, "AUTOMATION_UNSUPPORTED_ACCOUNT", e, t);
1824
- }
1825
- if (!i) {
1826
- let t = await Vi(r) ? Ii : Li;
1827
- throw new E(t, "AUTOMATION_UNSUPPORTED_ACCOUNT", e);
1828
- }
1829
- let o = D().easContractAddress?.toLowerCase();
1830
- if (o && a.toLowerCase() !== o) throw new E(Ri, "AUTOMATION_UNSUPPORTED_ACCOUNT", e);
1831
- }
1832
- function Ui(e) {
1833
- let t = e instanceof at ? `${e.shortMessage} ${e.details} ${e.message}` : String(e);
1834
- return /insufficient funds|insufficient balance/i.test(t);
1835
- }
1836
- async function Wi(e) {
1837
- let { managedAddress: t, tx: n, action: r, code: i = "AUTOMATION_PREFLIGHT_FAILED", requireSimulation: a = !0 } = e, o = (e) => xe().call({
1838
- account: t,
1839
- to: n.to,
1840
- data: n.data,
1841
- value: n.value,
1842
- ...e ? { stateOverride: [{
1843
- address: t,
1844
- balance: lt("1000")
1845
- }] } : {}
1846
- });
1847
- try {
1848
- try {
1849
- await o(!1);
1850
- } catch (e) {
1851
- if (!Ui(e)) throw e;
1852
- await o(!0);
1853
- }
1854
- } catch (e) {
1855
- let n = tn(e);
1856
- if (!n && !a) return;
1857
- let o = n ? rn(en(e)) : "could not be simulated";
1858
- throw new E(`Simulated ${r} from ${t} ${o}; nothing was sent.`, i, t, e);
1859
- }
1860
- }
1861
- //#endregion
1862
- //#region src/helpers/ensureExecutorModule.ts
1863
- var Gi = () => `The executor module could not be installed on your publishing account on ${O()}. Reconnect and try again, or contact support if this persists.`;
1864
- async function Ki(e, t, n) {
1865
- let { modularAccountModuleContract: r } = n;
1866
- if (!r || !await oe(e)) return { status: "skipped" };
1867
- let i = await ne(e);
1868
- return i ? qi(e, i.executor, r) : { status: "skipped" };
1869
- }
1870
- async function qi(e, t, n) {
1871
- if (t.toLowerCase() !== n.trim().toLowerCase()) throw new E(`Your publishing account's Seed executor is ${t}, but publish config sets modularAccountModuleContract to ${n}. Point modularAccountModuleContract at the account's executor.`, "EXECUTOR_MODULE_NOT_INSTALLED", e);
1872
- let r = e, i, a, o;
1873
- try {
1874
- if (await fe(r, t)) return { status: "already-installed" };
1875
- let { getManagedAccountAdmin: n } = await import("./managedAccountAdmin-B3DPMmhR.js").then((e) => e.n), s = ue(await n(e));
1876
- i = s.txSender.address;
1877
- let c = await s.txSender.sendTransaction(f(r));
1878
- o = c.transactionHash;
1879
- try {
1880
- a = await T(c.transactionHash);
1881
- } catch (e) {
1882
- if (!(e instanceof de)) throw e;
1883
- }
1884
- } catch (t) {
1885
- throw t instanceof E ? t : new E(Gi(), "EXECUTOR_MODULE_NOT_INSTALLED", e, t);
1886
- }
1887
- let s = a && Ji(a, r, t);
1888
- if (s) return {
1889
- status: "installed",
1890
- eas: s,
1891
- transactionHash: o
1892
- };
1893
- let c = await Yi(r, i);
1894
- if (c === "already-installed") return { status: "already-installed" };
1895
- throw new E(`installSeedExecutor in transaction ${o} did not install the Seed executor on ${e}${c ? `: ${c}` : ""}.`, "EXECUTOR_MODULE_NOT_INSTALLED", e);
1896
- }
1897
- function Ji(e, t, n) {
1898
- if (ut({
1899
- abi: ie,
1900
- eventName: "SeedExecutorInstalled",
1901
- logs: e.logs,
1902
- strict: !1
1903
- }).some((e) => ct(e.address, t) && e.args.executor && ct(e.args.executor, n))) return ut({
1904
- abi: y,
1905
- eventName: "ModuleInitialized",
1906
- logs: e.logs,
1907
- strict: !1
1908
- }).find((e) => ct(e.address, n) && e.args.account && ct(e.args.account, t))?.args.eas;
1909
- }
1910
- async function Yi(e, t) {
1911
- try {
1912
- await Wi({
1913
- managedAddress: t,
1914
- tx: f(e),
1915
- action: "installSeedExecutor",
1916
- requireSimulation: !1
1917
- });
1918
- return;
1919
- } catch (e) {
1920
- let t = rn(en(e instanceof E ? e.underlyingCause : e));
1921
- return t === "reverted with SeedExecutorAlreadyInstalled" ? "already-installed" : t;
1922
- }
1923
- }
1924
- //#endregion
1925
- //#region src/helpers/ensureManagedAccountReady.ts
1926
- var Xi = () => `Could not connect the managed publishing account on ${O()}. Reconnect with the same sign-in method and try again.`, Zi = () => `Your publishing smart account is not deployed on ${O()} yet. Complete wallet setup, enable autoDeployManagedAccount in config if appropriate, then try again.`, Qi = () => `The managed account could not be confirmed on ${O()} after deployment. Wait a moment and retry, or check your network connection.`, $i = () => `Automatic deployment of the managed publishing account failed on ${O()}. Retry or deploy the account through your wallet provider.`;
1927
- async function ea() {
1928
- let { useModularExecutor: e } = D();
1929
- if (!e) return { kind: "skip" };
1930
- let t;
1931
- try {
1932
- t = await Ei(A());
1933
- } catch (e) {
1934
- return {
1935
- kind: "unavailable",
1936
- cause: e
1937
- };
1938
- }
1939
- return await yi(t) ? {
1940
- kind: "ready",
1941
- managedAddress: t
1942
- } : {
1943
- kind: "not_deployed",
1944
- managedAddress: t
1945
- };
1946
- }
1947
- async function ta() {
1948
- pi();
1949
- let e = Mi();
1950
- await e.autoConnect({
1951
- client: j(),
1952
- chain: A()
1953
- });
1954
- let t = e.getAccount();
1955
- if (!t) throw new E(Xi(), "MANAGED_ACCOUNT_UNAVAILABLE");
1956
- return t;
1957
- }
1958
- var na = 9e4;
1959
- async function ra(e) {
1960
- let t;
1961
- try {
1962
- await Promise.race([Ci(e), new Promise((e, n) => {
1963
- t = setTimeout(() => n(/* @__PURE__ */ Error(`Managed account deploy timed out after ${na / 1e3}s`)), na);
1964
- })]);
1965
- } finally {
1966
- t != null && clearTimeout(t);
1967
- }
1968
- }
1969
- async function ia(e) {
1970
- let t = D(), n = await ta(), { fromThirdwebAccount: r } = await import("./chainConfig-BDMRU4m8.js").then((e) => e.g), i = {
1971
- managedAddress: e,
1972
- managedSigningAccount: r(n)
1973
- };
1974
- try {
1975
- if (t.deployManagedAccount) await t.deployManagedAccount(i);
1976
- else {
1977
- let e = await Oi();
1978
- if (e) {
1979
- let t = Pi();
1980
- await t.autoConnect({
1981
- client: j(),
1982
- chain: A()
1983
- }), await wi({
1984
- adminAddress: t.getAdminAccount?.()?.address ?? e.address,
1985
- signingAccount: e
1986
- });
1987
- } else await ra(n);
1988
- }
1989
- } catch (t) {
1990
- if (await bi(e, /UserOp|user operation/i.test(Ee(t)) ? 15 : 5)) return;
1991
- throw new E($i(), "MANAGED_ACCOUNT_NOT_DEPLOYED", e, t);
1992
- }
1993
- if (!await bi(e)) throw new E(Qi(), "MANAGED_ACCOUNT_NOT_DEPLOYED", e);
1994
- }
1995
- async function aa() {
1996
- let e = D();
1997
- if (!e.useModularExecutor) throw Error("runModularExecutorPublishPrep: useModularExecutor is false");
1998
- let t = await ea();
1999
- if (t.kind === "unavailable") return {
2000
- ok: !1,
2001
- error: new E(Xi(), "MANAGED_ACCOUNT_UNAVAILABLE", void 0, t.cause)
2002
- };
2003
- if (t.kind === "not_deployed") {
2004
- if (e.autoDeployManagedAccount) {
2005
- try {
2006
- await ia(t.managedAddress);
2007
- } catch (e) {
2008
- return {
2009
- ok: !1,
2010
- error: te(e) ? e : new E($i(), "MANAGED_ACCOUNT_NOT_DEPLOYED", t.managedAddress, e)
2011
- };
2012
- }
2013
- if (t = await ea(), t.kind !== "ready") return {
2014
- ok: !1,
2015
- error: new E(Qi(), "MANAGED_ACCOUNT_NOT_DEPLOYED", t.kind === "not_deployed" ? t.managedAddress : void 0)
2016
- };
2017
- } else return {
2018
- ok: !1,
2019
- error: new E(Zi(), "MANAGED_ACCOUNT_NOT_DEPLOYED", t.managedAddress)
2020
- };
2021
- }
2022
- if (t.kind === "ready") {
2023
- if (e.modularAccountModuleContract) try {
2024
- let n = await ta();
2025
- await Ki(t.managedAddress, n, e);
2026
- } catch (e) {
2027
- console.warn(`[@seedprotocol/publish] Executor module setup failed on ${O()}; publishing continues, but publish automation needs it.`, e);
2028
- }
2029
- return {
2030
- ok: !0,
2031
- managedAddress: t.managedAddress
2032
- };
2033
- }
2034
- throw Error("runModularExecutorPublishPrep: unexpected readiness state");
2035
- }
2036
- //#endregion
2037
- //#region src/helpers/resolvePublishWallet.ts
2038
- function oa(e) {
2039
- if (i(e.wallet)) return e.wallet;
2040
- if (i(e.account)) return e.account;
2041
- let t = pe();
2042
- if (t) return t;
2043
- throw Error("@seedprotocol/publish: no PublishWallet available. Pass fromEthersWallet / fromEip1193Provider / fromThirdwebAccount, or call setPublishWallet / useSeedWallet.");
2044
- }
2045
- //#endregion
2046
- //#region src/services/publish/helpers/verifyArweaveTransactionsExist.ts
2047
- async function sa(e) {
2048
- if (e.length === 0) return;
2049
- let { arweaveUploadVerificationBaseUrl: t } = D(), n = await Promise.all(e.map((e) => Ue(t, e)));
2050
- for (let t = 0; t < e.length; t++) {
2051
- let r = e[t], i = n[t];
2052
- if (i) {
2053
- if (i.status === 404) throw Error(`Arweave transaction ${r} not found. Upload may have failed. Delete this publish record and try again.`);
2054
- if (i.status !== 200) {
2055
- let e = i.status === 504 ? "request timed out (upload service did not respond in time)" : `status: ${i.status}`;
2056
- throw Error(`Arweave transaction ${r} is not yet available from the upload service (${e}). Wait and retry.`);
2057
- }
2058
- }
2059
- }
2060
- }
2061
- //#endregion
2062
- //#region src/services/arweaveL1Finalize/enqueue.ts
2063
- var ca = "pending_l1";
2064
- async function la(e) {
2065
- let { useArweaveBundler: t } = D();
2066
- if (!t) return;
2067
- let n = e.arweaveTransactions ?? [], r = e.publishUploads ?? [];
2068
- if (n.length === 0 || n.length !== r.length) return;
2069
- let i = ke.getAppDb();
2070
- if (!i) return;
2071
- let a = Date.now();
2072
- for (let e = 0; e < n.length; e++) {
2073
- let t = n[e], o = r[e];
2074
- if (!o) continue;
2075
- let s = t.transaction?.id;
2076
- if (s && typeof s == "string") try {
2077
- await i.insert(Pe).values({
2078
- seedLocalId: o.seedLocalId,
2079
- dataItemId: s,
2080
- versionLocalId: o.versionLocalId ?? null,
2081
- itemPropertyName: o.itemPropertyName ?? null,
2082
- phase: ca,
2083
- createdAt: a,
2084
- updatedAt: a
2085
- }).onConflictDoNothing();
2086
- } catch {}
2087
- }
2088
- }
2089
- //#endregion
2090
- //#region src/helpers/ensureManagedAccountEasConfigured.ts
2091
- var ua = () => `Could not verify or set the EAS contract address on your publishing account on ${O()}.`, da = "ManagedAccount EAS pointer does not match publish config. Configure EAS with the user’s ManagedAccount wallet before automation publish (session keys cannot call setEas).", fa = (e) => `Your publishing account's Seed extension uses EAS ${e}, but publish config sets easContractAddress to a different contract. The extension's EAS is fixed at deployment; fix easContractAddress.`;
2092
- function pa(e) {
2093
- return e.toLowerCase();
2094
- }
2095
- function ma(e) {
2096
- let { easContractAddress: t } = D(), n = pa(t);
2097
- if (!n || n === pa(ft)) throw new E("Publish config is missing a valid easContractAddress.", "MANAGED_ACCOUNT_SET_EAS_FAILED", e);
2098
- return n;
2099
- }
2100
- async function ha(e) {
2101
- try {
2102
- let t = await se(e);
2103
- return pa(typeof t == "string" ? t : String(t));
2104
- } catch (t) {
2105
- throw new E(ua(), "MANAGED_ACCOUNT_SET_EAS_FAILED", e, t);
2106
- }
2107
- }
2108
- async function ga(e) {
2109
- let t = ma(e);
2110
- if (await ha(e) !== t) throw new E(da, "MANAGED_ACCOUNT_SET_EAS_FAILED", e);
2111
- }
2112
- async function _a(e, t) {
2113
- let n = ma(e), r = await ha(e);
2114
- if (r !== n) {
2115
- if (r !== pa(ft)) throw new E(fa(r), "MANAGED_ACCOUNT_SET_EAS_FAILED", e);
2116
- try {
2117
- let n = typeof t == "function" ? await t() : t, r = i(n) ? n.txSender : he(n) ? n : (() => {
2118
- throw Error("@seedprotocol/publish: ensureManagedAccountEasConfigured requires PublishWallet or SeedTxSender");
2119
- })(), { easContractAddress: a } = D(), o = S(e, a), s = await r.sendTransaction(o);
2120
- await T(s.transactionHash);
2121
- } catch (t) {
2122
- throw new E(ua(), "MANAGED_ACCOUNT_SET_EAS_FAILED", e, t);
2123
- }
2124
- }
2125
- }
2126
- //#endregion
2127
- //#region src/services/publish/actors/createAttestations.ts
2128
- var va = R("seedProtocol:services:publish:actors");
2129
- function ya(e) {
2130
- return !!e && /^0x[0-9a-fA-F]{40}$/.test(e.trim());
2131
- }
2132
- function ba(e) {
2133
- let { useModularExecutor: t, publisherAddress: n, modularAccountModuleContract: r, managedAddress: i, routeToExecutorModule: a } = e;
2134
- if (t) {
2135
- if (!i) throw Error("resolvePublishRouting: managedAddress is required when useModularExecutor is true");
2136
- let e = r?.trim();
2137
- if (a) {
2138
- if (!ya(e)) throw Error("resolvePublishRouting: modularAccountModuleContract is required when routeToExecutorModule is true");
2139
- return {
2140
- txTargetAddress: e,
2141
- contractAddressForEvents: e
2142
- };
2143
- }
2144
- return {
2145
- txTargetAddress: i,
2146
- contractAddressForEvents: e || i
2147
- };
2148
- }
2149
- return {
2150
- txTargetAddress: n,
2151
- contractAddressForEvents: n
2152
- };
2153
- }
2154
- var xa = L(async ({ input: { context: e } }) => {
2155
- let { address: t, account: n, wallet: r } = e, i = e.arweaveTransactions ?? [], a = e.publishUploads ?? [], { item: o } = e, { modularAccountModuleContract: s, useModularExecutor: l } = D();
2156
- if (!t || typeof t != "string" || !t.trim()) throw Error("No wallet address for publish. Connect a wallet and try again.");
2157
- if (!r && !n) throw Error("Wallet session is missing. Reconnect your wallet and retry the publish.");
2158
- if (!l && !await oe(t)) throw Error("EOA publishing must use the direct EAS path (multiPublish requires a deployed publisher contract). If you see this, attestation routing is misconfigured.");
2159
- if (!o?.seedLocalId) throw Error("Attestation recovery failed: Item data is missing. Delete this publish record and try a full publish from the beginning.");
2160
- if (typeof o.getPublishUploads != "function" && (o = await Dn(o.seedLocalId)), i.length !== a.length) throw Error("Attestation recovery failed: Arweave transaction data is missing or incomplete. Delete this publish record and try a full publish from the beginning.");
2161
- let u = ba({
2162
- useModularExecutor: !1,
2163
- publisherAddress: t
2164
- }), d = oa(e), f = !1;
2165
- await Tn(o, d, { managedAddress: t });
2166
- let p = i.map((e, t) => {
2167
- let n = e.transaction?.id;
2168
- if (!n || typeof n != "string") throw Error("Attestation recovery failed: Arweave transaction data did not survive restore. Delete this publish record and try a full publish from the beginning.");
2169
- let r = a[t];
2170
- if (!r) throw Error("Publish upload index mismatch");
2171
- return {
2172
- ...r,
2173
- txId: n
2174
- };
2175
- });
2176
- await sa(p.map((e) => e.txId));
2177
- let m = await o.getPublishPayload(p, { publishMode: e.publishMode ?? "patch" }), h = Array.isArray(m) ? m : [m];
2178
- if (l) {
2179
- let e = d?.signer?.address, n = !1;
2180
- if (t && e) {
2181
- let { isAutomationSessionActive: r } = await import("./ensureAutomationSessionKey-bw6knEyC.js").then((e) => e.n);
2182
- n = await r(t, e);
2183
- }
2184
- if (n) {
2185
- let e = s?.trim();
2186
- if (!ya(e)) throw Error("@seedprotocol/publish: automation publish requires PublishConfig.modularAccountModuleContract (executor module). Session keys are module-only and cannot call the ManagedAccount directly.");
2187
- u = ba({
2188
- useModularExecutor: l,
2189
- publisherAddress: t,
2190
- modularAccountModuleContract: e,
2191
- managedAddress: t,
2192
- routeToExecutorModule: !0
2193
- }), f = !0, await Hi(t);
2194
- } else {
2195
- let e = await aa();
2196
- if (!e.ok) throw e.error;
2197
- u = ba({
2198
- useModularExecutor: l,
2199
- publisherAddress: t,
2200
- modularAccountModuleContract: s,
2201
- managedAddress: e.managedAddress
2202
- });
2203
- let { ensureModularPublishBootstrap: n } = await import("./ensureModularPublishBootstrap-Vc4Jz_B9.js").then((e) => e.n), { fromThirdwebAccount: r } = await import("./chainConfig-BDMRU4m8.js").then((e) => e.g);
2204
- d = r(await n(e.managedAddress));
2205
- }
2206
- } else await _a(t, d);
2207
- let g = async (e) => {
2208
- let n = u.txTargetAddress, r = f ? c(n, e, 5000000n) : ve(n, e, 5000000n);
2209
- await Wi(f ? {
2210
- managedAddress: t,
2211
- tx: r,
2212
- action: "multiPublish via the executor module"
2213
- } : {
2214
- managedAddress: d.txSender.address,
2215
- tx: r,
2216
- action: "multiPublish",
2217
- code: "PUBLISH_PREFLIGHT_FAILED",
2218
- requireSimulation: !1
2219
- });
2220
- try {
2221
- return await d.txSender.sendTransaction(r);
2222
- } catch (e) {
2223
- throw un(e, d.txSender.address);
2224
- }
2225
- }, _ = h.length > 1 && Xr(h), v, y = null, b = [];
2226
- if (_) {
2227
- let e = structuredClone(h), n = {}, r = {};
2228
- for (let i = 0; i < e.length; i++) {
2229
- e = await Qe(e, n);
2230
- let a = e[i], s = /* @__PURE__ */ new Set([a.localId]), c = $r({
2231
- ...a,
2232
- propertiesToUpdate: Zr(a.propertiesToUpdate, s)
2233
- }), d = /* @__PURE__ */ new Map([[c.localId, c]]);
2234
- ei([c], d);
2235
- let f = await g([c]), p = await T(f.transactionHash);
2236
- if (!p) throw Error("Failed to send transaction");
2237
- y = p;
2238
- for (let e of Rr(p, l)) e.attestationUid && b.push(e.attestationUid);
2239
- let { requests: [m] } = await ri({
2240
- receipt: p,
2241
- requests: [c],
2242
- rootSeedLocalId: o.seedLocalId,
2243
- useModularExecutor: l,
2244
- contractAddressForEvents: u.contractAddressForEvents,
2245
- publisherAddress: t
2246
- });
2247
- m?.versionUid && q(m.versionUid) !== U && (r[a.localId] = m.versionUid);
2248
- let h = !c.seedUid || q(c.seedUid) === U ? m?.seedUid : void 0;
2249
- h && q(h) !== U && (n[a.localId] = h, e[i] = {
2250
- ...e[i],
2251
- seedUid: h
2252
- }, b.push(h));
2253
- }
2254
- for (let t of e) {
2255
- let e = t?.localId, r = t?.seedUid;
2256
- e && r && q(r) !== U && (n[e] = q(r));
2257
- }
2258
- v = (await Qe(structuredClone(h), n)).map((e) => $r({
2259
- ...e,
2260
- seedUid: n[e.localId] ?? e.seedUid,
2261
- versionUid: r[e.localId] ?? e.versionUid
2262
- }));
2263
- } else {
2264
- let e = h.map((e) => $r(e));
2265
- ei(e, new Map(e.map((e) => [e?.localId, e])));
2266
- let n = Array.isArray(m) ? e : [e[0]], r = await g(n), i = await T(r.transactionHash);
2267
- if (!i) throw Error("Failed to send transaction");
2268
- y = i;
2269
- for (let e of Rr(i, l)) e.attestationUid && b.push(e.attestationUid);
2270
- v = (await ri({
2271
- receipt: i,
2272
- requests: n,
2273
- rootSeedLocalId: o.seedLocalId,
2274
- useModularExecutor: l,
2275
- contractAddressForEvents: u.contractAddressForEvents,
2276
- publisherAddress: t
2277
- })).requests;
2278
- }
2279
- Kr(o, v);
2280
- let x = o, S = v.find((e) => e?.localId === o.seedLocalId)?.seedUid;
2281
- S && S !== U && await qr(x, t, y ? await Lr(y) : void 0), va("requestData", m), la(e);
2282
- try {
2283
- let { clearHtmlEmbeddedImageCoPublishRows: e } = await import("@seedprotocol/sdk"), t = /* @__PURE__ */ new Set([o.seedLocalId]);
2284
- for (let e of v) e?.localId && t.add(e.localId);
2285
- for (let n of t) await e(n);
2286
- } catch {}
2287
- let { collectPublishedBatch: ee } = await import("./collectBatchUids-CnIe9jUB.js").then((e) => e.t), C = v.find((e) => e?.localId === o.seedLocalId) ?? v[0];
2288
- for (let e of v) e?.seedUid && b.push(String(e.seedUid)), e?.versionUid && b.push(String(e.versionUid));
2289
- return {
2290
- easPayload: m,
2291
- publishedBatch: C?.seedUid ? ee({
2292
- seedUid: String(C.seedUid),
2293
- versionUid: C.versionUid ? String(C.versionUid) : void 0,
2294
- extraUids: b
2295
- }) : null
2296
- };
2297
- }), Sa = R("seedProtocol:services:publish:verifyAttestations"), Ca = "0x" + "0".repeat(64), wa = 64, Ta = (e) => e == null ? "0x" + "0".repeat(wa) : typeof e == "string" ? "0x" + (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0").padStart(wa, "0").slice(-64) : "0x" + "0".repeat(wa), Ea = 5e3, Da = 6;
2298
- async function Oa({ normalizedRequests: e, item: t }) {
2299
- let n = t.seedLocalId;
2300
- for (let t of e) {
2301
- if (t.listOfAttestations.length === 0 || t.versionUid === Ca) continue;
2302
- let e = t.listOfAttestations.map((e) => Ta(e.schema).toLowerCase()), r = [], i;
2303
- for (let e = 1; e <= Da; e++) try {
2304
- e > 1 && await new Promise((e) => setTimeout(e, Ea)), r = await Re({ versionUids: [t.versionUid] });
2305
- break;
2306
- } catch (t) {
2307
- if (i = t, Sa("verifyAttestations attempt %d failed:", e, t), e === Da) throw Sa("verifyAttestations: giving up after %d attempts", Da), i;
2308
- }
2309
- let a = r.map((e) => e.schemaId ? Ta(e.schemaId).toLowerCase() : "").filter(Boolean), o = new Set(a);
2310
- if (e.filter((e) => !o.has(e)).length > 0) throw new le(`Publish verification failed: Seed and Version attestations were created, but property/metadata attestations are missing or incomplete. Expected ${e.length} property attestations for schema(s) ${e.join(", ")}; found ${a.length}. Use PublishManager.retryAttestations('${n}') to retry.`, n, e, a, "METADATA_PROPERTIES_MISSING");
2311
- }
2312
- }
2313
- //#endregion
2314
- //#region src/services/publish/actors/createAttestationsDirectToEas.ts
2315
- var ka = R("seedProtocol:services:publish:createAttestationsDirectToEas"), Aa = 64, Y = (e) => {
2316
- if (e == null) return "0x" + "0".repeat(Aa);
2317
- if (typeof e == "string") return "0x" + (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0").padStart(Aa, "0").slice(-64);
2318
- if (e instanceof Uint8Array || typeof ArrayBuffer < "u" && e instanceof ArrayBuffer) {
2319
- let t = e instanceof Uint8Array ? e : new Uint8Array(e);
2320
- return "0x" + Array.from(t).map((e) => e.toString(16).padStart(2, "0")).join("").padStart(Aa, "0").slice(-64);
2321
- }
2322
- return "0x" + "0".repeat(Aa);
2323
- }, ja = (e) => {
2324
- if (e == null || typeof e == "string" && (e === "" || e === "0x")) return "0x";
2325
- if (typeof e == "string") {
2326
- let t = (e.startsWith("0x") ? e.slice(2) : e).replace(/[^0-9a-fA-F]/g, "0");
2327
- return "0x" + (t.length % 2 == 1 ? "0" + t : t);
2328
- }
2329
- if (e instanceof Uint8Array || typeof ArrayBuffer < "u" && e instanceof ArrayBuffer) {
2330
- let t = e instanceof Uint8Array ? e : new Uint8Array(e);
2331
- return "0x" + Array.from(t).map((e) => e.toString(16).padStart(2, "0")).join("");
2332
- }
2333
- return "0x";
2334
- }, Ma = async (e) => {
2335
- let t;
2336
- try {
2337
- t = await N.find({ seedLocalId: e });
2338
- } catch {}
2339
- return t || new Promise((t) => {
2340
- let n = setInterval(() => {
2341
- try {
2342
- N.find({ seedLocalId: e }).then((e) => {
2343
- e && (clearInterval(n), t(e));
2344
- });
2345
- } catch {}
2346
- }, 200);
2347
- });
2348
- }, Na = (e) => Array.isArray(e?._rawListIdsForResolve) || e?._easDataType === "bytes32[]" || typeof e?._schemaDef == "string" && e._schemaDef.startsWith("bytes32[]"), Pa = (e) => Array.isArray(e?._rawListIdsForResolve) && e._rawListIdsForResolve.length > 0 || !!e?._unresolvedValue;
2349
- async function Fa(e, t, n) {
2350
- let r = e?.listOfAttestations ?? [];
2351
- if (!r.some(Pa)) return;
2352
- let [i] = await Qe([e], n);
2353
- r.forEach((e, n) => {
2354
- let r = i?.listOfAttestations?.[n];
2355
- if (!Pa(e) || !r || Pa(r)) return;
2356
- let a = Array.isArray(r.data) ? r.data[0]?.data : r.data?.data, o = t.listOfAttestations[n]?.data?.[0];
2357
- o && a != null && (o.data = ja(a));
2358
- });
2359
- }
2360
- var Ia = L(async ({ input: { context: e, event: t } }) => {
2361
- let { address: n, account: r, wallet: i } = e, a = e.arweaveTransactions ?? [], o = e.publishUploads ?? [], { item: c } = e;
2362
- if (!n || typeof n != "string" || !n.trim()) throw Error("No wallet address for publish. Connect a wallet and try again.");
2363
- if (!i && !r) throw Error("Wallet session is missing. Reconnect your wallet and retry the publish.");
2364
- if (!c?.seedLocalId) throw Error("Attestation recovery failed: Item data is missing. Delete this publish record and try a full publish from the beginning.");
2365
- if (typeof c.getPublishUploads != "function" && (c = await Ma(c.seedLocalId)), a.length !== o.length) throw Error("Attestation recovery failed: Arweave transaction data is missing or incomplete. Delete this publish record and try a full publish from the beginning.");
2366
- let l = oa(e), d = l.txSender;
2367
- await Tn(c, l, { managedAddress: n });
2368
- let f = a.map((e, t) => {
2369
- let n = e.transaction?.id;
2370
- if (!n || typeof n != "string") throw Error("Attestation recovery failed: Arweave transaction data did not survive restore. Delete this publish record and try a full publish from the beginning.");
2371
- let r = o[t];
2372
- if (!r) throw Error("Publish upload index mismatch");
2373
- return {
2374
- ...r,
2375
- txId: n
2376
- };
2377
- });
2378
- await sa(f.map((e) => e.txId));
2379
- let m = await c.getPublishPayload(f, { publishMode: e.publishMode ?? "patch" }), h = Array.isArray(m) ? m : [m], _ = h.map((e) => {
2380
- let t = (e?.listOfAttestations ?? []).map((e) => {
2381
- let t = Array.isArray(e?.data) ? e.data : [];
2382
- return {
2383
- schema: Y(e?.schema),
2384
- data: t.map((e) => ({
2385
- ...e,
2386
- refUID: Y(e?.refUID),
2387
- data: ja(e?.data)
2388
- })),
2389
- ...typeof e?._propertyName == "string" && e._propertyName !== "" ? { _propertyName: e._propertyName } : {},
2390
- ...typeof e?._propertyNameForSchema == "string" && e._propertyNameForSchema !== "" ? { _propertyNameForSchema: e._propertyNameForSchema } : {},
2391
- ...Na(e) ? { _isList: !0 } : {}
2392
- };
2393
- }), n = (e?.propertiesToUpdate ?? []).map((e) => ({
2394
- ...e,
2395
- propertySchemaUid: Y(e?.propertySchemaUid)
2396
- }));
2397
- return {
2398
- ...e,
2399
- seedUid: Y(e?.seedUid),
2400
- seedSchemaUid: Y(e?.seedSchemaUid),
2401
- versionUid: Y(e?.versionUid),
2402
- versionSchemaUid: Y(e?.versionSchemaUid),
2403
- listOfAttestations: t,
2404
- propertiesToUpdate: n
2405
- };
2406
- }), y = new Map(_.map((e) => [e.localId, e])), b = {
2407
- recipient: Rt,
2408
- expirationTime: BigInt(0),
2409
- revocable: !0,
2410
- refUID: g,
2411
- data: g,
2412
- value: BigInt(0)
2413
- };
2414
- for (let e of _) for (let t of e.propertiesToUpdate ?? []) {
2415
- let e = t.publishLocalId, n = Y(t.propertySchemaUid);
2416
- if (!e || !n) continue;
2417
- let r = y.get(e);
2418
- if (!r?.listOfAttestations) continue;
2419
- let i = r.listOfAttestations.find((e) => Y(e?.schema)?.toLowerCase() === n?.toLowerCase());
2420
- i && !i._isList && (!Array.isArray(i.data) || i.data.length === 0) && (i.data = [{
2421
- ...b,
2422
- refUID: g
2423
- }]);
2424
- }
2425
- let x = Date.now(), S = [], ee = /* @__PURE__ */ new Map(), C = {};
2426
- for (let e of _) e.localId && e.seedUid !== g && (C[e.localId] = e.seedUid);
2427
- for (let e = 0; e < _.length; e++) {
2428
- let t = _[e], r = t.seedUid, i = t.versionUid;
2429
- if (r === g) {
2430
- let e = v({
2431
- schema: t.seedSchemaUid,
2432
- data: {
2433
- refUID: g,
2434
- data: s(t.seedSchemaUid),
2435
- revocable: t.seedIsRevocable
2436
- }
2437
- }), n = await d.sendTransaction(e), i = await T(n.transactionHash);
2438
- if (!i) throw Error("Failed to create Seed attestation");
2439
- x = await Lr(i);
2440
- let { easContractAddress: a } = D(), o = u(i, a);
2441
- if (!o || o === g) throw Error("Failed to get Seed UID from attestation receipt");
2442
- r = o, t.seedUid = o, t.localId && (ee.set(t.localId, {
2443
- seedUid: o,
2444
- attestationMs: x
2445
- }), C[t.localId] = o), S.push(o), ka("created Seed attestation", r);
2446
- } else r !== g && S.push(r);
2447
- if (r !== g && i === g) {
2448
- let e = v({
2449
- schema: t.versionSchemaUid,
2450
- data: {
2451
- refUID: r,
2452
- data: s(t.versionSchemaUid),
2453
- revocable: !0
2454
- }
2455
- }), a = await d.sendTransaction(e), o = await T(a.transactionHash);
2456
- if (!o) throw Error("Failed to create Version attestation");
2457
- x = await Lr(o);
2458
- let { easContractAddress: c } = D(), l = u(o, c);
2459
- if (!l || l === g) throw Error("Failed to get Version UID from attestation receipt");
2460
- i = l, t.versionUid = l, S.push(l), await rt({
2461
- seedLocalId: t.localId,
2462
- versionUid: l,
2463
- publisher: n,
2464
- attestationCreatedAt: x
2465
- }), ka("created Version attestation", i);
2466
- } else i !== g && S.push(i);
2467
- for (let e of t.listOfAttestations) for (let t of e.data) t.refUID = i;
2468
- await Fa(h[e], t, C);
2469
- for (let e of t.propertiesToUpdate ?? []) {
2470
- let t = y.get(e.publishLocalId);
2471
- if (!t?.listOfAttestations) continue;
2472
- let n = Y(e.propertySchemaUid), i = t.listOfAttestations.find((e) => Y(e?.schema)?.toLowerCase() === n?.toLowerCase());
2473
- i?.data?.[0] && !i._isList && (i.data[0].data = s(r));
2474
- }
2475
- let a = t.listOfAttestations.map((e) => ({
2476
- schema: e.schema,
2477
- data: e.data.map((e) => ({
2478
- recipient: e.recipient ?? Rt,
2479
- expirationTime: e.expirationTime ?? 0n,
2480
- revocable: e.revocable ?? !0,
2481
- refUID: e.refUID ?? g,
2482
- data: e.data ?? "0x",
2483
- value: e.value ?? 0n
2484
- }))
2485
- }));
2486
- if (a.length > 0) {
2487
- let n = De(a), r = await d.sendTransaction(n), o = await T(r.transactionHash);
2488
- if (!o) throw Error("Failed to create property attestations");
2489
- x = await Lr(o), ka("created property attestations for request", e);
2490
- let { easContractAddress: s } = D(), c = p(o, s);
2491
- for (let e of c) e.uid && S.push(e.uid);
2492
- let l = t.listOfAttestations, u = c.length === l.length;
2493
- await Ne({
2494
- seedLocalId: t.localId,
2495
- attestationCreatedAtMs: x ?? null,
2496
- versionUid: i === g ? null : i,
2497
- pairs: c.map((e, t) => ({
2498
- schemaUid: e.schemaUid,
2499
- attestationUid: e.uid,
2500
- propertyName: u && typeof l[t]?._propertyName == "string" && l[t]._propertyName !== "" ? l[t]._propertyName : void 0
2501
- }))
2502
- });
2503
- }
2504
- }
2505
- Kr(c, _);
2506
- let te = c, w = _.find((e) => e.localId === c.seedLocalId) ?? _[0];
2507
- w?.seedUid && w.seedUid !== g && await qr(te, n, ee.get(w.localId)?.attestationMs ?? x);
2508
- for (let [e, { seedUid: t, attestationMs: r }] of ee) e !== w?.localId && await ii({
2509
- seedLocalId: e,
2510
- seedUid: t,
2511
- publisherAddress: n,
2512
- attestationCreatedAtMs: r
2513
- });
2514
- try {
2515
- await Oa({
2516
- normalizedRequests: _,
2517
- item: c
2518
- });
2519
- } catch (e) {
2520
- throw e instanceof le || ka("verifyAttestations failed (non-verification error):", e), e;
2521
- }
2522
- ka("direct EAS publish complete"), la(e);
2523
- try {
2524
- let { clearHtmlEmbeddedImageCoPublishRows: e } = await import("@seedprotocol/sdk"), t = /* @__PURE__ */ new Set([c.seedLocalId]);
2525
- for (let e of _) e?.localId && t.add(e.localId);
2526
- for (let n of t) await e(n);
2527
- } catch {}
2528
- let { collectPublishedBatch: ne } = await import("./collectBatchUids-CnIe9jUB.js").then((e) => e.t), re = w;
2529
- return {
2530
- easPayload: m,
2531
- publishedBatch: re?.seedUid ? ne({
2532
- seedUid: String(re.seedUid),
2533
- versionUid: re.versionUid ? String(re.versionUid) : void 0,
2534
- extraUids: S
2535
- }) : null
2536
- };
2537
- }), La = async (e) => {
2538
- let t;
2539
- try {
2540
- t = await N.find({ seedLocalId: e });
2541
- } catch {}
2542
- return t || new Promise((t) => {
2543
- let n = setInterval(() => {
2544
- N.find({ seedLocalId: e }).then((e) => {
2545
- e && (clearInterval(n), t(e));
2546
- }).catch(() => {});
2547
- }, 200);
2548
- });
2549
- };
2550
- async function Ra(e) {
2551
- let t = typeof e.getPublishUploads == "function" ? e : await La(e.seedLocalId);
2552
- return await qe(t);
2553
- }
2554
- //#endregion
2555
- //#region src/services/publish/actors/checking.ts
2556
- var X = /* @__PURE__ */ new Set();
2557
- async function za(e) {
2558
- let t = D();
2559
- return t.useDirectEas ? "directEas" : t.useModularExecutor || await oe(e) ? "multiPublish" : "directEas";
2560
- }
2561
- var Ba = Ht(({ sendBack: e, input: { context: t } }) => {
2562
- let { item: n, account: r, wallet: i, publishMode: a, address: o } = t;
2563
- return (async () => {
2564
- if (!await Ge(n)) e({ type: "notOwner" });
2565
- else if (X.has(n.seedLocalId)) e({ type: "redundantPublishProcess" });
2566
- else {
2567
- X.add(n.seedLocalId);
2568
- try {
2569
- await Fe(), await ce();
2570
- let t = await He(n, { publishMode: a ?? "patch" });
2571
- if (t.length > 0) {
2572
- X.delete(n.seedLocalId), e({
2573
- type: "validationFailed",
2574
- errors: new Me(t).validationErrors
2575
- });
2576
- return;
2577
- }
2578
- let s = i ?? r;
2579
- s && await Tn(n, s, { managedAddress: typeof o == "string" ? o : void 0 });
2580
- let c = await it(n, [], { publishMode: a ?? "patch" });
2581
- if (!c.isValid) {
2582
- X.delete(n.seedLocalId), e({
2583
- type: "validationFailed",
2584
- errors: c.errors
2585
- });
2586
- return;
2587
- }
2588
- if (!o || typeof o != "string" || !o.trim()) {
2589
- X.delete(n.seedLocalId), e({
2590
- type: "validationFailed",
2591
- errors: [{ message: "No publisher address for publish. Connect a wallet and try again." }]
2592
- });
2593
- return;
2594
- }
2595
- let l;
2596
- try {
2597
- l = await za(o.trim());
2598
- } catch (t) {
2599
- X.delete(n.seedLocalId), e({
2600
- type: "checkingFailed",
2601
- error: Error(`Could not verify whether the publisher is a deployed contract on ${O()}. Check your RPC connection and retry.`, { cause: t })
2602
- });
2603
- return;
2604
- }
2605
- let u = await Ra(n), d = D().useArweaveBundler, f = { attestationStrategy: l };
2606
- e(u ? d ? {
2607
- type: "validPublishProcessBundler",
2608
- ...f
2609
- } : {
2610
- type: "validPublishProcess",
2611
- ...f
2612
- } : {
2613
- type: "skipArweave",
2614
- ...f
2615
- });
2616
- } catch (t) {
2617
- X.delete(n.seedLocalId), console.error("[checking] failed", t), e({
2618
- type: "checkingFailed",
2619
- error: t instanceof Error ? t : Error(String(t))
2620
- });
2621
- }
2622
- }
2623
- })().catch((t) => {
2624
- X.delete(n.seedLocalId), console.error("[checking] unhandled rejection", t), e({
2625
- type: "checkingFailed",
2626
- error: t instanceof Error ? t : Error(String(t))
2627
- });
2628
- }), () => {
2629
- X.delete(n.seedLocalId);
2630
- };
2631
- }), { SUCCESS: Va, FAILURE: Z } = me;
2632
- function Ha(e) {
2633
- let t = e.attestationStrategy;
2634
- return t === "directEas" || t !== "multiPublish" && D().useDirectEas;
2635
- }
2636
- function Ua(e) {
2637
- let t = e.attestationStrategy;
2638
- return t === "multiPublish" || t !== "directEas" && !D().useDirectEas;
2639
- }
2640
- function Q(e) {
2641
- let t = e;
2642
- return t.error ?? t.data;
2643
- }
2644
- var Wa = Ut({
2645
- types: {
2646
- context: {},
2647
- input: {}
2648
- },
2649
- actors: {
2650
- createArweaveTransactions: An,
2651
- createArweaveTransactionsPhase2: jn,
2652
- createArweaveDataItems: yr,
2653
- createArweaveDataItemsPhase2: xr,
2654
- sendReimbursementRequest: Or,
2655
- pollForConfirmation: kr,
2656
- uploadData: jr,
2657
- uploadViaBundler: Ir,
2658
- createAttestations: xa,
2659
- createAttestationsDirectToEas: Ia,
2660
- checking: Ba,
2661
- preparingHtmlEmbedded: Mn,
2662
- rewritingHtmlEmbedded: Pn
2663
- },
2664
- actions: {
2665
- handleError: ({ event: e }) => {
2666
- let t = Q(e);
2667
- t == null ? console.error("Unknown error (full event):", e) : console.error(t);
2668
- },
2669
- assignErrorCreatingArweaveTransactions: I({
2670
- error: ({ event: e }) => Q(e),
2671
- errorStep: () => "creatingArweaveTransactions"
2672
- }),
2673
- assignErrorCreatingArweaveDataItems: I({
2674
- error: ({ event: e }) => Q(e),
2675
- errorStep: () => "creatingArweaveDataItems"
2676
- }),
2677
- assignErrorSendingReimbursementRequest: I({
2678
- error: ({ event: e }) => Q(e),
2679
- errorStep: () => "sendingReimbursementRequest"
2680
- }),
2681
- assignErrorPollingForConfirmation: I({
2682
- error: ({ event: e }) => Q(e),
2683
- errorStep: () => "pollingForConfirmation"
2684
- }),
2685
- assignErrorUploadingData: I({
2686
- error: ({ event: e }) => Q(e),
2687
- errorStep: () => "uploadingData"
2688
- }),
2689
- assignErrorPreparingHtmlEmbedded: I({
2690
- error: ({ event: e }) => Q(e),
2691
- errorStep: () => "preparingHtmlEmbedded"
2692
- }),
2693
- assignErrorRewritingHtmlEmbedded: I({
2694
- error: ({ event: e }) => Q(e),
2695
- errorStep: () => "rewritingHtmlEmbedded"
2696
- }),
2697
- assignErrorCreatingArweaveTransactionsPhase2: I({
2698
- error: ({ event: e }) => Q(e),
2699
- errorStep: () => "creatingArweaveTransactionsPhase2"
2700
- }),
2701
- assignErrorUploadingDataPhase2: I({
2702
- error: ({ event: e }) => Q(e),
2703
- errorStep: () => "uploadingDataPhase2"
2704
- }),
2705
- assignErrorUploadingViaBundler: I({
2706
- error: ({ event: e }) => Q(e),
2707
- errorStep: () => "uploadingViaBundler"
2708
- }),
2709
- assignErrorCreatingArweaveDataItemsPhase2: I({
2710
- error: ({ event: e }) => Q(e),
2711
- errorStep: () => "creatingArweaveDataItemsPhase2"
2712
- }),
2713
- assignErrorUploadingViaBundlerPhase2: I({
2714
- error: ({ event: e }) => Q(e),
2715
- errorStep: () => "uploadingViaBundlerPhase2"
2716
- }),
2717
- assignErrorCreatingAttestations: I({
2718
- error: ({ event: e }) => Q(e),
2719
- errorStep: () => "creatingAttestations"
2720
- }),
2721
- assignErrorCreatingAttestationsDirectToEas: I({
2722
- error: ({ event: e }) => Q(e),
2723
- errorStep: () => "creatingAttestationsDirectToEas"
2724
- }),
2725
- assignAccountFromRetry: I({
2726
- wallet: ({ event: e }) => {
2727
- let t = e;
2728
- return t.wallet ?? t.account;
2729
- },
2730
- account: ({ event: e }) => {
2731
- let t = e;
2732
- return t.wallet ?? t.account;
2733
- }
2734
- }),
2735
- assignErrorNotOwner: I({
2736
- error: () => /* @__PURE__ */ Error("Item is read-only: you do not own this item. Only the publisher can publish."),
2737
- errorStep: () => "checking"
2738
- }),
2739
- assignErrorValidationFailed: I({
2740
- error: ({ event: e }) => {
2741
- let t = e.errors ?? [], n = t.length > 0 ? `Validation failed (${t.length} error${t.length === 1 ? "" : "s"}):\n${t.map((e) => e.message).join("\n")}` : "Validation failed", r = Error(n);
2742
- return r.validationErrors = t, r;
2743
- },
2744
- errorStep: () => "checking"
2745
- }),
2746
- assignErrorCheckingFailed: I({
2747
- error: ({ event: e }) => {
2748
- let t = e.error;
2749
- return t instanceof Error ? t : Error(String(t ?? "Publish check failed"));
2750
- },
2751
- errorStep: () => "checking"
2752
- })
2753
- }
2754
- }).createMachine({
2755
- id: "publish",
2756
- initial: "checking",
2757
- context: ({ input: e }) => e,
2758
- states: {
2759
- checking: {
2760
- on: {
2761
- notOwner: {
2762
- target: Z,
2763
- actions: ["assignErrorNotOwner", "handleError"]
2764
- },
2765
- validationFailed: {
2766
- target: Z,
2767
- actions: ["assignErrorValidationFailed", "handleError"]
2768
- },
2769
- redundantPublishProcess: { target: "stopping" },
2770
- checkingFailed: {
2771
- target: Z,
2772
- actions: ["assignErrorCheckingFailed", "handleError"]
2773
- },
2774
- validPublishProcess: {
2775
- target: "preparingHtmlEmbedded",
2776
- actions: I({ attestationStrategy: ({ event: e }) => e.attestationStrategy })
2777
- },
2778
- validPublishProcessBundler: {
2779
- target: "preparingHtmlEmbedded",
2780
- actions: I({ attestationStrategy: ({ event: e }) => e.attestationStrategy })
2781
- },
2782
- skipArweave: [{
2783
- guard: ({ context: e }) => Ha(e),
2784
- target: "creatingAttestationsDirectToEas",
2785
- actions: I({
2786
- arweaveTransactions: () => [],
2787
- publishUploads: () => [],
2788
- attestationStrategy: ({ event: e }) => e.attestationStrategy
2789
- })
2790
- }, {
2791
- guard: ({ context: e }) => Ua(e),
2792
- target: "creatingAttestations",
2793
- actions: I({
2794
- arweaveTransactions: () => [],
2795
- publishUploads: () => [],
2796
- attestationStrategy: ({ event: e }) => e.attestationStrategy
2797
- })
2798
- }]
2799
- },
2800
- invoke: {
2801
- src: "checking",
2802
- input: ({ context: e }) => ({ context: e })
2803
- }
2804
- },
2805
- preparingHtmlEmbedded: { invoke: {
2806
- src: "preparingHtmlEmbedded",
2807
- input: ({ context: e }) => ({ context: e }),
2808
- onDone: [{
2809
- guard: () => D().useArweaveBundler,
2810
- target: "creatingArweaveDataItems",
2811
- actions: I({ htmlEmbeddedDeferredHtmlSeedLocalIds: ({ event: e }) => e.output.deferredHtmlSeedLocalIds })
2812
- }, {
2813
- target: "creatingArweaveTransactions",
2814
- actions: I({ htmlEmbeddedDeferredHtmlSeedLocalIds: ({ event: e }) => e.output.deferredHtmlSeedLocalIds })
2815
- }],
2816
- onError: {
2817
- target: Z,
2818
- actions: ["assignErrorPreparingHtmlEmbedded", "handleError"]
2819
- }
2820
- } },
2821
- creatingArweaveTransactions: { invoke: {
2822
- src: "createArweaveTransactions",
2823
- input: ({ context: e, event: t }) => ({
2824
- context: e,
2825
- event: t
2826
- }),
2827
- onDone: {
2828
- target: "sendingReimbursementRequest",
2829
- actions: I({
2830
- arweaveTransactions: ({ event: e }) => e.output.arweaveTransactions,
2831
- publishUploads: ({ event: e }) => e.output.publishUploads
2832
- })
2833
- },
2834
- onError: {
2835
- target: "failure",
2836
- actions: ["assignErrorCreatingArweaveTransactions", "handleError"]
2837
- }
2838
- } },
2839
- creatingArweaveDataItems: { invoke: {
2840
- src: "createArweaveDataItems",
2841
- input: ({ context: e, event: t }) => ({
2842
- context: e,
2843
- event: t
2844
- }),
2845
- onDone: {
2846
- target: "uploadingViaBundler",
2847
- actions: I({
2848
- arweaveTransactions: ({ event: e }) => e.output.arweaveTransactions,
2849
- publishUploads: ({ event: e }) => e.output.publishUploads,
2850
- signedDataItems: ({ event: e }) => e.output.signedDataItems
2851
- })
2852
- },
2853
- onError: {
2854
- target: "failure",
2855
- actions: ["assignErrorCreatingArweaveDataItems", "handleError"]
2856
- }
2857
- } },
2858
- sendingReimbursementRequest: { invoke: {
2859
- src: "sendReimbursementRequest",
2860
- input: ({ context: e, event: t }) => ({
2861
- context: e,
2862
- event: t
2863
- }),
2864
- onDone: {
2865
- target: "pollingForConfirmation",
2866
- actions: I({
2867
- requestResponse: ({ event: e }) => e.output,
2868
- reimbursementTransactionId: ({ event: e }) => e.output.transactionId
2869
- })
2870
- },
2871
- onError: {
2872
- target: "failure",
2873
- actions: ["assignErrorSendingReimbursementRequest", "handleError"]
2874
- }
2875
- } },
2876
- pollingForConfirmation: { invoke: {
2877
- src: "pollForConfirmation",
2878
- input: ({ context: e, event: t }) => ({
2879
- context: e,
2880
- event: t
2881
- }),
2882
- onDone: {
2883
- target: "uploadingData",
2884
- actions: I({ reimbursementConfirmed: !0 })
2885
- },
2886
- onError: {
2887
- target: "failure",
2888
- actions: ["assignErrorPollingForConfirmation", "handleError"]
2889
- }
2890
- } },
2891
- uploadingViaBundler: {
2892
- on: {
2893
- uploadComplete: [
2894
- {
2895
- guard: ({ context: e }) => Ha(e),
2896
- target: "creatingAttestationsDirectToEas",
2897
- actions: I({
2898
- completionPercentage: 100,
2899
- signedDataItems: () => void 0,
2900
- arweaveUploadData: () => void 0
2901
- })
2902
- },
2903
- {
2904
- guard: (e) => (e.context?.htmlEmbeddedDeferredHtmlSeedLocalIds?.length ?? 0) > 0,
2905
- target: "rewritingHtmlEmbedded",
2906
- actions: I({
2907
- htmlEmbeddedPhase1PublishUploads: ({ context: e }) => e.publishUploads ?? [],
2908
- htmlEmbeddedPhase1ArweaveTransactions: ({ context: e }) => e.arweaveTransactions ?? [],
2909
- signedDataItems: () => void 0,
2910
- arweaveUploadData: () => void 0
2911
- })
2912
- },
2913
- {
2914
- guard: ({ context: e }) => Ua(e),
2915
- target: "creatingAttestations",
2916
- actions: I({
2917
- completionPercentage: 100,
2918
- signedDataItems: () => void 0,
2919
- arweaveUploadData: () => void 0
2920
- })
2921
- }
2922
- ],
2923
- uploadError: {
2924
- target: "failure",
2925
- actions: ["assignErrorUploadingViaBundler", "handleError"]
2926
- }
2927
- },
2928
- invoke: {
2929
- src: "uploadViaBundler",
2930
- input: ({ context: e }) => ({ context: e })
2931
- }
2932
- },
2933
- creatingArweaveDataItemsPhase2: { invoke: {
2934
- src: "createArweaveDataItemsPhase2",
2935
- input: ({ context: e, event: t }) => ({
2936
- context: e,
2937
- event: t
2938
- }),
2939
- onDone: {
2940
- target: "uploadingViaBundlerPhase2",
2941
- actions: I({
2942
- arweaveTransactions: ({ event: e }) => e.output.arweaveTransactions,
2943
- publishUploads: ({ event: e }) => e.output.publishUploads,
2944
- signedDataItems: ({ event: e }) => e.output.signedDataItems,
2945
- uploaderState: () => void 0,
2946
- currentTransactionIndex: () => void 0
2947
- })
2948
- },
2949
- onError: {
2950
- target: Z,
2951
- actions: ["assignErrorCreatingArweaveDataItemsPhase2", "handleError"]
2952
- }
2953
- } },
2954
- uploadingViaBundlerPhase2: {
2955
- on: {
2956
- uploadComplete: [{
2957
- guard: ({ context: e }) => Ha(e),
2958
- target: "creatingAttestationsDirectToEas",
2959
- actions: I({
2960
- completionPercentage: 100,
2961
- signedDataItems: () => void 0,
2962
- arweaveUploadData: () => void 0
2963
- })
2964
- }, {
2965
- guard: ({ context: e }) => Ua(e),
2966
- target: "creatingAttestations",
2967
- actions: I({
2968
- completionPercentage: 100,
2969
- signedDataItems: () => void 0,
2970
- arweaveUploadData: () => void 0,
2971
- publishUploads: ({ context: e }) => [...e.htmlEmbeddedPhase1PublishUploads ?? [], ...e.publishUploads ?? []],
2972
- arweaveTransactions: ({ context: e }) => [...e.htmlEmbeddedPhase1ArweaveTransactions ?? [], ...e.arweaveTransactions ?? []]
2973
- })
2974
- }],
2975
- uploadError: {
2976
- target: Z,
2977
- actions: ["assignErrorUploadingViaBundlerPhase2", "handleError"]
2978
- }
2979
- },
2980
- invoke: {
2981
- src: "uploadViaBundler",
2982
- input: ({ context: e }) => ({ context: e })
2983
- }
2984
- },
2985
- uploadingData: {
2986
- on: {
2987
- updatePercentage: { actions: I({
2988
- completionPercentage: ({ event: e }) => e.completionPercentage,
2989
- uploaderState: ({ event: e }) => e.uploaderState,
2990
- currentTransactionIndex: ({ event: e }) => e.currentTransactionIndex
2991
- }) },
2992
- uploadComplete: [
2993
- {
2994
- guard: ({ context: e }) => Ha(e),
2995
- target: "creatingAttestationsDirectToEas",
2996
- actions: I({ completionPercentage: 100 })
2997
- },
2998
- {
2999
- guard: (e) => (e.context?.htmlEmbeddedDeferredHtmlSeedLocalIds?.length ?? 0) > 0,
3000
- target: "rewritingHtmlEmbedded",
3001
- actions: I({
3002
- htmlEmbeddedPhase1PublishUploads: ({ context: e }) => e.publishUploads ?? [],
3003
- htmlEmbeddedPhase1ArweaveTransactions: ({ context: e }) => e.arweaveTransactions ?? []
3004
- })
3005
- },
3006
- {
3007
- guard: ({ context: e }) => Ua(e),
3008
- target: "creatingAttestations",
3009
- actions: I({ completionPercentage: 100 })
3010
- }
3011
- ],
3012
- uploadError: {
3013
- target: "failure",
3014
- actions: ["assignErrorUploadingData", "handleError"]
3015
- }
3016
- },
3017
- invoke: {
3018
- src: "uploadData",
3019
- input: ({ context: e }) => ({ context: e })
3020
- }
3021
- },
3022
- rewritingHtmlEmbedded: { invoke: {
3023
- src: "rewritingHtmlEmbedded",
3024
- input: ({ context: e }) => ({ context: e }),
3025
- onDone: [{
3026
- guard: () => !D().useArweaveBundler,
3027
- target: "creatingArweaveTransactionsPhase2"
3028
- }, {
3029
- guard: () => D().useArweaveBundler,
3030
- target: "creatingArweaveDataItemsPhase2"
3031
- }],
3032
- onError: {
3033
- target: Z,
3034
- actions: ["assignErrorRewritingHtmlEmbedded", "handleError"]
3035
- }
3036
- } },
3037
- creatingArweaveTransactionsPhase2: { invoke: {
3038
- src: "createArweaveTransactionsPhase2",
3039
- input: ({ context: e, event: t }) => ({
3040
- context: e,
3041
- event: t
3042
- }),
3043
- onDone: {
3044
- target: "uploadingDataPhase2",
3045
- actions: I({
3046
- arweaveTransactions: ({ event: e }) => e.output.arweaveTransactions,
3047
- publishUploads: ({ event: e }) => e.output.publishUploads,
3048
- uploaderState: () => void 0,
3049
- currentTransactionIndex: () => void 0
3050
- })
3051
- },
3052
- onError: {
3053
- target: Z,
3054
- actions: ["assignErrorCreatingArweaveTransactionsPhase2", "handleError"]
3055
- }
3056
- } },
3057
- uploadingDataPhase2: {
3058
- on: {
3059
- updatePercentage: { actions: I({
3060
- completionPercentage: ({ event: e }) => e.completionPercentage,
3061
- uploaderState: ({ event: e }) => e.uploaderState,
3062
- currentTransactionIndex: ({ event: e }) => e.currentTransactionIndex
3063
- }) },
3064
- uploadComplete: [{
3065
- guard: ({ context: e }) => Ha(e),
3066
- target: "creatingAttestationsDirectToEas",
3067
- actions: I({ completionPercentage: 100 })
3068
- }, {
3069
- guard: ({ context: e }) => Ua(e),
3070
- target: "creatingAttestations",
3071
- actions: I({
3072
- completionPercentage: 100,
3073
- publishUploads: ({ context: e }) => [...e.htmlEmbeddedPhase1PublishUploads ?? [], ...e.publishUploads ?? []],
3074
- arweaveTransactions: ({ context: e }) => [...e.htmlEmbeddedPhase1ArweaveTransactions ?? [], ...e.arweaveTransactions ?? []]
3075
- })
3076
- }],
3077
- uploadError: {
3078
- target: Z,
3079
- actions: ["assignErrorUploadingDataPhase2", "handleError"]
3080
- }
3081
- },
3082
- invoke: {
3083
- src: "uploadData",
3084
- input: ({ context: e }) => ({ context: e })
3085
- }
3086
- },
3087
- creatingAttestations: { invoke: {
3088
- src: "createAttestations",
3089
- input: ({ context: e, event: t }) => ({
3090
- context: e,
3091
- event: t
3092
- }),
3093
- onDone: {
3094
- target: Va,
3095
- actions: I({
3096
- easPayload: ({ event: e }) => e.output?.easPayload,
3097
- publishedBatch: ({ event: e }) => e.output?.publishedBatch ?? null
3098
- })
3099
- },
3100
- onError: {
3101
- target: "attestationFailureRecoverable",
3102
- actions: ["assignErrorCreatingAttestations", "handleError"]
3103
- }
3104
- } },
3105
- attestationFailureRecoverable: { on: { retry: {
3106
- target: "creatingAttestations",
3107
- actions: ["assignAccountFromRetry"]
3108
- } } },
3109
- creatingAttestationsDirectToEas: { invoke: {
3110
- src: "createAttestationsDirectToEas",
3111
- input: ({ context: e, event: t }) => ({
3112
- context: e,
3113
- event: t
3114
- }),
3115
- onDone: {
3116
- target: Va,
3117
- actions: I({
3118
- easPayload: ({ event: e }) => e.output?.easPayload,
3119
- publishedBatch: ({ event: e }) => e.output?.publishedBatch ?? null
3120
- })
3121
- },
3122
- onError: {
3123
- target: "attestationFailureRecoverableDirectToEas",
3124
- actions: ["assignErrorCreatingAttestationsDirectToEas", "handleError"]
3125
- }
3126
- } },
3127
- attestationFailureRecoverableDirectToEas: { on: { retry: {
3128
- target: "creatingAttestationsDirectToEas",
3129
- actions: ["assignAccountFromRetry"]
3130
- } } },
3131
- stopping: {
3132
- entry: ({ context: e }) => {
3133
- console.log(`Actor for ${e.item?.seedLocalId} stopped`);
3134
- },
3135
- type: "final"
3136
- },
3137
- [Va]: {
3138
- entry: ({ context: e }) => {
3139
- let t = e.publishedBatch, n = e.onPublished;
3140
- if (!n || !t?.seedUid) return;
3141
- let r = e.item?.seedLocalId;
3142
- r && Promise.resolve(n({
3143
- seedLocalId: r,
3144
- seedUid: t.seedUid,
3145
- versionUid: t.versionUid,
3146
- attestationUids: t.attestationUids
3147
- })).catch((e) => {
3148
- console.warn("[publish] onPublished callback failed:", e);
3149
- });
3150
- },
3151
- type: "final"
3152
- },
3153
- [Z]: {
3154
- entry: ({ context: e }) => {},
3155
- type: "final"
3156
- }
3157
- }
3158
- }), Ga = I(({ context: e, event: t }) => {
3159
- let n = t, r = n.publishProcesses ?? /* @__PURE__ */ new Map(), i = n.subscriptions ?? /* @__PURE__ */ new Map();
3160
- return {
3161
- publishProcesses: new Map(r),
3162
- subscriptions: new Map(i)
3163
- };
3164
- }), Ka = null;
3165
- function qa(e) {
3166
- Ka = e;
3167
- }
3168
- function Ja() {
3169
- return Ka;
3170
- }
3171
- //#endregion
3172
- //#region src/services/publishManager/actors/subscribe.ts
3173
- var Ya = R("seedProtocol:services:PublishManager:actors:subscribe");
3174
- function Xa(e) {
3175
- let t = e.value;
3176
- return typeof t == "string" ? t : t && typeof t == "object" ? Object.keys(t)[0] ?? "" : "";
3177
- }
3178
- function Za(e) {
3179
- return a.includes(e);
3180
- }
3181
- var Qa = Ht(({ receive: e, input: { publishProcess: n, seedLocalId: r } }) => {
3182
- let i = Ja(), a = null, o = () => {
3183
- a != null && (clearInterval(a), a = null);
3184
- }, s = (e) => {
3185
- let s = Xa(e);
3186
- Za(s) && a == null && i ? a = setInterval(() => {
3187
- try {
3188
- let e = n.getSnapshot();
3189
- if (e.status === "done" || !Za(Xa(e))) {
3190
- o();
3191
- return;
3192
- }
3193
- } catch {
3194
- return;
3195
- }
3196
- i?.savePublish(r, n);
3197
- }, t) : Za(s) || o();
3198
- }, c = n.subscribe(async (e) => {
3199
- Ya("Publish state:", e.value), i && (e.status === "done" ? (o(), i.savePublish(r, n, { triggerPublishDone: !0 })) : (i.savePublish(r, n), s(e)));
3200
- });
3201
- e(({ type: e }) => {
3202
- e === "UNSUBSCRIBE" && (Ya("Received UNSUBSCRIBE event"), o(), c.unsubscribe(), i?.removeSubscription(r));
3203
- });
3204
- }), $a = /* @__PURE__ */ new Map(), eo = 1;
3205
- function to(e) {
3206
- let t = eo++;
3207
- return $a.set(t, e), t;
3208
- }
3209
- function no(e, t) {
3210
- if (e == null) return;
3211
- let n = $a.get(e);
3212
- n && ($a.delete(e), n(t));
3213
- }
3214
- //#endregion
3215
- //#region src/services/publishManager/actions/createPublish.ts
3216
- function ro(e) {
3217
- if (e) {
3218
- if (i(e)) return e;
3219
- if (m(e)) {
3220
- let t = pe();
3221
- if (t && t.signer.address.toLowerCase() === e.address.toLowerCase()) return t;
3222
- throw Error("@seedprotocol/publish: createPublish requires a PublishWallet (signer + txSender). Use fromEthersWallet, fromEip1193Provider, or fromThirdwebAccount.");
3223
- }
3224
- throw Error("@seedprotocol/publish: createPublish account must be a PublishWallet. Thirdweb Account must be wrapped with fromThirdwebAccount from @seedprotocol/publish/thirdweb.");
3225
- }
3226
- }
3227
- function io(e) {
3228
- if (e) {
3229
- if (e instanceof F.Wallet) return e;
3230
- if (i(e)) return e.signer;
3231
- if (m(e)) return e;
3232
- }
3233
- }
3234
- var ao = Vt(({ event: e, enqueue: t }) => {
3235
- let { item: n, address: r, account: i, options: a, createToken: o } = e;
3236
- r != null && typeof r == "string" && r.trim().length > 0 ? (t.assign(({ context: e, spawn: t }) => {
3237
- let { publishProcesses: s } = e;
3238
- if (s && s.has(n.seedLocalId)) return console.warn(`Publish process with seedLocalId "${n.seedLocalId}" already exists.`), no(o, void 0), e;
3239
- let c = typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : `run_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`, l = D(), u = [...l.arweaveUploadTags ?? [], ...a?.arweaveUploadTags ?? []], d = ro(i) ?? pe() ?? void 0, f = t(Wa, { input: {
3240
- item: n,
3241
- address: r,
3242
- wallet: d,
3243
- account: d,
3244
- modelName: n.modelName,
3245
- schemaId: n.schemaUid,
3246
- signDataItems: a?.signDataItems,
3247
- dataItemSigner: io(a?.dataItemSigner),
3248
- signArweaveTransactions: a?.signArweaveTransactions,
3249
- arweaveJwk: a?.arweaveJwk,
3250
- publishMode: a?.publishMode ?? "patch",
3251
- publishRunId: c,
3252
- arweaveUploadTags: u.length ? u : void 0,
3253
- htmlEmbeddedDataUriPolicy: a?.htmlEmbeddedDataUriPolicy ?? l.htmlEmbeddedDataUriPolicy ?? "materialize",
3254
- onPublished: a?.onPublished ?? l.onPublished
3255
- } });
3256
- s.set(n.seedLocalId, f);
3257
- let p = new Map(e.settledPublishes);
3258
- return p.delete(n.seedLocalId), no(o, f), {
3259
- ...e,
3260
- publishProcesses: s,
3261
- settledPublishes: p
3262
- };
3263
- }), t.assign(({ context: e, spawn: t }) => {
3264
- let { subscriptions: r, publishProcesses: i } = e, a = i.get(n.seedLocalId);
3265
- if (!a) return console.warn(`Publish process with seedLocalId "${n.seedLocalId}" does not exist.`), e;
3266
- if (r.has(n.seedLocalId)) return console.warn(`Subscription with seedLocalId "${n.seedLocalId}" already exists.`), e;
3267
- let o = t(Qa, { input: {
3268
- publishProcess: a,
3269
- seedLocalId: n.seedLocalId
3270
- } });
3271
- return r.set(n.seedLocalId, o), {
3272
- ...e,
3273
- subscriptions: new Map(r)
3274
- };
3275
- })) : (console.warn("[createPublish] No valid wallet address; skipping spawn."), no(o, void 0));
3276
- }), oo = ({ context: e, event: t }) => {
3277
- let { seedLocalId: n, account: r } = t, a = e.publishProcesses.get(n);
3278
- if (!a) {
3279
- console.warn(`Publish process with seedLocalId "${n}" does not exist.`);
3280
- return;
3281
- }
3282
- let o = r == null ? pe() ?? void 0 : i(r) ? r : void 0;
3283
- r != null && !o && console.warn("[retryAttestations] account must be a PublishWallet. Use fromThirdwebAccount / fromEip1193Provider / fromEthersWallet."), a.send({
3284
- type: "retry",
3285
- account: o,
3286
- wallet: o
3287
- });
3288
- };
3289
- //#endregion
3290
- //#region src/services/publishManager/actions/stopScopedOrStandaloneChild.ts
3291
- function so(e, t, n) {
3292
- t._parent === e ? n.stopChild(t) : t.stop();
3293
- }
3294
- //#endregion
3295
- //#region src/services/publishManager/actors/savePublish.ts
3296
- var co = R("seedProtocol:services:PublishManager:actors:savePublish"), lo = /* @__PURE__ */ new Map();
3297
- function uo(e, t) {
3298
- let n = (lo.get(e) ?? Promise.resolve()).then(t);
3299
- return lo.set(e, n.catch(() => {})), n;
3300
- }
3301
- function fo(e) {
3302
- return e === "completed" || e === "failed" || e === "interrupted";
3303
- }
3304
- function po(e) {
3305
- return e.status === "done" ? e.value === "success" ? "completed" : e.value === "failure" ? "failed" : "completed" : "in_progress";
3306
- }
3307
- var mo = 500, ho = 2e3, go = 100;
3308
- function _o(e) {
3309
- return JSON.stringify(e, (e, t) => typeof t == "bigint" ? t.toString() : t);
3310
- }
3311
- function vo(e) {
3312
- if (typeof e != "object" || !e) return;
3313
- let t = e, n = t.snapshot, r = (t.context ?? n?.context)?.publishRunId;
3314
- return typeof r == "string" && r.length > 0 ? r : void 0;
3315
- }
3316
- function yo(e) {
3317
- if (e instanceof Error) return e.message;
3318
- if (typeof e == "object") {
3319
- let t = e.message;
3320
- return typeof t == "string" ? t : void 0;
3321
- }
3322
- return String(e);
3323
- }
3324
- function bo(e) {
3325
- if (typeof e != "object" || !e) return;
3326
- let t = e.code;
3327
- return typeof t == "string" && t.length > 0 ? t.slice(0, go) : void 0;
3328
- }
3329
- function xo(e, t) {
3330
- if (!e?.error || t !== "failed" && t !== "in_progress") return {};
3331
- let n = e.error, r = yo(n)?.slice(0, mo), i = e.errorStep, a = bo(n), o;
3332
- if (n instanceof Error && n.stack) o = n.stack.slice(0, ho);
3333
- else if (typeof n == "object" && n) try {
3334
- o = JSON.stringify(n).slice(0, ho);
3335
- } catch {
3336
- o = String(n).slice(0, ho);
3337
- }
3338
- else n != null && (o = String(n).slice(0, ho));
3339
- return {
3340
- ...r === void 0 ? {} : { errorMessage: r },
3341
- errorStep: i,
3342
- ...n instanceof Error || r !== void 0 ? { errorDetails: o } : {},
3343
- errorCode: a ?? null
3344
- };
3345
- }
3346
- function So(e) {
3347
- return uo(e, async () => {
3348
- let t = ke.getAppDb();
3349
- if (!t) {
3350
- co("markInProgressPublishInterrupted: DB not ready, skipping");
3351
- return;
3352
- }
3353
- let n = await t.select().from(P).where(Wt(z(P.seedLocalId, e), z(P.status, "in_progress"))).orderBy(Gt(P.updatedAt)).limit(1);
3354
- if (n.length === 0) return;
3355
- let r = Date.now();
3356
- await t.update(P).set({
3357
- status: "interrupted",
3358
- completedAt: r,
3359
- updatedAt: r,
3360
- errorMessage: null,
3361
- errorStep: null,
3362
- errorDetails: null,
3363
- errorCode: null
3364
- }).where(z(P.id, n[0].id));
3365
- });
3366
- }
3367
- var Co = Ht(({ sendBack: e, input: { persistedSnapshot: t, seedLocalId: n, triggerPublishDone: r } }) => {
3368
- co("savePublish seedLocalId", n);
3369
- let i = t;
3370
- uo(n, async () => {
3371
- let a = ke.getAppDb();
3372
- if (!a) {
3373
- co("savePublish: DB not ready, skipping"), e({
3374
- type: "SAVE_PUBLISH_DONE",
3375
- seedLocalId: n,
3376
- triggerPublishDone: r
3377
- });
3378
- return;
3379
- }
3380
- let o = await a.select().from(P).where(Wt(z(P.seedLocalId, n), z(P.status, "in_progress"))).orderBy(Gt(P.updatedAt)).limit(1), s = typeof t == "string" ? t : _o(t), c = po(i), l = Date.now(), u = xo(i.context, c);
3381
- if (o.length > 0) {
3382
- let e = o[0];
3383
- await a.update(P).set({
3384
- persistedSnapshot: s,
3385
- status: c,
3386
- updatedAt: l,
3387
- ...i.status === "done" && c !== "in_progress" ? { completedAt: l } : {},
3388
- ...u
3389
- }).where(z(P.id, e.id));
3390
- } else {
3391
- let e = vo(i);
3392
- if (e != null && c === "in_progress" && i.status !== "done") {
3393
- let t = (await a.select().from(P).where(z(P.seedLocalId, n)).orderBy(Gt(P.startedAt)).limit(1))[0];
3394
- if (t && fo(t.status)) try {
3395
- if (vo(JSON.parse(t.persistedSnapshot)) === e) {
3396
- co("savePublish: skip stale insert — same publishRunId as latest terminal row", n, e);
3397
- return;
3398
- }
3399
- } catch {}
3400
- }
3401
- let t = i.context?.item, r = i.context?.modelName ?? t?.modelName ?? "", o = i.context?.schemaId ?? t?.schemaId;
3402
- await a.insert(P).values({
3403
- seedLocalId: n,
3404
- modelName: r,
3405
- schemaId: o ?? null,
3406
- status: c,
3407
- startedAt: l,
3408
- persistedSnapshot: s,
3409
- createdAt: l,
3410
- updatedAt: l,
3411
- ...u
3412
- });
3413
- }
3414
- }).then(() => {
3415
- e({
3416
- type: "SAVE_PUBLISH_DONE",
3417
- seedLocalId: n,
3418
- triggerPublishDone: r
3419
- });
3420
- }).catch((t) => {
3421
- co("savePublish error", t), e({
3422
- type: "SAVE_PUBLISH_DONE",
3423
- seedLocalId: n,
3424
- triggerPublishDone: r
3425
- });
3426
- });
3427
- }), wo = R("seedProtocol:PublishManager:publishLocks"), To = () => typeof navigator < "u" ? navigator.locks : void 0, Eo = /* @__PURE__ */ new Map();
3428
- function Do(e) {
3429
- return `seed:publish:${e}`;
3430
- }
3431
- async function Oo(e) {
3432
- if (Eo.has(e)) return !0;
3433
- let t = To();
3434
- return !t || new Promise((n, r) => {
3435
- t.request(Do(e), {
3436
- mode: "exclusive",
3437
- ifAvailable: !0
3438
- }, (t) => {
3439
- if (!t) n(!1);
3440
- else return new Promise((t) => {
3441
- Eo.set(e, () => {
3442
- Eo.delete(e), t();
3443
- }), n(!0);
3444
- });
3445
- }).catch((t) => {
3446
- wo(`publish lock request for ${e} failed`, t), r(t);
3447
- });
3448
- });
3449
- }
3450
- function ko(e) {
3451
- Eo.get(e)?.();
3452
- }
3453
- function Ao() {
3454
- for (let e of [...Eo.values()]) e();
3455
- }
3456
- function jo(e) {
3457
- return Eo.has(e);
3458
- }
3459
- //#endregion
3460
- //#region src/services/publishManager/actions/stopPublish.ts
3461
- var Mo = Vt(({ context: e, event: t, enqueue: n, self: r }) => {
3462
- let { publishProcesses: i, subscriptions: a } = e, { seedLocalId: o } = t;
3463
- So(o).catch((e) => {
3464
- console.warn(`[stopPublish] Failed to mark publish_processes row interrupted for "${o}":`, e);
3465
- }), ko(o);
3466
- let s = i.get(o);
3467
- if (!s) {
3468
- console.warn(`Publish process with seedLocalId "${o}" does not exist.`);
3469
- return;
3470
- }
3471
- so(r, s, n);
3472
- let c = a.get(o);
3473
- c && so(r, c, n);
3474
- let l = new Map(i);
3475
- l.delete(o);
3476
- let u = new Map(a);
3477
- u.delete(o), n.assign({
3478
- publishProcesses: l,
3479
- subscriptions: u
3480
- });
3481
- }), No = R("seedProtocol:PublishManager:index"), Po = Vt(({ context: e, enqueue: t, self: n }) => {
3482
- No("Stopping all actors..."), e.publishProcesses.forEach((e) => {
3483
- so(n, e, t);
3484
- }), e.subscriptions.forEach((e) => {
3485
- so(n, e, t);
3486
- }), Ao(), t.assign({
3487
- publishProcesses: /* @__PURE__ */ new Map(),
3488
- subscriptions: /* @__PURE__ */ new Map()
3489
- });
3490
- }), Fo = Vt(({ context: e, event: t, enqueue: n }) => {
3491
- let { seedLocalId: r } = t, i = e.publishProcesses.get(r);
3492
- if (!i) {
3493
- console.warn(`Publish process with seedLocalId "${r}" does not exist.`);
3494
- return;
3495
- }
3496
- n.stopChild(i);
3497
- let a = e.subscriptions.get(r);
3498
- a && n.stopChild(a);
3499
- let o = new Map(e.publishProcesses);
3500
- o.delete(r);
3501
- let s = new Map(e.subscriptions);
3502
- s.delete(r), n.assign({
3503
- publishProcesses: o,
3504
- subscriptions: s
3505
- });
3506
- }), Io = I(({ context: e, event: t }) => {
3507
- let { subscriptions: n } = e, { seedLocalId: r, newSubscription: i } = t;
3508
- return i && n.set(r, i), { subscriptions: new Map(n) };
3509
- }), Lo = ["signedDataItems", "arweaveUploadData"];
3510
- function Ro(e) {
3511
- if (typeof e != "object" || !e) return e;
3512
- let t = { ...e };
3513
- for (let e of Lo) delete t[e];
3514
- return t;
3515
- }
3516
- function zo(e) {
3517
- if (typeof e != "object" || !e) return e;
3518
- let t = e, n = { ...t };
3519
- t.context != null && typeof t.context == "object" && (n.context = Ro(t.context));
3520
- let r = t.snapshot;
3521
- if (typeof r == "object" && r) {
3522
- let e = r, t = { ...e };
3523
- e.context != null && typeof e.context == "object" && (t.context = Ro(e.context)), n.snapshot = t;
3524
- }
3525
- return n;
3526
- }
3527
- function Bo(e) {
3528
- try {
3529
- return zo(e.getPersistedSnapshot?.() ?? e.getSnapshot());
3530
- } catch {
3531
- let t = e.getSnapshot(), n = t.context;
3532
- if (!n?.item) return zo(t);
3533
- let r = n.item;
3534
- return zo({
3535
- ...t,
3536
- context: {
3537
- ...n,
3538
- item: {
3539
- seedLocalId: r.seedLocalId,
3540
- modelName: r.modelName,
3541
- schemaId: r.schemaId
3542
- }
3543
- }
3544
- });
3545
- }
3546
- }
3547
- var Vo = I(({ context: e, event: t, spawn: n }) => {
3548
- let { publishProcesses: r } = e, { seedLocalId: i, publishProcess: a, triggerPublishDone: o } = t;
3549
- if (!a) return e;
3550
- let s = new Map(r);
3551
- s.set(i, a);
3552
- let c = Bo(a);
3553
- return n(Co, {
3554
- id: `savePublish_${i}_${Date.now()}`,
3555
- input: {
3556
- persistedSnapshot: c,
3557
- seedLocalId: i,
3558
- triggerPublishDone: o
3559
- }
3560
- }), { publishProcesses: s };
3561
- }), Ho = I(({ context: e, event: t }) => {
3562
- let { publishProcesses: n, subscriptions: r, settledPublishes: i } = e, a = t.seedLocalId;
3563
- ko(a);
3564
- let o = r.get(a);
3565
- o && o.send({ type: "UNSUBSCRIBE" });
3566
- let s = n.get(a), c = new Map(n);
3567
- c.delete(a);
3568
- let l = new Map(r);
3569
- l.delete(a);
3570
- let u = new Map(i);
3571
- return s && u.set(a, s), {
3572
- publishProcesses: c,
3573
- subscriptions: l,
3574
- settledPublishes: u
3575
- };
3576
- }), Uo = I(({ context: e, event: t }) => {
3577
- let { subscriptions: n } = e, r = t.seedLocalId, i = new Map(n);
3578
- return i.delete(r), { subscriptions: i };
3579
- }), Wo = 6e4, Go = 2e3;
3580
- function Ko(e, t) {
3581
- let n = typeof process < "u" ? process.env[e] : void 0;
3582
- if (n == null || n === "") return t;
3583
- let r = Number(n);
3584
- return Number.isFinite(r) && r >= 0 ? r : t;
3585
- }
3586
- async function qo(e, t) {
3587
- let n = Date.now() + e;
3588
- for (; Date.now() < n;) {
3589
- try {
3590
- if (ke.isAppDbReady() && ke.getAppDb()) return !0;
3591
- } catch {}
3592
- await new Promise((e) => setTimeout(e, t));
3593
- }
3594
- return !1;
3595
- }
3596
- function Jo(e) {
3597
- let t = e.value;
3598
- return typeof t == "string" ? t : t && typeof t == "object" ? Object.keys(t)[0] ?? "" : "";
3599
- }
3600
- function Yo(e) {
3601
- let t = Jo(e);
3602
- if (t === "pollingForConfirmation" && (!e.context?.reimbursementTransactionId || !e.context?.requestResponse)) return !1;
3603
- if (t === "uploadingData") {
3604
- let t = e.context?.arweaveTransactions, n = e.context?.publishUploads;
3605
- if (!Array.isArray(t) || t.length === 0 || !Array.isArray(n)) return !1;
3606
- }
3607
- return !0;
3608
- }
3609
- function Xo(e) {
3610
- return typeof e == "object" && !!e && "xstate$$type" in e && e.xstate$$type === 1 && typeof e.id == "string";
3611
- }
3612
- function Zo(e, t, n) {
3613
- e.context = e.context ?? {};
3614
- let r = e.context.item;
3615
- Xo(r) ? e.context.item = {
3616
- seedLocalId: t,
3617
- modelName: e.context.modelName ?? n.modelName ?? "",
3618
- schemaId: e.context.schemaId ?? n.schemaId ?? void 0
3619
- } : e.context.item = {
3620
- ...typeof r == "object" && r && !Array.isArray(r) ? r : {},
3621
- seedLocalId: t,
3622
- modelName: r?.modelName ?? e.context.modelName ?? n.modelName ?? "",
3623
- schemaId: r?.schemaId ?? e.context.schemaId ?? n.schemaId ?? void 0
3624
- };
3625
- }
3626
- var Qo = Ht(({ sendBack: e, input: { context: t } }) => {
3627
- let n = async () => {
3628
- let e = /* @__PURE__ */ new Map(), t = /* @__PURE__ */ new Map();
3629
- if (!await qo(Ko("SEED_PUBLISH_RESTORE_WAIT_MS", Wo), Ko("SEED_PUBLISH_RESTORE_POLL_MS", Go))) return {
3630
- newPublishProcesses: e,
3631
- newSubscriptions: t
3632
- };
3633
- let n = ke.getAppDb();
3634
- if (!n) return {
3635
- newPublishProcesses: e,
3636
- newSubscriptions: t
3637
- };
3638
- let r = await n.select().from(P).where(z(P.status, "in_progress")), i = /* @__PURE__ */ new Map(), a = [...r].sort((e, t) => (t.updatedAt ?? t.createdAt ?? 0) - (e.updatedAt ?? e.createdAt ?? 0));
3639
- for (let e of a) i.has(e.seedLocalId) || i.set(e.seedLocalId, e);
3640
- let o = Array.from(i.values());
3641
- for (let n of o) {
3642
- let r;
3643
- try {
3644
- r = JSON.parse(n.persistedSnapshot);
3645
- } catch {
3646
- continue;
3647
- }
3648
- if (r.status === "done") continue;
3649
- let i = r.context?.item?.seedLocalId ?? n.seedLocalId;
3650
- if (!i || !Yo(r) || !await Oo(i)) continue;
3651
- Zo(r, i, n);
3652
- let a = Bt(Wa, {
3653
- snapshot: r,
3654
- input: void 0
3655
- }), o = Bt(Qa, { input: {
3656
- publishProcess: a,
3657
- seedLocalId: i
3658
- } });
3659
- e.set(i, a), t.set(i, o), a.start(), o.start();
3660
- }
3661
- return {
3662
- newPublishProcesses: e,
3663
- newSubscriptions: t
3664
- };
3665
- }, r = () => ({
3666
- newPublishProcesses: /* @__PURE__ */ new Map(),
3667
- newSubscriptions: /* @__PURE__ */ new Map()
3668
- });
3669
- n().then((t) => {
3670
- let { newPublishProcesses: n, newSubscriptions: i } = t ?? r();
3671
- e({
3672
- type: "RESTORE_FROM_DB_DONE",
3673
- publishProcesses: n,
3674
- subscriptions: i
3675
- });
3676
- }).catch(() => {
3677
- let { newPublishProcesses: t, newSubscriptions: n } = r();
3678
- e({
3679
- type: "RESTORE_FROM_DB_DONE",
3680
- publishProcesses: t,
3681
- subscriptions: n
3682
- });
3683
- });
3684
- }), $o = I(({ context: e, event: t }) => ({ pendingCreates: [...e.pendingCreates ?? [], t] })), es = Vt(({ context: e, enqueue: t }) => {
3685
- let n = e.pendingCreates ?? [];
3686
- if (n.length !== 0) {
3687
- t.assign({ pendingCreates: [] });
3688
- for (let e of n) t.raise(e);
3689
- }
3690
- }), ts = R("seedProtocol:PublishManager:index"), ns = Ut({
3691
- types: {
3692
- context: {},
3693
- input: {},
3694
- events: {}
3695
- },
3696
- actors: { restoreFromDb: Qo },
3697
- actions: {
3698
- assignRestoreFromDb: Ga,
3699
- createPublish: ao,
3700
- queueCreatePublish: $o,
3701
- drainPendingCreates: es,
3702
- addSubscription: Io,
3703
- requestSavePublish: Vo,
3704
- publishDone: Ho,
3705
- removeSubscription: Uo,
3706
- retryAttestations: oo,
3707
- stopPublish: Mo,
3708
- stopAll: Po,
3709
- query: Fo
3710
- }
3711
- }).createMachine({
3712
- id: "publishManager",
3713
- initial: "restoreFromDb",
3714
- context: {
3715
- publishProcesses: /* @__PURE__ */ new Map(),
3716
- subscriptions: /* @__PURE__ */ new Map(),
3717
- pendingCreates: [],
3718
- settledPublishes: /* @__PURE__ */ new Map()
3719
- },
3720
- states: {
3721
- restoreFromDb: {
3722
- on: {
3723
- RESTORE_FROM_DB_DONE: {
3724
- target: "active",
3725
- actions: ["assignRestoreFromDb"]
3726
- },
3727
- CREATE_PUBLISH: { actions: ["queueCreatePublish"] }
3728
- },
3729
- invoke: {
3730
- src: "restoreFromDb",
3731
- input: ({ context: e }) => ({ context: e })
3732
- }
3733
- },
3734
- active: {
3735
- entry: "drainPendingCreates",
3736
- on: {
3737
- CREATE_PUBLISH: { actions: ["createPublish"] },
3738
- ADD_SUBSCRIPTION: { actions: ["addSubscription"] },
3739
- REQUEST_SAVE_PUBLISH: { actions: ["requestSavePublish"] },
3740
- SAVE_PUBLISH_DONE: [{
3741
- guard: ({ event: e }) => e.triggerPublishDone === !0,
3742
- actions: ["publishDone"]
3743
- }],
3744
- PUBLISH_DONE: { actions: ["publishDone"] },
3745
- REMOVE_SUBSCRIPTION: { actions: ["removeSubscription"] },
3746
- RETRY_ATTESTATIONS: { actions: ["retryAttestations"] },
3747
- STOP_PUBLISH: { actions: ["stopPublish"] },
3748
- QUERY: { actions: ["query"] },
3749
- STOP_ALL: { actions: ["stopAll"] }
3750
- }
3751
- }
3752
- }
3753
- }), $ = Bt(ns, { input: {
3754
- publishProcesses: /* @__PURE__ */ new Map(),
3755
- subscriptions: /* @__PURE__ */ new Map(),
3756
- pendingCreates: [],
3757
- settledPublishes: /* @__PURE__ */ new Map()
3758
- } }), rs = !1;
3759
- function is() {
3760
- if (!rs) {
3761
- try {
3762
- $.start();
3763
- } catch (e) {
3764
- let t = e instanceof Error ? e.message : String(e);
3765
- if (!/already started/i.test(t)) throw e;
3766
- }
3767
- rs = !0;
3768
- }
3769
- }
3770
- qa({
3771
- savePublish: (e, t, n) => {
3772
- $.send({
3773
- type: "REQUEST_SAVE_PUBLISH",
3774
- seedLocalId: e,
3775
- publishProcess: t,
3776
- triggerPublishDone: n?.triggerPublishDone
3777
- });
3778
- },
3779
- onPublishDone: (e) => {
3780
- $.send({
3781
- type: "PUBLISH_DONE",
3782
- seedLocalId: e
3783
- });
3784
- },
3785
- removeSubscription: (e) => {
3786
- $.send({
3787
- type: "REMOVE_SUBSCRIPTION",
3788
- seedLocalId: e
3789
- });
3790
- }
3791
- });
3792
- var as = $.subscribe((e) => {
3793
- ts("PublishManager snapshot:", e);
3794
- });
3795
- typeof document < "u" && (is(), window.addEventListener("load", () => {
3796
- ts("PublishManager started");
3797
- }), window.addEventListener("beforeunload", () => {
3798
- as.unsubscribe(), $.stop();
3799
- }));
3800
- var os = {
3801
- getService: () => $,
3802
- ready: () => (is(), $.getSnapshot().value === "active" ? Promise.resolve() : new Promise((e) => {
3803
- let t = $.subscribe((n) => {
3804
- n.value === "active" && (t.unsubscribe(), e());
3805
- });
3806
- $.getSnapshot().value === "active" && (t.unsubscribe(), e());
3807
- })),
3808
- createPublish: async (e, t, n, r) => {
3809
- let { seedLocalId: i } = e, a = jo(i);
3810
- if (!await Oo(i)) {
3811
- console.warn(`[createPublish] "${i}" is already publishing in another tab; skipping.`);
3812
- return;
3813
- }
3814
- let o = await new Promise((i) => {
3815
- let a = to(i);
3816
- $.send({
3817
- type: "CREATE_PUBLISH",
3818
- item: e,
3819
- address: t,
3820
- account: n,
3821
- options: r,
3822
- createToken: a
3823
- });
3824
- });
3825
- return !o && !a && ko(i), o;
3826
- },
3827
- retryAttestations: (e, t) => $.send({
3828
- type: "RETRY_ATTESTATIONS",
3829
- seedLocalId: e,
3830
- account: t
3831
- }),
3832
- stopPublish: (e) => $.send({
3833
- type: "STOP_PUBLISH",
3834
- seedLocalId: e
3835
- }),
3836
- query: (e) => $.send({
3837
- type: "QUERY",
3838
- seedLocalId: e
3839
- }),
3840
- stopAll: () => $.send({ type: "STOP_ALL" }),
3841
- getPublish: (e) => {
3842
- let t = $.getSnapshot().context;
3843
- return t.publishProcesses.get(e) ?? t.settledPublishes.get(e);
3844
- },
3845
- savePublish: (e, t) => $.send({
3846
- type: "REQUEST_SAVE_PUBLISH",
3847
- seedLocalId: e,
3848
- publishProcess: t
3849
- }),
3850
- addSubscription: (e, t) => $.send({
3851
- type: "ADD_SUBSCRIPTION",
3852
- seedLocalId: e,
3853
- newSubscription: t
3854
- }),
3855
- removeSubscription: (e) => $.send({
3856
- type: "REMOVE_SUBSCRIPTION",
3857
- seedLocalId: e
3858
- })
3859
- };
3860
- //#endregion
3861
- //#region src/helpers/approvedTargetsForAutomationPublish.ts
3862
- function ss() {
3863
- let e = D().modularAccountModuleContract?.trim();
3864
- if (!e || !/^0x[0-9a-fA-F]{40}$/.test(e)) throw Error("@seedprotocol/publish: session keys require PublishConfig.modularAccountModuleContract (their only approved target is the Seed executor module).");
3865
- return [e.toLowerCase()];
3866
- }
3867
- //#endregion
3868
- //#region src/helpers/automationSessionKeyPermissions.ts
3869
- var cs = "publish,revoke";
3870
- function ls(e) {
3871
- let t = {
3872
- approvedTargets: ss(),
3873
- nativeTokenLimitPerTransaction: 0
3874
- };
3875
- return typeof e?.expiresAt == "number" && e.expiresAt > 0 && (t.expiresAt = Math.trunc(e.expiresAt)), t;
3876
- }
3877
- function us(e, t = cs) {
3878
- let n = `${[...e.approvedTargets].map((e) => e.toLowerCase()).sort().join(",")}|${e.nativeTokenLimitPerTransaction}|${e.expiresAt ?? 0}|${t.trim()}`;
3879
- return ht(gt(n));
3880
- }
3881
- function ds(e) {
3882
- let t = {
3883
- approvedTargets: e.approvedTargets,
3884
- nativeTokenLimitPerTransaction: e.nativeTokenLimitPerTransaction
3885
- };
3886
- return e.expiresAt != null && e.expiresAt > 0 ? {
3887
- ...t,
3888
- permissionEndTimestamp: /* @__PURE__ */ new Date(e.expiresAt * 1e3)
3889
- } : t;
3890
- }
3891
- //#endregion
3892
- //#region src/services/publishAuthorization/index.ts
3893
- var fs = "0x0000000000000000000000000000000000000000", ps = !0, ms = "0x0000000000000000000000000000000000000000";
3894
- function hs(e) {
3895
- if (i(e)) return e.txSender;
3896
- if (he(e)) return e;
3897
- throw Error("@seedprotocol/publish: publish authorization write APIs require a PublishWallet or SeedTxSender");
3898
- }
3899
- async function gs(e, t) {
3900
- let n = await e.sendTransaction(t);
3901
- return T(n.transactionHash);
3902
- }
3903
- function _s(e, t) {
3904
- let n = t.trim();
3905
- if (!/^0x[0-9a-fA-F]{40}$/.test(n)) throw Error(`@seedprotocol/publish: ${e} must be a valid address`);
3906
- return n;
3907
- }
3908
- function vs() {
3909
- return Lt.getSchemaUID(vt, fs, ps);
3910
- }
3911
- async function ys(e) {
3912
- let t = hs(e), n = vs();
3913
- return await V(n) || (await gs(t, dn({
3914
- schema: vt,
3915
- resolverAddress: fs,
3916
- revocable: ps
3917
- })), await gs(t, pn({
3918
- schemaUid: n,
3919
- schemaName: bt
3920
- }))), n;
3921
- }
3922
- function bs(e) {
3923
- return new It(vt).encodeData([
3924
- {
3925
- name: "identity",
3926
- value: e.identity,
3927
- type: "address"
3928
- },
3929
- {
3930
- name: "sessionKey",
3931
- value: e.sessionKey,
3932
- type: "address"
3933
- },
3934
- {
3935
- name: "app",
3936
- value: e.app,
3937
- type: "address"
3938
- },
3939
- {
3940
- name: "scopes",
3941
- value: e.scopes,
3942
- type: "string"
3943
- },
3944
- {
3945
- name: "grantedAt",
3946
- value: e.grantedAt,
3947
- type: "uint64"
3948
- },
3949
- {
3950
- name: "expiresAt",
3951
- value: e.expiresAt,
3952
- type: "uint64"
3953
- },
3954
- {
3955
- name: "permissionsHash",
3956
- value: Ot(e.permissionsHash),
3957
- type: "bytes32"
3958
- }
3959
- ]);
3960
- }
3961
- async function xs(e) {
3962
- let t = hs(e.wallet), n = e.ensureSchema === !1 ? vs() : await ys(e.wallet), r = _s("identity", e.identity), i = _s("sessionKey", e.sessionKey), a = e.app?.trim() ? _s("app", e.app) : ms, o = e.grantedAt ?? Math.floor(Date.now() / 1e3), s = typeof e.expiresAt == "number" && e.expiresAt > 0 ? Math.trunc(e.expiresAt) : 0, c = e.scopes ?? St, l = Ot(e.permissionsHash ?? us(ls({ expiresAt: s > 0 ? s : void 0 }), c === St ? "publish,revoke" : c));
3963
- if (l === zt) throw Error("@seedprotocol/publish: attestPublishAuthorization requires a non-zero permissionsHash");
3964
- let d = typeof e.expirationTime == "number" && e.expirationTime > 0 ? e.expirationTime : s > 0 ? s : o + _t, f = bs({
3965
- identity: r,
3966
- sessionKey: i,
3967
- app: a,
3968
- scopes: c,
3969
- grantedAt: o,
3970
- expiresAt: s,
3971
- permissionsHash: l
3972
- }), p = await gs(t, v({
3973
- schema: n,
3974
- data: {
3975
- recipient: i,
3976
- expirationTime: BigInt(d),
3977
- revocable: !0,
3978
- refUID: zt,
3979
- data: f,
3980
- value: 0n
3981
- }
3982
- }));
3983
- if (!p) throw Error("@seedprotocol/publish: attestPublishAuthorization failed — no receipt");
3984
- let { easContractAddress: m } = D(), h = u(p, m);
3985
- if (!h || !Dt(h)) throw Error("@seedprotocol/publish: attestPublishAuthorization failed — could not parse attestation UID");
3986
- return {
3987
- uid: h,
3988
- schemaUid: n,
3989
- permissionsHash: l,
3990
- grantedAt: o,
3991
- expiresAt: s,
3992
- expirationTime: d
3993
- };
3994
- }
3995
- async function Ss(e) {
3996
- let t = hs(e.wallet), r = e.schemaUid ?? vs(), i = Ot(e.uid);
3997
- if (!Dt(i)) throw Error("@seedprotocol/publish: revokePublishAuthorization requires a valid attestation uid");
3998
- if (!await gs(t, n([{
3999
- schema: r,
4000
- data: [{ uid: i }]
4001
- }]))) throw Error("@seedprotocol/publish: revokePublishAuthorization failed — no receipt");
4002
- }
4003
- async function Cs(e) {
4004
- let t = (await Et({
4005
- identities: e.identities,
4006
- excludeRevoked: !1
4007
- })).find((t) => t.id?.toLowerCase() === e.uid.toLowerCase());
4008
- if (!t) return null;
4009
- let n = Tt(t.decodedDataJson ?? "[]"), r = typeof t.expirationTime == "number" ? t.expirationTime : typeof t.expirationTime == "string" ? Number(t.expirationTime) : null;
4010
- return {
4011
- uid: t.id,
4012
- decoded: n,
4013
- assess: wt({
4014
- decoded: n,
4015
- expirationTime: r
4016
- }),
4017
- expirationTime: r
4018
- };
4019
- }
4020
- //#endregion
4021
- export { B as $, Ei as A, pi as B, Hi as C, wi as D, Ti as E, vi as F, ai as G, _i as H, Fi as I, hr as J, si as K, yi as L, Mi as M, Pi as N, Ci as O, fi as P, dn as Q, bi as R, Ki as S, Si as T, gi as U, ci as V, hi as W, pn as X, Tn as Y, V as Z, ga as _, xs as a, aa as b, vs as c, ls as d, on as et, us as f, Wa as g, os as h, Cs as i, Oi as j, Di as k, Ss as l, ss as m, xt as n, Qt as nt, bs as o, ds as p, $n as q, Ct as r, ys as s, yt as t, Zt as tt, cs as u, _a as v, Wi as w, ia as x, ea as y, xi as z };
4022
-
4023
- //# sourceMappingURL=publishAuthorization-CAFF5jQ2.js.map