@shelby-protocol/sdk 0.3.0 → 0.4.0

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