@shelby-protocol/sdk 0.3.0 → 0.3.1

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