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