@shelby-protocol/sdk 0.3.0 → 0.4.0

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