@shelby-protocol/sdk 0.2.4 → 0.3.1

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