@shelby-protocol/sdk 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/dist/browser/index.d.ts +12 -3
  2. package/dist/browser/index.mjs +3717 -142
  3. package/dist/core/aptos-explorer.mjs +46 -5
  4. package/dist/core/blobs.mjs +12 -4
  5. package/dist/core/chunk.mjs +58 -9
  6. package/dist/core/clients/ShelbyBlobClient.d.ts +0 -43
  7. package/dist/core/clients/ShelbyBlobClient.mjs +1084 -17
  8. package/dist/core/clients/ShelbyClient.d.ts +12 -2
  9. package/dist/core/clients/ShelbyClient.mjs +2915 -23
  10. package/dist/core/clients/ShelbyClientConfig.mjs +0 -1
  11. package/dist/core/clients/ShelbyMetadataClient.d.ts +0 -18
  12. package/dist/core/clients/ShelbyMetadataClient.mjs +306 -6
  13. package/dist/core/clients/ShelbyMicropaymentChannelClient.d.ts +7 -49
  14. package/dist/core/clients/ShelbyMicropaymentChannelClient.mjs +839 -13
  15. package/dist/core/clients/ShelbyPlacementGroupClient.mjs +307 -8
  16. package/dist/core/clients/ShelbyRPCClient.d.ts +106 -3
  17. package/dist/core/clients/ShelbyRPCClient.mjs +1261 -12
  18. package/dist/core/clients/index.d.ts +2 -1
  19. package/dist/core/clients/index.mjs +3420 -39
  20. package/dist/core/clients/utils.mjs +65 -6
  21. package/dist/core/commitments.mjs +270 -11
  22. package/dist/core/constants.d.ts +2 -2
  23. package/dist/core/constants.mjs +39 -16
  24. package/dist/core/erasure/clay-codes.mjs +129 -4
  25. package/dist/core/erasure/constants.mjs +33 -10
  26. package/dist/core/erasure/default.mjs +191 -9
  27. package/dist/core/erasure/index.mjs +266 -23
  28. package/dist/core/erasure/reed-solomon.mjs +68 -4
  29. package/dist/core/erasure/utils.mjs +0 -2
  30. package/dist/core/errors.mjs +29 -8
  31. package/dist/core/index.d.ts +1 -1
  32. package/dist/core/index.mjs +3711 -142
  33. package/dist/core/layout.mjs +37 -5
  34. package/dist/core/networks.mjs +10 -5
  35. package/dist/core/operations/generated/sdk.d.ts +9 -0
  36. package/dist/core/operations/generated/sdk.mjs +183 -18
  37. package/dist/core/operations/index.mjs +284 -24
  38. package/dist/core/promises.mjs +4 -4
  39. package/dist/core/rpc-responses.mjs +29 -10
  40. package/dist/core/shelby-explorer.mjs +31 -6
  41. package/dist/core/strings.mjs +0 -2
  42. package/dist/core/types/blobs.mjs +0 -1
  43. package/dist/core/types/index.mjs +230 -9
  44. package/dist/core/types/payments.d.ts +6 -6
  45. package/dist/core/types/payments.mjs +230 -5
  46. package/dist/core/types/placement_groups.mjs +0 -1
  47. package/dist/core/types/storage_providers.mjs +0 -1
  48. package/dist/core/utils.mjs +94 -8
  49. package/dist/node/clients/ShelbyNodeClient.d.ts +1 -0
  50. package/dist/node/clients/ShelbyNodeClient.mjs +2919 -24
  51. package/dist/node/clients/index.d.ts +1 -0
  52. package/dist/node/clients/index.mjs +2920 -26
  53. package/dist/node/index.d.ts +1 -1
  54. package/dist/node/index.mjs +3734 -149
  55. package/dist/node/parallel/commitment_worker.d.ts +9 -0
  56. package/dist/node/parallel/commitment_worker.mjs +298 -0
  57. package/dist/node/parallel/commitment_worker_pool.d.ts +35 -0
  58. package/dist/node/parallel/commitment_worker_pool.mjs +286 -0
  59. package/dist/node/parallel/default_commitment_worker_pool.d.ts +24 -0
  60. package/dist/node/parallel/default_commitment_worker_pool.mjs +302 -0
  61. package/dist/node/parallel/index.d.ts +11 -0
  62. package/dist/node/parallel/index.mjs +563 -0
  63. package/dist/node/parallel/parallel_commitments.d.ts +32 -0
  64. package/dist/node/parallel/parallel_commitments.mjs +561 -0
  65. package/dist/node/parallel/worker_pool.d.ts +74 -0
  66. package/dist/node/parallel/worker_pool.mjs +248 -0
  67. package/dist/node/testUtil.mjs +8 -4
  68. package/package.json +6 -2
  69. package/dist/chunk-3NRBHSMQ.mjs +0 -12
  70. package/dist/chunk-5BVSWXQJ.mjs +0 -801
  71. package/dist/chunk-6FJNAUU5.mjs +0 -278
  72. package/dist/chunk-6XSZRDLJ.mjs +0 -375
  73. package/dist/chunk-7P6ASYW6.mjs +0 -9
  74. package/dist/chunk-A4IG6GSE.mjs +0 -21
  75. package/dist/chunk-AD2G3QYD.mjs +0 -0
  76. package/dist/chunk-AUQDI5BS.mjs +0 -43
  77. package/dist/chunk-AY3HBWXA.mjs +0 -51
  78. package/dist/chunk-BDSW5PHM.mjs +0 -37
  79. package/dist/chunk-C6RQ3AEU.mjs +0 -51
  80. package/dist/chunk-CQ6QPIZK.mjs +0 -37
  81. package/dist/chunk-D6GQHO6G.mjs +0 -15
  82. package/dist/chunk-EM67QTMR.mjs +0 -0
  83. package/dist/chunk-I6NG5GNL.mjs +0 -8
  84. package/dist/chunk-JTXYKO3U.mjs +0 -38
  85. package/dist/chunk-KG2TMLEV.mjs +0 -207
  86. package/dist/chunk-M3CP5TFP.mjs +0 -39
  87. package/dist/chunk-M7W43K2Q.mjs +0 -505
  88. package/dist/chunk-MB7C7VQF.mjs +0 -0
  89. package/dist/chunk-MNCQBEMS.mjs +0 -55
  90. package/dist/chunk-MQUVYMNQ.mjs +0 -0
  91. package/dist/chunk-NEO7Z3ZQ.mjs +0 -49
  92. package/dist/chunk-NHWWORCH.mjs +0 -72
  93. package/dist/chunk-OEK24ON7.mjs +0 -135
  94. package/dist/chunk-QQ57OGQ2.mjs +0 -0
  95. package/dist/chunk-RNNJXTX2.mjs +0 -154
  96. package/dist/chunk-S6Q4OG7H.mjs +0 -83
  97. package/dist/chunk-TET3DJEO.mjs +0 -199
  98. package/dist/chunk-UEZNZBJO.mjs +0 -104
  99. package/dist/chunk-V46D5NBW.mjs +0 -11
  100. package/dist/chunk-V4B3GAMQ.mjs +0 -42
  101. package/dist/chunk-WFWRBNTW.mjs +0 -412
  102. package/dist/chunk-WTICJPDB.mjs +0 -0
  103. package/dist/chunk-XNEIWM4O.mjs +0 -0
  104. package/dist/chunk-Z4FZ7W6L.mjs +0 -39
  105. package/dist/chunk-Z7RFCADT.mjs +0 -0
  106. package/dist/chunk-ZHXCVRZX.mjs +0 -0
@@ -1,31 +1,2925 @@
1
- import "../../chunk-MB7C7VQF.mjs";
1
+ // src/core/clients/ShelbyMetadataClient.ts
2
2
  import {
3
- ShelbyNodeClient
4
- } from "../../chunk-V46D5NBW.mjs";
5
- import "../../chunk-6XSZRDLJ.mjs";
6
- import "../../chunk-WFWRBNTW.mjs";
7
- import "../../chunk-5BVSWXQJ.mjs";
8
- import "../../chunk-XNEIWM4O.mjs";
9
- import "../../chunk-NHWWORCH.mjs";
10
- import "../../chunk-AY3HBWXA.mjs";
11
- import "../../chunk-OEK24ON7.mjs";
3
+ AccountAddress as AccountAddress2,
4
+ Aptos,
5
+ Hex as Hex2
6
+ } from "@aptos-labs/ts-sdk";
7
+
8
+ // src/core/constants.ts
9
+ import { Network } from "@aptos-labs/ts-sdk";
10
+ var NetworkToShelbyRPCBaseUrl = {
11
+ [Network.SHELBYNET]: "https://api.shelbynet.shelby.xyz/shelby",
12
+ [Network.NETNA]: void 0,
13
+ [Network.DEVNET]: void 0,
14
+ [Network.TESTNET]: "https://api.testnet.shelby.xyz/shelby",
15
+ [Network.MAINNET]: void 0,
16
+ [Network.LOCAL]: "http://localhost:9090",
17
+ [Network.CUSTOM]: void 0
18
+ };
19
+ var NetworkToShelbyBlobIndexerBaseUrl = {
20
+ [Network.SHELBYNET]: "https://api.shelbynet.aptoslabs.com/nocode/v1/public/alias/shelby/shelbynet/v1/graphql",
21
+ [Network.NETNA]: void 0,
22
+ [Network.DEVNET]: void 0,
23
+ [Network.TESTNET]: "https://api.testnet.aptoslabs.com/nocode/v1/public/alias/shelby/testnet/v1/graphql",
24
+ [Network.MAINNET]: void 0,
25
+ [Network.LOCAL]: "http://localhost:8091/v1/graphql",
26
+ [Network.CUSTOM]: void 0
27
+ };
28
+ var NetworkToGasStationBaseUrl = {
29
+ [Network.SHELBYNET]: "https://api.shelbynet.shelby.xyz/gs/v1",
30
+ [Network.NETNA]: void 0,
31
+ [Network.DEVNET]: void 0,
32
+ [Network.TESTNET]: "https://api.testnet.shelby.xyz/gs/v1",
33
+ [Network.MAINNET]: void 0,
34
+ [Network.LOCAL]: void 0,
35
+ [Network.CUSTOM]: void 0
36
+ };
37
+ var SHELBY_DEPLOYER = "0x85fdb9a176ab8ef1d9d9c1b60d60b3924f0800ac1de1cc2085fb0b8bb4988e6a";
38
+ var MICROPAYMENTS_DEPLOYER = "0x1ae7275148bf6ef742b658fd9cbcc2e094201606f4a7bc707bab0201da8043ee";
39
+
40
+ // src/core/utils.ts
41
+ import {
42
+ AccountAddress,
43
+ Hex
44
+ } from "@aptos-labs/ts-sdk";
45
+ async function* readInChunks(input, chunkSize) {
46
+ let idx = 0;
47
+ if (isReadableStream(input)) {
48
+ const reader = input.getReader();
49
+ let buffer = new Uint8Array(chunkSize);
50
+ let bufferWriteOffset = 0;
51
+ try {
52
+ while (true) {
53
+ const { value, done } = await reader.read();
54
+ if (done) break;
55
+ if (value === void 0) continue;
56
+ let srcOffset = 0;
57
+ while (srcOffset < value.length) {
58
+ const remainingCapacity = chunkSize - bufferWriteOffset;
59
+ const bytesToCopy = Math.min(
60
+ remainingCapacity,
61
+ value.length - srcOffset
62
+ );
63
+ buffer.set(
64
+ value.subarray(srcOffset, srcOffset + bytesToCopy),
65
+ bufferWriteOffset
66
+ );
67
+ bufferWriteOffset += bytesToCopy;
68
+ srcOffset += bytesToCopy;
69
+ if (bufferWriteOffset >= chunkSize) {
70
+ yield [idx++, buffer];
71
+ buffer = new Uint8Array(chunkSize);
72
+ bufferWriteOffset = 0;
73
+ }
74
+ }
75
+ }
76
+ } finally {
77
+ reader.releaseLock();
78
+ }
79
+ if (bufferWriteOffset > 0) {
80
+ yield [idx++, buffer.subarray(0, bufferWriteOffset)];
81
+ }
82
+ return;
83
+ }
84
+ const view = toUint8Array(input);
85
+ for (let offset = 0; offset < view.byteLength; offset += chunkSize) {
86
+ yield [
87
+ idx++,
88
+ view.subarray(offset, Math.min(offset + chunkSize, view.byteLength))
89
+ ];
90
+ }
91
+ }
92
+ function zeroPadBytes(buffer, desiredLength) {
93
+ if (buffer.byteLength === desiredLength) {
94
+ return buffer;
95
+ }
96
+ if (buffer.byteLength > desiredLength) {
97
+ return buffer.subarray(0, desiredLength);
98
+ }
99
+ const paddedBuffer = new Uint8Array(desiredLength);
100
+ paddedBuffer.set(buffer);
101
+ return paddedBuffer;
102
+ }
103
+ async function concatHashes(parts) {
104
+ const chunks = parts.map((part) => Hex.fromHexInput(part).toUint8Array());
105
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);
106
+ const combined = new Uint8Array(totalLength);
107
+ let offset = 0;
108
+ for (const chunk of chunks) {
109
+ combined.set(chunk, offset);
110
+ offset += chunk.byteLength;
111
+ }
112
+ return Hex.fromHexInput(
113
+ new Uint8Array(await crypto.subtle.digest("SHA-256", combined))
114
+ );
115
+ }
116
+ function isReadableStream(value) {
117
+ return typeof value === "object" && value !== null && "getReader" in value && typeof value.getReader === "function";
118
+ }
119
+ function toUint8Array(view) {
120
+ return view instanceof Uint8Array ? view : new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
121
+ }
122
+ function buildRequestUrl(path, baseUrl) {
123
+ const baseHasSlash = baseUrl.endsWith("/");
124
+ const safeBase = baseHasSlash ? baseUrl : `${baseUrl}/`;
125
+ const safePath = path.replace(/^\/+/, "");
126
+ return new URL(safePath, safeBase);
127
+ }
128
+ function getBlobNameSuffix(blobName) {
129
+ const parts = blobName.split("/");
130
+ return parts.slice(1).join("/") || "";
131
+ }
132
+ function normalizeAddress(address) {
133
+ return AccountAddress.from(address, { maxMissingChars: 63 });
134
+ }
135
+
136
+ // src/core/clients/utils.ts
137
+ import { AptosConfig } from "@aptos-labs/ts-sdk";
138
+ var getAptosConfig = (config) => {
139
+ const baseFaucetConfig = config.faucet?.authToken ? { AUTH_TOKEN: config.faucet.authToken } : void 0;
140
+ if (config.aptos) {
141
+ return new AptosConfig({
142
+ // Spread user's aptos config first
143
+ ...config.aptos,
144
+ // Network from top-level is authoritative - cannot be overridden
145
+ network: config.network,
146
+ // Merge clientConfig with API_KEY default
147
+ clientConfig: {
148
+ API_KEY: config.apiKey,
149
+ ...config.aptos.clientConfig
150
+ },
151
+ // Merge faucetConfig: aptos config first, then base authToken (authoritative)
152
+ faucetConfig: {
153
+ ...config.aptos.faucetConfig,
154
+ ...baseFaucetConfig
155
+ }
156
+ });
157
+ }
158
+ return new AptosConfig({
159
+ network: config.network,
160
+ clientConfig: {
161
+ API_KEY: config.apiKey
162
+ },
163
+ faucetConfig: baseFaucetConfig
164
+ });
165
+ };
166
+ var getShelbyRPCBaseUrl = (config) => {
167
+ return config.rpc?.baseUrl ?? NetworkToShelbyRPCBaseUrl[config.network] ?? NetworkToShelbyRPCBaseUrl.testnet;
168
+ };
169
+
170
+ // src/core/clients/ShelbyMetadataClient.ts
171
+ function parseStorageProviderState(raw) {
172
+ switch (raw.__variant__) {
173
+ case "Active":
174
+ return {
175
+ variant: "Active",
176
+ quota: raw.quota.value,
177
+ stakeAtStartOfStakingEpoch: raw.stake_at_start_of_staking_epoch,
178
+ faulty: raw.faulty,
179
+ leaving: raw.leaving
180
+ };
181
+ case "Waitlisted":
182
+ return {
183
+ variant: "Waitlisted"
184
+ };
185
+ case "Frozen":
186
+ return {
187
+ variant: "Frozen",
188
+ frozenReason: raw.frozen_reason,
189
+ frozenFrom: raw.frozen_from,
190
+ frozenTill: raw.frozen_till
191
+ };
192
+ }
193
+ }
194
+ var ShelbyMetadataClient = class {
195
+ aptos;
196
+ deployer;
197
+ /**
198
+ * The ShelbyMetadataClient is used to interact with the Shelby contract on the Aptos blockchain. This
199
+ * includes functions like gathering basic details about the Shelby system, including storage provider information.
200
+ *
201
+ * @param config.aptos.config - The Aptos config.
202
+ * @param config.shelbyDeployer - The deployer account address of the Shelby contract. If not provided, the default deployer address will be used.
203
+ *
204
+ * @example
205
+ * ```typescript
206
+ * const aptos = new Aptos(new AptosConfig({ network: Network.TESTNET }));
207
+ * const metadataClient = new ShelbyMetadataClient({ aptos });
208
+ * ```
209
+ */
210
+ constructor(config) {
211
+ this.aptos = new Aptos(getAptosConfig(config));
212
+ this.deployer = config.deployer ?? AccountAddress2.fromString(SHELBY_DEPLOYER);
213
+ }
214
+ /**
215
+ * Retrieves storage provider list from the blockchain.
216
+ *
217
+ * @returns A list of storage providers, or empty array if none exist.
218
+ *
219
+ * @example
220
+ * ```typescript
221
+ * const spList = await client.getStorageProviders();
222
+ * ```
223
+ */
224
+ async getStorageProviders() {
225
+ try {
226
+ const rawMetadata = await this.aptos.view({
227
+ payload: {
228
+ function: `${this.deployer.toString()}::storage_provider_registry::get_all_storage_providers`,
229
+ functionArguments: []
230
+ }
231
+ });
232
+ const metadata = rawMetadata[0];
233
+ return metadata.map((provider) => ({
234
+ address: normalizeAddress(provider.address),
235
+ ipAddress: provider.ip_address,
236
+ port: provider.port,
237
+ blsPublicKey: Hex2.fromHexInput(provider.bls_public_key).toUint8Array(),
238
+ availabilityZone: provider.availability_zone,
239
+ state: parseStorageProviderState(provider.state)
240
+ }));
241
+ } catch (error) {
242
+ if (error instanceof Error && // Depending on the network, the error message may show up differently.
243
+ error.message?.includes("sub_status: Some(404)")) {
244
+ return [];
245
+ }
246
+ throw error;
247
+ }
248
+ }
249
+ /**
250
+ * Retrieves the list of placement group addresses.
251
+ *
252
+ * @returns The placement group address list, or an empty array if none exist.
253
+ *
254
+ * @example
255
+ * ```typescript
256
+ * const pgList = await client.getPlacementGroupAddresses();
257
+ * ```
258
+ */
259
+ async getPlacementGroupAddresses() {
260
+ try {
261
+ const pgSizeMetadata = await this.aptos.view({
262
+ payload: {
263
+ function: `${this.deployer.toString()}::placement_group_registry::get_number_of_placement_groups`,
264
+ functionArguments: []
265
+ }
266
+ });
267
+ const finalPlacementGroupIndex = pgSizeMetadata[0] - 1;
268
+ const addressMetadataArray = await this.aptos.view({
269
+ payload: {
270
+ function: `${this.deployer.toString()}::placement_group_registry::get_placement_group_addresses`,
271
+ functionArguments: [0, finalPlacementGroupIndex]
272
+ }
273
+ });
274
+ const metadata = addressMetadataArray[0];
275
+ return metadata.map((pg) => normalizeAddress(pg));
276
+ } catch (error) {
277
+ if (error instanceof Error && // Depending on the network, the error message may show up differently.
278
+ (error.message?.includes("sub_status: Some(404)") || error.message?.includes("E_PLACEMENT_GROUP_NOT_FOUND"))) {
279
+ return [];
280
+ }
281
+ throw error;
282
+ }
283
+ }
284
+ /**
285
+ * Retrieves the list of slice addresses.
286
+ *
287
+ * @returns The slice group list, or an empty array if none exist.
288
+ *
289
+ * @example
290
+ * ```typescript
291
+ * const pgList = await client.getSliceAddresses();
292
+ * ```
293
+ */
294
+ async getSliceAddresses() {
295
+ try {
296
+ const sliceSizeMetadata = await this.aptos.view({
297
+ payload: {
298
+ function: `${this.deployer.toString()}::slice_registry::get_number_of_slices`,
299
+ functionArguments: []
300
+ }
301
+ });
302
+ const finalSliceIndex = sliceSizeMetadata[0] - 1;
303
+ const addressMetadataArray = await this.aptos.view({
304
+ payload: {
305
+ function: `${this.deployer.toString()}::slice_registry::get_slice_addresses`,
306
+ functionArguments: [0, finalSliceIndex]
307
+ }
308
+ });
309
+ const metadata = addressMetadataArray[0];
310
+ return metadata.map((slice) => normalizeAddress(slice));
311
+ } catch (error) {
312
+ if (error instanceof Error && // Depending on the network, the error message may show up differently.
313
+ (error.message?.includes("sub_status: Some(404)") || error.message?.includes("E_SLICE_NOT_FOUND"))) {
314
+ return [];
315
+ }
316
+ throw error;
317
+ }
318
+ }
319
+ /**
320
+ * Gets the placement group address for a slice.
321
+ *
322
+ * @param sliceAddress - The address of the slice account.
323
+ * @returns The placement group address as a string.
324
+ */
325
+ async getPlacementGroupAddressForSlice(sliceAddress) {
326
+ const sliceMetadata = await this.aptos.view({
327
+ payload: {
328
+ function: `${this.deployer.toString()}::slice::get_slice_info`,
329
+ functionArguments: [sliceAddress.toString()]
330
+ }
331
+ });
332
+ return sliceMetadata[0].placement_group_assignments[0].placement_group_address;
333
+ }
334
+ /**
335
+ * Retrieves the designated storage providers for a slice.
336
+ *
337
+ * Designated SPs are those appointed to store data for their slots:
338
+ * - Active: Currently serving data
339
+ * - Receiving: Receiving data during slot transfer
340
+ * - Repairing: Repairing data after crash or failed transfer
341
+ * - Reconstructing: Reconstructing data if the repair fails
342
+ *
343
+ * @param params.account - The address of the slice account.
344
+ * @returns An array where result[i] is the designated SP for slot i, or null if no SP is designated.
345
+ *
346
+ * @example
347
+ * ```typescript
348
+ * const providers = await client.getDesignatedStorageProvidersForSlice({ account: sliceAddress });
349
+ * ```
350
+ */
351
+ async getDesignatedStorageProvidersForSlice(params) {
352
+ const placementGroupAddress = await this.getPlacementGroupAddressForSlice(
353
+ params.account
354
+ );
355
+ const rawMetadata = await this.aptos.view({
356
+ payload: {
357
+ function: `${this.deployer.toString()}::placement_group::get_designated_storage_providers`,
358
+ functionArguments: [placementGroupAddress]
359
+ }
360
+ });
361
+ const providers = rawMetadata[0];
362
+ return providers.map(
363
+ (opt) => opt.vec.length > 0 ? normalizeAddress(opt.vec[0]) : null
364
+ );
365
+ }
366
+ /**
367
+ * Retrieves the serving storage providers for a slice.
368
+ *
369
+ * Serving SPs are those that can respond to read requests. The serving logic is:
370
+ * - If an Active SP exists for a slot: Only the Active SP is serving
371
+ * - If no Active SP (transition in progress): Both Designated and Vacating SPs serve
372
+ *
373
+ * Each slot may have multiple serving SPs during transitions.
374
+ *
375
+ * @param params.account - The address of the slice account.
376
+ * @returns An array where result[i] contains the serving SPs for slot i.
377
+ *
378
+ * @example
379
+ * ```typescript
380
+ * const providers = await client.getServingStorageProvidersForSlice({ account: sliceAddress });
381
+ * ```
382
+ */
383
+ async getServingStorageProvidersForSlice(params) {
384
+ const placementGroupAddress = await this.getPlacementGroupAddressForSlice(
385
+ params.account
386
+ );
387
+ const rawMetadata = await this.aptos.view({
388
+ payload: {
389
+ function: `${this.deployer.toString()}::placement_group::get_serving_storage_providers`,
390
+ functionArguments: [placementGroupAddress]
391
+ }
392
+ });
393
+ const providers = rawMetadata[0];
394
+ return providers.map(
395
+ (slotProviders) => slotProviders.map((addr) => normalizeAddress(addr))
396
+ );
397
+ }
398
+ };
399
+
400
+ // src/core/clients/ShelbyClient.ts
401
+ import {
402
+ Aptos as Aptos3,
403
+ DEFAULT_TXN_TIMEOUT_SEC,
404
+ Network as Network3,
405
+ TransactionResponseType
406
+ } from "@aptos-labs/ts-sdk";
407
+ import pLimit from "p-limit";
408
+
409
+ // src/core/blobs.ts
410
+ var createBlobKey = (params) => {
411
+ return `@${normalizeAddress(params.account).toStringLongWithoutPrefix()}/${params.blobName}`;
412
+ };
413
+
414
+ // src/core/commitments.ts
415
+ import { Hex as Hex3 } from "@aptos-labs/ts-sdk";
416
+ import { z } from "zod";
417
+
418
+ // src/core/erasure/constants.ts
419
+ var ERASURE_CODE_PARAMS = {
420
+ ["ClayCode_16Total_10Data_13Helper" /* ClayCode_16Total_10Data_13Helper */]: {
421
+ // total chunks (data + parity)
422
+ erasure_n: 16,
423
+ // data chunks
424
+ erasure_k: 10,
425
+ // helper nodes
426
+ erasure_d: 13,
427
+ // enum index
428
+ enumIndex: 0
429
+ },
430
+ ["ClayCode_4Total_2Data_3Helper" /* ClayCode_4Total_2Data_3Helper */]: {
431
+ // total chunks (data + parity)
432
+ erasure_n: 4,
433
+ // data chunks
434
+ erasure_k: 2,
435
+ // helper nodes
436
+ erasure_d: 3,
437
+ // enum index
438
+ enumIndex: 1
439
+ }
440
+ };
441
+ var DEFAULT_ERASURE_N = ERASURE_CODE_PARAMS["ClayCode_16Total_10Data_13Helper" /* ClayCode_16Total_10Data_13Helper */].erasure_n;
442
+ var DEFAULT_ERASURE_K = ERASURE_CODE_PARAMS["ClayCode_16Total_10Data_13Helper" /* ClayCode_16Total_10Data_13Helper */].erasure_k;
443
+ var DEFAULT_ERASURE_D = ERASURE_CODE_PARAMS["ClayCode_16Total_10Data_13Helper" /* ClayCode_16Total_10Data_13Helper */].erasure_d;
444
+ var DEFAULT_ERASURE_M = DEFAULT_ERASURE_N - DEFAULT_ERASURE_K;
445
+
446
+ // src/core/chunk.ts
447
+ var CHUNK_SIZE_PARAMS = {
448
+ ["ChunkSet10MiB_Chunk1MiB" /* ChunkSet10MiB_Chunk1MiB */]: {
449
+ // 1MiB
450
+ chunkSizeBytes: 1 * 1024 * 1024,
451
+ // 10MiB
452
+ chunksetSizeBytes: 10 * 1024 * 1024
453
+ },
454
+ ["ChunkSet2MiB_Chunk1MiB" /* ChunkSet2MiB_Chunk1MiB */]: {
455
+ // 1MiB
456
+ chunkSizeBytes: 1 * 1024 * 1024,
457
+ // 2MiB
458
+ chunksetSizeBytes: 2 * 1024 * 1024
459
+ }
460
+ };
461
+ var DEFAULT_CHUNK_SIZE_BYTES = CHUNK_SIZE_PARAMS["ChunkSet10MiB_Chunk1MiB" /* ChunkSet10MiB_Chunk1MiB */].chunkSizeBytes;
462
+ var DEFAULT_CHUNKSET_SIZE_BYTES = CHUNK_SIZE_PARAMS["ChunkSet10MiB_Chunk1MiB" /* ChunkSet10MiB_Chunk1MiB */].chunksetSizeBytes;
463
+ var ERASURE_CODE_AND_CHUNK_MAPPING = {
464
+ ["ClayCode_16Total_10Data_13Helper" /* ClayCode_16Total_10Data_13Helper */]: {
465
+ ...CHUNK_SIZE_PARAMS.ChunkSet10MiB_Chunk1MiB
466
+ },
467
+ ["ClayCode_4Total_2Data_3Helper" /* ClayCode_4Total_2Data_3Helper */]: {
468
+ ...CHUNK_SIZE_PARAMS.ChunkSet2MiB_Chunk1MiB
469
+ }
470
+ };
471
+
472
+ // src/core/commitments.ts
473
+ var COMMITMENT_SCHEMA_VERSION = "1.3";
474
+ var ChunksetCommitmentSchema = z.object({
475
+ // Chunkset root (vector commitment of child chunks)
476
+ chunkset_root: z.string(),
477
+ // the size is known statically from the current configuration
478
+ chunk_commitments: z.array(z.string())
479
+ }).refine(
480
+ (data) => {
481
+ return data.chunk_commitments.length === DEFAULT_ERASURE_K + DEFAULT_ERASURE_M;
482
+ },
483
+ {
484
+ message: `Chunkset must have exactly ${DEFAULT_ERASURE_K + DEFAULT_ERASURE_M} chunks (ERASURE_K + ERASURE_M = ${DEFAULT_ERASURE_K} + ${DEFAULT_ERASURE_M})`,
485
+ path: ["chunk_commitments"]
486
+ }
487
+ );
488
+ function expectedTotalChunksets(rawSize, chunksetSize = DEFAULT_CHUNKSET_SIZE_BYTES) {
489
+ if (chunksetSize <= 0) {
490
+ throw new Error("chunksetSize must be positive");
491
+ }
492
+ if (rawSize === 0) return 1;
493
+ return Math.ceil(rawSize / chunksetSize);
494
+ }
495
+ var BlobCommitmentsSchema = z.object({
496
+ schema_version: z.string(),
497
+ raw_data_size: z.number(),
498
+ // FIXME I am not sure about this being here, or if it should be somewhere else
499
+ blob_merkle_root: z.string(),
500
+ chunkset_commitments: z.array(ChunksetCommitmentSchema)
501
+ }).refine(
502
+ (data) => {
503
+ return expectedTotalChunksets(data.raw_data_size) === data.chunkset_commitments.length;
504
+ },
505
+ {
506
+ message: "Total chunkset count mismatches with raw data size",
507
+ // FIXME put more details in here
508
+ path: ["chunkset_commitments"]
509
+ }
510
+ );
511
+ async function generateMerkleRoot(leafHashes) {
512
+ if (!leafHashes.length) {
513
+ throw new Error(
514
+ "An empty array cannot be used to construct a Merkle tree."
515
+ );
516
+ }
517
+ const zeroArray = new Uint8Array(leafHashes[0].toUint8Array().length);
518
+ const zeroBytes = Hex3.fromHexInput(zeroArray);
519
+ let currentLeaves = leafHashes;
520
+ while (currentLeaves.length > 1) {
521
+ if (currentLeaves.length % 2 !== 0) {
522
+ currentLeaves.push(zeroBytes);
523
+ }
524
+ const nextLeaves = [];
525
+ for (let i = 0; i < currentLeaves.length; i += 2) {
526
+ nextLeaves.push(
527
+ await concatHashes([
528
+ currentLeaves[i].toUint8Array(),
529
+ currentLeaves[i + 1].toUint8Array()
530
+ ])
531
+ );
532
+ }
533
+ currentLeaves = nextLeaves;
534
+ }
535
+ return currentLeaves[0];
536
+ }
537
+ async function generateChunksetCommitments(chunksetIdx, chunksetData, expectedChunksetSize, provider, onChunk) {
538
+ const { erasure_n } = provider.config;
539
+ const chunksetPayload = zeroPadBytes(chunksetData, expectedChunksetSize);
540
+ const { chunks } = provider.encode(chunksetPayload);
541
+ if (chunks.length !== erasure_n) {
542
+ throw new Error(
543
+ `Erasure provider produced ${chunks.length} chunks, expected ${erasure_n}.`
544
+ );
545
+ }
546
+ const chunkRoots = provider.getChunkMerkleRoots();
547
+ let chunkIdx = 0;
548
+ for (const chunkData of chunks) {
549
+ if (onChunk !== void 0) {
550
+ await onChunk(chunksetIdx, chunkIdx, chunkData);
551
+ }
552
+ chunkIdx += 1;
553
+ }
554
+ const a = await generateMerkleRoot(
555
+ chunkRoots.map((a2) => Hex3.fromHexInput(a2))
556
+ );
557
+ const entry = {
558
+ chunkset_root: a.toString(),
559
+ chunk_commitments: chunkRoots.map(
560
+ (chunk) => Hex3.fromHexInput(chunk).toString()
561
+ )
562
+ };
563
+ return { h: a, entry };
564
+ }
565
+ async function generateCommitments(provider, fullData, onChunk) {
566
+ const expectedChunksetSize = provider.config.chunkSizeBytes * provider.config.erasure_k;
567
+ const chunksetCommitments = [];
568
+ const chunksetCommitmentHashes = [];
569
+ let rawDataSize = 0;
570
+ const chunksetGen = readInChunks(fullData, expectedChunksetSize);
571
+ for await (const [chunksetIdx, chunksetData] of chunksetGen) {
572
+ rawDataSize += chunksetData.length;
573
+ const { h, entry } = await generateChunksetCommitments(
574
+ chunksetIdx,
575
+ chunksetData,
576
+ expectedChunksetSize,
577
+ provider,
578
+ onChunk
579
+ );
580
+ chunksetCommitments.push(entry);
581
+ chunksetCommitmentHashes.push(h);
582
+ }
583
+ if (rawDataSize === 0) {
584
+ const zeroChunkset = new Uint8Array(expectedChunksetSize);
585
+ const { h, entry } = await generateChunksetCommitments(
586
+ 0,
587
+ zeroChunkset,
588
+ expectedChunksetSize,
589
+ provider,
590
+ onChunk
591
+ );
592
+ chunksetCommitments.push(entry);
593
+ chunksetCommitmentHashes.push(h);
594
+ }
595
+ return {
596
+ schema_version: COMMITMENT_SCHEMA_VERSION,
597
+ raw_data_size: rawDataSize,
598
+ blob_merkle_root: (await generateMerkleRoot(chunksetCommitmentHashes)).toString(),
599
+ chunkset_commitments: chunksetCommitments
600
+ };
601
+ }
602
+
603
+ // src/core/erasure/clay-codes.ts
604
+ import {
605
+ createDecoder,
606
+ createEncoder
607
+ } from "@shelby-protocol/clay-codes";
608
+ function getTotalChunks(config) {
609
+ return config.erasure_n;
610
+ }
611
+ var ClayErasureCodingProvider = class _ClayErasureCodingProvider {
612
+ config;
613
+ encoderCache;
614
+ decoderCache;
615
+ lastFunction;
616
+ constructor(config) {
617
+ this.config = config;
618
+ this.lastFunction = "none" /* NONE */;
619
+ }
620
+ /**
621
+ * Static factory method to create an initialized ClayErasureCodingProvider
622
+ */
623
+ static async create(config) {
624
+ const provider = new _ClayErasureCodingProvider(config);
625
+ [provider.encoderCache, provider.decoderCache] = await Promise.all([
626
+ createEncoder({
627
+ n: getTotalChunks(config),
628
+ k: config.erasure_k,
629
+ d: config.erasure_d,
630
+ chunkSizeBytes: config.chunkSizeBytes
631
+ }),
632
+ createDecoder({
633
+ n: getTotalChunks(config),
634
+ k: config.erasure_k,
635
+ d: config.erasure_d,
636
+ chunkSizeBytes: config.chunkSizeBytes,
637
+ erasedChunkIndexes: []
638
+ })
639
+ ]);
640
+ return provider;
641
+ }
642
+ encode(data) {
643
+ const { erasure_k, chunkSizeBytes } = this.config;
644
+ if (!this.encoderCache) {
645
+ throw new Error("Encoder cache is missing");
646
+ }
647
+ const systematicCapacity = erasure_k * chunkSizeBytes;
648
+ if (data.byteLength > systematicCapacity) {
649
+ throw new Error(
650
+ `Data size ${data.byteLength} bytes exceeds systematic capacity ${systematicCapacity} bytes (erasure_k=${erasure_k} * chunkSizeBytes=${chunkSizeBytes}).`
651
+ );
652
+ }
653
+ if (this.requiresPadding(data.length)) {
654
+ throw new Error(
655
+ `Data size ${data.length} bytes does not match systematic capacity ${systematicCapacity} bytes (erasure_k=${erasure_k} * chunkSizeBytes=${chunkSizeBytes}). Provide pre-padded data before encoding.`
656
+ );
657
+ }
658
+ this.lastFunction = "encoded" /* ENCODED */;
659
+ return this.encoderCache.erasureCode(data);
660
+ }
661
+ decode(available, config) {
662
+ if (!this.decoderCache) {
663
+ throw new Error("Decoder cache is missing");
664
+ }
665
+ const { erasure_k, chunkSizeBytes } = this.config;
666
+ if (available.length < erasure_k) {
667
+ throw new Error(
668
+ `Insufficient available chunks: need at least ${erasure_k}, received ${available.length}.`
669
+ );
670
+ }
671
+ for (let i = 0; i < available.length; i++) {
672
+ const chunk = available[i];
673
+ if (chunk.length !== chunkSizeBytes) {
674
+ throw new Error(
675
+ `Chunk ${i} size ${chunk.length} bytes does not match expected chunkSizeBytes ${chunkSizeBytes}.`
676
+ );
677
+ }
678
+ }
679
+ this.lastFunction = "decoded" /* DECODED */;
680
+ return this.decoderCache.decode(available, config);
681
+ }
682
+ getChunkMerkleRoots() {
683
+ if (this.decoderCache && this.lastFunction === "decoded" /* DECODED */)
684
+ return this.decoderCache.getChunkMerkleRoots();
685
+ if (this.encoderCache && this.lastFunction === "encoded" /* ENCODED */)
686
+ return this.encoderCache.getChunkMerkleRoots();
687
+ throw new Error(
688
+ "You must call encode or decode before calling getChunkMerkleRoots"
689
+ );
690
+ }
691
+ /**
692
+ * Determines if data can be erasure coded as-is or requires padding.
693
+ *
694
+ * Data can be erasure coded without padding if its size exactly matches
695
+ * the total systematic data capacity (k * chunkSizeBytes).
696
+ *
697
+ * @param dataSize - Size of the data in bytes
698
+ * @returns true if data needs padding, false if it can be coded as-is
699
+ */
700
+ requiresPadding(dataSize) {
701
+ const { erasure_k, chunkSizeBytes } = this.config;
702
+ const systematicCapacity = erasure_k * chunkSizeBytes;
703
+ return dataSize !== systematicCapacity;
704
+ }
705
+ };
706
+
707
+ // src/core/erasure/default.ts
708
+ function defaultErasureCodingConfig() {
709
+ const encoding = Number(process.env.SHELBY_ENCODING) || 0;
710
+ if (encoding === 0) {
711
+ return erasureCodingConfig16Total10Data13Helper();
712
+ }
713
+ return erasureCodingConfig4Total2Data3Helper();
714
+ }
715
+ function erasureCodingConfig16Total10Data13Helper() {
716
+ return erasureCodingConfig(
717
+ "ClayCode_16Total_10Data_13Helper" /* ClayCode_16Total_10Data_13Helper */
718
+ );
719
+ }
720
+ function erasureCodingConfig4Total2Data3Helper() {
721
+ return erasureCodingConfig("ClayCode_4Total_2Data_3Helper" /* ClayCode_4Total_2Data_3Helper */);
722
+ }
723
+ function erasureCodingConfig(encodingScheme) {
724
+ return {
725
+ erasure_n: ERASURE_CODE_PARAMS[encodingScheme].erasure_n,
726
+ erasure_k: ERASURE_CODE_PARAMS[encodingScheme].erasure_k,
727
+ erasure_d: ERASURE_CODE_PARAMS[encodingScheme].erasure_d,
728
+ chunkSizeBytes: DEFAULT_CHUNK_SIZE_BYTES,
729
+ enumIndex: ERASURE_CODE_PARAMS[encodingScheme].enumIndex
730
+ };
731
+ }
732
+
733
+ // src/core/erasure/reed-solomon.ts
734
+ import { createWasmReedSolomonBinding } from "@shelby-protocol/reed-solomon";
735
+ var DEFAULT_CHUNK_SIZE_BYTES2 = 2 * 1024 * 1024;
736
+
737
+ // src/core/clients/ShelbyBlobClient.ts
738
+ import {
739
+ AccountAddress as AccountAddress3,
740
+ Aptos as Aptos2,
741
+ Hex as Hex4,
742
+ U32
743
+ } from "@aptos-labs/ts-sdk";
744
+
745
+ // src/core/operations/index.ts
746
+ import { Network as Network2 } from "@aptos-labs/ts-sdk";
747
+ import { GraphQLClient } from "graphql-request";
748
+
749
+ // src/core/operations/generated/sdk.ts
750
+ import gql from "graphql-tag";
751
+ var GetBlobsDocument = gql`
752
+ query getBlobs($where: blobs_bool_exp, $orderBy: [blobs_order_by!], $limit: Int, $offset: Int) {
753
+ blobs(where: $where, order_by: $orderBy, limit: $limit, offset: $offset) {
754
+ owner
755
+ blob_commitment
756
+ blob_name
757
+ created_at
758
+ expires_at
759
+ num_chunksets
760
+ is_deleted
761
+ is_written
762
+ placement_group
763
+ size
764
+ updated_at
765
+ slice_address
766
+ }
767
+ }
768
+ `;
769
+ var GetBlobActivitiesDocument = gql`
770
+ query getBlobActivities($where: blob_activities_bool_exp, $orderBy: [blob_activities_order_by!], $limit: Int, $offset: Int) {
771
+ blob_activities(
772
+ where: $where
773
+ order_by: $orderBy
774
+ limit: $limit
775
+ offset: $offset
776
+ ) {
777
+ blob_name
778
+ event_index
779
+ event_type
780
+ transaction_hash
781
+ transaction_version
782
+ timestamp
783
+ owner
784
+ }
785
+ }
786
+ `;
787
+ var GetBlobsCountDocument = gql`
788
+ query getBlobsCount($where: blobs_bool_exp) {
789
+ blobs_aggregate(where: $where) {
790
+ aggregate {
791
+ count
792
+ }
793
+ }
794
+ }
795
+ `;
796
+ var GetBlobActivitiesCountDocument = gql`
797
+ query getBlobActivitiesCount($where: blob_activities_bool_exp) {
798
+ blob_activities_aggregate(where: $where) {
799
+ aggregate {
800
+ count
801
+ }
802
+ }
803
+ }
804
+ `;
805
+ var GetTotalBlobsSizeDocument = gql`
806
+ query getTotalBlobsSize($where: blobs_bool_exp) {
807
+ blobs_aggregate(where: $where) {
808
+ aggregate {
809
+ sum {
810
+ size
811
+ }
812
+ }
813
+ }
814
+ }
815
+ `;
816
+ var GetPlacementGroupSlotsDocument = gql`
817
+ query getPlacementGroupSlots($where: placement_group_slots_bool_exp, $orderBy: [placement_group_slots_order_by!], $limit: Int, $offset: Int) {
818
+ placement_group_slots(
819
+ where: $where
820
+ order_by: $orderBy
821
+ limit: $limit
822
+ offset: $offset
823
+ ) {
824
+ placement_group
825
+ slot_index
826
+ storage_provider
827
+ status
828
+ updated_at
829
+ }
830
+ }
831
+ `;
832
+ var GetPlacementGroupSlotsCountDocument = gql`
833
+ query getPlacementGroupSlotsCount($where: placement_group_slots_bool_exp) {
834
+ placement_group_slots_aggregate(where: $where) {
835
+ aggregate {
836
+ count
837
+ }
838
+ }
839
+ }
840
+ `;
841
+ var GetProcessorStatusDocument = gql`
842
+ query getProcessorStatus {
843
+ processor_status {
844
+ last_success_version
845
+ last_transaction_timestamp
846
+ last_updated
847
+ }
848
+ }
849
+ `;
850
+ var defaultWrapper = (action, _operationName, _operationType, _variables) => action();
851
+ function getSdk(client, withWrapper = defaultWrapper) {
852
+ return {
853
+ getBlobs(variables, requestHeaders, signal) {
854
+ return withWrapper((wrappedRequestHeaders) => client.request({ document: GetBlobsDocument, variables, requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders }, signal }), "getBlobs", "query", variables);
855
+ },
856
+ getBlobActivities(variables, requestHeaders, signal) {
857
+ return withWrapper((wrappedRequestHeaders) => client.request({ document: GetBlobActivitiesDocument, variables, requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders }, signal }), "getBlobActivities", "query", variables);
858
+ },
859
+ getBlobsCount(variables, requestHeaders, signal) {
860
+ return withWrapper((wrappedRequestHeaders) => client.request({ document: GetBlobsCountDocument, variables, requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders }, signal }), "getBlobsCount", "query", variables);
861
+ },
862
+ getBlobActivitiesCount(variables, requestHeaders, signal) {
863
+ return withWrapper((wrappedRequestHeaders) => client.request({ document: GetBlobActivitiesCountDocument, variables, requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders }, signal }), "getBlobActivitiesCount", "query", variables);
864
+ },
865
+ getTotalBlobsSize(variables, requestHeaders, signal) {
866
+ return withWrapper((wrappedRequestHeaders) => client.request({ document: GetTotalBlobsSizeDocument, variables, requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders }, signal }), "getTotalBlobsSize", "query", variables);
867
+ },
868
+ getPlacementGroupSlots(variables, requestHeaders, signal) {
869
+ return withWrapper((wrappedRequestHeaders) => client.request({ document: GetPlacementGroupSlotsDocument, variables, requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders }, signal }), "getPlacementGroupSlots", "query", variables);
870
+ },
871
+ getPlacementGroupSlotsCount(variables, requestHeaders, signal) {
872
+ return withWrapper((wrappedRequestHeaders) => client.request({ document: GetPlacementGroupSlotsCountDocument, variables, requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders }, signal }), "getPlacementGroupSlotsCount", "query", variables);
873
+ },
874
+ getProcessorStatus(variables, requestHeaders, signal) {
875
+ return withWrapper((wrappedRequestHeaders) => client.request({ document: GetProcessorStatusDocument, variables, requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders }, signal }), "getProcessorStatus", "query", variables);
876
+ }
877
+ };
878
+ }
879
+
880
+ // src/core/operations/index.ts
881
+ function createShelbyIndexerClient(baseUrl, options) {
882
+ const graphqlClient = new GraphQLClient(baseUrl, options);
883
+ return getSdk(graphqlClient);
884
+ }
885
+ function getShelbyIndexerClient(config) {
886
+ const aptosConfig = getAptosConfig(config);
887
+ let { apiKey: indexerApiKey, baseUrl } = config.indexer ?? {};
888
+ if (!baseUrl) {
889
+ switch (aptosConfig?.network) {
890
+ // TODO: Add endpoints for core networks
891
+ case Network2.MAINNET:
892
+ case Network2.TESTNET:
893
+ case Network2.DEVNET:
894
+ case Network2.SHELBYNET:
895
+ case Network2.LOCAL:
896
+ baseUrl = NetworkToShelbyBlobIndexerBaseUrl[aptosConfig.network];
897
+ break;
898
+ }
899
+ }
900
+ if (baseUrl === void 0) {
901
+ throw new Error(
902
+ "The ShelbyClientConfig does not support the Shelby indexer. Please configure the endpoint in the ShelbyClientConfig.indexer.endpoint or provide a supported Aptos network."
903
+ );
904
+ }
905
+ const apiKey = indexerApiKey ?? config.apiKey;
906
+ return createShelbyIndexerClient(baseUrl, {
907
+ headers: {
908
+ ...apiKey ? { Authorization: `Bearer ${apiKey}` } : {},
909
+ "x-aptos-client": "shelby-ts-sdk"
910
+ }
911
+ });
912
+ }
913
+
914
+ // src/core/clients/ShelbyBlobClient.ts
915
+ var MissingTransactionSubmitterError = class extends Error {
916
+ constructor() {
917
+ super(
918
+ "USD sponsorship (usdSponsor) requires a transaction submitter to be configured. The sponsored transaction is a multi-agent transaction that must be co-signed by the sponsor. Configure a transaction submitter via aptos.pluginSettings.TRANSACTION_SUBMITTER that routes transactions to a service (like a gas station) capable of providing the sponsor's signature."
919
+ );
920
+ this.name = "MissingTransactionSubmitterError";
921
+ }
922
+ };
923
+ var ShelbyBlobClient = class _ShelbyBlobClient {
924
+ aptos;
925
+ deployer;
926
+ indexer;
927
+ defaultOptions;
928
+ orderless;
929
+ /**
930
+ * The ShelbyBlobClient is used to interact with the Shelby contract on the Aptos blockchain. This
931
+ * includes functions for registering blob commitments and retrieving blob metadata.
932
+ *
933
+ * @param config - The client configuration object.
934
+ * @param config.network - The Shelby network to use.
935
+ * @param defaultOptions - Optional default options for blob operations.
936
+ *
937
+ * @example
938
+ * ```typescript
939
+ * const blobClient = new ShelbyBlobClient({
940
+ * aptos: {
941
+ * network: Network.SHELBYNET,
942
+ * clientConfig: {
943
+ * API_KEY: "AG-***",
944
+ * },
945
+ * },
946
+ * });
947
+ * ```
948
+ *
949
+ * @example
950
+ * ```typescript
951
+ * // With default options for USD sponsorship
952
+ * const blobClient = new ShelbyBlobClient(
953
+ * {
954
+ * network: Network.SHELBYNET,
955
+ * aptos: {
956
+ * pluginSettings: {
957
+ * TRANSACTION_SUBMITTER: myGasStationSubmitter,
958
+ * },
959
+ * },
960
+ * },
961
+ * {
962
+ * usdSponsor: { feePayerAddress: sponsorAddress },
963
+ * }
964
+ * );
965
+ * ```
966
+ */
967
+ constructor(config, defaultOptions) {
968
+ this.aptos = new Aptos2(getAptosConfig(config));
969
+ this.deployer = config.deployer ?? AccountAddress3.fromString(SHELBY_DEPLOYER);
970
+ this.indexer = getShelbyIndexerClient(config);
971
+ this.defaultOptions = defaultOptions ?? {};
972
+ this.orderless = config.orderless ?? false;
973
+ }
974
+ /**
975
+ * Merges method-level options with default options, giving precedence to method-level values.
976
+ */
977
+ mergeOptions(options) {
978
+ return {
979
+ build: options?.build ?? this.defaultOptions.build,
980
+ submit: options?.submit ?? this.defaultOptions.submit,
981
+ usdSponsor: options?.usdSponsor ?? this.defaultOptions.usdSponsor,
982
+ chunksetSizeBytes: options?.chunksetSizeBytes ?? this.defaultOptions.chunksetSizeBytes
983
+ };
984
+ }
985
+ /**
986
+ * Validates that if USD sponsorship is requested, a transaction submitter is
987
+ * configured as well. Checks both the client-level and method-level transaction
988
+ * submitter configurations. Throws MissingTransactionSubmitterError if usdSponsor is
989
+ * provided without a transaction submitter.
990
+ */
991
+ validateUsdSponsorConfig(usdSponsor, submit) {
992
+ if (!usdSponsor) {
993
+ return;
994
+ }
995
+ const hasClientSubmitter = this.aptos.config.getTransactionSubmitter();
996
+ const hasMethodSubmitter = submit?.transactionSubmitter !== void 0 && submit?.transactionSubmitter !== null;
997
+ if (!hasClientSubmitter && !hasMethodSubmitter) {
998
+ throw new MissingTransactionSubmitterError();
999
+ }
1000
+ }
1001
+ /**
1002
+ * Merges orderless replay protection into transaction options when
1003
+ * `config.orderless` is enabled. If the caller already supplies options
1004
+ * (e.g. custom gas limits), those are preserved and the nonce is injected
1005
+ * alongside them. When orderless mode is off, user options are returned as-is.
1006
+ */
1007
+ orderlessTxOptions(userOptions) {
1008
+ if (!this.orderless) return userOptions;
1009
+ return {
1010
+ replayProtectionNonce: crypto.getRandomValues(new Uint32Array(1))[0],
1011
+ ...userOptions
1012
+ };
1013
+ }
1014
+ /**
1015
+ * Retrieves the blob metadata from the blockchain. If it does not exist,
1016
+ * returns `undefined`.
1017
+ *
1018
+ * @param params.account - The account namespace the blob is stored in (e.g. "0x1")
1019
+ * @param params.name - The name of the blob (e.g. "foo/bar")
1020
+ * @returns The blob metadata.
1021
+ *
1022
+ * @example
1023
+ * ```typescript
1024
+ * const metadata = await client.getBlobMetadata({
1025
+ * account: AccountAddress.fromString("0x1"),
1026
+ * name: "foo/bar.txt",
1027
+ * });
1028
+ * ```
1029
+ */
1030
+ async getBlobMetadata(params) {
1031
+ try {
1032
+ const rawMetadata = await this.aptos.view({
1033
+ payload: {
1034
+ function: `${this.deployer.toString()}::blob_metadata::get_blob_metadata`,
1035
+ functionArguments: [
1036
+ createBlobKey({
1037
+ account: params.account,
1038
+ blobName: params.name
1039
+ })
1040
+ ]
1041
+ }
1042
+ });
1043
+ if (!rawMetadata?.[0]?.vec?.[0]) {
1044
+ return void 0;
1045
+ }
1046
+ const metadata = rawMetadata[0].vec[0];
1047
+ let encoding;
1048
+ if (metadata.encoding.__variant__ === "ClayCode_16Total_10Data_13Helper") {
1049
+ encoding = {
1050
+ variant: "clay",
1051
+ ...ERASURE_CODE_PARAMS[metadata.encoding.__variant__],
1052
+ ...ERASURE_CODE_AND_CHUNK_MAPPING[metadata.encoding.__variant__]
1053
+ };
1054
+ } else if (metadata.encoding.__variant__ === "ClayCode_4Total_2Data_3Helper") {
1055
+ encoding = {
1056
+ variant: "clay",
1057
+ ...ERASURE_CODE_PARAMS[metadata.encoding.__variant__],
1058
+ ...ERASURE_CODE_AND_CHUNK_MAPPING[metadata.encoding.__variant__]
1059
+ };
1060
+ } else {
1061
+ throw new Error(
1062
+ "Could not parse encoding from Shelby Smart Contract, this SDK is out of date."
1063
+ );
1064
+ }
1065
+ return {
1066
+ blobMerkleRoot: Hex4.fromHexInput(
1067
+ metadata.blob_commitment
1068
+ ).toUint8Array(),
1069
+ owner: normalizeAddress(metadata.owner),
1070
+ name: params.name,
1071
+ blobNameSuffix: getBlobNameSuffix(params.name),
1072
+ size: Number(metadata.blob_size),
1073
+ encoding,
1074
+ expirationMicros: Number(metadata.expiration_micros),
1075
+ creationMicros: Number(metadata.creation_micros),
1076
+ sliceAddress: normalizeAddress(metadata.slice.inner),
1077
+ isWritten: metadata.is_written
1078
+ };
1079
+ } catch (error) {
1080
+ if (error instanceof Error && // Depending on the network, the error message may show up differently.
1081
+ (error.message?.includes("sub_status: Some(404)") || error.message?.includes("EBLOB_NOT_FOUND"))) {
1082
+ return void 0;
1083
+ }
1084
+ throw error;
1085
+ }
1086
+ }
1087
+ /**
1088
+ * Retrieves all the blobs and their metadata for an account from the
1089
+ * blockchain.
1090
+ *
1091
+ * @param params.account - The account namespace the blobs are stored in (e.g. "0x1")
1092
+ * @param params.pagination (optional) - The pagination options.
1093
+ * @param params.orderBy (optional) - The order by clause to sort the blobs by.
1094
+ * @returns The blob metadata for all the blobs for the account.
1095
+ *
1096
+ * @example
1097
+ * ```typescript
1098
+ * // BlobMetadata[]
1099
+ * const blobs = await client.getAccountBlobs({
1100
+ * account: AccountAddress.fromString("0x1"),
1101
+ * });
1102
+ * ```
1103
+ */
1104
+ getAccountBlobs(params) {
1105
+ const { where, ...rest } = params;
1106
+ return this.getBlobs({
1107
+ where: {
1108
+ ...where,
1109
+ owner: { _eq: normalizeAddress(params.account).toString() }
1110
+ },
1111
+ pagination: rest.pagination,
1112
+ orderBy: rest.orderBy
1113
+ });
1114
+ }
1115
+ /**
1116
+ * Retrieves blobs and their metadata from the blockchain.
1117
+ *
1118
+ * @param params.where (optional) - The where clause to filter the blobs by.
1119
+ * @param params.pagination (optional) - The pagination options.
1120
+ * @param params.orderBy (optional) - The order by clause to sort the blobs by.
1121
+ * @returns The blob metadata for all the blobs that match the where clause.
1122
+ *
1123
+ * @example
1124
+ * ```typescript
1125
+ * // BlobMetadata[]
1126
+ * const blobs = await client.getBlobs({
1127
+ * where: { owner: { _eq: AccountAddress.fromString("0x1").toString() } },
1128
+ * });
1129
+ * ```
1130
+ */
1131
+ async getBlobs(params = {}) {
1132
+ const { limit, offset } = params.pagination ?? {};
1133
+ const { orderBy, where } = params;
1134
+ const currentMicros = String(Date.now() * 1e3);
1135
+ const defaultActiveFilter = {
1136
+ expires_at: { _gte: currentMicros },
1137
+ is_deleted: { _eq: "0" }
1138
+ };
1139
+ const finalWhere = where !== void 0 ? { ...defaultActiveFilter, ...where } : defaultActiveFilter;
1140
+ const { blobs } = await this.indexer.getBlobs({
1141
+ where: finalWhere,
1142
+ limit,
1143
+ offset,
1144
+ orderBy
1145
+ });
1146
+ return blobs.map(
1147
+ (blob) => ({
1148
+ owner: normalizeAddress(blob.owner),
1149
+ name: blob.blob_name,
1150
+ blobNameSuffix: getBlobNameSuffix(blob.blob_name),
1151
+ blobMerkleRoot: Hex4.fromHexInput(blob.blob_commitment).toUint8Array(),
1152
+ size: Number(blob.size),
1153
+ // TODO: Add encoding when supported in NCI
1154
+ encoding: {
1155
+ variant: "clay",
1156
+ ...ERASURE_CODE_PARAMS.ClayCode_16Total_10Data_13Helper,
1157
+ ...ERASURE_CODE_AND_CHUNK_MAPPING.ClayCode_16Total_10Data_13Helper
1158
+ },
1159
+ expirationMicros: Number(blob.expires_at),
1160
+ creationMicros: Number(blob.created_at),
1161
+ sliceAddress: normalizeAddress(blob.slice_address),
1162
+ isWritten: Boolean(Number(blob.is_written)),
1163
+ isDeleted: Boolean(Number(blob.is_deleted))
1164
+ })
1165
+ );
1166
+ }
1167
+ async getBlobActivities(params) {
1168
+ const { limit, offset } = params.pagination ?? {};
1169
+ const { orderBy, where } = params;
1170
+ const { blob_activities } = await this.indexer.getBlobActivities({
1171
+ where,
1172
+ limit,
1173
+ offset,
1174
+ orderBy
1175
+ });
1176
+ const activityTypeMapping = {
1177
+ [`${this.deployer.toStringLong()}::blob_metadata::BlobRegisteredEvent`]: "register_blob",
1178
+ [`${this.deployer.toStringLong()}::blob_metadata::BlobDeletedEvent`]: "delete_blob",
1179
+ [`${this.deployer.toStringLong()}::blob_metadata::BlobExpirationExtendedEvent`]: "extend_blob_expiration",
1180
+ [`${this.deployer.toStringLong()}::blob_metadata::BlobWrittenEvent`]: "write_blob"
1181
+ };
1182
+ return blob_activities.map(
1183
+ (activity) => ({
1184
+ blobName: activity.blob_name,
1185
+ accountAddress: normalizeAddress(activity.blob_name.substring(1, 65)),
1186
+ type: activityTypeMapping[activity.event_type] ?? "unknown",
1187
+ eventType: activity.event_type,
1188
+ eventIndex: Number(activity.event_index),
1189
+ transactionHash: activity.transaction_hash,
1190
+ // Using Number here in JS is technically not okay because txn version can be
1191
+ // as large as u64::MAX, but it should be fine for a long while.
1192
+ transactionVersion: Number(activity.transaction_version),
1193
+ timestamp: `${activity.timestamp}Z`
1194
+ })
1195
+ );
1196
+ }
1197
+ /**
1198
+ * Retrieves the total number of blobs from the blockchain.
1199
+ *
1200
+ * @param params.where (optional) - The where clause to filter the blobs by.
1201
+ * @returns The total number of blobs.
1202
+ *
1203
+ * @example
1204
+ * ```typescript
1205
+ * const count = await client.getBlobsCount();
1206
+ * ```
1207
+ */
1208
+ async getBlobsCount(params) {
1209
+ const { where } = params;
1210
+ const { blobs_aggregate } = await this.indexer.getBlobsCount({ where });
1211
+ return blobs_aggregate?.aggregate?.count ?? 0;
1212
+ }
1213
+ /**
1214
+ * Retrieves the total size of blobs from the blockchain.
1215
+ *
1216
+ * @param params.where (optional) - The where clause to filter the blobs by.
1217
+ * @returns The total size of blobs in bytes.
1218
+ *
1219
+ * @example
1220
+ * ```typescript
1221
+ * const size = await client.getTotalBlobsSize();
1222
+ * ```
1223
+ */
1224
+ async getTotalBlobsSize(params = {}) {
1225
+ const { where } = params;
1226
+ const { blobs_aggregate } = await this.indexer.getTotalBlobsSize({ where });
1227
+ return Number(blobs_aggregate?.aggregate?.sum?.size ?? 0);
1228
+ }
1229
+ /**
1230
+ * Retrieves the total number of blob activities from the blockchain.
1231
+ *
1232
+ * @param params.where (optional) - The where clause to filter the blob activities by.
1233
+ * @returns The total number of blob activities.
1234
+ *
1235
+ * @example
1236
+ * ```typescript
1237
+ * const count = await client.getBlobActivitiesCount();
1238
+ * ```
1239
+ */
1240
+ async getBlobActivitiesCount(params) {
1241
+ const { where } = params;
1242
+ const { blob_activities_aggregate } = await this.indexer.getBlobActivitiesCount({ where });
1243
+ return blob_activities_aggregate?.aggregate?.count ?? 0;
1244
+ }
1245
+ /**
1246
+ * Registers a blob on the blockchain by writing its merkle root and metadata.
1247
+ *
1248
+ * @param params.account - The account that is signing and paying for the transaction.
1249
+ * @param params.blobName - The name/path of the blob (e.g. "foo/bar.txt").
1250
+ * @param params.blobMerkleRoot - The merkle root of the blob commitments.
1251
+ * @param params.size - The size of the blob in bytes.
1252
+ * @param params.expirationMicros - The expiration time of the blob in microseconds.
1253
+ * @param params.options - Optional transaction building options.
1254
+ * @param params.options.chunksetSizeBytes - Custom chunkset size (defaults to DEFAULT_CHUNKSET_SIZE_BYTES).
1255
+ * @param params.options.build - Additional Aptos transaction building options.
1256
+ *
1257
+ * @returns An object containing the pending transaction.
1258
+ *
1259
+ * @example
1260
+ * ```typescript
1261
+ * const provider = await ClayErasureCodingProvider.create();
1262
+ * const blobCommitments = await generateCommitments(provider, data);
1263
+ *
1264
+ * const { transaction } = await client.registerBlob({
1265
+ * account: signer,
1266
+ * blobName: "foo/bar.txt",
1267
+ * blobMerkleRoot: blobCommitments.blob_merkle_root,
1268
+ * size: data.length,
1269
+ * expirationMicros: Date.now() * 1000 + 3600_000_000, // 1 hour from now in microseconds
1270
+ * });
1271
+ * ```
1272
+ */
1273
+ async registerBlob(params) {
1274
+ const options = this.mergeOptions(params.options);
1275
+ this.validateUsdSponsorConfig(options.usdSponsor, options.submit);
1276
+ const config = params.config ?? defaultErasureCodingConfig();
1277
+ const chunksetSize = config.chunkSizeBytes * config.erasure_k;
1278
+ const buildArgs = {
1279
+ ...options.build,
1280
+ options: this.orderlessTxOptions(options.build?.options),
1281
+ data: _ShelbyBlobClient.createRegisterBlobPayload({
1282
+ deployer: this.deployer,
1283
+ account: params.account.accountAddress,
1284
+ blobName: params.blobName,
1285
+ blobSize: params.size,
1286
+ blobMerkleRoot: params.blobMerkleRoot,
1287
+ numChunksets: expectedTotalChunksets(params.size, chunksetSize),
1288
+ expirationMicros: params.expirationMicros,
1289
+ useSponsoredUsdVariant: options.usdSponsor !== void 0,
1290
+ encoding: config.enumIndex
1291
+ }),
1292
+ sender: params.account.accountAddress
1293
+ };
1294
+ const transaction = options.usdSponsor ? await this.aptos.transaction.build.multiAgent({
1295
+ ...buildArgs,
1296
+ secondarySignerAddresses: [options.usdSponsor.feePayerAddress]
1297
+ }) : await this.aptos.transaction.build.simple(buildArgs);
1298
+ return {
1299
+ transaction: await this.aptos.signAndSubmitTransaction({
1300
+ signer: params.account,
1301
+ transaction,
1302
+ ...options.submit
1303
+ })
1304
+ };
1305
+ }
1306
+ /**
1307
+ * Deletes a blob on the blockchain.
1308
+ *
1309
+ * @param params.account - The account that is signing and paying for the transaction.
1310
+ * @param params.blobName - The name/path of the blob (e.g. "foo/bar.txt").
1311
+ * @param params.options - Optional transaction building options.
1312
+ *
1313
+ * @returns An object containing the pending transaction.
1314
+ *
1315
+ * @example
1316
+ * ```typescript
1317
+ *
1318
+ * const { transaction } = await client.deleteBlob({
1319
+ * account: signer,
1320
+ * blobName: "foo/bar.txt",
1321
+ * });
1322
+ * ```
1323
+ */
1324
+ async deleteBlob(params) {
1325
+ const transaction = await this.aptos.transaction.build.simple({
1326
+ options: this.orderlessTxOptions(params.options),
1327
+ data: _ShelbyBlobClient.createDeleteBlobPayload({
1328
+ deployer: this.deployer,
1329
+ blobName: params.blobName
1330
+ }),
1331
+ sender: params.account.accountAddress
1332
+ });
1333
+ return {
1334
+ transaction: await this.aptos.signAndSubmitTransaction({
1335
+ signer: params.account,
1336
+ transaction
1337
+ })
1338
+ };
1339
+ }
1340
+ /**
1341
+ * Deletes multiple blobs on the blockchain in a single atomic transaction.
1342
+ *
1343
+ * **Note:** This function requires the `delete_multiple_blobs` entry function
1344
+ * which will be deployed to the smart contract on 2026-02-04. Using this
1345
+ * function before that date will result in a transaction failure.
1346
+ *
1347
+ * This operation is atomic: if any blob deletion fails (e.g., blob not found),
1348
+ * the entire transaction fails and no blobs are deleted.
1349
+ *
1350
+ * @param params.account - The account that is signing and paying for the transaction.
1351
+ * @param params.blobNames - Array of blob name suffixes without the account address prefix
1352
+ * (e.g. ["foo/bar.txt", "baz.txt"], NOT ["0x1/foo/bar.txt"]). The account address
1353
+ * prefix is automatically derived from the signer.
1354
+ * @param params.options - Optional transaction building options.
1355
+ *
1356
+ * @returns An object containing the pending transaction.
1357
+ *
1358
+ * @example
1359
+ * ```typescript
1360
+ *
1361
+ * const { transaction } = await client.deleteMultipleBlobs({
1362
+ * account: signer,
1363
+ * blobNames: ["foo/bar.txt", "baz.txt"],
1364
+ * });
1365
+ * ```
1366
+ */
1367
+ async deleteMultipleBlobs(params) {
1368
+ const transaction = await this.aptos.transaction.build.simple({
1369
+ options: this.orderlessTxOptions(params.options),
1370
+ data: _ShelbyBlobClient.createDeleteMultipleBlobsPayload({
1371
+ deployer: this.deployer,
1372
+ blobNames: params.blobNames
1373
+ }),
1374
+ sender: params.account.accountAddress
1375
+ });
1376
+ return {
1377
+ transaction: await this.aptos.signAndSubmitTransaction({
1378
+ signer: params.account,
1379
+ transaction
1380
+ })
1381
+ };
1382
+ }
1383
+ /**
1384
+ * Registers multiple blobs on the blockchain by writing their merkle roots and metadata.
1385
+ *
1386
+ * @param params.account - The account that is signing and paying for the transaction.
1387
+ * @param params.expirationMicros - The expiration time of the blobs in microseconds.
1388
+ * @param params.blobs - The blobs to register.
1389
+ * @param params.blobs.blobName - The name/path of the blob (e.g. "foo/bar.txt").
1390
+ * @param params.blobs.blobSize - The size of the blob in bytes.
1391
+ * @param params.blobs.blobMerkleRoot - The merkle root of the blob commitments as a hex string.
1392
+ * @param params.options - Optional transaction building options.
1393
+ * @param params.options.chunksetSizeBytes - Custom chunkset size (defaults to DEFAULT_CHUNKSET_SIZE_BYTES).
1394
+ * @param params.options.build - Additional Aptos transaction building options.
1395
+ *
1396
+ * @returns An object containing the pending transaction.
1397
+ *
1398
+ * @example
1399
+ * ```typescript
1400
+ * const provider = await ClayErasureCodingProvider.create();
1401
+ * const blobCommitments = await generateCommitments(provider, data);
1402
+ *
1403
+ * const { transaction } = await client.batchRegisterBlobs({
1404
+ * account: signer,
1405
+ * expirationMicros: Date.now() * 1000 + 3600_000_000, // 1 hour from now in microseconds
1406
+ * blobs: [
1407
+ * {
1408
+ * blobName: "foo/bar.txt",
1409
+ * blobSize: data.length,
1410
+ * blobMerkleRoot: blobCommitments.blob_merkle_root,
1411
+ * },
1412
+ * ],
1413
+ * });
1414
+ * ```
1415
+ */
1416
+ async batchRegisterBlobs(params) {
1417
+ const options = this.mergeOptions(params.options);
1418
+ this.validateUsdSponsorConfig(options.usdSponsor, options.submit);
1419
+ const config = params.config ?? defaultErasureCodingConfig();
1420
+ const chunksetSize = config.chunkSizeBytes * config.erasure_k;
1421
+ const buildArgs = {
1422
+ ...options.build,
1423
+ options: this.orderlessTxOptions(options.build?.options),
1424
+ sender: params.account.accountAddress,
1425
+ data: _ShelbyBlobClient.createBatchRegisterBlobsPayload({
1426
+ deployer: this.deployer,
1427
+ account: params.account.accountAddress,
1428
+ expirationMicros: params.expirationMicros,
1429
+ blobs: params.blobs.map((blob) => ({
1430
+ blobName: blob.blobName,
1431
+ blobSize: blob.blobSize,
1432
+ blobMerkleRoot: blob.blobMerkleRoot,
1433
+ numChunksets: expectedTotalChunksets(blob.blobSize, chunksetSize)
1434
+ })),
1435
+ useSponsoredUsdVariant: options.usdSponsor !== void 0,
1436
+ encoding: config.enumIndex
1437
+ })
1438
+ };
1439
+ const transaction = options.usdSponsor ? await this.aptos.transaction.build.multiAgent({
1440
+ ...buildArgs,
1441
+ secondarySignerAddresses: [options.usdSponsor.feePayerAddress]
1442
+ }) : await this.aptos.transaction.build.simple(buildArgs);
1443
+ return {
1444
+ transaction: await this.aptos.signAndSubmitTransaction({
1445
+ signer: params.account,
1446
+ transaction,
1447
+ ...options.submit
1448
+ })
1449
+ };
1450
+ }
1451
+ /**
1452
+ * Creates a transaction payload to register a blob on the blockchain.
1453
+ * This is a static helper method for constructing the Move function call payload.
1454
+ *
1455
+ * @param params.deployer - Optional deployer account address. Defaults to SHELBY_DEPLOYER.
1456
+ * @param params.account - The account that will own the blob.
1457
+ * @param params.blobName - The name/path of the blob (e.g. "foo/bar.txt").
1458
+ * @param params.blobSize - The size of the blob in bytes.
1459
+ * @param params.blobMerkleRoot - The merkle root of the blob commitments as a hex string.
1460
+ * @param params.expirationMicros - The expiration time of the blob in microseconds.
1461
+ * @param params.numChunksets - The total number of chunksets in the blob.
1462
+ *
1463
+ * @returns An Aptos transaction payload data object for the register_blob Move function.
1464
+ *
1465
+ * @see https://github.com/shelby/shelby/blob/e08e84742cf2b80ad8bb7227deb3013398076d53/move/shelby_contract/sources/global_metadata.move#L357
1466
+ */
1467
+ static createRegisterBlobPayload(params) {
1468
+ const functionName = params.useSponsoredUsdVariant ? "register_blob_with_sponsor" : "register_blob";
1469
+ return {
1470
+ function: `${(params.deployer ?? SHELBY_DEPLOYER).toString()}::blob_metadata::${functionName}`,
1471
+ functionArguments: [
1472
+ params.blobName,
1473
+ params.expirationMicros,
1474
+ Hex4.fromHexString(params.blobMerkleRoot).toUint8Array(),
1475
+ params.numChunksets,
1476
+ params.blobSize,
1477
+ // TODO
1478
+ 0,
1479
+ // payment tier
1480
+ params.encoding
1481
+ ]
1482
+ };
1483
+ }
1484
+ /**
1485
+ * Creates a transaction payload to register multiple blobs on the blockchain.
1486
+ * This is a static helper method for constructing the Move function call payload.
1487
+ *
1488
+ * @param params.deployer - Optional deployer account address. Defaults to SHELBY_DEPLOYER.
1489
+ * @param params.account - The account that will own the blobs.
1490
+ * @param params.expirationMicros - The expiration time of the blobs in microseconds.
1491
+ * @param params.blobs - The blobs to register.
1492
+ * @param params.blobs.blobName - The name/path of the blob (e.g. "foo/bar.txt").
1493
+ * @param params.blobs.blobSize - The size of the blob in bytes.
1494
+ * @param params.blobs.blobMerkleRoot - The merkle root of the blob commitments as a hex string.
1495
+ * @param params.blobs.numChunksets - The total number of chunksets in the blob.
1496
+ *
1497
+ * @returns An Aptos transaction payload data object for the register_multiple_blobs Move function.
1498
+ *
1499
+ * @see https://github.com/shelby/shelby/blob/e08e84742cf2b80ad8bb7227deb3013398076d53/move/shelby_contract/sources/global_metadata.move#L357
1500
+ */
1501
+ static createBatchRegisterBlobsPayload(params) {
1502
+ const functionName = params.useSponsoredUsdVariant ? "register_multiple_blobs_with_sponsor" : "register_multiple_blobs";
1503
+ const blobNames = [];
1504
+ const blobMerkleRoots = [];
1505
+ const blobNumChunksets = [];
1506
+ const blobSizes = [];
1507
+ params.blobs.forEach((blob) => {
1508
+ blobNames.push(blob.blobName);
1509
+ blobMerkleRoots.push(
1510
+ Hex4.fromHexString(blob.blobMerkleRoot).toUint8Array()
1511
+ );
1512
+ blobNumChunksets.push(blob.numChunksets);
1513
+ blobSizes.push(blob.blobSize);
1514
+ });
1515
+ return {
1516
+ function: `${(params.deployer ?? SHELBY_DEPLOYER).toString()}::blob_metadata::${functionName}`,
1517
+ functionArguments: [
1518
+ blobNames,
1519
+ params.expirationMicros,
1520
+ blobMerkleRoots,
1521
+ blobNumChunksets,
1522
+ blobSizes,
1523
+ // TODO
1524
+ 0,
1525
+ // payment tier
1526
+ params.encoding
1527
+ ]
1528
+ };
1529
+ }
1530
+ /**
1531
+ * Creates a transaction payload to delete a blob on the blockchain.
1532
+ * This is a static helper method for constructing the Move function call payload.
1533
+ *
1534
+ * @param params.deployer - Optional deployer account address. Defaults to SHELBY_DEPLOYER.
1535
+ * @param params.blobName - The blob name (e.g. "bar.txt", without the account address prefix).
1536
+ *
1537
+ * @returns An Aptos transaction payload data object for the delete_blob Move function.
1538
+ *
1539
+ * @see https://github.com/shelby/shelby/blob/64e9d7b4f0005e586faeb1e4085c79159234b6b6/move/shelby_contract/sources/global_metadata.move#L616
1540
+ */
1541
+ static createDeleteBlobPayload(params) {
1542
+ return {
1543
+ function: `${(params.deployer ?? SHELBY_DEPLOYER).toString()}::blob_metadata::delete_blob`,
1544
+ functionArguments: [params.blobName]
1545
+ };
1546
+ }
1547
+ /**
1548
+ * Creates a transaction payload to delete multiple blobs on the blockchain.
1549
+ * This is a static helper method for constructing the Move function call payload.
1550
+ *
1551
+ * **Note:** This function requires the `delete_multiple_blobs` entry function
1552
+ * which will be deployed to the smart contract on 2026-02-04. Using this
1553
+ * function before that date will result in a transaction failure.
1554
+ *
1555
+ * This operation is atomic: if any blob deletion fails (e.g., blob not found),
1556
+ * the entire transaction fails and no blobs are deleted.
1557
+ *
1558
+ * @param params.deployer - Optional deployer account address. Defaults to SHELBY_DEPLOYER.
1559
+ * @param params.blobNames - Array of blob name suffixes without the account address prefix
1560
+ * (e.g. ["foo/bar.txt", "baz.txt"], NOT ["0x1/foo/bar.txt"]). The account address
1561
+ * prefix is automatically derived from the transaction sender.
1562
+ *
1563
+ * @returns An Aptos transaction payload data object for the delete_multiple_blobs Move function.
1564
+ *
1565
+ * @see https://github.com/shelby/shelby/blob/main/move/shelby_contract/sources/blob_metadata.move
1566
+ */
1567
+ static createDeleteMultipleBlobsPayload(params) {
1568
+ return {
1569
+ function: `${(params.deployer ?? SHELBY_DEPLOYER).toString()}::blob_metadata::delete_multiple_blobs`,
1570
+ functionArguments: [params.blobNames]
1571
+ };
1572
+ }
1573
+ static createBlobAcknowledgementsPayload(params) {
1574
+ const ackBitMask = params.storageProviderAcks.reduce(
1575
+ (acc, ack) => acc | 1 << ack.slot,
1576
+ 0
1577
+ );
1578
+ return {
1579
+ function: `${SHELBY_DEPLOYER}::blob_metadata::add_blob_acknowledgements`,
1580
+ functionArguments: [
1581
+ createBlobKey({
1582
+ account: params.blobOwner,
1583
+ blobName: params.blobName
1584
+ }),
1585
+ params.creationMicros,
1586
+ new U32(Number(ackBitMask)),
1587
+ params.storageProviderAcks.map((ack) => ack.signature)
1588
+ ]
1589
+ };
1590
+ }
1591
+ async addBlobAcknowledgements(params) {
1592
+ const transaction = await this.aptos.transaction.build.simple({
1593
+ ...params.options?.build,
1594
+ options: this.orderlessTxOptions(params.options?.build?.options),
1595
+ data: _ShelbyBlobClient.createBlobAcknowledgementsPayload({
1596
+ blobOwner: params.blobOwner,
1597
+ blobName: params.blobName,
1598
+ creationMicros: params.creationMicros,
1599
+ storageProviderAcks: params.storageProviderAcks
1600
+ }),
1601
+ sender: params.account.accountAddress
1602
+ });
1603
+ return {
1604
+ transaction: await this.aptos.signAndSubmitTransaction({
1605
+ signer: params.account,
1606
+ transaction
1607
+ })
1608
+ };
1609
+ }
1610
+ };
1611
+
1612
+ // src/core/clients/ShelbyRPCClient.ts
12
1613
  import {
13
- ShelbyMetadataClient
14
- } from "../../chunk-6FJNAUU5.mjs";
15
- import "../../chunk-KG2TMLEV.mjs";
16
- import "../../chunk-NEO7Z3ZQ.mjs";
17
- import "../../chunk-TET3DJEO.mjs";
18
- import "../../chunk-V4B3GAMQ.mjs";
19
- import "../../chunk-Z4FZ7W6L.mjs";
20
- import "../../chunk-I6NG5GNL.mjs";
21
- import "../../chunk-M3CP5TFP.mjs";
22
- import "../../chunk-3NRBHSMQ.mjs";
23
- import "../../chunk-RNNJXTX2.mjs";
24
- import "../../chunk-UEZNZBJO.mjs";
25
- import "../../chunk-JTXYKO3U.mjs";
26
- import "../../chunk-AUQDI5BS.mjs";
27
- import "../../chunk-MNCQBEMS.mjs";
28
- import "../../chunk-7P6ASYW6.mjs";
1614
+ Hex as Hex6
1615
+ } from "@aptos-labs/ts-sdk";
1616
+
1617
+ // src/core/layout.ts
1618
+ import { z as z2 } from "zod";
1619
+ var BlobNameSchema = z2.string().min(1, "Blob name path parameter cannot be empty.").max(
1620
+ 190,
1621
+ "Blob name suffix cannot exceed 190 characters (on-chain full key limit is 256 bytes)."
1622
+ ).refine((name) => !name.endsWith("/"), {
1623
+ message: "Blob name cannot end with a slash"
1624
+ });
1625
+
1626
+ // src/core/promises.ts
1627
+ function sleep(ms) {
1628
+ return new Promise((resolve) => setTimeout(resolve, ms));
1629
+ }
1630
+
1631
+ // src/core/rpc-responses.ts
1632
+ import { z as z3 } from "zod";
1633
+ var ChallengeResponseSchema = z3.object({
1634
+ challenge: z3.string(),
1635
+ expiresAt: z3.number()
1636
+ });
1637
+ var MultipartUploadStatusResponseSchema = z3.object({
1638
+ uploadId: z3.string(),
1639
+ completedParts: z3.array(z3.number()),
1640
+ partSize: z3.number(),
1641
+ nParts: z3.number(),
1642
+ uploadedBytes: z3.number()
1643
+ });
1644
+ var StartMultipartUploadResponseSchema = z3.object({
1645
+ uploadId: z3.string()
1646
+ });
1647
+ var UploadPartResponseSchema = z3.object({
1648
+ success: z3.literal(true)
1649
+ });
1650
+ var CompleteMultipartUploadResponseSchema = z3.object({
1651
+ success: z3.literal(true)
1652
+ });
1653
+ var RPCErrorResponseSchema = z3.object({
1654
+ error: z3.string()
1655
+ });
1656
+ var StaleMicropaymentErrorResponseSchema = z3.object({
1657
+ error: z3.string().optional(),
1658
+ storedMicropayment: z3.string().optional()
1659
+ });
1660
+
1661
+ // src/core/types/payments.ts
1662
+ import {
1663
+ AccountAddress as AccountAddress4,
1664
+ Deserializer,
1665
+ Hex as Hex5,
1666
+ Serializer
1667
+ } from "@aptos-labs/ts-sdk";
1668
+ var MICROPAYMENTS_MODULE_NAME = "micropayments";
1669
+ var WITHDRAW_APPROVAL_STRUCT_NAME = "WithdrawApproval";
1670
+ function serializeTypeInfo(serializer, moduleAddress, moduleName, structName) {
1671
+ moduleAddress.serialize(serializer);
1672
+ const moduleNameBytes = new TextEncoder().encode(moduleName);
1673
+ serializer.serializeBytes(moduleNameBytes);
1674
+ const structNameBytes = new TextEncoder().encode(structName);
1675
+ serializer.serializeBytes(structNameBytes);
1676
+ }
1677
+ var StaleChannelStateError = class _StaleChannelStateError extends Error {
1678
+ /**
1679
+ * The last valid micropayment stored by the server.
1680
+ * Clients can use this to reset their local channel state.
1681
+ */
1682
+ storedMicropayment;
1683
+ constructor(storedMicropayment, message) {
1684
+ super(
1685
+ message ?? "Client has stale channel state. Use the returned micropayment to reset local state."
1686
+ );
1687
+ this.name = "StaleChannelStateError";
1688
+ this.storedMicropayment = storedMicropayment;
1689
+ }
1690
+ /**
1691
+ * Returns the stored micropayment as a base64-encoded string.
1692
+ */
1693
+ toBase64() {
1694
+ const bytes = this.storedMicropayment.bcsToBytes();
1695
+ const binaryString = Array.from(
1696
+ bytes,
1697
+ (byte) => String.fromCharCode(byte)
1698
+ ).join("");
1699
+ return btoa(binaryString);
1700
+ }
1701
+ /**
1702
+ * Creates a StaleChannelStateError from a base64-encoded micropayment string.
1703
+ */
1704
+ static fromBase64(base64, message) {
1705
+ const binaryString = atob(base64);
1706
+ const bytes = Uint8Array.from(binaryString, (char) => char.charCodeAt(0));
1707
+ const micropayment = SenderBuiltMicropayment.deserialize(bytes);
1708
+ return new _StaleChannelStateError(micropayment, message);
1709
+ }
1710
+ };
1711
+ var SenderBuiltMicropayment = class _SenderBuiltMicropayment {
1712
+ /**
1713
+ * The sender's address (owner of the payment channel).
1714
+ */
1715
+ sender;
1716
+ /**
1717
+ * The receiver's address (beneficiary of the withdrawal).
1718
+ */
1719
+ receiver;
1720
+ /**
1721
+ * The unique ID of the payment channel.
1722
+ */
1723
+ paymentChannelId;
1724
+ /**
1725
+ * The cumulative amount the receiver is authorized to withdraw.
1726
+ */
1727
+ amount;
1728
+ /**
1729
+ * The fungible asset metadata address.
1730
+ */
1731
+ fungibleAssetAddress;
1732
+ /**
1733
+ * Monotonically increasing sequence number for replay protection.
1734
+ */
1735
+ sequenceNumber;
1736
+ /**
1737
+ * The sender's Ed25519 public key (32 bytes).
1738
+ * Used by the receiver to verify the signature before submitting.
1739
+ */
1740
+ publicKey;
1741
+ /**
1742
+ * The Ed25519 signature of the SignedMessage<WithdrawApproval> struct.
1743
+ * The SignedMessage includes TypeInfo for domain separation.
1744
+ */
1745
+ signature;
1746
+ /**
1747
+ * The deployer address of the micropayments module.
1748
+ * This is needed to reconstruct the TypeInfo for signature verification.
1749
+ */
1750
+ deployer;
1751
+ constructor(sender, receiver, paymentChannelId, amount, fungibleAssetAddress, sequenceNumber, publicKey, signature, deployer) {
1752
+ this.sender = sender;
1753
+ this.receiver = receiver;
1754
+ this.paymentChannelId = paymentChannelId;
1755
+ this.amount = amount;
1756
+ this.fungibleAssetAddress = fungibleAssetAddress;
1757
+ this.sequenceNumber = sequenceNumber;
1758
+ this.publicKey = publicKey;
1759
+ this.signature = signature;
1760
+ this.deployer = deployer ?? AccountAddress4.fromString(MICROPAYMENTS_DEPLOYER);
1761
+ }
1762
+ /**
1763
+ * Creates the BCS-serialized message that was signed.
1764
+ * This is a SignedMessage<WithdrawApproval> which includes:
1765
+ * 1. TypeInfo (module_address, module_name, struct_name)
1766
+ * 2. WithdrawApproval struct fields
1767
+ *
1768
+ * This format is used with signature_verify_strict_t for domain separation.
1769
+ */
1770
+ getSignedMessage() {
1771
+ return _SenderBuiltMicropayment.buildSignedMessage({
1772
+ deployer: this.deployer,
1773
+ sender: this.sender,
1774
+ receiver: this.receiver,
1775
+ fungibleAssetAddress: this.fungibleAssetAddress,
1776
+ amount: this.amount,
1777
+ paymentChannelId: this.paymentChannelId,
1778
+ sequenceNumber: this.sequenceNumber
1779
+ });
1780
+ }
1781
+ /**
1782
+ * Static helper to build the SignedMessage<WithdrawApproval> bytes from raw parameters.
1783
+ * This can be used to create the message for signing without constructing the full object.
1784
+ *
1785
+ * @param params - The withdrawal approval parameters.
1786
+ * @returns The BCS-serialized SignedMessage<WithdrawApproval> bytes.
1787
+ */
1788
+ static buildSignedMessage(params) {
1789
+ const serializer = new Serializer();
1790
+ serializeTypeInfo(
1791
+ serializer,
1792
+ params.deployer,
1793
+ MICROPAYMENTS_MODULE_NAME,
1794
+ WITHDRAW_APPROVAL_STRUCT_NAME
1795
+ );
1796
+ params.sender.serialize(serializer);
1797
+ params.receiver.serialize(serializer);
1798
+ params.fungibleAssetAddress.serialize(serializer);
1799
+ serializer.serializeU64(params.amount);
1800
+ serializer.serializeU64(params.paymentChannelId);
1801
+ serializer.serializeU64(params.sequenceNumber);
1802
+ return serializer.toUint8Array();
1803
+ }
1804
+ serialize(serializer) {
1805
+ this.sender.serialize(serializer);
1806
+ this.receiver.serialize(serializer);
1807
+ this.fungibleAssetAddress.serialize(serializer);
1808
+ serializer.serializeU64(this.amount);
1809
+ serializer.serializeU64(this.paymentChannelId);
1810
+ serializer.serializeU64(this.sequenceNumber);
1811
+ serializer.serializeBytes(this.publicKey);
1812
+ serializer.serializeBytes(this.signature);
1813
+ this.deployer.serialize(serializer);
1814
+ }
1815
+ bcsToBytes() {
1816
+ const serializer = new Serializer();
1817
+ this.serialize(serializer);
1818
+ return serializer.toUint8Array();
1819
+ }
1820
+ bcsToHex() {
1821
+ return Hex5.fromHexInput(this.bcsToBytes());
1822
+ }
1823
+ toStringWithoutPrefix() {
1824
+ return this.bcsToHex().toStringWithoutPrefix();
1825
+ }
1826
+ toString() {
1827
+ return this.bcsToHex().toString();
1828
+ }
1829
+ /**
1830
+ * Deserializes a SenderBuiltMicropayment from BCS bytes.
1831
+ * @param bytes - The bytes to deserialize from (Uint8Array or hex string).
1832
+ * @returns A new SenderBuiltMicropayment instance.
1833
+ */
1834
+ static deserialize(bytes) {
1835
+ const bytesArray = typeof bytes === "string" ? Hex5.fromHexInput(bytes).toUint8Array() : bytes;
1836
+ const deserializer = new Deserializer(bytesArray);
1837
+ const sender = AccountAddress4.deserialize(deserializer);
1838
+ const receiver = AccountAddress4.deserialize(deserializer);
1839
+ const fungibleAssetAddress = AccountAddress4.deserialize(deserializer);
1840
+ const amount = deserializer.deserializeU64();
1841
+ const paymentChannelId = deserializer.deserializeU64();
1842
+ const sequenceNumber = deserializer.deserializeU64();
1843
+ const publicKey = deserializer.deserializeBytes();
1844
+ const signature = deserializer.deserializeBytes();
1845
+ const deployer = AccountAddress4.deserialize(deserializer);
1846
+ return new _SenderBuiltMicropayment(
1847
+ sender,
1848
+ receiver,
1849
+ paymentChannelId,
1850
+ amount,
1851
+ fungibleAssetAddress,
1852
+ sequenceNumber,
1853
+ publicKey,
1854
+ signature,
1855
+ deployer
1856
+ );
1857
+ }
1858
+ };
1859
+
1860
+ // src/core/clients/ShelbyRPCClient.ts
1861
+ var MICROPAYMENT_HEADER = "X-Shelby-Micropayment";
1862
+ var BLOB_OWNER_CHALLENGE_HEADER = "X-Shelby-Challenge";
1863
+ var BLOB_OWNER_SIGNATURE_HEADER = "X-Shelby-Signature";
1864
+ var BLOB_OWNER_PUBLIC_KEY_HEADER = "X-Shelby-Public-Key";
1865
+ var BLOB_OWNER_AUTH_SCHEME_HEADER = "X-Shelby-Auth-Scheme";
1866
+ var BLOB_OWNER_IDENTITY_HEADER = "X-Shelby-Identity";
1867
+ var BLOB_OWNER_DOMAIN_HEADER = "X-Shelby-Domain";
1868
+ var BLOB_OWNER_AUTH_FUNCTION_HEADER = "X-Shelby-Auth-Function";
1869
+ function buildAuthHeaders(auth) {
1870
+ const signatureBase64 = btoa(
1871
+ Array.from(auth.signature, (byte) => String.fromCharCode(byte)).join("")
1872
+ );
1873
+ const publicKeyHex = Hex6.fromHexInput(auth.publicKey).toString();
1874
+ const headers = {
1875
+ [BLOB_OWNER_CHALLENGE_HEADER]: auth.challenge,
1876
+ [BLOB_OWNER_SIGNATURE_HEADER]: signatureBase64,
1877
+ [BLOB_OWNER_PUBLIC_KEY_HEADER]: publicKeyHex
1878
+ };
1879
+ if (auth.authScheme === "derivable") {
1880
+ headers[BLOB_OWNER_AUTH_SCHEME_HEADER] = auth.authScheme;
1881
+ headers[BLOB_OWNER_IDENTITY_HEADER] = auth.identity;
1882
+ headers[BLOB_OWNER_DOMAIN_HEADER] = auth.domain;
1883
+ headers[BLOB_OWNER_AUTH_FUNCTION_HEADER] = auth.authFunction;
1884
+ } else if (auth.authScheme) {
1885
+ headers[BLOB_OWNER_AUTH_SCHEME_HEADER] = auth.authScheme;
1886
+ }
1887
+ return headers;
1888
+ }
1889
+ function encodeURIComponentKeepSlashes(str) {
1890
+ return encodeURIComponent(str).replace(/%2F/g, "/");
1891
+ }
1892
+ function validateTotalBytes(totalBytes) {
1893
+ if (!Number.isInteger(totalBytes) || totalBytes < 0) {
1894
+ throw new Error("totalBytes must be a non-negative integer");
1895
+ }
1896
+ }
1897
+ function isRetryableStatus(status) {
1898
+ return status === 408 || status === 429 || status >= 500;
1899
+ }
1900
+ function getErrorCode(error) {
1901
+ if (typeof error === "object" && error !== null && "code" in error && typeof error.code === "string") {
1902
+ return error.code;
1903
+ }
1904
+ if (error instanceof Error) {
1905
+ const match = error.message.match(/\bE[A-Z0-9_]+\b/);
1906
+ return match?.[0];
1907
+ }
1908
+ return void 0;
1909
+ }
1910
+ var ShelbyRPCClient = class {
1911
+ baseUrl;
1912
+ apiKey;
1913
+ rpcConfig;
1914
+ indexer;
1915
+ #signChallengeOverride;
1916
+ /**
1917
+ * Creates a new ShelbyRPCClient for interacting with Shelby RPC nodes.
1918
+ * This client handles blob storage operations including upload and download.
1919
+ *
1920
+ * @param config - The client configuration object.
1921
+ * @param config.network - The Shelby network to use.
1922
+ * @param options.signChallengeHandler - Optional override for challenge
1923
+ * signing. When set, `putBlobResumable` uses this instead of the built-in
1924
+ * `signChallenge`. Intended for kit-level overrides (e.g. Solana DAA).
1925
+ *
1926
+ * @example
1927
+ * ```typescript
1928
+ * const client = new ShelbyRPCClient({
1929
+ * network: Network.SHELBYNET,
1930
+ * apiKey: "AG-***",
1931
+ * });
1932
+ * ```
1933
+ */
1934
+ constructor(config, options) {
1935
+ this.baseUrl = getShelbyRPCBaseUrl(config);
1936
+ this.apiKey = config.apiKey ?? config.rpc?.apiKey;
1937
+ this.rpcConfig = config.rpc ?? {};
1938
+ this.indexer = getShelbyIndexerClient(config);
1939
+ this.#signChallengeOverride = options?.signChallengeHandler;
1940
+ }
1941
+ /**
1942
+ * Request an authentication challenge for the given account.
1943
+ * The challenge must be signed and included in subsequent authenticated requests.
1944
+ *
1945
+ * @param account - The Aptos account address to authenticate as.
1946
+ * @returns The challenge string and expiration timestamp.
1947
+ *
1948
+ * @example
1949
+ * ```typescript
1950
+ * const { challenge, expiresAt } = await client.getChallenge(account.accountAddress);
1951
+ * const auth = client.signChallenge(account, challenge);
1952
+ * ```
1953
+ */
1954
+ async getChallenge(account) {
1955
+ const response = await fetch(
1956
+ buildRequestUrl("/v1/auth/challenge", this.baseUrl),
1957
+ {
1958
+ method: "POST",
1959
+ headers: {
1960
+ "Content-Type": "application/json",
1961
+ ...this.apiKey ? { Authorization: `Bearer ${this.apiKey}` } : {}
1962
+ },
1963
+ body: JSON.stringify({ account: account.toString() })
1964
+ }
1965
+ );
1966
+ if (!response.ok) {
1967
+ const errorBody = await response.text().catch(() => "");
1968
+ throw new Error(
1969
+ `Failed to get challenge: status ${response.status}, body: ${errorBody}`
1970
+ );
1971
+ }
1972
+ return ChallengeResponseSchema.parse(await response.json());
1973
+ }
1974
+ /**
1975
+ * Check if there's an existing multipart upload for a blob.
1976
+ * Returns the upload status including which parts have been uploaded.
1977
+ *
1978
+ * @param account - The account that owns the blob.
1979
+ * @param blobName - The name of the blob.
1980
+ * @returns The upload status, or undefined if no pending upload exists.
1981
+ *
1982
+ * @example
1983
+ * ```typescript
1984
+ * const status = await client.getMultipartUploadStatus(account, "myblob.txt");
1985
+ * if (status) {
1986
+ * console.log(`Resuming upload ${status.uploadId}, ${status.completedParts.length} parts done`);
1987
+ * }
1988
+ * ```
1989
+ */
1990
+ async getMultipartUploadStatus(account, blobName) {
1991
+ const url = new URL(buildRequestUrl("/v1/multipart-uploads", this.baseUrl));
1992
+ url.searchParams.set("account", account.toString());
1993
+ url.searchParams.set("blobName", blobName);
1994
+ const response = await fetch(url.toString(), {
1995
+ method: "GET",
1996
+ headers: {
1997
+ ...this.apiKey ? { Authorization: `Bearer ${this.apiKey}` } : {}
1998
+ }
1999
+ });
2000
+ if (response.status === 404) {
2001
+ return void 0;
2002
+ }
2003
+ if (!response.ok) {
2004
+ const errorBody = await response.text().catch(() => "");
2005
+ throw new Error(
2006
+ `Failed to get multipart upload status: status ${response.status}, body: ${errorBody}`
2007
+ );
2008
+ }
2009
+ return MultipartUploadStatusResponseSchema.parse(await response.json());
2010
+ }
2011
+ /**
2012
+ * Sign a challenge using the given account and return auth credentials.
2013
+ *
2014
+ * @param account - The Aptos account to sign with.
2015
+ * @param challenge - The hex-encoded challenge string from getChallenge().
2016
+ * @returns BlobOwnerAuth credentials for authenticated requests.
2017
+ */
2018
+ signChallenge(account, challenge) {
2019
+ const challengeBytes = Hex6.fromHexInput(challenge).toUint8Array();
2020
+ const signature = account.sign(challengeBytes);
2021
+ return {
2022
+ challenge,
2023
+ signature: signature.toUint8Array(),
2024
+ publicKey: account.publicKey.toUint8Array()
2025
+ };
2026
+ }
2027
+ async #uploadPart(uploadId, partIdx, partData) {
2028
+ const nRetries = 5;
2029
+ let lastResponse;
2030
+ let lastError;
2031
+ let attempts = 0;
2032
+ const partUrl = buildRequestUrl(
2033
+ `/v1/multipart-uploads/${uploadId}/parts/${partIdx}`,
2034
+ this.baseUrl
2035
+ );
2036
+ for (let i = 0; i < nRetries; ++i) {
2037
+ attempts++;
2038
+ try {
2039
+ lastResponse = await fetch(partUrl, {
2040
+ method: "PUT",
2041
+ headers: {
2042
+ "Content-Type": "application/octet-stream",
2043
+ ...this.apiKey ? { Authorization: `Bearer ${this.apiKey}` } : {}
2044
+ },
2045
+ body: partData
2046
+ });
2047
+ lastError = void 0;
2048
+ } catch (error) {
2049
+ lastError = error;
2050
+ if (i < nRetries - 1) {
2051
+ const delay = 2 ** i * 100;
2052
+ await sleep(delay);
2053
+ continue;
2054
+ }
2055
+ break;
2056
+ }
2057
+ if (lastResponse.ok) return;
2058
+ if (!isRetryableStatus(lastResponse.status)) {
2059
+ break;
2060
+ }
2061
+ if (i < nRetries - 1) {
2062
+ const delay = 2 ** i * 100;
2063
+ await sleep(delay);
2064
+ }
2065
+ }
2066
+ if (lastError !== void 0) {
2067
+ const errorCode = getErrorCode(lastError);
2068
+ const errorMessage = lastError instanceof Error ? lastError.message : String(lastError);
2069
+ throw new Error(
2070
+ `Failed to upload part ${partIdx} for multipart upload ${uploadId} after ${attempts} attempt${attempts === 1 ? "" : "s"}. The connection to the Shelby RPC endpoint was interrupted while sending data${errorCode ? ` (${errorCode})` : ""}. Endpoint: ${partUrl.toString()}, partBytes: ${partData.length}. Last error: ${errorMessage}`,
2071
+ { cause: lastError }
2072
+ );
2073
+ }
2074
+ const errorBody = await lastResponse?.text().catch(() => "");
2075
+ throw new Error(
2076
+ `Failed to upload part ${partIdx} for multipart upload ${uploadId} after ${attempts} attempt${attempts === 1 ? "" : "s"}. status: ${lastResponse?.status}, body: ${errorBody}`
2077
+ );
2078
+ }
2079
+ async #putBlobMultipart(account, blobName, blobData, totalBytes, partSize = 5 * 1024 * 1024, onProgress) {
2080
+ validateTotalBytes(totalBytes);
2081
+ const startResponse = await fetch(
2082
+ buildRequestUrl("/v1/multipart-uploads", this.baseUrl),
2083
+ {
2084
+ method: "POST",
2085
+ headers: {
2086
+ "Content-Type": "application/json",
2087
+ ...this.apiKey ? { Authorization: `Bearer ${this.apiKey}` } : {}
2088
+ },
2089
+ body: JSON.stringify({
2090
+ rawAccount: account.toString(),
2091
+ rawBlobName: blobName,
2092
+ rawPartSize: partSize
2093
+ })
2094
+ }
2095
+ );
2096
+ if (!startResponse.ok) {
2097
+ let errorBodyText = "Could not read error body";
2098
+ try {
2099
+ errorBodyText = await startResponse.text();
2100
+ } catch (_e) {
2101
+ }
2102
+ throw new Error(
2103
+ `Failed to start multipart upload! status: ${startResponse.status}, body: ${errorBodyText}`
2104
+ );
2105
+ }
2106
+ const { uploadId } = StartMultipartUploadResponseSchema.parse(
2107
+ await startResponse.json()
2108
+ );
2109
+ const totalParts = Math.ceil(totalBytes / partSize);
2110
+ let uploadedBytes = 0;
2111
+ for await (const [partIdx, partData] of readInChunks(blobData, partSize)) {
2112
+ await this.#uploadPart(uploadId, partIdx, partData);
2113
+ uploadedBytes += partData.length;
2114
+ onProgress?.({
2115
+ phase: "uploading",
2116
+ partIdx,
2117
+ totalParts,
2118
+ partBytes: partData.length,
2119
+ uploadedBytes,
2120
+ totalBytes
2121
+ });
2122
+ }
2123
+ if (uploadedBytes !== totalBytes) {
2124
+ throw new Error(
2125
+ `Uploaded bytes (${uploadedBytes}) did not match declared totalBytes (${totalBytes})`
2126
+ );
2127
+ }
2128
+ const finalPartIdx = totalParts > 0 ? totalParts - 1 : 0;
2129
+ onProgress?.({
2130
+ phase: "finalizing",
2131
+ partIdx: finalPartIdx,
2132
+ totalParts,
2133
+ // no part uploaded in this phase
2134
+ partBytes: 0,
2135
+ uploadedBytes: totalBytes,
2136
+ totalBytes
2137
+ });
2138
+ const completeResponse = await fetch(
2139
+ buildRequestUrl(
2140
+ `/v1/multipart-uploads/${uploadId}/complete`,
2141
+ this.baseUrl
2142
+ ),
2143
+ {
2144
+ method: "POST",
2145
+ headers: {
2146
+ "Content-Type": "application/json",
2147
+ ...this.apiKey ? { Authorization: `Bearer ${this.apiKey}` } : {}
2148
+ }
2149
+ }
2150
+ );
2151
+ if (!completeResponse.ok) {
2152
+ let errorBodyText = "Could not read error body";
2153
+ try {
2154
+ errorBodyText = await completeResponse.text();
2155
+ } catch (_e) {
2156
+ }
2157
+ throw new Error(
2158
+ `Failed to complete multipart upload! status: ${completeResponse.status}, body: ${errorBodyText}`
2159
+ );
2160
+ }
2161
+ }
2162
+ /**
2163
+ * Uploads blob data to the Shelby RPC node for storage by storage providers.
2164
+ * This method should be called after blob commitments have been registered on the blockchain.
2165
+ * Uses multipart upload for efficient handling of large files.
2166
+ *
2167
+ * @param params.account - The account that owns the blob.
2168
+ * @param params.blobName - The name/path of the blob (e.g. "folder/file.txt").
2169
+ * @param params.blobData - The raw blob data as a Uint8Array or ReadableStream.
2170
+ * @param params.totalBytes - Total byte length. Required for streams; optional for Uint8Array.
2171
+ *
2172
+ * @example
2173
+ * ```typescript
2174
+ * const blobData = new TextEncoder().encode("Hello, world!");
2175
+ *
2176
+ * await client.putBlob({
2177
+ * account: AccountAddress.from("0x1"),
2178
+ * blobName: "greetings/hello.txt",
2179
+ * blobData,
2180
+ * });
2181
+ * ```
2182
+ */
2183
+ async putBlob(params) {
2184
+ BlobNameSchema.parse(params.blobName);
2185
+ let totalBytes;
2186
+ if (params.blobData instanceof Uint8Array) {
2187
+ totalBytes = params.totalBytes ?? params.blobData.length;
2188
+ if (totalBytes !== params.blobData.length) {
2189
+ throw new Error(
2190
+ "totalBytes must match blobData.length when blobData is a Uint8Array"
2191
+ );
2192
+ }
2193
+ } else {
2194
+ if (params.totalBytes === void 0) {
2195
+ throw new Error(
2196
+ "totalBytes is required when blobData is a ReadableStream"
2197
+ );
2198
+ }
2199
+ totalBytes = params.totalBytes;
2200
+ }
2201
+ validateTotalBytes(totalBytes);
2202
+ await this.#putBlobMultipart(
2203
+ params.account,
2204
+ params.blobName,
2205
+ params.blobData,
2206
+ totalBytes,
2207
+ void 0,
2208
+ params.onProgress
2209
+ );
2210
+ }
2211
+ /**
2212
+ * Upload a part with authentication headers.
2213
+ */
2214
+ async #uploadPartWithAuth(uploadId, partIdx, partData, auth) {
2215
+ const nRetries = 5;
2216
+ let lastResponse;
2217
+ let lastError;
2218
+ let attempts = 0;
2219
+ const partUrl = buildRequestUrl(
2220
+ `/v1/multipart-uploads/${uploadId}/parts/${partIdx}`,
2221
+ this.baseUrl
2222
+ );
2223
+ const authHeaders = buildAuthHeaders(auth);
2224
+ for (let i = 0; i < nRetries; ++i) {
2225
+ attempts++;
2226
+ try {
2227
+ lastResponse = await fetch(partUrl, {
2228
+ method: "PUT",
2229
+ headers: {
2230
+ "Content-Type": "application/octet-stream",
2231
+ ...this.apiKey ? { Authorization: `Bearer ${this.apiKey}` } : {},
2232
+ ...authHeaders
2233
+ },
2234
+ body: partData
2235
+ });
2236
+ lastError = void 0;
2237
+ } catch (error) {
2238
+ lastError = error;
2239
+ if (i < nRetries - 1) {
2240
+ const delay = 2 ** i * 100;
2241
+ await sleep(delay);
2242
+ continue;
2243
+ }
2244
+ break;
2245
+ }
2246
+ if (lastResponse.ok) return;
2247
+ if (!isRetryableStatus(lastResponse.status)) {
2248
+ break;
2249
+ }
2250
+ if (i < nRetries - 1) {
2251
+ const delay = 2 ** i * 100;
2252
+ await sleep(delay);
2253
+ }
2254
+ }
2255
+ if (lastError !== void 0) {
2256
+ const errorCode = getErrorCode(lastError);
2257
+ const errorMessage = lastError instanceof Error ? lastError.message : String(lastError);
2258
+ throw new Error(
2259
+ `Failed to upload part ${partIdx} for multipart upload ${uploadId} after ${attempts} attempt${attempts === 1 ? "" : "s"}. ${errorCode ? `(${errorCode}) ` : ""}Last error: ${errorMessage}`,
2260
+ { cause: lastError }
2261
+ );
2262
+ }
2263
+ const errorBody = await lastResponse?.text().catch(() => "");
2264
+ throw new Error(
2265
+ `Failed to upload part ${partIdx} for multipart upload ${uploadId} after ${attempts} attempt${attempts === 1 ? "" : "s"}. status: ${lastResponse?.status}, body: ${errorBody}`
2266
+ );
2267
+ }
2268
+ /**
2269
+ * Uploads blob data to the Shelby RPC node with authentication and resume support.
2270
+ * This method authenticates using challenge-response and can resume interrupted uploads.
2271
+ *
2272
+ * @param params.account - The Aptos Account (with signing capability) that owns the blob.
2273
+ * @param params.blobName - The name/path of the blob (e.g. "folder/file.txt").
2274
+ * @param params.blobData - The raw blob data as a Uint8Array or ReadableStream.
2275
+ * @param params.totalBytes - Total byte length. Required for streams; optional for Uint8Array.
2276
+ * @param params.onProgress - Optional callback for upload progress.
2277
+ *
2278
+ * @example
2279
+ * ```typescript
2280
+ * await client.putBlobResumable({
2281
+ * account: myAccount, // Aptos Account with signing capability
2282
+ * blobName: "documents/report.pdf",
2283
+ * blobData: fileData,
2284
+ * totalBytes: fileData.length,
2285
+ * });
2286
+ * ```
2287
+ */
2288
+ async putBlobResumable(params) {
2289
+ BlobNameSchema.parse(params.blobName);
2290
+ let totalBytes;
2291
+ if (params.blobData instanceof Uint8Array) {
2292
+ totalBytes = params.totalBytes ?? params.blobData.length;
2293
+ if (totalBytes !== params.blobData.length) {
2294
+ throw new Error(
2295
+ "totalBytes must match blobData.length when blobData is a Uint8Array"
2296
+ );
2297
+ }
2298
+ } else {
2299
+ if (params.totalBytes === void 0) {
2300
+ throw new Error(
2301
+ "totalBytes is required when blobData is a ReadableStream"
2302
+ );
2303
+ }
2304
+ totalBytes = params.totalBytes;
2305
+ }
2306
+ validateTotalBytes(totalBytes);
2307
+ const partSize = params.partSize ?? 5 * 1024 * 1024;
2308
+ const { challenge } = await this.getChallenge(
2309
+ params.account.accountAddress
2310
+ );
2311
+ const signFn = this.#signChallengeOverride ?? this.signChallenge.bind(this);
2312
+ const auth = signFn(params.account, challenge);
2313
+ const authHeaders = buildAuthHeaders(auth);
2314
+ const existingUpload = await this.getMultipartUploadStatus(
2315
+ params.account.accountAddress,
2316
+ params.blobName
2317
+ );
2318
+ let uploadId;
2319
+ let completedPartsSet;
2320
+ let totalParts;
2321
+ if (existingUpload) {
2322
+ uploadId = existingUpload.uploadId;
2323
+ completedPartsSet = new Set(existingUpload.completedParts);
2324
+ totalParts = existingUpload.nParts;
2325
+ if (existingUpload.partSize !== partSize) {
2326
+ throw new Error(
2327
+ `Cannot resume upload: part size mismatch. Existing upload uses ${existingUpload.partSize} bytes, but ${partSize} was requested.`
2328
+ );
2329
+ }
2330
+ } else {
2331
+ const startResponse = await fetch(
2332
+ buildRequestUrl("/v1/multipart-uploads", this.baseUrl),
2333
+ {
2334
+ method: "POST",
2335
+ headers: {
2336
+ "Content-Type": "application/json",
2337
+ ...this.apiKey ? { Authorization: `Bearer ${this.apiKey}` } : {},
2338
+ ...authHeaders
2339
+ },
2340
+ body: JSON.stringify({
2341
+ rawAccount: params.account.accountAddress.toString(),
2342
+ rawBlobName: params.blobName,
2343
+ rawPartSize: partSize
2344
+ })
2345
+ }
2346
+ );
2347
+ if (!startResponse.ok) {
2348
+ const errorBodyText = await startResponse.text().catch(() => "");
2349
+ throw new Error(
2350
+ `Failed to start multipart upload! status: ${startResponse.status}, body: ${errorBodyText}`
2351
+ );
2352
+ }
2353
+ const parsed = StartMultipartUploadResponseSchema.parse(
2354
+ await startResponse.json()
2355
+ );
2356
+ uploadId = parsed.uploadId;
2357
+ completedPartsSet = /* @__PURE__ */ new Set();
2358
+ totalParts = Math.ceil(totalBytes / partSize);
2359
+ }
2360
+ let uploadedBytes = 0;
2361
+ let partIdx = 0;
2362
+ for await (const [idx, partData] of readInChunks(
2363
+ params.blobData,
2364
+ partSize
2365
+ )) {
2366
+ partIdx = idx;
2367
+ if (completedPartsSet.has(partIdx)) {
2368
+ uploadedBytes += partData.length;
2369
+ continue;
2370
+ }
2371
+ await this.#uploadPartWithAuth(uploadId, partIdx, partData, auth);
2372
+ uploadedBytes += partData.length;
2373
+ params.onProgress?.({
2374
+ phase: "uploading",
2375
+ partIdx,
2376
+ totalParts,
2377
+ partBytes: partData.length,
2378
+ uploadedBytes,
2379
+ totalBytes
2380
+ });
2381
+ }
2382
+ const finalPartIdx = totalParts > 0 ? totalParts - 1 : 0;
2383
+ params.onProgress?.({
2384
+ phase: "finalizing",
2385
+ partIdx: finalPartIdx,
2386
+ totalParts,
2387
+ partBytes: 0,
2388
+ uploadedBytes: totalBytes,
2389
+ totalBytes
2390
+ });
2391
+ const completeResponse = await fetch(
2392
+ buildRequestUrl(
2393
+ `/v1/multipart-uploads/${uploadId}/complete`,
2394
+ this.baseUrl
2395
+ ),
2396
+ {
2397
+ method: "POST",
2398
+ headers: {
2399
+ "Content-Type": "application/json",
2400
+ ...this.apiKey ? { Authorization: `Bearer ${this.apiKey}` } : {},
2401
+ ...authHeaders
2402
+ }
2403
+ }
2404
+ );
2405
+ if (!completeResponse.ok) {
2406
+ const errorBodyText = await completeResponse.text().catch(() => "");
2407
+ throw new Error(
2408
+ `Failed to complete multipart upload! status: ${completeResponse.status}, body: ${errorBodyText}`
2409
+ );
2410
+ }
2411
+ }
2412
+ /**
2413
+ * Downloads a blob from the Shelby RPC node.
2414
+ * Returns a streaming response with validation to ensure data integrity.
2415
+ *
2416
+ * @param params.account - The account that owns the blob.
2417
+ * @param params.blobName - The name/path of the blob (e.g. "folder/file.txt").
2418
+ * @param params.range - Optional byte range for partial downloads.
2419
+ * @param params.range.start - Starting byte position (inclusive).
2420
+ * @param params.range.end - Ending byte position (inclusive, optional).
2421
+ * @param params.micropayment - Optional micropayment to attach to the request.
2422
+ *
2423
+ * @returns A ShelbyBlob object containing the account, name, readable stream, and content length.
2424
+ *
2425
+ * @throws Error if the download fails or content length doesn't match.
2426
+ * @throws StaleChannelStateError if the micropayment is stale (server has newer state).
2427
+ *
2428
+ * @example
2429
+ * ```typescript
2430
+ * // Download entire blob
2431
+ * const blob = await client.getBlob({
2432
+ * account: AccountAddress.from("0x1"),
2433
+ * blobName: "documents/report.pdf"
2434
+ * });
2435
+ *
2436
+ * // Download partial content (bytes 100-199)
2437
+ * const partial = await client.getBlob({
2438
+ * account: AccountAddress.from("0x1"),
2439
+ * blobName: "large-file.bin",
2440
+ * range: { start: 100, end: 199 }
2441
+ * });
2442
+ *
2443
+ * // Download with micropayment
2444
+ * const blob = await client.getBlob({
2445
+ * account: AccountAddress.from("0x1"),
2446
+ * blobName: "documents/report.pdf",
2447
+ * micropayment: senderBuiltMicropayment
2448
+ * });
2449
+ * ```
2450
+ */
2451
+ async getBlob(params) {
2452
+ BlobNameSchema.parse(params.blobName);
2453
+ const url = buildRequestUrl(
2454
+ `/v1/blobs/${params.account.toString()}/${encodeURIComponentKeepSlashes(
2455
+ params.blobName
2456
+ )}`,
2457
+ this.baseUrl
2458
+ );
2459
+ const headers = new Headers();
2460
+ if (params.range !== void 0) {
2461
+ const { start, end } = params.range;
2462
+ if (end === void 0) {
2463
+ headers.set("Range", `bytes=${start}-`);
2464
+ } else {
2465
+ if (end < start) {
2466
+ throw new Error("Range end cannot be less than start.");
2467
+ }
2468
+ headers.set("Range", `bytes=${start}-${end}`);
2469
+ }
2470
+ }
2471
+ if (this.apiKey) {
2472
+ headers.set("Authorization", `Bearer ${this.apiKey}`);
2473
+ }
2474
+ if (params.micropayment) {
2475
+ const bytes = params.micropayment.bcsToBytes();
2476
+ const binaryString = Array.from(
2477
+ bytes,
2478
+ (byte) => String.fromCharCode(byte)
2479
+ ).join("");
2480
+ headers.set(MICROPAYMENT_HEADER, btoa(binaryString));
2481
+ }
2482
+ const response = await fetch(url, { headers });
2483
+ if (response.status === 409) {
2484
+ let json;
2485
+ try {
2486
+ json = await response.json();
2487
+ } catch {
2488
+ throw new Error(
2489
+ `Failed to download blob: ${response.status} ${response.statusText}`
2490
+ );
2491
+ }
2492
+ const parseResult = StaleMicropaymentErrorResponseSchema.safeParse(json);
2493
+ if (!parseResult.success) {
2494
+ throw new Error(
2495
+ `Failed to download blob: ${response.status} ${response.statusText}`
2496
+ );
2497
+ }
2498
+ const errorBody = parseResult.data;
2499
+ if (errorBody.storedMicropayment) {
2500
+ throw StaleChannelStateError.fromBase64(
2501
+ errorBody.storedMicropayment,
2502
+ errorBody.error
2503
+ );
2504
+ }
2505
+ throw new Error(
2506
+ errorBody.error ?? `Failed to download blob: ${response.status} ${response.statusText}`
2507
+ );
2508
+ }
2509
+ if (!response.ok) {
2510
+ throw new Error(
2511
+ `Failed to download blob: ${response.status} ${response.statusText}`
2512
+ );
2513
+ }
2514
+ if (!response.body) {
2515
+ throw new Error("Response body is null");
2516
+ }
2517
+ const contentLengthHeader = response.headers.get("content-length");
2518
+ if (contentLengthHeader === null) {
2519
+ throw new Error(
2520
+ "Response did not have content-length header, which is required"
2521
+ );
2522
+ }
2523
+ const expectedContentLength = Number.parseInt(contentLengthHeader, 10);
2524
+ if (Number.isNaN(expectedContentLength)) {
2525
+ throw new Error(
2526
+ `Invalid content-length header received: ${contentLengthHeader}`
2527
+ );
2528
+ }
2529
+ const validatingStream = new ReadableStream({
2530
+ start(controller) {
2531
+ const maybeReader = response.body?.getReader();
2532
+ if (!maybeReader) {
2533
+ controller.error(new Error("Response body reader is unavailable"));
2534
+ return;
2535
+ }
2536
+ const reader = maybeReader;
2537
+ let bytesReceived = 0;
2538
+ function pump() {
2539
+ return reader.read().then(({ done, value }) => {
2540
+ if (done) {
2541
+ if (bytesReceived !== expectedContentLength) {
2542
+ controller.error(
2543
+ new Error(
2544
+ `Downloaded data size (${bytesReceived} bytes) does not match content-length header (${expectedContentLength} bytes). This might indicate a partial or corrupted download.`
2545
+ )
2546
+ );
2547
+ return;
2548
+ }
2549
+ controller.close();
2550
+ return;
2551
+ }
2552
+ bytesReceived += value.byteLength;
2553
+ controller.enqueue(value);
2554
+ return pump();
2555
+ }).catch((error) => {
2556
+ controller.error(error);
2557
+ });
2558
+ }
2559
+ return pump();
2560
+ }
2561
+ });
2562
+ return {
2563
+ account: normalizeAddress(params.account),
2564
+ name: params.blobName,
2565
+ readable: validatingStream,
2566
+ contentLength: expectedContentLength
2567
+ };
2568
+ }
2569
+ };
2570
+
2571
+ // src/core/clients/ShelbyClient.ts
2572
+ var ShelbyClient = class {
2573
+ /**
2574
+ * The coordination client is used to interact with the Aptos blockchain which handles the commitments
2575
+ * and metadata for blobs.
2576
+ */
2577
+ coordination;
2578
+ /**
2579
+ * The metadata client is used for protocol-level metadata queries.
2580
+ */
2581
+ metadata;
2582
+ /**
2583
+ * The RPC client is used to interact with the Shelby RPC node which can be responsible for storing,
2584
+ * confirming, and retrieving blobs from the storage layer.
2585
+ *
2586
+ * If not provided, the default RPC client will be created.
2587
+ */
2588
+ rpc;
2589
+ /**
2590
+ * The configuration for the Shelby client.
2591
+ */
2592
+ config;
2593
+ /**
2594
+ * The Aptos client.
2595
+ *
2596
+ * If not provided, a default Aptos client will be created.
2597
+ */
2598
+ aptos;
2599
+ /**
2600
+ * The erasure coding provider used for encoding/decoding operations.
2601
+ * Lazily initialized on first use if not provided.
2602
+ */
2603
+ _provider;
2604
+ /**
2605
+ * Creates a new ShelbyClient instance for interacting with the Shelby Protocol.
2606
+ * This client combines blockchain operations (via coordination) and storage operations (via RPC).
2607
+ *
2608
+ * @param config - The client configuration object.
2609
+ * @param config.aptos.config - The Aptos network configuration.
2610
+ * @param config.shelby.rpc.baseUrl - The base URL of the Shelby RPC node (optional, defaults to devnet).
2611
+ * @param config.shelby.indexer - The indexer configuration for GraphQL queries.
2612
+ * @param provider - Optional erasure coding provider for encoding/decoding operations.
2613
+ * If not provided, a ClayErasureCodingProvider will be created on first use.
2614
+ * Pass a shared provider to reuse across multiple clients.
2615
+ *
2616
+ * @example
2617
+ * ```typescript
2618
+ * // Basic usage (provider created automatically)
2619
+ * const client = new ShelbyClient({
2620
+ * network: Network.SHELBYNET,
2621
+ * });
2622
+ *
2623
+ * // Advanced: Share provider across multiple clients
2624
+ * const provider = await ClayErasureCodingProvider.create();
2625
+ * const mainnetClient = new ShelbyClient(mainnetConfig, provider);
2626
+ * const devnetClient = new ShelbyClient(devnetConfig, provider);
2627
+ * ```
2628
+ */
2629
+ constructor(config, provider) {
2630
+ this.config = config;
2631
+ this.aptos = new Aptos3(getAptosConfig(config));
2632
+ this.coordination = new ShelbyBlobClient(config);
2633
+ this.metadata = new ShelbyMetadataClient(config);
2634
+ this.rpc = new ShelbyRPCClient(config, {
2635
+ signChallengeHandler: (account, challenge) => this.signChallenge(account, challenge)
2636
+ });
2637
+ this._provider = provider;
2638
+ }
2639
+ /**
2640
+ * Sign an authentication challenge for blob owner verification.
2641
+ *
2642
+ * The default implementation delegates to `ShelbyRPCClient.signChallenge`
2643
+ * which works for standard Ed25519 accounts. Kits that use derived /
2644
+ * abstracted accounts (Solana, Ethereum) should override this method to
2645
+ * provide the correct public key bytes and derivation metadata.
2646
+ */
2647
+ signChallenge(account, challenge) {
2648
+ return this.rpc.signChallenge(account, challenge);
2649
+ }
2650
+ /**
2651
+ * Get the erasure coding provider, creating it if necessary.
2652
+ * This allows lazy initialization for users who don't provide a provider.
2653
+ */
2654
+ async getProvider() {
2655
+ if (!this._provider) {
2656
+ this._provider = await ClayErasureCodingProvider.create(
2657
+ defaultErasureCodingConfig()
2658
+ );
2659
+ }
2660
+ return this._provider;
2661
+ }
2662
+ /**
2663
+ * The base URL for the Shelby RPC node.
2664
+ */
2665
+ get baseUrl() {
2666
+ return getShelbyRPCBaseUrl(this.config);
2667
+ }
2668
+ /**
2669
+ * Uploads a blob to the Shelby network.
2670
+ * This method handles the complete upload flow including commitment generation,
2671
+ * blockchain registration, and storage upload.
2672
+ *
2673
+ * Note: This method accepts only `Uint8Array` and buffers the entire blob in memory.
2674
+ * For streaming uploads of large files (e.g. >2 GiB), orchestrate the steps manually
2675
+ * using `generateCommitments()`, `coordination.registerBlob()`, and `rpc.putBlob()`
2676
+ * with a `ReadableStream`.
2677
+ *
2678
+ * @param params.blobData - The raw data to upload as a Uint8Array.
2679
+ * @param params.signer - The account that signs and pays for the transaction.
2680
+ * @param params.blobName - The name/path of the blob (e.g. "folder/file.txt").
2681
+ * @param params.expirationMicros - The expiration time in microseconds since Unix epoch.
2682
+ * @param params.options - Optional upload configuration.
2683
+ * @param params.options.chunksetSizeBytes - Custom chunkset size.
2684
+ * @param params.options.build - Additional Aptos transaction options.
2685
+ *
2686
+ * @returns The transaction and generated blob commitments (when implemented).
2687
+ *
2688
+ * @example
2689
+ * ```typescript
2690
+ * await client.upload({
2691
+ * blobData: Buffer.from("Hello, World!"),
2692
+ * signer: account,
2693
+ * blobName: "hello.txt",
2694
+ * expirationMicros: Date.now() * 1000 + 86400_000_000 // 24 hours from now
2695
+ * });
2696
+ * ```
2697
+ */
2698
+ async upload(params) {
2699
+ const existingBlobMetadata = await this.coordination.getBlobMetadata({
2700
+ account: params.signer.accountAddress,
2701
+ name: params.blobName
2702
+ });
2703
+ if (!existingBlobMetadata) {
2704
+ const provider = await this.getProvider();
2705
+ const blobCommitments = await generateCommitments(
2706
+ provider,
2707
+ params.blobData
2708
+ );
2709
+ const { transaction: pendingRegisterBlobTransaction } = await this.coordination.registerBlob({
2710
+ account: params.signer,
2711
+ blobName: params.blobName,
2712
+ blobMerkleRoot: blobCommitments.blob_merkle_root,
2713
+ size: params.blobData.length,
2714
+ expirationMicros: params.expirationMicros,
2715
+ config: provider.config,
2716
+ options: params.options
2717
+ });
2718
+ await this.coordination.aptos.waitForTransaction({
2719
+ transactionHash: pendingRegisterBlobTransaction.hash
2720
+ });
2721
+ }
2722
+ await this.rpc.putBlobResumable({
2723
+ account: params.signer,
2724
+ blobName: params.blobName,
2725
+ blobData: params.blobData
2726
+ });
2727
+ }
2728
+ /**
2729
+ * Uploads a batch of blobs to the Shelby network.
2730
+ * This method handles the complete upload flow including commitment generation,
2731
+ * blockchain registration, and storage upload.
2732
+ *
2733
+ * Note: This method accepts only `Uint8Array` and buffers each blob in memory.
2734
+ * For streaming uploads of large files, orchestrate the steps manually using
2735
+ * `generateCommitments()`, `coordination.registerBlob()`, and `rpc.putBlob()`
2736
+ * with a `ReadableStream`.
2737
+ *
2738
+ * @param params.blobs - The blobs to upload.
2739
+ * @param params.blobs.blobData - The raw data to upload as a Uint8Array.
2740
+ * @param params.blobs.blobName - The name/path of the blob (e.g. "folder/file.txt").
2741
+ * @param params.expirationMicros - The expiration time in microseconds since Unix epoch.
2742
+ * @param params.signer - The account that signs and pays for the transaction.
2743
+ * @param params.options - Optional upload configuration.
2744
+ * @param params.options.chunksetSizeBytes - Custom chunkset size.
2745
+ * @param params.options.build - Additional Aptos transaction options.
2746
+ *
2747
+ * @returns The transaction and generated blob commitments (when implemented).
2748
+ *
2749
+ * @example
2750
+ * ```typescript
2751
+ * await client.batchUpload({
2752
+ * blobs: [
2753
+ * { blobData: Buffer.from("Hello, World!"), blobName: "hello.txt" },
2754
+ * { blobData: Buffer.from("Hello, World 2!"), blobName: "hello2.txt" },
2755
+ * ],
2756
+ * expirationMicros: Date.now() * 1000 + 86400_000_000 // 24 hours from now
2757
+ * });
2758
+ * ```
2759
+ */
2760
+ async batchUpload(params) {
2761
+ const existingBlobs = await this.coordination.getBlobs({
2762
+ where: {
2763
+ blob_name: {
2764
+ _in: params.blobs.map(
2765
+ (blob) => createBlobKey({
2766
+ account: params.signer.accountAddress,
2767
+ blobName: blob.blobName
2768
+ })
2769
+ )
2770
+ }
2771
+ }
2772
+ });
2773
+ const blobsToRegister = params.blobs.filter(
2774
+ (blob) => !existingBlobs.some(
2775
+ (existingBlob) => existingBlob.name === createBlobKey({
2776
+ account: params.signer.accountAddress,
2777
+ blobName: blob.blobName
2778
+ })
2779
+ )
2780
+ );
2781
+ if (blobsToRegister.length > 0) {
2782
+ const provider = await this.getProvider();
2783
+ const blobCommitments = await Promise.all(
2784
+ blobsToRegister.map(
2785
+ async (blob) => generateCommitments(provider, blob.blobData)
2786
+ )
2787
+ );
2788
+ const { transaction: pendingRegisterBlobTransaction } = await this.coordination.batchRegisterBlobs({
2789
+ account: params.signer,
2790
+ expirationMicros: params.expirationMicros,
2791
+ blobs: blobsToRegister.map((blob, index) => ({
2792
+ blobName: blob.blobName,
2793
+ blobSize: blob.blobData.length,
2794
+ blobMerkleRoot: blobCommitments[index].blob_merkle_root
2795
+ })),
2796
+ config: provider.config,
2797
+ options: params.options
2798
+ });
2799
+ await this.coordination.aptos.waitForTransaction({
2800
+ transactionHash: pendingRegisterBlobTransaction.hash,
2801
+ options: { waitForIndexer: true }
2802
+ });
2803
+ }
2804
+ const limit = pLimit(3);
2805
+ await Promise.all(
2806
+ params.blobs.map(
2807
+ (blob) => limit(
2808
+ () => this.rpc.putBlobResumable({
2809
+ account: params.signer,
2810
+ blobName: blob.blobName,
2811
+ blobData: blob.blobData
2812
+ })
2813
+ )
2814
+ )
2815
+ );
2816
+ }
2817
+ /**
2818
+ * Downloads a blob from the Shelby RPC node.
2819
+ *
2820
+ * @param params.account - The account namespace the blob is stored in (e.g. "0x1")
2821
+ * @param params.blobName - The name of the blob (e.g. "foo/bar")
2822
+ * @param params.range - The range of the blob to download.
2823
+ *
2824
+ * @returns A `ShelbyBlob` object containing the blob data.
2825
+ *
2826
+ * @example
2827
+ * ```typescript
2828
+ * const blob = await client.download({
2829
+ * account,
2830
+ * blobName: "foo/bar.txt",
2831
+ * });
2832
+ * ```
2833
+ */
2834
+ async download(params) {
2835
+ return await this.rpc.getBlob(params);
2836
+ }
2837
+ /**
2838
+ *
2839
+ * Funds an account with ShelbyUSD tokens.
2840
+ *
2841
+ * @param params.address - The address to fund.
2842
+ * @param params.amount - The amount to fund.
2843
+ * @returns The transaction hash of the funded account.
2844
+ *
2845
+ * @example
2846
+ * ```typescript
2847
+ * const hash = await client.fundAccountWithShelbyUSD({
2848
+ * address: "0x1",
2849
+ * amount: 100000000,
2850
+ * });
2851
+ * ```
2852
+ */
2853
+ async fundAccountWithShelbyUSD(params) {
2854
+ if (this.config.network === Network3.TESTNET) {
2855
+ throw new Error(
2856
+ `ShelbyUSD cannot be minted programmatically on ${Network3.TESTNET}. Please use the faucet at https://docs.shelby.xyz/apis/faucet/shelbyusd instead.`
2857
+ );
2858
+ }
2859
+ const { address, amount } = params;
2860
+ try {
2861
+ const faucet = this.config.faucet?.baseUrl ?? "https://faucet.shelbynet.shelby.xyz/fund?asset=shelbyusd";
2862
+ const authToken = this.config.faucet?.authToken;
2863
+ const response = await fetch(`${faucet}`, {
2864
+ method: "POST",
2865
+ body: JSON.stringify({
2866
+ address: normalizeAddress(address).toString(),
2867
+ amount
2868
+ }),
2869
+ headers: {
2870
+ "Content-Type": "application/json",
2871
+ ...authToken ? { Authorization: `Bearer ${authToken}` } : {}
2872
+ }
2873
+ });
2874
+ if (!response.ok) {
2875
+ const errorBody = await response.text();
2876
+ throw new Error(`Failed to fund account: ${errorBody}`);
2877
+ }
2878
+ const json = await response.json();
2879
+ const res = await this.aptos.waitForTransaction({
2880
+ transactionHash: json.txn_hashes[0],
2881
+ options: {
2882
+ timeoutSecs: DEFAULT_TXN_TIMEOUT_SEC,
2883
+ checkSuccess: true
2884
+ }
2885
+ });
2886
+ if (res.type === TransactionResponseType.User) {
2887
+ return res.hash;
2888
+ }
2889
+ throw new Error(
2890
+ `Unexpected transaction received for fund account: ${res.type}`
2891
+ );
2892
+ } catch (error) {
2893
+ throw new Error(`Failed to fund account: ${error}`);
2894
+ }
2895
+ }
2896
+ /**
2897
+ * Fund an account with APT tokens
2898
+ *
2899
+ * @param params.address - The address to fund
2900
+ * @param params.amount - The amount to fund
2901
+ * @returns The transaction hash of the funded account
2902
+ *
2903
+ * @example
2904
+ * ```typescript
2905
+ * const hash = await client.fundAccountWithAPT({
2906
+ * address: "0x1",
2907
+ * amount: 100000000,
2908
+ * });
2909
+ * ```
2910
+ */
2911
+ async fundAccountWithAPT(params) {
2912
+ const transaction = await this.aptos.fundAccount({
2913
+ accountAddress: params.address,
2914
+ amount: params.amount
2915
+ });
2916
+ return transaction.hash;
2917
+ }
2918
+ };
2919
+
2920
+ // src/node/clients/ShelbyNodeClient.ts
2921
+ var ShelbyNodeClient = class extends ShelbyClient {
2922
+ };
29
2923
  export {
30
2924
  ShelbyMetadataClient,
31
2925
  ShelbyNodeClient