@mysten/payment-kit 0.1.9 → 0.1.10

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.
@@ -1,527 +0,0 @@
1
- # Registry Management
2
-
3
- > Create, configure, and manage payment registries and accepted coin types on Sui.
4
-
5
- > **Note:** This package is in active development and should be used with caution. APIs are
6
- > experimental and subject to breaking changes without notice. We recommend thoroughly testing any
7
- > implementation before using in production environments.
8
-
9
- Payment registries are the core of Payment Kit's duplicate prevention and payment tracking system.
10
- This guide covers creating, configuring, and managing payment registries.
11
-
12
- ## Understanding payment registries
13
-
14
- A `PaymentRegistry` is an onchain object that:
15
-
16
- - Stores `PaymentRecord` dynamic fields for each unique payment
17
- - Manages configuration settings (expiration, fund management)
18
- - Can be owned and administered by a specific account
19
- - Provides namespaced payment tracking
20
-
21
- ### Default registry
22
-
23
- Payment Kit provides a default registry that's ready to use:
24
-
25
- ```ts
26
- // Use the default registry
27
- const tx = client.paymentKit.tx.processRegistryPayment({
28
- nonce: crypto.randomUUID(),
29
- coinType: '0x2::sui::SUI',
30
- amount: 1000000000,
31
- receiver,
32
- sender: senderAddress,
33
- });
34
- ```
35
-
36
- ### When to create a custom registry
37
-
38
- Consider creating your own registry when:
39
-
40
- - You want isolated payment tracking for your application
41
- - You need custom expiration policies
42
- - You want to manage funds centrally
43
- - You need better indexing of your payments
44
- - You want to avoid potential congestion on the default registry
45
-
46
- ## Creating a registry
47
-
48
- ### Basic registry creation
49
-
50
- Creating a registry is straightforward. You only need to provide a unique name:
51
-
52
- ```ts
53
- // Create a new registry
54
- const tx = client.paymentKit.tx.createRegistry({
55
- registryName: 'my-app-payments',
56
- });
57
-
58
- const result = await client.signAndExecuteTransaction({
59
- transaction: tx,
60
- signer: keypair,
61
- options: {
62
- showEffects: true,
63
- showObjectChanges: true,
64
- },
65
- });
66
-
67
- // Check transaction status
68
- if (result.$kind === 'FailedTransaction') {
69
- throw new Error(`Registry creation failed: ${result.FailedTransaction.status.error?.message}`);
70
- }
71
-
72
- console.log('Registry created!');
73
- console.log('Transaction:', result.Transaction.digest);
74
- ```
75
-
76
- ### What gets created
77
-
78
- When you create a registry, two objects are created:
79
-
80
- 1. **PaymentRegistry**: The registry object that stores payment records
81
- 2. **RegistryAdminCap**: A capability object that grants admin permissions
82
-
83
- ### Extracting the admin capability
84
-
85
- The `RegistryAdminCap` is crucial for configuring your registry:
86
-
87
- ```ts
88
- // Find the admin cap in the transaction result
89
- const adminCapObject = result.Transaction.objectChanges?.find(
90
- (change) => change.type === 'created' && change.objectType.includes('RegistryAdminCap'),
91
- );
92
-
93
- if (adminCapObject && 'objectId' in adminCapObject) {
94
- const adminCapId = adminCapObject.objectId;
95
-
96
- console.log('Admin Capability ID:', adminCapId);
97
-
98
- // Store this ID - you'll need it to configure the registry
99
- await database.saveAdminCap({
100
- registryName: 'my-app-payments',
101
- adminCapId: adminCapId,
102
- owner: senderAddress,
103
- });
104
- }
105
- ```
106
-
107
- ### Deriving the registry ID
108
-
109
- Payment Kit derives registry IDs deterministically from the registry name:
110
-
111
- ```ts
112
- // You can compute the registry ID without querying the chain
113
- const registryName = 'random-registry-name';
114
- const registryId = client.paymentKit.getRegistryIdFromName(registryName);
115
-
116
- console.log('Registry ID:', registryId);
117
- ```
118
-
119
- This allows you to reference registries by name throughout your application.
120
-
121
- ## Registry configuration
122
-
123
- Registries have two main configuration options:
124
-
125
- ### Step 1: Epoch expiration duration
126
-
127
- Controls how long payment records persist before they can be deleted.
128
-
129
- **Default**: 30 epochs (~30 days on Mainnet)
130
-
131
- ```ts
132
- // Set expiration to 60 epochs
133
- const tx = client.paymentKit.tx.setConfigEpochExpirationDuration({
134
- registryName: 'my-app-payments',
135
- epochExpirationDuration: 60,
136
- adminCapId: adminCapId,
137
- });
138
-
139
- const result = await client.signAndExecuteTransaction({
140
- transaction: tx,
141
- signer: keypair,
142
- });
143
-
144
- // Check transaction status
145
- if (result.$kind === 'FailedTransaction') {
146
- throw new Error(`Configuration update failed: ${result.FailedTransaction.status.error?.message}`);
147
- }
148
-
149
- console.log('Expiration set to 60 epochs');
150
- ```
151
-
152
- **How It Works:**
153
-
154
- When a payment is recorded, it stores the current epoch. After the expiration duration has passed,
155
- anyone can delete the record to reclaim storage fees:
156
-
157
- ```ts
158
- // Current epoch: 1000
159
- // Payment recorded at epoch: 1000
160
- // Expiration duration: 30
161
- // Can be deleted after epoch: 1030
162
- ```
163
-
164
- **Use Cases:**
165
-
166
- - **Short expiration (7-14 epochs)**: High-volume, time-sensitive payments (subscriptions, tickets)
167
- - **Medium expiration (30-60 epochs)**: Standard e-commerce transactions
168
- - **Long expiration (180+ epochs)**: Important financial records requiring long-term verification
169
-
170
- ### Step 2: Registry managed funds
171
-
172
- Controls whether payments must be sent to the registry itself for later withdrawal.
173
-
174
- **Default**: Disabled (funds go directly to receivers)
175
-
176
- ```ts
177
- // Enable registry-managed funds
178
- const tx = client.paymentKit.tx.setConfigRegistryManagedFunds({
179
- registryName: 'my-app-payments',
180
- registryManagedFunds: true,
181
- adminCapId: adminCapId,
182
- });
183
-
184
- await client.signAndExecuteTransaction({
185
- transaction: tx,
186
- signer: keypair,
187
- });
188
-
189
- console.log('Registry now manages funds');
190
- ```
191
-
192
- **How it works:**
193
-
194
- When enabled:
195
-
196
- - All payments must specify the registry as the receiver
197
- - Coins are transferred to the registry object
198
- - Registry admin can withdraw accumulated funds later
199
- - Simplifies coin merging for high-throughput scenarios
200
-
201
- ```ts
202
- // With registry-managed funds enabled
203
- const registryId = getRegistryIdFromName('my-app-payments', namespaceId);
204
-
205
- const tx = client.paymentKit.tx.processRegistryPayment({
206
- nonce: crypto.randomUUID(),
207
- coinType: '0x2::sui::SUI',
208
- amount: 1000000000,
209
- receiver: registryId, // Must be the registry itself
210
- sender: senderAddress,
211
- registryName: 'my-app-payments',
212
- });
213
- ```
214
-
215
- **Use Cases:**
216
-
217
- - Platforms collecting payments on behalf of sellers
218
- - Applications that need to batch process payouts
219
- - Scenarios with very high transaction volumes
220
- - Simplified accounting and reconciliation
221
-
222
- ### Configuring both settings
223
-
224
- You can configure both settings independently:
225
-
226
- ```ts
227
- const tx = new Transaction();
228
-
229
- // Set expiration duration
230
- tx.add(
231
- client.paymentKit.calls.setConfigEpochExpirationDuration({
232
- registryName: 'my-app-payments',
233
- epochExpirationDuration: 90,
234
- adminCapId: adminCapId,
235
- }),
236
- );
237
-
238
- // Enable managed funds
239
- tx.add(
240
- client.paymentKit.calls.setConfigRegistryManagedFunds({
241
- registryName: 'my-app-payments',
242
- registryManagedFunds: true,
243
- adminCapId: adminCapId,
244
- }),
245
- );
246
-
247
- // Apply both configurations in one transaction
248
- await client.signAndExecuteTransaction({
249
- transaction: tx,
250
- signer: keypair,
251
- });
252
- ```
253
-
254
- ## Withdrawing funds from a registry
255
-
256
- If you've enabled registry-managed funds, you can withdraw accumulated coins:
257
-
258
- ```ts
259
- // Withdraw all SUI from the registry
260
- const tx = client.paymentKit.tx.withdrawFromRegistry({
261
- coinType: '0x2::sui::SUI',
262
- registryName: 'my-app-payments',
263
- adminCapId: adminCapId,
264
- });
265
-
266
- const result = await client.signAndExecuteTransaction({
267
- transaction: tx,
268
- signer: keypair,
269
- options: {
270
- showEffects: true,
271
- },
272
- });
273
-
274
- console.log('Funds withdrawn!');
275
- ```
276
-
277
- **Important notes:**
278
-
279
- - Only the admin cap owner can withdraw funds
280
- - You must specify the coin type to withdraw
281
- - All coins of that type are withdrawn in one operation
282
- - The withdrawn coins are sent to the transaction sender
283
-
284
- ### Withdrawing multiple coin types
285
-
286
- If your registry accumulates different coin types:
287
-
288
- ```ts
289
- const tx = new Transaction();
290
-
291
- // Withdraw SUI
292
- tx.add(
293
- client.paymentKit.calls.withdrawFromRegistry({
294
- coinType: '0x2::sui::SUI',
295
- registryName: 'my-app-payments',
296
- adminCapId: adminCapId,
297
- }),
298
- );
299
-
300
- // Withdraw custom token
301
- tx.add(
302
- client.paymentKit.calls.withdrawFromRegistry({
303
- coinType: '0xabc123::my_token::MY_TOKEN',
304
- registryName: 'my-app-payments',
305
- adminCapId: adminCapId,
306
- }),
307
- );
308
-
309
- await client.signAndExecuteTransaction({
310
- transaction: tx,
311
- signer: keypair,
312
- });
313
- ```
314
-
315
- ## Deleting expired payment records
316
-
317
- After the expiration period, payment records can be deleted to reclaim storage fees:
318
-
319
- ```ts
320
- // Delete an expired payment record
321
- const tx = client.paymentKit.tx.deletePaymentRecord({
322
- nonce: crypto.randomUUID(),
323
- coinType: '0x2::sui::SUI',
324
- amount: 1000000000,
325
- receiver,
326
- registryName: 'my-app-payments',
327
- });
328
-
329
- const result = await client.signAndExecuteTransaction({
330
- transaction: tx,
331
- signer: keypair,
332
- });
333
-
334
- console.log('Record deleted, storage rebate received');
335
- ```
336
-
337
- **Key points:**
338
-
339
- - Records can only be deleted after expiration
340
- - Anyone can delete expired records (permissionless cleanup)
341
- - The deleter receives a small storage rebate
342
- - This incentivizes automatic cleanup of old records
343
-
344
- ### Checking if a record can be deleted
345
-
346
- ```ts
347
- // Get the payment record
348
- const record = await client.paymentKit.getPaymentRecord({
349
- nonce: crypto.randomUUID(),
350
- coinType: '0x2::sui::SUI',
351
- amount: 1000000000,
352
- receiver,
353
- registryName: 'my-app-payments',
354
- });
355
-
356
- if (record) {
357
- const recordEpoch = parseInt(record.epochAtTimeOfRecord);
358
- const currentEpoch = await client.core
359
- .getLatestSuiSystemState()
360
- .then((state) => Number(state.epoch));
361
-
362
- const expirationDuration = 30; // Your registry's setting
363
- const canDelete = currentEpoch >= recordEpoch + expirationDuration;
364
-
365
- console.log('Record epoch:', recordEpoch);
366
- console.log('Current epoch:', currentEpoch);
367
- console.log('Can delete:', canDelete);
368
- }
369
- ```
370
-
371
- ## Using registry ID directly
372
-
373
- If you know the registry ID, you can use it instead of the name:
374
-
375
- ```ts
376
- const registryId = '0x123abc...';
377
-
378
- // Process payment using registry ID
379
- const tx = client.paymentKit.tx.processRegistryPayment({
380
- nonce: crypto.randomUUID(),
381
- coinType: '0x2::sui::SUI',
382
- amount: 1000000000,
383
- receiver,
384
- sender: senderAddress,
385
- registryId: registryId, // Use ID instead of name
386
- });
387
-
388
- // Query using registry ID
389
- const record = await client.paymentKit.getPaymentRecord({
390
- nonce: crypto.randomUUID(),
391
- coinType: '0x2::sui::SUI',
392
- amount: 1000000000,
393
- receiver,
394
- registryId: registryId,
395
- });
396
- ```
397
-
398
- ## Complete registry setup example
399
-
400
- Here's a complete workflow for setting up a custom registry:
401
-
402
- ```ts
403
- const client = new SuiGrpcClient({
404
- network: 'testnet',
405
- baseUrl: 'https://fullnode.testnet.sui.io:443',
406
- }).$extend(paymentKit());
407
-
408
- const keypair = Ed25519Keypair.generate();
409
- const registryName = 'my-marketplace-registry';
410
-
411
- // Step 1: Create the registry
412
- console.log('Creating registry...');
413
- const createTx = client.paymentKit.tx.createRegistry({
414
- registryName: registryName,
415
- });
416
-
417
- const createResult = await client.signAndExecuteTransaction({
418
- transaction: createTx,
419
- signer: keypair,
420
- options: {
421
- showEffects: true,
422
- showObjectChanges: true,
423
- },
424
- });
425
-
426
- // Check transaction status
427
- if (createResult.$kind === 'FailedTransaction') {
428
- throw new Error(
429
- `Registry creation failed: ${createResult.FailedTransaction.status.error?.message}`,
430
- );
431
- }
432
-
433
- // Step 2: Extract the admin cap
434
- const adminCapObject = createResult.Transaction.objectChanges?.find(
435
- (change) => change.type === 'created' && change.objectType.includes('RegistryAdminCap'),
436
- );
437
-
438
- const adminCapId = adminCapObject && 'objectId' in adminCapObject ? adminCapObject.objectId : '';
439
-
440
- console.log('Registry created!');
441
- console.log('Admin Cap ID:', adminCapId);
442
-
443
- // Step 3: Configure the registry
444
- console.log('Configuring registry...');
445
- const configTx = new Transaction();
446
-
447
- // Set 60-epoch expiration
448
- configTx.add(
449
- client.paymentKit.calls.setConfigEpochExpirationDuration({
450
- registryName: registryName,
451
- epochExpirationDuration: 60,
452
- adminCapId: adminCapId,
453
- }),
454
- );
455
-
456
- // Enable managed funds
457
- configTx.add(
458
- client.paymentKit.calls.setConfigRegistryManagedFunds({
459
- registryName: registryName,
460
- registryManagedFunds: true,
461
- adminCapId: adminCapId,
462
- }),
463
- );
464
-
465
- const configResult = await client.signAndExecuteTransaction({
466
- transaction: configTx,
467
- signer: keypair,
468
- });
469
-
470
- // Check transaction status
471
- if (configResult.$kind === 'FailedTransaction') {
472
- throw new Error(`Configuration failed: ${configResult.FailedTransaction.status.error?.message}`);
473
- }
474
-
475
- console.log('Registry configured!');
476
- console.log('Ready to process payments');
477
-
478
- // Step 4: Process a payment
479
- const registryId = getRegistryIdFromName(registryName, namespaceId);
480
-
481
- const paymentTx = client.paymentKit.tx.processRegistryPayment({
482
- nonce: crypto.randomUUID(),
483
- coinType: '0x2::sui::SUI',
484
- amount: 1000000000,
485
- receiver: registryId, // Funds go to registry
486
- sender: keypair.getPublicKey().toSuiAddress(),
487
- registryName: registryName,
488
- });
489
-
490
- const paymentResult = await client.signAndExecuteTransaction({
491
- transaction: paymentTx,
492
- signer: keypair,
493
- });
494
-
495
- // Check transaction status
496
- if (paymentResult.$kind === 'FailedTransaction') {
497
- throw new Error(`Payment failed: ${paymentResult.FailedTransaction.status.error?.message}`);
498
- }
499
-
500
- console.log('First payment processed:', paymentResult.Transaction.digest);
501
- ```
502
-
503
- ## Best practices
504
-
505
- 1. **Store admin caps securely**: Treat your admin capability like private keys - they control your
506
- registry
507
-
508
- 2. **Use descriptive names**: Choose registry names that clearly identify their purpose (for
509
- example, `acme-subscriptions`, `store-123-payments`)
510
-
511
- 3. **Set appropriate expiration**: Balance storage costs with verification needs
512
- - Short expiration = lower storage costs
513
- - Long expiration = longer verification period
514
-
515
- 4. **Monitor registry growth**: Track the number of payment records to anticipate storage costs
516
-
517
- 5. **Plan fund management**: Decide upfront whether to use registry-managed funds based on your
518
- withdrawal patterns
519
-
520
- 6. **Document your configuration**: Keep records of your registry settings for operational
521
- consistency
522
-
523
- 7. **Test thoroughly**: Always test registry operations on Testnet before Mainnet deployment
524
-
525
- ## Next steps
526
-
527
- - [SDK API Reference](./payment-kit-sdk) - Complete SDK API documentation