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