@shelby-protocol/sdk 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/dist/browser/index.d.ts +12 -3
  2. package/dist/browser/index.mjs +3717 -142
  3. package/dist/core/aptos-explorer.mjs +46 -5
  4. package/dist/core/blobs.mjs +12 -4
  5. package/dist/core/chunk.mjs +58 -9
  6. package/dist/core/clients/ShelbyBlobClient.d.ts +0 -43
  7. package/dist/core/clients/ShelbyBlobClient.mjs +1084 -17
  8. package/dist/core/clients/ShelbyClient.d.ts +12 -2
  9. package/dist/core/clients/ShelbyClient.mjs +2915 -23
  10. package/dist/core/clients/ShelbyClientConfig.mjs +0 -1
  11. package/dist/core/clients/ShelbyMetadataClient.d.ts +0 -18
  12. package/dist/core/clients/ShelbyMetadataClient.mjs +306 -6
  13. package/dist/core/clients/ShelbyMicropaymentChannelClient.d.ts +7 -49
  14. package/dist/core/clients/ShelbyMicropaymentChannelClient.mjs +839 -13
  15. package/dist/core/clients/ShelbyPlacementGroupClient.mjs +307 -8
  16. package/dist/core/clients/ShelbyRPCClient.d.ts +106 -3
  17. package/dist/core/clients/ShelbyRPCClient.mjs +1261 -12
  18. package/dist/core/clients/index.d.ts +2 -1
  19. package/dist/core/clients/index.mjs +3420 -39
  20. package/dist/core/clients/utils.mjs +65 -6
  21. package/dist/core/commitments.mjs +270 -11
  22. package/dist/core/constants.d.ts +2 -2
  23. package/dist/core/constants.mjs +39 -16
  24. package/dist/core/erasure/clay-codes.mjs +129 -4
  25. package/dist/core/erasure/constants.mjs +33 -10
  26. package/dist/core/erasure/default.mjs +191 -9
  27. package/dist/core/erasure/index.mjs +266 -23
  28. package/dist/core/erasure/reed-solomon.mjs +68 -4
  29. package/dist/core/erasure/utils.mjs +0 -2
  30. package/dist/core/errors.mjs +29 -8
  31. package/dist/core/index.d.ts +1 -1
  32. package/dist/core/index.mjs +3711 -142
  33. package/dist/core/layout.mjs +37 -5
  34. package/dist/core/networks.mjs +10 -5
  35. package/dist/core/operations/generated/sdk.d.ts +9 -0
  36. package/dist/core/operations/generated/sdk.mjs +183 -18
  37. package/dist/core/operations/index.mjs +284 -24
  38. package/dist/core/promises.mjs +4 -4
  39. package/dist/core/rpc-responses.mjs +29 -10
  40. package/dist/core/shelby-explorer.mjs +31 -6
  41. package/dist/core/strings.mjs +0 -2
  42. package/dist/core/types/blobs.mjs +0 -1
  43. package/dist/core/types/index.mjs +230 -9
  44. package/dist/core/types/payments.d.ts +6 -6
  45. package/dist/core/types/payments.mjs +230 -5
  46. package/dist/core/types/placement_groups.mjs +0 -1
  47. package/dist/core/types/storage_providers.mjs +0 -1
  48. package/dist/core/utils.mjs +94 -8
  49. package/dist/node/clients/ShelbyNodeClient.d.ts +1 -0
  50. package/dist/node/clients/ShelbyNodeClient.mjs +2919 -24
  51. package/dist/node/clients/index.d.ts +1 -0
  52. package/dist/node/clients/index.mjs +2920 -26
  53. package/dist/node/index.d.ts +1 -1
  54. package/dist/node/index.mjs +3734 -149
  55. package/dist/node/parallel/commitment_worker.d.ts +9 -0
  56. package/dist/node/parallel/commitment_worker.mjs +298 -0
  57. package/dist/node/parallel/commitment_worker_pool.d.ts +35 -0
  58. package/dist/node/parallel/commitment_worker_pool.mjs +286 -0
  59. package/dist/node/parallel/default_commitment_worker_pool.d.ts +24 -0
  60. package/dist/node/parallel/default_commitment_worker_pool.mjs +302 -0
  61. package/dist/node/parallel/index.d.ts +11 -0
  62. package/dist/node/parallel/index.mjs +563 -0
  63. package/dist/node/parallel/parallel_commitments.d.ts +32 -0
  64. package/dist/node/parallel/parallel_commitments.mjs +561 -0
  65. package/dist/node/parallel/worker_pool.d.ts +74 -0
  66. package/dist/node/parallel/worker_pool.mjs +248 -0
  67. package/dist/node/testUtil.mjs +8 -4
  68. package/package.json +6 -2
  69. package/dist/chunk-3NRBHSMQ.mjs +0 -12
  70. package/dist/chunk-5BVSWXQJ.mjs +0 -801
  71. package/dist/chunk-6FJNAUU5.mjs +0 -278
  72. package/dist/chunk-6XSZRDLJ.mjs +0 -375
  73. package/dist/chunk-7P6ASYW6.mjs +0 -9
  74. package/dist/chunk-A4IG6GSE.mjs +0 -21
  75. package/dist/chunk-AD2G3QYD.mjs +0 -0
  76. package/dist/chunk-AUQDI5BS.mjs +0 -43
  77. package/dist/chunk-AY3HBWXA.mjs +0 -51
  78. package/dist/chunk-BDSW5PHM.mjs +0 -37
  79. package/dist/chunk-C6RQ3AEU.mjs +0 -51
  80. package/dist/chunk-CQ6QPIZK.mjs +0 -37
  81. package/dist/chunk-D6GQHO6G.mjs +0 -15
  82. package/dist/chunk-EM67QTMR.mjs +0 -0
  83. package/dist/chunk-I6NG5GNL.mjs +0 -8
  84. package/dist/chunk-JTXYKO3U.mjs +0 -38
  85. package/dist/chunk-KG2TMLEV.mjs +0 -207
  86. package/dist/chunk-M3CP5TFP.mjs +0 -39
  87. package/dist/chunk-M7W43K2Q.mjs +0 -505
  88. package/dist/chunk-MB7C7VQF.mjs +0 -0
  89. package/dist/chunk-MNCQBEMS.mjs +0 -55
  90. package/dist/chunk-MQUVYMNQ.mjs +0 -0
  91. package/dist/chunk-NEO7Z3ZQ.mjs +0 -49
  92. package/dist/chunk-NHWWORCH.mjs +0 -72
  93. package/dist/chunk-OEK24ON7.mjs +0 -135
  94. package/dist/chunk-QQ57OGQ2.mjs +0 -0
  95. package/dist/chunk-RNNJXTX2.mjs +0 -154
  96. package/dist/chunk-S6Q4OG7H.mjs +0 -83
  97. package/dist/chunk-TET3DJEO.mjs +0 -199
  98. package/dist/chunk-UEZNZBJO.mjs +0 -104
  99. package/dist/chunk-V46D5NBW.mjs +0 -11
  100. package/dist/chunk-V4B3GAMQ.mjs +0 -42
  101. package/dist/chunk-WFWRBNTW.mjs +0 -412
  102. package/dist/chunk-WTICJPDB.mjs +0 -0
  103. package/dist/chunk-XNEIWM4O.mjs +0 -0
  104. package/dist/chunk-Z4FZ7W6L.mjs +0 -39
  105. package/dist/chunk-Z7RFCADT.mjs +0 -0
  106. package/dist/chunk-ZHXCVRZX.mjs +0 -0
@@ -1,17 +1,843 @@
1
+ // src/core/clients/ShelbyMicropaymentChannelClient.ts
1
2
  import {
2
- ShelbyMicropaymentChannelClient
3
- } from "../../chunk-M7W43K2Q.mjs";
4
- import "../../chunk-QQ57OGQ2.mjs";
5
- import "../../chunk-MQUVYMNQ.mjs";
6
- import "../../chunk-ZHXCVRZX.mjs";
7
- import "../../chunk-AD2G3QYD.mjs";
8
- import "../../chunk-KG2TMLEV.mjs";
9
- import "../../chunk-NEO7Z3ZQ.mjs";
10
- import "../../chunk-TET3DJEO.mjs";
11
- import "../../chunk-V4B3GAMQ.mjs";
12
- import "../../chunk-UEZNZBJO.mjs";
13
- import "../../chunk-MNCQBEMS.mjs";
14
- import "../../chunk-7P6ASYW6.mjs";
3
+ AccountAddress as AccountAddress3,
4
+ Aptos,
5
+ MoveVector
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://api.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 MICROPAYMENTS_DEPLOYER = "0x1ae7275148bf6ef742b658fd9cbcc2e094201606f4a7bc707bab0201da8043ee";
38
+
39
+ // src/core/operations/index.ts
40
+ import { Network as Network2 } from "@aptos-labs/ts-sdk";
41
+ import { GraphQLClient } from "graphql-request";
42
+
43
+ // src/core/clients/utils.ts
44
+ import { AptosConfig } from "@aptos-labs/ts-sdk";
45
+ var getAptosConfig = (config) => {
46
+ const baseFaucetConfig = config.faucet?.authToken ? { AUTH_TOKEN: config.faucet.authToken } : void 0;
47
+ if (config.aptos) {
48
+ return new AptosConfig({
49
+ // Spread user's aptos config first
50
+ ...config.aptos,
51
+ // Network from top-level is authoritative - cannot be overridden
52
+ network: config.network,
53
+ // Merge clientConfig with API_KEY default
54
+ clientConfig: {
55
+ API_KEY: config.apiKey,
56
+ ...config.aptos.clientConfig
57
+ },
58
+ // Merge faucetConfig: aptos config first, then base authToken (authoritative)
59
+ faucetConfig: {
60
+ ...config.aptos.faucetConfig,
61
+ ...baseFaucetConfig
62
+ }
63
+ });
64
+ }
65
+ return new AptosConfig({
66
+ network: config.network,
67
+ clientConfig: {
68
+ API_KEY: config.apiKey
69
+ },
70
+ faucetConfig: baseFaucetConfig
71
+ });
72
+ };
73
+
74
+ // src/core/operations/generated/sdk.ts
75
+ import gql from "graphql-tag";
76
+ var GetBlobsDocument = gql`
77
+ query getBlobs($where: blobs_bool_exp, $orderBy: [blobs_order_by!], $limit: Int, $offset: Int) {
78
+ blobs(where: $where, order_by: $orderBy, limit: $limit, offset: $offset) {
79
+ owner
80
+ blob_commitment
81
+ blob_name
82
+ created_at
83
+ expires_at
84
+ num_chunksets
85
+ is_deleted
86
+ is_written
87
+ placement_group
88
+ size
89
+ updated_at
90
+ slice_address
91
+ }
92
+ }
93
+ `;
94
+ var GetBlobActivitiesDocument = gql`
95
+ query getBlobActivities($where: blob_activities_bool_exp, $orderBy: [blob_activities_order_by!], $limit: Int, $offset: Int) {
96
+ blob_activities(
97
+ where: $where
98
+ order_by: $orderBy
99
+ limit: $limit
100
+ offset: $offset
101
+ ) {
102
+ blob_name
103
+ event_index
104
+ event_type
105
+ transaction_hash
106
+ transaction_version
107
+ timestamp
108
+ owner
109
+ }
110
+ }
111
+ `;
112
+ var GetBlobsCountDocument = gql`
113
+ query getBlobsCount($where: blobs_bool_exp) {
114
+ blobs_aggregate(where: $where) {
115
+ aggregate {
116
+ count
117
+ }
118
+ }
119
+ }
120
+ `;
121
+ var GetBlobActivitiesCountDocument = gql`
122
+ query getBlobActivitiesCount($where: blob_activities_bool_exp) {
123
+ blob_activities_aggregate(where: $where) {
124
+ aggregate {
125
+ count
126
+ }
127
+ }
128
+ }
129
+ `;
130
+ var GetTotalBlobsSizeDocument = gql`
131
+ query getTotalBlobsSize($where: blobs_bool_exp) {
132
+ blobs_aggregate(where: $where) {
133
+ aggregate {
134
+ sum {
135
+ size
136
+ }
137
+ }
138
+ }
139
+ }
140
+ `;
141
+ var GetPlacementGroupSlotsDocument = gql`
142
+ query getPlacementGroupSlots($where: placement_group_slots_bool_exp, $orderBy: [placement_group_slots_order_by!], $limit: Int, $offset: Int) {
143
+ placement_group_slots(
144
+ where: $where
145
+ order_by: $orderBy
146
+ limit: $limit
147
+ offset: $offset
148
+ ) {
149
+ placement_group
150
+ slot_index
151
+ storage_provider
152
+ status
153
+ updated_at
154
+ }
155
+ }
156
+ `;
157
+ var GetPlacementGroupSlotsCountDocument = gql`
158
+ query getPlacementGroupSlotsCount($where: placement_group_slots_bool_exp) {
159
+ placement_group_slots_aggregate(where: $where) {
160
+ aggregate {
161
+ count
162
+ }
163
+ }
164
+ }
165
+ `;
166
+ var GetProcessorStatusDocument = gql`
167
+ query getProcessorStatus {
168
+ processor_status {
169
+ last_success_version
170
+ last_transaction_timestamp
171
+ last_updated
172
+ }
173
+ }
174
+ `;
175
+ var defaultWrapper = (action, _operationName, _operationType, _variables) => action();
176
+ function getSdk(client, withWrapper = defaultWrapper) {
177
+ return {
178
+ getBlobs(variables, requestHeaders, signal) {
179
+ return withWrapper((wrappedRequestHeaders) => client.request({ document: GetBlobsDocument, variables, requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders }, signal }), "getBlobs", "query", variables);
180
+ },
181
+ getBlobActivities(variables, requestHeaders, signal) {
182
+ return withWrapper((wrappedRequestHeaders) => client.request({ document: GetBlobActivitiesDocument, variables, requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders }, signal }), "getBlobActivities", "query", variables);
183
+ },
184
+ getBlobsCount(variables, requestHeaders, signal) {
185
+ return withWrapper((wrappedRequestHeaders) => client.request({ document: GetBlobsCountDocument, variables, requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders }, signal }), "getBlobsCount", "query", variables);
186
+ },
187
+ getBlobActivitiesCount(variables, requestHeaders, signal) {
188
+ return withWrapper((wrappedRequestHeaders) => client.request({ document: GetBlobActivitiesCountDocument, variables, requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders }, signal }), "getBlobActivitiesCount", "query", variables);
189
+ },
190
+ getTotalBlobsSize(variables, requestHeaders, signal) {
191
+ return withWrapper((wrappedRequestHeaders) => client.request({ document: GetTotalBlobsSizeDocument, variables, requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders }, signal }), "getTotalBlobsSize", "query", variables);
192
+ },
193
+ getPlacementGroupSlots(variables, requestHeaders, signal) {
194
+ return withWrapper((wrappedRequestHeaders) => client.request({ document: GetPlacementGroupSlotsDocument, variables, requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders }, signal }), "getPlacementGroupSlots", "query", variables);
195
+ },
196
+ getPlacementGroupSlotsCount(variables, requestHeaders, signal) {
197
+ return withWrapper((wrappedRequestHeaders) => client.request({ document: GetPlacementGroupSlotsCountDocument, variables, requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders }, signal }), "getPlacementGroupSlotsCount", "query", variables);
198
+ },
199
+ getProcessorStatus(variables, requestHeaders, signal) {
200
+ return withWrapper((wrappedRequestHeaders) => client.request({ document: GetProcessorStatusDocument, variables, requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders }, signal }), "getProcessorStatus", "query", variables);
201
+ }
202
+ };
203
+ }
204
+
205
+ // src/core/operations/index.ts
206
+ function createShelbyIndexerClient(baseUrl, options) {
207
+ const graphqlClient = new GraphQLClient(baseUrl, options);
208
+ return getSdk(graphqlClient);
209
+ }
210
+ function getShelbyIndexerClient(config) {
211
+ const aptosConfig = getAptosConfig(config);
212
+ let { apiKey: indexerApiKey, baseUrl } = config.indexer ?? {};
213
+ if (!baseUrl) {
214
+ switch (aptosConfig?.network) {
215
+ // TODO: Add endpoints for core networks
216
+ case Network2.MAINNET:
217
+ case Network2.TESTNET:
218
+ case Network2.DEVNET:
219
+ case Network2.SHELBYNET:
220
+ case Network2.LOCAL:
221
+ baseUrl = NetworkToShelbyBlobIndexerBaseUrl[aptosConfig.network];
222
+ break;
223
+ }
224
+ }
225
+ if (baseUrl === void 0) {
226
+ throw new Error(
227
+ "The ShelbyClientConfig does not support the Shelby indexer. Please configure the endpoint in the ShelbyClientConfig.indexer.endpoint or provide a supported Aptos network."
228
+ );
229
+ }
230
+ const apiKey = indexerApiKey ?? config.apiKey;
231
+ return createShelbyIndexerClient(baseUrl, {
232
+ headers: {
233
+ ...apiKey ? { Authorization: `Bearer ${apiKey}` } : {},
234
+ "x-aptos-client": "shelby-ts-sdk"
235
+ }
236
+ });
237
+ }
238
+
239
+ // src/core/types/payments.ts
240
+ import {
241
+ AccountAddress,
242
+ Deserializer,
243
+ Hex,
244
+ Serializer
245
+ } from "@aptos-labs/ts-sdk";
246
+ var MICROPAYMENTS_MODULE_NAME = "micropayments";
247
+ var WITHDRAW_APPROVAL_STRUCT_NAME = "WithdrawApproval";
248
+ function serializeTypeInfo(serializer, moduleAddress, moduleName, structName) {
249
+ moduleAddress.serialize(serializer);
250
+ const moduleNameBytes = new TextEncoder().encode(moduleName);
251
+ serializer.serializeBytes(moduleNameBytes);
252
+ const structNameBytes = new TextEncoder().encode(structName);
253
+ serializer.serializeBytes(structNameBytes);
254
+ }
255
+ var SenderBuiltMicropayment = class _SenderBuiltMicropayment {
256
+ /**
257
+ * The sender's address (owner of the payment channel).
258
+ */
259
+ sender;
260
+ /**
261
+ * The receiver's address (beneficiary of the withdrawal).
262
+ */
263
+ receiver;
264
+ /**
265
+ * The unique ID of the payment channel.
266
+ */
267
+ paymentChannelId;
268
+ /**
269
+ * The cumulative amount the receiver is authorized to withdraw.
270
+ */
271
+ amount;
272
+ /**
273
+ * The fungible asset metadata address.
274
+ */
275
+ fungibleAssetAddress;
276
+ /**
277
+ * Monotonically increasing sequence number for replay protection.
278
+ */
279
+ sequenceNumber;
280
+ /**
281
+ * The sender's Ed25519 public key (32 bytes).
282
+ * Used by the receiver to verify the signature before submitting.
283
+ */
284
+ publicKey;
285
+ /**
286
+ * The Ed25519 signature of the SignedMessage<WithdrawApproval> struct.
287
+ * The SignedMessage includes TypeInfo for domain separation.
288
+ */
289
+ signature;
290
+ /**
291
+ * The deployer address of the micropayments module.
292
+ * This is needed to reconstruct the TypeInfo for signature verification.
293
+ */
294
+ deployer;
295
+ constructor(sender, receiver, paymentChannelId, amount, fungibleAssetAddress, sequenceNumber, publicKey, signature, deployer) {
296
+ this.sender = sender;
297
+ this.receiver = receiver;
298
+ this.paymentChannelId = paymentChannelId;
299
+ this.amount = amount;
300
+ this.fungibleAssetAddress = fungibleAssetAddress;
301
+ this.sequenceNumber = sequenceNumber;
302
+ this.publicKey = publicKey;
303
+ this.signature = signature;
304
+ this.deployer = deployer ?? AccountAddress.fromString(MICROPAYMENTS_DEPLOYER);
305
+ }
306
+ /**
307
+ * Creates the BCS-serialized message that was signed.
308
+ * This is a SignedMessage<WithdrawApproval> which includes:
309
+ * 1. TypeInfo (module_address, module_name, struct_name)
310
+ * 2. WithdrawApproval struct fields
311
+ *
312
+ * This format is used with signature_verify_strict_t for domain separation.
313
+ */
314
+ getSignedMessage() {
315
+ return _SenderBuiltMicropayment.buildSignedMessage({
316
+ deployer: this.deployer,
317
+ sender: this.sender,
318
+ receiver: this.receiver,
319
+ fungibleAssetAddress: this.fungibleAssetAddress,
320
+ amount: this.amount,
321
+ paymentChannelId: this.paymentChannelId,
322
+ sequenceNumber: this.sequenceNumber
323
+ });
324
+ }
325
+ /**
326
+ * Static helper to build the SignedMessage<WithdrawApproval> bytes from raw parameters.
327
+ * This can be used to create the message for signing without constructing the full object.
328
+ *
329
+ * @param params - The withdrawal approval parameters.
330
+ * @returns The BCS-serialized SignedMessage<WithdrawApproval> bytes.
331
+ */
332
+ static buildSignedMessage(params) {
333
+ const serializer = new Serializer();
334
+ serializeTypeInfo(
335
+ serializer,
336
+ params.deployer,
337
+ MICROPAYMENTS_MODULE_NAME,
338
+ WITHDRAW_APPROVAL_STRUCT_NAME
339
+ );
340
+ params.sender.serialize(serializer);
341
+ params.receiver.serialize(serializer);
342
+ params.fungibleAssetAddress.serialize(serializer);
343
+ serializer.serializeU64(params.amount);
344
+ serializer.serializeU64(params.paymentChannelId);
345
+ serializer.serializeU64(params.sequenceNumber);
346
+ return serializer.toUint8Array();
347
+ }
348
+ serialize(serializer) {
349
+ this.sender.serialize(serializer);
350
+ this.receiver.serialize(serializer);
351
+ this.fungibleAssetAddress.serialize(serializer);
352
+ serializer.serializeU64(this.amount);
353
+ serializer.serializeU64(this.paymentChannelId);
354
+ serializer.serializeU64(this.sequenceNumber);
355
+ serializer.serializeBytes(this.publicKey);
356
+ serializer.serializeBytes(this.signature);
357
+ this.deployer.serialize(serializer);
358
+ }
359
+ bcsToBytes() {
360
+ const serializer = new Serializer();
361
+ this.serialize(serializer);
362
+ return serializer.toUint8Array();
363
+ }
364
+ bcsToHex() {
365
+ return Hex.fromHexInput(this.bcsToBytes());
366
+ }
367
+ toStringWithoutPrefix() {
368
+ return this.bcsToHex().toStringWithoutPrefix();
369
+ }
370
+ toString() {
371
+ return this.bcsToHex().toString();
372
+ }
373
+ /**
374
+ * Deserializes a SenderBuiltMicropayment from BCS bytes.
375
+ * @param bytes - The bytes to deserialize from (Uint8Array or hex string).
376
+ * @returns A new SenderBuiltMicropayment instance.
377
+ */
378
+ static deserialize(bytes) {
379
+ const bytesArray = typeof bytes === "string" ? Hex.fromHexInput(bytes).toUint8Array() : bytes;
380
+ const deserializer = new Deserializer(bytesArray);
381
+ const sender = AccountAddress.deserialize(deserializer);
382
+ const receiver = AccountAddress.deserialize(deserializer);
383
+ const fungibleAssetAddress = AccountAddress.deserialize(deserializer);
384
+ const amount = deserializer.deserializeU64();
385
+ const paymentChannelId = deserializer.deserializeU64();
386
+ const sequenceNumber = deserializer.deserializeU64();
387
+ const publicKey = deserializer.deserializeBytes();
388
+ const signature = deserializer.deserializeBytes();
389
+ const deployer = AccountAddress.deserialize(deserializer);
390
+ return new _SenderBuiltMicropayment(
391
+ sender,
392
+ receiver,
393
+ paymentChannelId,
394
+ amount,
395
+ fungibleAssetAddress,
396
+ sequenceNumber,
397
+ publicKey,
398
+ signature,
399
+ deployer
400
+ );
401
+ }
402
+ };
403
+
404
+ // src/core/utils.ts
405
+ import {
406
+ AccountAddress as AccountAddress2,
407
+ Hex as Hex2
408
+ } from "@aptos-labs/ts-sdk";
409
+ function normalizeAddress(address) {
410
+ return AccountAddress2.from(address, { maxMissingChars: 63 });
411
+ }
412
+
413
+ // src/core/clients/ShelbyMicropaymentChannelClient.ts
414
+ var ShelbyMicropaymentChannelClient = class _ShelbyMicropaymentChannelClient {
415
+ aptos;
416
+ deployer;
417
+ indexer;
418
+ /**
419
+ * The ShelbyMicropaymentChannelClient is used to interact with the Micropayment contract on the Aptos blockchain. This
420
+ * includes functions for the full lifecycle of micropayment channels: creation, withdrawals, expiration extensions, etc.
421
+ *
422
+ * @param config - The client configuration object.
423
+ * @param config.network - The Shelby network to use.
424
+ *
425
+ * @example
426
+ * ```typescript
427
+ * const client = new ShelbyMicropaymentChannelClient({
428
+ * aptos: {
429
+ * network: Network.SHELBYNET,
430
+ * clientConfig: {
431
+ * API_KEY: "AG-***",
432
+ * },
433
+ * },
434
+ * });
435
+ * ```
436
+ */
437
+ constructor(config) {
438
+ this.aptos = new Aptos(getAptosConfig(config));
439
+ this.deployer = config.deployer ?? AccountAddress3.fromString(MICROPAYMENTS_DEPLOYER);
440
+ this.indexer = getShelbyIndexerClient(config);
441
+ }
442
+ /**
443
+ * Calls initialize function so caller can thereafter create micropayment channels.
444
+ *
445
+ * @param params.sender - The account that will be sending funds to various receivers in micropayment channels.
446
+ * @param params.options - Optional transaction building options.
447
+ *
448
+ * @returns An object containing the pending transaction.
449
+ *
450
+ * @example
451
+ * ```typescript
452
+ *
453
+ * const { transaction } = await client.initializePaymentChannels({
454
+ * sender: sender,
455
+ * });
456
+ * ```
457
+ */
458
+ async initializePaymentChannels(params) {
459
+ const transaction = await this.aptos.transaction.build.simple({
460
+ options: params.options,
461
+ data: {
462
+ function: `${(this.deployer ?? MICROPAYMENTS_DEPLOYER).toString()}::micropayments::initialize_payment_channels`,
463
+ functionArguments: []
464
+ },
465
+ sender: params.sender.accountAddress
466
+ });
467
+ return {
468
+ transaction: await this.aptos.signAndSubmitTransaction({
469
+ signer: params.sender,
470
+ transaction
471
+ })
472
+ };
473
+ }
474
+ /**
475
+ * Creates a micropayment channel to start a channel bweteen a sender and a receiver for a specific asset.
476
+ *
477
+ * @param params.deployer - Optional deployer account address. Defaults to SHELBY_DEPLOYER.
478
+ * @param params.sender - The account that will be sending funds.
479
+ * @param params.receiver - The account that will be receiving funds.
480
+ * @param params.expirationMicros - The expiration of the micropayment channel.
481
+ * @param params.depositAmount - The amount of the asset locked to the channel.
482
+ * @param params.fungibleAssetAddress - The account address of the fungible asset.
483
+ * @param params.options - Optional transaction building options.
484
+ *
485
+ * @returns An object containing the pending transaction.
486
+ *
487
+ * @example
488
+ * ```typescript
489
+ *
490
+ * const { transaction } = await client.createChannel({
491
+ * sender: sender,
492
+ * receiver: receiver,
493
+ * expirationMicros: Date.now() * 1000 + 86400_000_000, // 1 day from now in microseconds
494
+ * depositAmount: 0.001,
495
+ * fungibleAssetAddress: fungibleAssetAddress,
496
+ * });
497
+ * ```
498
+ */
499
+ async createChannel(params) {
500
+ const transaction = await this.aptos.transaction.build.simple({
501
+ options: params.options,
502
+ data: _ShelbyMicropaymentChannelClient.makeCreateMicropaymentChannelPayload(
503
+ {
504
+ deployer: this.deployer,
505
+ receiver: params.receiver,
506
+ expirationMicros: params.expirationMicros,
507
+ depositAmount: params.depositAmount,
508
+ fungibleAssetAddress: params.fungibleAssetAddress,
509
+ publicKey: params.publicKey ?? params.sender.publicKey.toUint8Array()
510
+ }
511
+ ),
512
+ sender: params.sender.accountAddress
513
+ });
514
+ return {
515
+ transaction: await this.aptos.signAndSubmitTransaction({
516
+ signer: params.sender,
517
+ transaction
518
+ })
519
+ };
520
+ }
521
+ /**
522
+ * Creates a micropayment channel creation payload to start a channel between a sender and a receiver for a specific asset.
523
+ * This is a static helper method for constructing the Move function call payload.
524
+ *
525
+ * @param params.deployer - Optional deployer account address. Defaults to MICROPAYMENTS_DEPLOYER.
526
+ * @param params.sender - The account that will be sending funds.
527
+ * @param params.receiver - The account that will be receiving funds.
528
+ * @param params.expirationMicros - The expiration of the micropayment channel.
529
+ * @param params.depositAmount - The amount of the asset locked to the channel.
530
+ * @param params.fungibleAssetAddress - The account address of the fungible asset.
531
+ * @param params.publicKey - The Ed25519 public key bytes for the channel.
532
+ *
533
+ * @returns An Aptos transaction payload data object for the create_channel Move function.
534
+ */
535
+ static makeCreateMicropaymentChannelPayload(params) {
536
+ return {
537
+ function: `${(params.deployer ?? MICROPAYMENTS_DEPLOYER).toString()}::micropayments::create_channel`,
538
+ functionArguments: [
539
+ params.receiver,
540
+ params.expirationMicros,
541
+ params.depositAmount,
542
+ params.fungibleAssetAddress,
543
+ MoveVector.U8(params.publicKey)
544
+ ]
545
+ };
546
+ }
547
+ /**
548
+ * Creates a micropayment that can be sent to a receiver.
549
+ * The sender signs a WithdrawApproval message that authorizes the receiver
550
+ * to withdraw funds from the micropayment channel.
551
+ *
552
+ * @param params.sender - The account that owns the payment channel and signs the approval.
553
+ * @param params.receiver - The account address that will receive funds.
554
+ * @param params.fungibleAssetAddress - The account address of the fungible asset.
555
+ * @param params.amount - The cumulative amount to authorize (not incremental).
556
+ * @param params.paymentChannelId - The id of the payment channel.
557
+ * @param params.sequenceNumber - The sequence number of the micropayment. Must be >= channel's next_withdrawn_sequence_number.
558
+ *
559
+ * @returns A SenderBuiltMicropayment containing the signed approval.
560
+ *
561
+ * @example
562
+ * ```typescript
563
+ * const senderBuiltMicropayment = client.createMicropayment({
564
+ * sender: senderAccount,
565
+ * receiver: receiverAddress,
566
+ * fungibleAssetAddress: fungibleAssetAddress,
567
+ * amount: 100,
568
+ * paymentChannelId: channelId,
569
+ * sequenceNumber: 1,
570
+ * });
571
+ * ```
572
+ */
573
+ createMicropayment(params) {
574
+ const message = SenderBuiltMicropayment.buildSignedMessage({
575
+ deployer: this.deployer,
576
+ sender: params.sender.accountAddress,
577
+ receiver: params.receiver,
578
+ fungibleAssetAddress: params.fungibleAssetAddress,
579
+ amount: params.amount,
580
+ paymentChannelId: params.paymentChannelId,
581
+ sequenceNumber: params.sequenceNumber
582
+ });
583
+ const signature = params.sender.sign(message);
584
+ return new SenderBuiltMicropayment(
585
+ params.sender.accountAddress,
586
+ params.receiver,
587
+ BigInt(params.paymentChannelId),
588
+ BigInt(params.amount),
589
+ params.fungibleAssetAddress,
590
+ BigInt(params.sequenceNumber),
591
+ params.sender.publicKey.toUint8Array(),
592
+ signature.toUint8Array(),
593
+ this.deployer
594
+ );
595
+ }
596
+ /**
597
+ * Creates a static payload for the receiver_withdraw Move function.
598
+ * This is a helper method for constructing the transaction payload.
599
+ *
600
+ * @param params.deployer - Optional deployer account address. Defaults to MICROPAYMENTS_DEPLOYER.
601
+ * @param params.sender - The sender's account address.
602
+ * @param params.fungibleAssetAddress - The account address of the fungible asset.
603
+ * @param params.amount - The cumulative amount authorized to withdraw.
604
+ * @param params.paymentChannelId - The payment channel id.
605
+ * @param params.sequenceNumber - The sequence number for this withdrawal.
606
+ * @param params.signature - The Ed25519 signature bytes.
607
+ *
608
+ * @returns An Aptos transaction payload data object for the receiver_withdraw Move function.
609
+ */
610
+ static createMicropaymentTransactionPayload(params) {
611
+ return {
612
+ function: `${(params.deployer ?? MICROPAYMENTS_DEPLOYER).toString()}::micropayments::receiver_withdraw`,
613
+ functionArguments: [
614
+ params.sender,
615
+ params.fungibleAssetAddress,
616
+ params.amount,
617
+ params.paymentChannelId,
618
+ params.sequenceNumber,
619
+ MoveVector.U8(params.signature)
620
+ ]
621
+ };
622
+ }
623
+ /**
624
+ * Withdraws funds from a micropayment channel as the receiver.
625
+ * The receiver submits the sender's signed approval to claim funds.
626
+ *
627
+ * @param params.receiver - The receiver account that will sign and submit the transaction.
628
+ * @param params.micropayment - The sender's signed micropayment approval.
629
+ * @param params.options - Optional transaction generation options.
630
+ *
631
+ * @returns An object containing the pending transaction.
632
+ *
633
+ * @example
634
+ * ```typescript
635
+ * const { transaction } = await client.receiverWithdraw({
636
+ * receiver: receiverAccount,
637
+ * micropayment: senderBuiltMicropayment,
638
+ * });
639
+ * ```
640
+ */
641
+ async receiverWithdraw(params) {
642
+ const transaction = await this.aptos.transaction.build.simple({
643
+ options: params.options,
644
+ data: _ShelbyMicropaymentChannelClient.createMicropaymentTransactionPayload(
645
+ {
646
+ deployer: this.deployer,
647
+ sender: params.micropayment.sender,
648
+ fungibleAssetAddress: params.micropayment.fungibleAssetAddress,
649
+ amount: params.micropayment.amount,
650
+ paymentChannelId: params.micropayment.paymentChannelId,
651
+ sequenceNumber: params.micropayment.sequenceNumber,
652
+ signature: params.micropayment.signature
653
+ }
654
+ ),
655
+ sender: params.receiver.accountAddress
656
+ });
657
+ return {
658
+ transaction: await this.aptos.signAndSubmitTransaction({
659
+ signer: params.receiver,
660
+ transaction
661
+ })
662
+ };
663
+ }
664
+ /**
665
+ * Extends the expiration time of a micropayment channel.
666
+ *
667
+ * @param params.sender - The owner of the account.
668
+ * @param params.receiver - The account address of the receiver.
669
+ * @param params.fungibleAssetAddress - The account address of the fungible asset.
670
+ * @param params.newExpirationMicros - The new expiration time in microseconds.
671
+ * @param params.options - Optional transaction generation options.
672
+ *
673
+ * @returns An object containing the pending transaction.
674
+ *
675
+ * @example
676
+ * ```typescript
677
+ * const { transaction } = await client.extendExpirationTime({
678
+ * sender: sender,
679
+ * receiver: receiverAddress,
680
+ * fungibleAssetAddress: fungibleAssetAddress,
681
+ * newExpirationMicros: Date.now() * 1000 + 172800_000_000, // 2 days from now
682
+ * });
683
+ * ```
684
+ */
685
+ async extendExpirationTime(params) {
686
+ const transaction = await this.aptos.transaction.build.simple({
687
+ options: params.options,
688
+ data: _ShelbyMicropaymentChannelClient.makeExtendExpirationTimePayload({
689
+ deployer: this.deployer,
690
+ receiver: params.receiver,
691
+ fungibleAssetAddress: params.fungibleAssetAddress,
692
+ newExpirationMicros: params.newExpirationMicros
693
+ }),
694
+ sender: params.sender.accountAddress
695
+ });
696
+ return {
697
+ transaction: await this.aptos.signAndSubmitTransaction({
698
+ signer: params.sender,
699
+ transaction
700
+ })
701
+ };
702
+ }
703
+ /**
704
+ * Creates a payload to extend the expiration time on a micropayment channel.
705
+ * This is a static helper method for constructing the Move function call payload.
706
+ *
707
+ * @param params.deployer - Optional deployer account address. Defaults to MICROPAYMENTS_DEPLOYER.
708
+ * @param params.receiver - The account that will be receiving funds.
709
+ * @param params.expirationMicros - The new expiration of the micropayment channel.
710
+ * @param params.fungibleAssetAddress - The account address of the fungible asset.
711
+ *
712
+ * @returns An Aptos transaction payload data object for the extend_expiration_time Move function.
713
+ */
714
+ static makeExtendExpirationTimePayload(params) {
715
+ return {
716
+ function: `${(params.deployer ?? MICROPAYMENTS_DEPLOYER).toString()}::micropayments::extend_expiration_time`,
717
+ functionArguments: [
718
+ params.receiver,
719
+ params.fungibleAssetAddress,
720
+ params.newExpirationMicros
721
+ ]
722
+ };
723
+ }
724
+ /**
725
+ * Increases the deposit amount locked in a micropayment channel.
726
+ *
727
+ * @param params.sender - The account that is increasing the deposit.
728
+ * @param params.receiver - The account address of the receiver.
729
+ * @param params.fungibleAssetAddress - The account address of the fungible asset.
730
+ * @param params.additionalAmount - The additional amount to deposit.
731
+ * @param params.options - Optional transaction generation options.
732
+ *
733
+ * @returns An object containing the pending transaction.
734
+ *
735
+ * @example
736
+ * ```typescript
737
+ * const { transaction } = await client.increaseDepositAmount({
738
+ * sender: sender,
739
+ * receiver: receiverAddress,
740
+ * fungibleAssetAddress: fungibleAssetAddress,
741
+ * additionalAmount: 500,
742
+ * });
743
+ * ```
744
+ */
745
+ async increaseDepositAmount(params) {
746
+ const transaction = await this.aptos.transaction.build.simple({
747
+ options: params.options,
748
+ data: _ShelbyMicropaymentChannelClient.makeIncreaseDepositAmountPayload({
749
+ deployer: this.deployer,
750
+ receiver: params.receiver,
751
+ fungibleAssetAddress: params.fungibleAssetAddress,
752
+ additionalAmount: params.additionalAmount
753
+ }),
754
+ sender: params.sender.accountAddress
755
+ });
756
+ return {
757
+ transaction: await this.aptos.signAndSubmitTransaction({
758
+ signer: params.sender,
759
+ transaction
760
+ })
761
+ };
762
+ }
763
+ /**
764
+ * Creates a payload to increase the deposit amount on a micropayment channel.
765
+ * This is a static helper method for constructing the Move function call payload.
766
+ *
767
+ * @param params.deployer - Optional deployer account address. Defaults to MICROPAYMENTS_DEPLOYER.
768
+ * @param params.receiver - The account that will be receiving funds.
769
+ * @param params.fungibleAssetAddress - The account address of the fungible asset.
770
+ * @param params.additionalAmount - The amount of the fungible asset to add to the channel's balance.
771
+ *
772
+ * @returns An Aptos transaction payload data object for the extend_expiration_time Move function.
773
+ */
774
+ static makeIncreaseDepositAmountPayload(params) {
775
+ return {
776
+ function: `${(params.deployer ?? MICROPAYMENTS_DEPLOYER).toString()}::micropayments::increase_deposit_amount`,
777
+ functionArguments: [
778
+ params.receiver,
779
+ params.fungibleAssetAddress,
780
+ params.additionalAmount
781
+ ]
782
+ };
783
+ }
784
+ /**
785
+ * Retrieves the vector of channels owned by the sender, optionally
786
+ * filtered by the receiver.
787
+ *
788
+ * @param params.sender - The account namespace owning the micropayment channels.
789
+ * @param params.receiver? - An optional receiver account address.
790
+ * @returns A vector of ChannelInfo objects.
791
+ *
792
+ * @example
793
+ * ```typescript
794
+ * const channelInfoVec = await client.getChannelInfo({
795
+ * sender: AccountAddress.fromString("0x1"),
796
+ * receiver: AccountAddress.fromString("0x2"),
797
+ * });
798
+ * ```
799
+ */
800
+ async getChannelInfo(params) {
801
+ const functionName = params.receiver ? "get_all_channels_from_sender_to_receiver" : "get_all_channels_from_sender";
802
+ const functionArguments = [params.sender];
803
+ if (params.receiver) {
804
+ functionArguments.push(params.receiver);
805
+ }
806
+ const rawArray = await this.aptos.view({
807
+ payload: {
808
+ function: `${this.deployer.toString()}::micropayments::${functionName}`,
809
+ functionArguments
810
+ }
811
+ });
812
+ const channelInfoArray = rawArray[0];
813
+ return channelInfoArray.map(
814
+ (channelInfo) => {
815
+ const publicKeyHex = channelInfo.public_key.startsWith("0x") ? channelInfo.public_key.slice(2) : channelInfo.public_key;
816
+ const publicKey = new Uint8Array(
817
+ publicKeyHex.match(/.{1,2}/g)?.map((byte) => Number.parseInt(byte, 16)) ?? []
818
+ );
819
+ return {
820
+ sender: params.sender,
821
+ receiver: params.receiver,
822
+ fungibleAssetAddress: normalizeAddress(
823
+ channelInfo.asset_metadata.inner
824
+ ),
825
+ balance: BigInt(channelInfo.balance),
826
+ creationMicros: BigInt(channelInfo.creation_micros),
827
+ expirationMicros: BigInt(channelInfo.expiration_micros),
828
+ nextWithdrawnSequenceNumber: BigInt(
829
+ channelInfo.next_withdrawn_sequence_number
830
+ ),
831
+ paymentChannelId: BigInt(channelInfo.payment_channel_id),
832
+ receiverWithdrawnAmount: BigInt(
833
+ channelInfo.receiver_withdrawn_amount
834
+ ),
835
+ publicKey
836
+ };
837
+ }
838
+ );
839
+ }
840
+ };
15
841
  export {
16
842
  ShelbyMicropaymentChannelClient
17
843
  };