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