@dignetwork/dig-sdk 0.0.1-alpha.98 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/LICENSE +21 -7
  2. package/README.md +267 -0
  3. package/dist/adapters.cjs +315 -0
  4. package/dist/adapters.cjs.map +1 -0
  5. package/dist/adapters.d.cts +20 -0
  6. package/dist/adapters.d.ts +20 -0
  7. package/dist/adapters.js +306 -0
  8. package/dist/adapters.js.map +1 -0
  9. package/dist/dev-shim-Bgw8X2E9.d.cts +118 -0
  10. package/dist/dev-shim-Bgw8X2E9.d.ts +118 -0
  11. package/dist/dig-client-entry-BIzuZ7Rs.d.cts +263 -0
  12. package/dist/dig-client-entry-BIzuZ7Rs.d.ts +263 -0
  13. package/dist/dig-client.cjs +330 -0
  14. package/dist/dig-client.cjs.map +1 -0
  15. package/dist/dig-client.d.cts +1 -0
  16. package/dist/dig-client.d.ts +1 -0
  17. package/dist/dig-client.js +319 -0
  18. package/dist/dig-client.js.map +1 -0
  19. package/dist/index.cjs +754 -0
  20. package/dist/index.cjs.map +1 -0
  21. package/dist/index.d.cts +192 -0
  22. package/dist/index.d.ts +192 -5
  23. package/dist/index.js +731 -19
  24. package/dist/index.js.map +1 -0
  25. package/dist/next.cjs +326 -0
  26. package/dist/next.cjs.map +1 -0
  27. package/dist/next.d.cts +23 -0
  28. package/dist/next.d.ts +23 -0
  29. package/dist/next.js +319 -0
  30. package/dist/next.js.map +1 -0
  31. package/dist/spend.cjs +14 -0
  32. package/dist/spend.cjs.map +1 -0
  33. package/dist/spend.d.cts +1 -0
  34. package/dist/spend.d.ts +1 -0
  35. package/dist/spend.js +3 -0
  36. package/dist/spend.js.map +1 -0
  37. package/dist/vite.cjs +338 -0
  38. package/dist/vite.cjs.map +1 -0
  39. package/dist/vite.d.cts +35 -0
  40. package/dist/vite.d.ts +35 -0
  41. package/dist/vite.js +332 -0
  42. package/dist/vite.js.map +1 -0
  43. package/package.json +87 -59
  44. package/vendor/PROVENANCE.md +102 -0
  45. package/vendor/dig_client.d.ts +150 -0
  46. package/vendor/dig_client.mjs +805 -0
  47. package/vendor/dig_client_bg.wasm +0 -0
  48. package/dist/DataIntegrityTree/DataIntegrityTree.d.ts +0 -163
  49. package/dist/DataIntegrityTree/DataIntegrityTree.d.ts.map +0 -1
  50. package/dist/DataIntegrityTree/DataIntegrityTree.js +0 -707
  51. package/dist/DataIntegrityTree/DataLayerError.d.ts +0 -6
  52. package/dist/DataIntegrityTree/DataLayerError.d.ts.map +0 -1
  53. package/dist/DataIntegrityTree/DataLayerError.js +0 -17
  54. package/dist/DataIntegrityTree/index.d.ts +0 -2
  55. package/dist/DataIntegrityTree/index.d.ts.map +0 -1
  56. package/dist/DataIntegrityTree/index.js +0 -17
  57. package/dist/DigNetwork/ContentServer.d.ts +0 -33
  58. package/dist/DigNetwork/ContentServer.d.ts.map +0 -1
  59. package/dist/DigNetwork/ContentServer.js +0 -308
  60. package/dist/DigNetwork/DigChallenge.d.ts +0 -82
  61. package/dist/DigNetwork/DigChallenge.d.ts.map +0 -1
  62. package/dist/DigNetwork/DigChallenge.js +0 -144
  63. package/dist/DigNetwork/DigNetwork.d.ts +0 -14
  64. package/dist/DigNetwork/DigNetwork.d.ts.map +0 -1
  65. package/dist/DigNetwork/DigNetwork.js +0 -169
  66. package/dist/DigNetwork/DigPeer.d.ts +0 -24
  67. package/dist/DigNetwork/DigPeer.d.ts.map +0 -1
  68. package/dist/DigNetwork/DigPeer.js +0 -118
  69. package/dist/DigNetwork/IncentiveServer.d.ts +0 -13
  70. package/dist/DigNetwork/IncentiveServer.d.ts.map +0 -1
  71. package/dist/DigNetwork/IncentiveServer.js +0 -76
  72. package/dist/DigNetwork/PropagationServer.d.ts +0 -75
  73. package/dist/DigNetwork/PropagationServer.d.ts.map +0 -1
  74. package/dist/DigNetwork/PropagationServer.js +0 -536
  75. package/dist/DigNetwork/index.d.ts +0 -4
  76. package/dist/DigNetwork/index.d.ts.map +0 -1
  77. package/dist/DigNetwork/index.js +0 -19
  78. package/dist/blockchain/DataStore.d.ts +0 -67
  79. package/dist/blockchain/DataStore.d.ts.map +0 -1
  80. package/dist/blockchain/DataStore.js +0 -413
  81. package/dist/blockchain/DataStoreSerializer.d.ts +0 -52
  82. package/dist/blockchain/DataStoreSerializer.d.ts.map +0 -1
  83. package/dist/blockchain/DataStoreSerializer.js +0 -109
  84. package/dist/blockchain/FullNodePeer.d.ts +0 -31
  85. package/dist/blockchain/FullNodePeer.d.ts.map +0 -1
  86. package/dist/blockchain/FullNodePeer.js +0 -295
  87. package/dist/blockchain/ServerCoin.d.ts +0 -29
  88. package/dist/blockchain/ServerCoin.d.ts.map +0 -1
  89. package/dist/blockchain/ServerCoin.js +0 -321
  90. package/dist/blockchain/Wallet.d.ts +0 -28
  91. package/dist/blockchain/Wallet.d.ts.map +0 -1
  92. package/dist/blockchain/Wallet.js +0 -253
  93. package/dist/blockchain/coins.d.ts +0 -6
  94. package/dist/blockchain/coins.d.ts.map +0 -1
  95. package/dist/blockchain/coins.js +0 -102
  96. package/dist/blockchain/index.d.ts +0 -8
  97. package/dist/blockchain/index.d.ts.map +0 -1
  98. package/dist/blockchain/index.js +0 -36
  99. package/dist/index.d.ts.map +0 -1
  100. package/dist/prompts.d.ts +0 -21
  101. package/dist/prompts.d.ts.map +0 -1
  102. package/dist/prompts.js +0 -149
  103. package/dist/types.d.ts +0 -64
  104. package/dist/types.d.ts.map +0 -1
  105. package/dist/types.js +0 -2
  106. package/dist/utils/ContentScanner.d.ts +0 -63
  107. package/dist/utils/ContentScanner.d.ts.map +0 -1
  108. package/dist/utils/ContentScanner.js +0 -175
  109. package/dist/utils/Environment.d.ts +0 -18
  110. package/dist/utils/Environment.d.ts.map +0 -1
  111. package/dist/utils/Environment.js +0 -85
  112. package/dist/utils/FileCache.d.ts +0 -11
  113. package/dist/utils/FileCache.d.ts.map +0 -1
  114. package/dist/utils/FileCache.js +0 -58
  115. package/dist/utils/FileTransfer.d.ts +0 -47
  116. package/dist/utils/FileTransfer.d.ts.map +0 -1
  117. package/dist/utils/FileTransfer.js +0 -209
  118. package/dist/utils/NconfManager.d.ts +0 -11
  119. package/dist/utils/NconfManager.d.ts.map +0 -1
  120. package/dist/utils/NconfManager.js +0 -56
  121. package/dist/utils/StoreArchiveManager.d.ts +0 -45
  122. package/dist/utils/StoreArchiveManager.d.ts.map +0 -1
  123. package/dist/utils/StoreArchiveManager.js +0 -153
  124. package/dist/utils/asyncPool.d.ts +0 -9
  125. package/dist/utils/asyncPool.d.ts.map +0 -1
  126. package/dist/utils/asyncPool.js +0 -23
  127. package/dist/utils/config.d.ts +0 -68
  128. package/dist/utils/config.d.ts.map +0 -1
  129. package/dist/utils/config.js +0 -223
  130. package/dist/utils/connectionUtils.d.ts +0 -10
  131. package/dist/utils/connectionUtils.d.ts.map +0 -1
  132. package/dist/utils/connectionUtils.js +0 -18
  133. package/dist/utils/credentialsUtils.d.ts +0 -8
  134. package/dist/utils/credentialsUtils.d.ts.map +0 -1
  135. package/dist/utils/credentialsUtils.js +0 -122
  136. package/dist/utils/directoryUtils.d.ts +0 -9
  137. package/dist/utils/directoryUtils.d.ts.map +0 -1
  138. package/dist/utils/directoryUtils.js +0 -110
  139. package/dist/utils/encryption.d.ts +0 -8
  140. package/dist/utils/encryption.d.ts.map +0 -1
  141. package/dist/utils/encryption.js +0 -55
  142. package/dist/utils/hashUtils.d.ts +0 -8
  143. package/dist/utils/hashUtils.d.ts.map +0 -1
  144. package/dist/utils/hashUtils.js +0 -44
  145. package/dist/utils/index.d.ts +0 -14
  146. package/dist/utils/index.d.ts.map +0 -1
  147. package/dist/utils/index.js +0 -29
  148. package/dist/utils/merkle.d.ts +0 -2
  149. package/dist/utils/merkle.d.ts.map +0 -1
  150. package/dist/utils/merkle.js +0 -28
  151. package/dist/utils/network.d.ts +0 -2
  152. package/dist/utils/network.d.ts.map +0 -1
  153. package/dist/utils/network.js +0 -54
  154. package/dist/utils/spinnerUtils.d.ts +0 -2
  155. package/dist/utils/spinnerUtils.d.ts.map +0 -1
  156. package/dist/utils/spinnerUtils.js +0 -47
  157. package/dist/utils/ssl.d.ts +0 -5
  158. package/dist/utils/ssl.d.ts.map +0 -1
  159. package/dist/utils/ssl.js +0 -50
  160. package/dist/utils/validationUtils.d.ts +0 -9
  161. package/dist/utils/validationUtils.d.ts.map +0 -1
  162. package/dist/utils/validationUtils.js +0 -55
package/dist/index.cjs ADDED
@@ -0,0 +1,754 @@
1
+ 'use strict';
2
+
3
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
4
+ // src/methods.ts
5
+ var WALLET_METHODS = [
6
+ "chip0002_connect",
7
+ "chip0002_chainId",
8
+ "chip0002_getPublicKeys",
9
+ "chip0002_getAssetCoins",
10
+ "chip0002_getAssetBalance",
11
+ "chip0002_signCoinSpends",
12
+ "chip0002_signMessage",
13
+ "chia_getAddress",
14
+ "chia_signMessageByAddress",
15
+ "chia_takeOffer"
16
+ ];
17
+ var SIGN_METHODS = [
18
+ "chia_signMessageByAddress",
19
+ "chip0002_signMessage"
20
+ ];
21
+ var DEFAULT_CHAIN = "chia:mainnet";
22
+
23
+ // src/provider/injected.ts
24
+ function getInjectedProvider() {
25
+ const g = globalThis;
26
+ return typeof g !== "undefined" ? g.chia : void 0;
27
+ }
28
+ function isInjectedAvailable(opts = {}) {
29
+ const p = getInjectedProvider();
30
+ if (!p) return false;
31
+ if (opts.anyChia) return typeof p.request === "function";
32
+ return !!p.isDIG;
33
+ }
34
+ var INJECTED_TOPIC = "injected";
35
+ var InjectedTransport = class {
36
+ constructor(provider, chain = DEFAULT_CHAIN) {
37
+ this.backend = "injected";
38
+ this.topic = INJECTED_TOPIC;
39
+ this.provider = provider;
40
+ this.chain = chain;
41
+ }
42
+ /** Connect: ask the native wallet to approve this origin. Blocks until approved/rejected. */
43
+ async connect(eager = false) {
44
+ if (typeof this.provider.connect === "function") {
45
+ await this.provider.connect(eager);
46
+ }
47
+ }
48
+ // The native wallet implements the full canonical set (it returns Sage-shaped responses), so
49
+ // support is a static allowlist — no per-session negotiation as with WalletConnect.
50
+ supports(method) {
51
+ return WALLET_METHODS.includes(method);
52
+ }
53
+ async request(method, params) {
54
+ if (!this.supports(method)) {
55
+ throw new Error(`The DIG Browser wallet does not support "${method}".`);
56
+ }
57
+ return this.provider.request({ method, params });
58
+ }
59
+ async disconnect() {
60
+ }
61
+ };
62
+
63
+ // src/provider/wc-retry.ts
64
+ function isTransientPublishError(err) {
65
+ const msg = (err instanceof Error ? err.message : typeof err === "string" ? err : "").toLowerCase();
66
+ if (!msg) return false;
67
+ return msg.includes("publish") || msg.includes("failed or timed out to publish") || msg.includes("websocket connection failed") || msg.includes("connection closed") || msg.includes("socket stalled") || msg.includes("request reset");
68
+ }
69
+
70
+ // src/provider/walletconnect.ts
71
+ var WalletConnectTransport = class _WalletConnectTransport {
72
+ constructor(client, session, chain, requestTimeoutMs) {
73
+ this.backend = "walletconnect";
74
+ this.client = client;
75
+ this.topic = session.topic;
76
+ this.chain = chain;
77
+ this.requestTimeoutMs = requestTimeoutMs;
78
+ }
79
+ /**
80
+ * Initialize SignClient, open a pairing (emitting the URI via `onUri`), and resolve to a
81
+ * connected transport once the user approves in Sage. Requires `@walletconnect/sign-client`.
82
+ */
83
+ static async connect(options) {
84
+ const chain = options.chain ?? DEFAULT_CHAIN;
85
+ const timeout = options.requestTimeoutMs ?? 6e4;
86
+ const SignClient = await loadSignClient();
87
+ const client = await SignClient.init({
88
+ logger: "error",
89
+ projectId: options.projectId,
90
+ metadata: options.metadata
91
+ });
92
+ const { uri, approval } = await client.connect({
93
+ // optionalNamespaces ONLY — Sage rejects requiredNamespaces.
94
+ optionalNamespaces: {
95
+ chia: { methods: WALLET_METHODS, chains: [chain], events: [] }
96
+ }
97
+ });
98
+ if (uri && options.onUri) options.onUri(uri);
99
+ const session = await approval();
100
+ return new _WalletConnectTransport(client, session, chain, timeout);
101
+ }
102
+ /**
103
+ * Restore an existing session that grants a sign method (so message signing actually reaches
104
+ * Sage). Returns a transport or null if none qualifies. Requires `@walletconnect/sign-client`.
105
+ */
106
+ static async restore(options) {
107
+ const chain = options.chain ?? DEFAULT_CHAIN;
108
+ const timeout = options.requestTimeoutMs ?? 6e4;
109
+ const SignClient = await loadSignClient();
110
+ const client = await SignClient.init({
111
+ logger: "error",
112
+ projectId: options.projectId,
113
+ metadata: options.metadata
114
+ });
115
+ const sessions = client.session.getAll();
116
+ for (let i = sessions.length - 1; i >= 0; i--) {
117
+ const s = sessions[i];
118
+ const methods = s.namespaces?.chia?.methods ?? [];
119
+ if (SIGN_METHODS.some((m) => methods.includes(m))) {
120
+ return new _WalletConnectTransport(client, s, chain, timeout);
121
+ }
122
+ }
123
+ return null;
124
+ }
125
+ sessionMethods() {
126
+ try {
127
+ return this.client.session.get(this.topic)?.namespaces?.chia?.methods ?? [];
128
+ } catch {
129
+ return [];
130
+ }
131
+ }
132
+ // True iff the active session granted `method` (empty list = unknown ⇒ treated as granted).
133
+ supports(method) {
134
+ const m = this.sessionMethods();
135
+ return m.length === 0 || m.includes(method);
136
+ }
137
+ async request(method, params) {
138
+ if (!this.supports(method)) {
139
+ throw new Error(
140
+ `Your wallet session does not grant "${method}". Disconnect and reconnect your wallet to refresh the session (and make sure Sage is up to date).`
141
+ );
142
+ }
143
+ const MAX_ATTEMPTS = 3;
144
+ let lastErr;
145
+ for (let i = 0; i < MAX_ATTEMPTS; i++) {
146
+ try {
147
+ return await this.attempt(method, params);
148
+ } catch (e) {
149
+ lastErr = e;
150
+ if (i < MAX_ATTEMPTS - 1 && isTransientPublishError(e)) {
151
+ await sleep(1200 * (i + 1));
152
+ continue;
153
+ }
154
+ throw e;
155
+ }
156
+ }
157
+ throw lastErr;
158
+ }
159
+ attempt(method, params) {
160
+ let t;
161
+ const timeout = new Promise((_, rej) => {
162
+ t = setTimeout(
163
+ () => rej(new Error("Sage did not respond \u2014 open the Sage app and try again.")),
164
+ this.requestTimeoutMs
165
+ );
166
+ });
167
+ return Promise.race([
168
+ this.client.request({ topic: this.topic, chainId: this.chain, request: { method, params } }),
169
+ timeout
170
+ ]).finally(() => clearTimeout(t));
171
+ }
172
+ async disconnect() {
173
+ try {
174
+ await this.client.disconnect({
175
+ topic: this.topic,
176
+ reason: { code: 6e3, message: "bye" }
177
+ });
178
+ } catch {
179
+ }
180
+ }
181
+ };
182
+ function sleep(ms) {
183
+ return new Promise((r) => setTimeout(r, ms));
184
+ }
185
+ async function loadSignClient() {
186
+ try {
187
+ const mod = await import('@walletconnect/sign-client');
188
+ const SignClient = mod.default ?? mod;
189
+ if (!SignClient || typeof SignClient.init !== "function") {
190
+ throw new Error("unexpected @walletconnect/sign-client shape");
191
+ }
192
+ return SignClient;
193
+ } catch {
194
+ throw new Error(
195
+ "WalletConnect fallback requires the optional peer dependency '@walletconnect/sign-client'. Install it (npm i @walletconnect/sign-client) to use the WalletConnect\u2192Sage transport."
196
+ );
197
+ }
198
+ }
199
+
200
+ // src/provider/methods.ts
201
+ function with0x(hex) {
202
+ if (!hex) return hex ?? null;
203
+ return hex.startsWith("0x") ? hex : `0x${hex}`;
204
+ }
205
+ function strip0x(h) {
206
+ return String(h ?? "").replace(/^0x/i, "").toLowerCase();
207
+ }
208
+ async function getAddress(request) {
209
+ const resp = await request("chia_getAddress", {});
210
+ if (typeof resp === "string") return resp;
211
+ const r = resp;
212
+ return r?.address ?? r?.data?.address ?? null;
213
+ }
214
+ async function getPublicKeys(request) {
215
+ const resp = await request("chip0002_getPublicKeys", { limit: 500, offset: 0 });
216
+ if (Array.isArray(resp)) return resp;
217
+ const r = resp;
218
+ return r?.publicKeys ?? r?.public_keys ?? r?.keys ?? [];
219
+ }
220
+ function normalizeSig(resp) {
221
+ const r = resp;
222
+ const publicKey = typeof r === "object" && r ? r.publicKey ?? r.public_key ?? r.pubkey ?? null : null;
223
+ const signature = typeof r === "string" ? r : r ? r.signature ?? r.aggregatedSignature ?? r.aggregated_signature ?? null : null;
224
+ return { publicKey: with0x(publicKey), signature };
225
+ }
226
+ async function signMessage(request, supports, message, address) {
227
+ if (supports("chia_signMessageByAddress")) {
228
+ return normalizeSig(await request("chia_signMessageByAddress", { message, address }));
229
+ }
230
+ const keys = await getPublicKeys(request);
231
+ const publicKey = keys[0];
232
+ if (!publicKey) throw new Error("Wallet returned no keys to sign with.");
233
+ const sig = normalizeSig(await request("chip0002_signMessage", { message, publicKey }));
234
+ return { publicKey: sig.publicKey ?? with0x(publicKey), signature: sig.signature };
235
+ }
236
+ async function signCoinSpends(request, coinSpends) {
237
+ const resp = await request("chip0002_signCoinSpends", { coinSpends, partialSign: true });
238
+ if (typeof resp === "string") return resp;
239
+ const r = resp;
240
+ return r?.signature ?? r?.aggregatedSignature ?? r?.aggregated_signature ?? "";
241
+ }
242
+ async function takeOffer(request, supports, offer, fee = 0) {
243
+ if (!supports("chia_takeOffer")) {
244
+ throw new Error("Your wallet session does not support taking offers. Reconnect your wallet.");
245
+ }
246
+ return request("chia_takeOffer", { offer, fee });
247
+ }
248
+ function balanceFrom(resp) {
249
+ const raw = resp == null ? null : typeof resp === "object" ? resp.confirmed ?? resp.spendable ?? resp.confirmedWalletBalance ?? resp.confirmed_wallet_balance ?? resp.balance ?? resp.data?.confirmed ?? null : resp;
250
+ if (raw == null) return null;
251
+ try {
252
+ return BigInt(raw).toString();
253
+ } catch {
254
+ return null;
255
+ }
256
+ }
257
+ async function getXchBalance(request) {
258
+ return balanceFrom(await request("chip0002_getAssetBalance", { type: null, assetId: null }));
259
+ }
260
+ async function getCatBalance(request, assetIdHex) {
261
+ return balanceFrom(
262
+ await request("chip0002_getAssetBalance", { type: "cat", assetId: strip0x(assetIdHex) })
263
+ );
264
+ }
265
+ async function getXchCoins(request, limit = 100) {
266
+ const resp = await request("chip0002_getAssetCoins", {
267
+ type: null,
268
+ assetId: null,
269
+ includedLocked: false,
270
+ offset: 0,
271
+ limit
272
+ });
273
+ return Array.isArray(resp) ? resp : resp?.coins ?? [];
274
+ }
275
+ async function getCatCoins(request, assetIdHex, limit = 200) {
276
+ const resp = await request("chip0002_getAssetCoins", {
277
+ type: "cat",
278
+ assetId: strip0x(assetIdHex),
279
+ includedLocked: false,
280
+ offset: 0,
281
+ limit
282
+ });
283
+ return Array.isArray(resp) ? resp : resp?.coins ?? [];
284
+ }
285
+
286
+ // src/provider/chia-provider.ts
287
+ var ChiaProvider = class _ChiaProvider {
288
+ constructor(transport) {
289
+ this.transport = transport;
290
+ }
291
+ /** Which transport is backing this provider. */
292
+ get backend() {
293
+ return this.transport.backend;
294
+ }
295
+ /** The connected session descriptor. */
296
+ get session() {
297
+ return {
298
+ backend: this.transport.backend,
299
+ chain: this.transport.chain,
300
+ topic: this.transport.topic,
301
+ address: this.cachedAddress ?? null
302
+ };
303
+ }
304
+ /** True iff a method is granted by the active session/transport. */
305
+ supports(method) {
306
+ return this.transport.supports(method);
307
+ }
308
+ /** Escape hatch: issue a raw CHIP-0002 request through the active transport. */
309
+ request(method, params = {}) {
310
+ return this.transport.request(method, params);
311
+ }
312
+ /**
313
+ * Connect a wallet using the selection policy. With `mode: "auto"` (default) it prefers an
314
+ * injected DIG wallet and falls back to WalletConnect.
315
+ */
316
+ static async connect(options = {}) {
317
+ const mode = options.mode ?? "auto";
318
+ const chain = options.chain ?? DEFAULT_CHAIN;
319
+ const tryInjected = async () => {
320
+ if (!isInjectedAvailable({ anyChia: options.acceptAnyInjected })) return null;
321
+ const provider = getInjectedProvider();
322
+ const transport = new InjectedTransport(provider, chain);
323
+ await transport.connect();
324
+ return new _ChiaProvider(transport);
325
+ };
326
+ const tryWalletConnect = async () => {
327
+ if (!options.walletConnect) {
328
+ throw new Error(
329
+ "WalletConnect options are required to connect via WalletConnect (pass { walletConnect: { projectId, metadata, onUri } })."
330
+ );
331
+ }
332
+ const transport = await WalletConnectTransport.connect({
333
+ ...options.walletConnect,
334
+ chain
335
+ });
336
+ return new _ChiaProvider(transport);
337
+ };
338
+ if (mode === "injected") {
339
+ const injected = await tryInjected();
340
+ if (!injected) {
341
+ throw new Error(
342
+ "No injected DIG wallet found. Open this page in the DIG Browser, or use mode 'auto'."
343
+ );
344
+ }
345
+ return injected;
346
+ }
347
+ if (mode === "walletconnect") return tryWalletConnect();
348
+ return await tryInjected() ?? await tryWalletConnect();
349
+ }
350
+ /** Wrap an already-constructed transport (advanced / restored sessions). */
351
+ static fromTransport(transport) {
352
+ return new _ChiaProvider(transport);
353
+ }
354
+ // ---- normalized CHIP-0002 surface -------------------------------------------------------------
355
+ /** The wallet's receive address (cached after first read). */
356
+ async getAddress() {
357
+ if (this.cachedAddress === void 0) {
358
+ this.cachedAddress = await getAddress((m, p) => this.transport.request(m, p));
359
+ }
360
+ return this.cachedAddress;
361
+ }
362
+ /** The wallet's (synthetic) public keys. */
363
+ getPublicKeys() {
364
+ return getPublicKeys((m, p) => this.transport.request(m, p));
365
+ }
366
+ /**
367
+ * Sign a UTF-8 message with the wallet BLS key. `address` defaults to the wallet's own address.
368
+ * Returns `{ publicKey, signature }`.
369
+ */
370
+ async signMessage(message, address) {
371
+ const addr = address ?? await this.getAddress() ?? "";
372
+ return signMessage(
373
+ (m, p) => this.transport.request(m, p),
374
+ (m) => this.transport.supports(m),
375
+ message,
376
+ addr
377
+ );
378
+ }
379
+ /** Sign raw CHIP-0035 coin spends (partialSign). Returns the aggregated signature hex. */
380
+ signCoinSpends(coinSpends) {
381
+ return signCoinSpends((m, p) => this.transport.request(m, p), coinSpends);
382
+ }
383
+ /** Accept a Chia offer string (e.g. an NFT offer). */
384
+ takeOffer(offer, fee = 0) {
385
+ return takeOffer(
386
+ (m, p) => this.transport.request(m, p),
387
+ (m) => this.transport.supports(m),
388
+ offer,
389
+ fee
390
+ );
391
+ }
392
+ /** Spendable XCH balance (mojos, string) or null. */
393
+ getXchBalance() {
394
+ return getXchBalance((m, p) => this.transport.request(m, p));
395
+ }
396
+ /** Spendable balance (base units, string) for a CAT `assetIdHex` (the tail hash), or null. */
397
+ getCatBalance(assetIdHex) {
398
+ return getCatBalance((m, p) => this.transport.request(m, p), assetIdHex);
399
+ }
400
+ /** Unspent XCH coins for funding a spend. */
401
+ getXchCoins(limit) {
402
+ return getXchCoins((m, p) => this.transport.request(m, p), limit);
403
+ }
404
+ /** Unspent CAT coins for `assetIdHex`. */
405
+ getCatCoins(assetIdHex, limit) {
406
+ return getCatCoins((m, p) => this.transport.request(m, p), assetIdHex, limit);
407
+ }
408
+ /** Disconnect the wallet (best-effort). */
409
+ disconnect() {
410
+ return this.transport.disconnect();
411
+ }
412
+ };
413
+ function connectWallet(options) {
414
+ return ChiaProvider.connect(options);
415
+ }
416
+
417
+ // src/loader.ts
418
+ var DIG_CLIENT_WASM_SHA256 = "ff486be806f908a2a90780e499a04dbd34e10e3b97be0470cb9ee841a1e49e77";
419
+ var _config = {};
420
+ var _ready = null;
421
+ function configureWasm(config) {
422
+ _config = { ...config };
423
+ _ready = null;
424
+ }
425
+ var isNode = typeof process !== "undefined" && !!process.versions?.node;
426
+ async function sha256Hex(bytes) {
427
+ if (isNode) {
428
+ const { createHash } = await import('crypto');
429
+ const view = bytes instanceof ArrayBuffer ? new Uint8Array(bytes) : new Uint8Array(
430
+ bytes.buffer,
431
+ bytes.byteOffset,
432
+ bytes.byteLength
433
+ );
434
+ return createHash("sha256").update(view).digest("hex");
435
+ }
436
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
437
+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
438
+ }
439
+ function assertIntegrity(hex) {
440
+ if (_config.skipIntegrity) return;
441
+ if (hex !== DIG_CLIENT_WASM_SHA256) {
442
+ throw new Error(
443
+ `dig-client wasm integrity check failed \u2014 refusing to run unverified crypto (expected ${DIG_CLIENT_WASM_SHA256}, got ${hex}).`
444
+ );
445
+ }
446
+ }
447
+ async function loadNode() {
448
+ const { readFile } = await import('fs/promises');
449
+ const { fileURLToPath, pathToFileURL } = await import('url');
450
+ const path = await import('path');
451
+ const here = path.dirname(fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))));
452
+ const vendorDir = path.resolve(here, "..", "vendor");
453
+ const wasmPath = path.join(vendorDir, "dig_client_bg.wasm");
454
+ const gluePath = path.join(vendorDir, "dig_client.mjs");
455
+ const buf = await readFile(wasmPath);
456
+ const bytes = new Uint8Array(buf.byteLength);
457
+ bytes.set(buf);
458
+ return { glueHref: pathToFileURL(gluePath).href, bytes };
459
+ }
460
+ async function loadBrowser() {
461
+ const glueHref = _config.glueUrl ?? new URL("../vendor/dig_client.mjs", (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))).href;
462
+ let bytes;
463
+ if (_config.wasmBytes) {
464
+ bytes = _config.wasmBytes;
465
+ } else {
466
+ const wasmUrl = _config.wasmUrl ?? new URL("../vendor/dig_client_bg.wasm", (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))).href;
467
+ const res = await fetch(wasmUrl);
468
+ if (!res.ok) throw new Error(`dig-client wasm fetch failed (${res.status})`);
469
+ bytes = await res.arrayBuffer();
470
+ }
471
+ return { glueHref, bytes };
472
+ }
473
+ function loadDigClientWasm() {
474
+ if (_ready) return _ready;
475
+ _ready = (async () => {
476
+ const { glueHref, bytes } = isNode ? await loadNode() : await loadBrowser();
477
+ assertIntegrity(await sha256Hex(bytes));
478
+ const mod = await import(
479
+ /* @vite-ignore */
480
+ glueHref
481
+ );
482
+ await mod.default({ module_or_path: bytes });
483
+ return mod;
484
+ })().catch((e) => {
485
+ _ready = null;
486
+ throw e;
487
+ });
488
+ return _ready;
489
+ }
490
+
491
+ // src/urn.ts
492
+ var URN_RE = /^urn:dig:chia:([0-9a-fA-F]{64})(?::([0-9a-fA-F]{64}))?\/(.+?)(?:\?salt=([0-9a-fA-F]+))?$/;
493
+ function parseUrn(raw) {
494
+ const s = String(raw ?? "").trim();
495
+ const m = URN_RE.exec(s);
496
+ if (!m) {
497
+ throw new Error(
498
+ "Not a valid dig URN (expected urn:dig:chia:<store-id>[:<root>]/<path>[?salt=<hex>])."
499
+ );
500
+ }
501
+ return {
502
+ storeId: m[1].toLowerCase(),
503
+ root: m[2] ? m[2].toLowerCase() : null,
504
+ resourceKey: m[3],
505
+ salt: m[4] ? m[4].toLowerCase() : null
506
+ };
507
+ }
508
+ function isUrn(raw) {
509
+ try {
510
+ parseUrn(raw);
511
+ return true;
512
+ } catch {
513
+ return false;
514
+ }
515
+ }
516
+ function reconstructUrn(storeId, resourceKey) {
517
+ const key = resourceKey && resourceKey.length > 0 ? resourceKey : "index.html";
518
+ return `urn:dig:chia:${storeId.toLowerCase()}/${key}`;
519
+ }
520
+ function reconstructUrnWithRoot(storeId, root, resourceKey) {
521
+ const key = resourceKey && resourceKey.length > 0 ? resourceKey : "index.html";
522
+ return `urn:dig:chia:${storeId.toLowerCase()}:${root.toLowerCase()}/${key}`;
523
+ }
524
+
525
+ // src/dig-client.ts
526
+ var DEFAULT_RPC = "https://rpc.dig.net";
527
+ var RPC_CHUNK_BYTES = 3 * 1024 * 1024;
528
+ function b64ToBytes(b64) {
529
+ if (typeof atob === "function") {
530
+ const bin = atob(b64);
531
+ const out = new Uint8Array(bin.length);
532
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
533
+ return out;
534
+ }
535
+ return new Uint8Array(globalThis.Buffer.from(b64, "base64"));
536
+ }
537
+ var DigClient = class {
538
+ constructor(options = {}) {
539
+ this.rpc = options.rpc ?? DEFAULT_RPC;
540
+ this.fetchImpl = options.fetch ?? (typeof fetch === "function" ? fetch.bind(globalThis) : undefinedFetch());
541
+ }
542
+ /** Load (and SRI-verify) the read-crypto wasm. Exposed for callers that want the raw functions. */
543
+ async wasm() {
544
+ return loadDigClientWasm();
545
+ }
546
+ /** `retrieval_key = SHA-256(canonical rootless URN)`, lowercase hex. */
547
+ async retrievalKey(storeId, resourceKey) {
548
+ return (await this.wasm()).retrievalKey(storeId, resourceKey);
549
+ }
550
+ /** Derive the per-URN AES-256-GCM-SIV key, lowercase hex. `salt` for a private store. */
551
+ async deriveKey(storeId, resourceKey, salt) {
552
+ return (await this.wasm()).deriveKey(storeId, resourceKey, salt ?? void 0);
553
+ }
554
+ /** Verify served `ciphertext` is included under `root` via the base64 merkle `proof`. */
555
+ async verifyInclusion(ciphertext, proof, root) {
556
+ return (await this.wasm()).verifyInclusion(ciphertext, proof, root);
557
+ }
558
+ /** Reconstruct the canonical rootless URN whose SHA-256 is the retrieval key. */
559
+ async reconstructUrn(storeId, resourceKey) {
560
+ return (await this.wasm()).reconstructUrn(storeId, resourceKey);
561
+ }
562
+ /**
563
+ * Derive, client-side, the two root-independent keys a URN maps to (retrieval + decryption).
564
+ * Nothing is sent to the network — pure local derivation via the wasm.
565
+ */
566
+ async deriveUrnKeys(input) {
567
+ const parsed = parseUrn(input.urn);
568
+ const wasm = await this.wasm();
569
+ const effSalt = input.salt ?? parsed.salt ?? void 0;
570
+ return {
571
+ storeId: parsed.storeId,
572
+ root: parsed.root,
573
+ resourceKey: parsed.resourceKey,
574
+ salt: effSalt ?? null,
575
+ retrievalKey: wasm.retrievalKey(parsed.storeId, parsed.resourceKey),
576
+ decryptionKey: wasm.deriveKey(parsed.storeId, parsed.resourceKey, effSalt)
577
+ };
578
+ }
579
+ /**
580
+ * Fetch + verify + decrypt one resource by URN. `root` is the on-chain generation root to verify
581
+ * against (resolved by the caller from the chain); when omitted, the root embedded in the URN is
582
+ * used. Returns the bytes plus advisory `verified`/`decrypted` flags. NEVER throws "not found"
583
+ * (presence is unknowable) — it throws only on a transport failure.
584
+ */
585
+ async read(input, opts = {}) {
586
+ const parsed = parseUrn(input.urn);
587
+ const effSalt = input.salt ?? parsed.salt ?? null;
588
+ const effRoot = input.root ?? parsed.root ?? null;
589
+ if (!effRoot) {
590
+ throw new Error(
591
+ "a confirmed on-chain root is required to read content (pass { root } or use a root-pinned URN)"
592
+ );
593
+ }
594
+ return this.readResource(
595
+ { storeId: parsed.storeId, resourceKey: parsed.resourceKey, root: effRoot, salt: effSalt },
596
+ opts
597
+ );
598
+ }
599
+ /** As `read`, but decoding the plaintext to a UTF-8 string when it decrypts (else throws). */
600
+ async readText(input, opts = {}) {
601
+ const r = await this.read(input, opts);
602
+ if (!r.decrypted) {
603
+ throw new Error(
604
+ "resource did not decrypt under this URN \u2014 wrong store/key/salt, or a decoy response"
605
+ );
606
+ }
607
+ return new TextDecoder().decode(r.bytes);
608
+ }
609
+ /**
610
+ * Read by explicit (storeId, resourceKey, root, salt) rather than a URN string. The oblivious
611
+ * download primitive the URN read is built on.
612
+ */
613
+ async readResource(input, opts = {}) {
614
+ const rpc = opts.rpc ?? this.rpc;
615
+ const wasm = await this.wasm();
616
+ const rk = wasm.retrievalKey(input.storeId, input.resourceKey);
617
+ const { ciphertext, proof, chunkLens } = await this.fetchCiphertext(
618
+ input.storeId,
619
+ rk,
620
+ input.root,
621
+ rpc
622
+ );
623
+ let verified = false;
624
+ try {
625
+ verified = !!wasm.verifyInclusion(ciphertext, proof, input.root);
626
+ } catch {
627
+ verified = false;
628
+ }
629
+ const keyHex = wasm.deriveKey(input.storeId, input.resourceKey, input.salt ?? void 0);
630
+ try {
631
+ const bytes = decryptResourceChunks(wasm, keyHex, ciphertext, chunkLens);
632
+ return {
633
+ storeId: input.storeId,
634
+ root: input.root,
635
+ resourceKey: input.resourceKey,
636
+ salt: input.salt ?? null,
637
+ bytes,
638
+ verified,
639
+ decrypted: true
640
+ };
641
+ } catch {
642
+ return {
643
+ storeId: input.storeId,
644
+ root: input.root,
645
+ resourceKey: input.resourceKey,
646
+ salt: input.salt ?? null,
647
+ bytes: ciphertext,
648
+ verified,
649
+ decrypted: false
650
+ };
651
+ }
652
+ }
653
+ // Stream the FULL ciphertext for a resource from the RPC by retrieval key, reassembling 3-MiB
654
+ // chunks. A null result is a TRANSPORT failure, never a presence judgment.
655
+ async fetchCiphertext(storeId, rk, root, rpc) {
656
+ let offset = 0;
657
+ let total = null;
658
+ let buf = null;
659
+ let proof = "";
660
+ let chunkLens = null;
661
+ for (; ; ) {
662
+ const r = await this.rpcCall(rpc, "dig.getContent", {
663
+ store_id: storeId,
664
+ root,
665
+ retrieval_key: rk,
666
+ offset,
667
+ length: RPC_CHUNK_BYTES
668
+ });
669
+ if (!r) throw new Error("The content network returned no data for this request.");
670
+ if (total === null) {
671
+ total = r.total_length >>> 0;
672
+ buf = new Uint8Array(total);
673
+ }
674
+ if (chunkLens === null && Array.isArray(r.chunk_lens)) {
675
+ chunkLens = r.chunk_lens.map((n) => n >>> 0);
676
+ }
677
+ const chunk = b64ToBytes(r.ciphertext ?? "");
678
+ const at = r.offset >>> 0;
679
+ buf.set(chunk.subarray(0, Math.max(0, Math.min(chunk.length, total - at))), at);
680
+ if (r.inclusion_proof) proof = r.inclusion_proof;
681
+ if (r.complete || r.next_offset == null) break;
682
+ offset = r.next_offset >>> 0;
683
+ }
684
+ return { ciphertext: buf ?? new Uint8Array(0), proof, chunkLens };
685
+ }
686
+ // One JSON-RPC 2.0 call. Throws on transport failure or a JSON-RPC error; returns `result`.
687
+ async rpcCall(rpc, method, params) {
688
+ let res;
689
+ try {
690
+ res = await this.fetchImpl(rpc, {
691
+ method: "POST",
692
+ headers: { "content-type": "application/json" },
693
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params })
694
+ });
695
+ } catch {
696
+ throw new Error("Could not reach the content network. Check your connection and try again.");
697
+ }
698
+ if (!res.ok) throw new Error(`dig RPC ${method} failed (${res.status})`);
699
+ const json = await res.json();
700
+ if (json && json.error) throw new Error(`dig RPC ${method}: ${json.error.message ?? "error"}`);
701
+ return json ? json.result ?? null : null;
702
+ }
703
+ };
704
+ function decryptResourceChunks(wasm, keyHex, ciphertext, chunkLens) {
705
+ const lens = chunkLens && chunkLens.length ? chunkLens : [ciphertext.length];
706
+ const total = lens.reduce((a, n) => a + n, 0);
707
+ if (total !== ciphertext.length) {
708
+ throw new Error("served ciphertext length does not match chunk lengths");
709
+ }
710
+ if (lens.length === 1) return wasm.decryptChunk(keyHex, ciphertext);
711
+ const parts = [];
712
+ let p = 0;
713
+ for (const len of lens) {
714
+ parts.push(wasm.decryptChunk(keyHex, ciphertext.subarray(p, p + len)));
715
+ p += len;
716
+ }
717
+ const out = new Uint8Array(parts.reduce((a, x) => a + x.length, 0));
718
+ let q = 0;
719
+ for (const part of parts) {
720
+ out.set(part, q);
721
+ q += part.length;
722
+ }
723
+ return out;
724
+ }
725
+ function undefinedFetch() {
726
+ return (() => {
727
+ throw new Error(
728
+ "No global fetch available. Pass { fetch } to DigClient (Node < 18 needs a fetch polyfill)."
729
+ );
730
+ });
731
+ }
732
+
733
+ exports.ChiaProvider = ChiaProvider;
734
+ exports.DEFAULT_CHAIN = DEFAULT_CHAIN;
735
+ exports.DEFAULT_RPC = DEFAULT_RPC;
736
+ exports.DIG_CLIENT_WASM_SHA256 = DIG_CLIENT_WASM_SHA256;
737
+ exports.DigClient = DigClient;
738
+ exports.INJECTED_TOPIC = INJECTED_TOPIC;
739
+ exports.InjectedTransport = InjectedTransport;
740
+ exports.SIGN_METHODS = SIGN_METHODS;
741
+ exports.WALLET_METHODS = WALLET_METHODS;
742
+ exports.WalletConnectTransport = WalletConnectTransport;
743
+ exports.configureWasm = configureWasm;
744
+ exports.connectWallet = connectWallet;
745
+ exports.getInjectedProvider = getInjectedProvider;
746
+ exports.isInjectedAvailable = isInjectedAvailable;
747
+ exports.isTransientPublishError = isTransientPublishError;
748
+ exports.isUrn = isUrn;
749
+ exports.loadDigClientWasm = loadDigClientWasm;
750
+ exports.parseUrn = parseUrn;
751
+ exports.reconstructUrn = reconstructUrn;
752
+ exports.reconstructUrnWithRoot = reconstructUrnWithRoot;
753
+ //# sourceMappingURL=index.cjs.map
754
+ //# sourceMappingURL=index.cjs.map