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