@mysten/payment-kit 0.1.2 → 0.1.3

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.
@@ -0,0 +1,252 @@
1
+ # Getting Started
2
+
3
+ > Install and set up Payment Kit for your Sui dApp
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
+ This guide will help you set up and start using the Payment Kit SDK in your Sui application.
10
+
11
+ ## Prerequisites
12
+
13
+ Before you begin, ensure you have:
14
+
15
+ - A Sui wallet with testnet/mainnet SUI tokens
16
+ - Basic understanding of TypeScript and the Sui blockchain
17
+
18
+ ## Installation
19
+
20
+ Install the Payment Kit SDK and the Sui TypeScript SDK:
21
+
22
+ ```bash npm2yarn
23
+ npm install --save @mysten/payment-kit @mysten/sui
24
+ ```
25
+
26
+ ## Setting Up the Client
27
+
28
+ The Payment Kit SDK extends the standard `SuiGrpcClient` to provide payment functionality. Here's
29
+ how to set it up:
30
+
31
+ ```ts
32
+ // Create a Sui client with Payment Kit extension
33
+ const client = new SuiGrpcClient({
34
+ network: 'testnet',
35
+ baseUrl: 'https://fullnode.testnet.sui.io:443',
36
+ }).$extend(paymentKit());
37
+ ```
38
+
39
+ The client will automatically configure the correct package IDs for the network you're using
40
+ (testnet or mainnet).
41
+
42
+ ## Your First Payment
43
+
44
+ Let's process a simple registry-based payment using the default payment registry:
45
+
46
+ ```ts
47
+ // Create or load your keypair
48
+ const keypair = Ed25519Keypair.generate();
49
+ const sender = keypair.getPublicKey().toSuiAddress();
50
+
51
+ // Create the payment transaction
52
+ const tx = client.paymentKit.tx.processRegistryPayment({
53
+ nonce: crypto.randomUUID(), // Unique identifier for this payment
54
+ coinType: '0x2::sui::SUI', // Coin type (SUI in this case)
55
+ amount: 1n * MIST_PER_SUI, // 1 SUI (in MIST)
56
+ receiver,
57
+ sender: sender,
58
+ });
59
+
60
+ // Sign and execute
61
+ const result = await client.signAndExecuteTransaction({
62
+ transaction: tx,
63
+ signer: keypair,
64
+ options: {
65
+ showEffects: true,
66
+ showEvents: true,
67
+ },
68
+ });
69
+
70
+ // Check transaction status
71
+ if (result.$kind === 'FailedTransaction') {
72
+ throw new Error(`Payment failed: ${result.FailedTransaction.status.error?.message}`);
73
+ }
74
+
75
+ console.log('Payment processed:', result.Transaction.digest);
76
+ ```
77
+
78
+ ## Understanding the Payment
79
+
80
+ In this example:
81
+
82
+ 1. **Nonce**: A unique identifier (UUIDv4) that prevents duplicate payments when using a registry
83
+ 2. **Coin Type**: The type of coin being transferred (SUI token)
84
+ 3. **Amount**: The payment amount in the smallest unit (MIST for SUI)
85
+ 4. **Receiver**: The address receiving the payment
86
+ 5. **Sender**: The address sending the payment (must match the transaction signer)
87
+ 6. **Registry Name**: The payment registry to use (defaults to `DEFAULT_REGISTRY_NAME`)
88
+
89
+ ## Verifying the Payment
90
+
91
+ After processing a payment, you can query the payment record to verify it exists:
92
+
93
+ ```ts
94
+ // Query the payment record
95
+ const paymentRecord = await client.paymentKit.getPaymentRecord({
96
+ nonce: crypto.randomUUID(),
97
+ coinType: '0x2::sui::SUI',
98
+ amount: 1n * MIST_PER_SUI,
99
+ receiver,
100
+ });
101
+
102
+ if (paymentRecord) {
103
+ console.log('Payment verified!');
104
+ console.log('Transaction:', paymentRecord.paymentTransactionDigest);
105
+ console.log('Epoch:', paymentRecord.epochAtTimeOfRecord);
106
+ } else {
107
+ console.log('Payment not found');
108
+ }
109
+ ```
110
+
111
+ ## Processing an Ephemeral Payment
112
+
113
+ If you don't need duplicate prevention or persistent storage, use ephemeral payments:
114
+
115
+ ```ts
116
+ const tx = client.paymentKit.tx.processEphemeralPayment({
117
+ nonce: crypto.randomUUID(),
118
+ coinType: '0x2::sui::SUI',
119
+ amount: 1n * MIST_PER_SUI,
120
+ receiver,
121
+ sender: sender,
122
+ });
123
+
124
+ const result = await client.signAndExecuteTransaction({
125
+ transaction: tx,
126
+ signer: keypair,
127
+ });
128
+
129
+ // Check transaction status
130
+ if (result.$kind === 'FailedTransaction') {
131
+ throw new Error(`Ephemeral payment failed: ${result.FailedTransaction.status.error?.message}`);
132
+ }
133
+
134
+ console.log('Ephemeral payment processed:', result.Transaction.digest);
135
+ ```
136
+
137
+ Ephemeral payments:
138
+
139
+ - Don't create a `PaymentRecord`
140
+ - Don't prevent duplicates
141
+ - Still emit a `PaymentReceipt` event
142
+ - Have lower gas costs
143
+
144
+ ## Working with Different Coin Types
145
+
146
+ Payment Kit supports any Sui coin type. Here's how to process payments with custom coins:
147
+
148
+ ```ts
149
+ // Example with a custom coin type
150
+ const customCoinType = '0xabcd...::my_coin::MY_COIN';
151
+
152
+ const tx = client.paymentKit.tx.processRegistryPayment({
153
+ nonce: crypto.randomUUID(),
154
+ coinType: customCoinType,
155
+ amount: 5000,
156
+ receiver,
157
+ sender: sender,
158
+ });
159
+
160
+ // Execute the transaction
161
+ const result = await client.signAndExecuteTransaction({
162
+ transaction: tx,
163
+ signer: keypair,
164
+ });
165
+ ```
166
+
167
+ ## Error Handling
168
+
169
+ Always wrap payment operations in try-catch blocks:
170
+
171
+ ```ts
172
+ try {
173
+ const tx = client.paymentKit.tx.processRegistryPayment({...});
174
+ const result = await client.signAndExecuteTransaction({
175
+ transaction: tx,
176
+ signer: keypair,
177
+ });
178
+
179
+ if (result.$kind === 'FailedTransaction') {
180
+ throw new Error(`Payment failed: ${result.FailedTransaction.status.error?.message}`);
181
+ }
182
+
183
+ console.log('Success:', result.Transaction.digest);
184
+ } catch (error) {
185
+ if (error.message.includes('Duplicate')) {
186
+ console.error('Payment already processed');
187
+ } else if (error.message.includes('insufficient')) {
188
+ console.error('Insufficient balance');
189
+ } else {
190
+ console.error('Payment failed:', error.message);
191
+ }
192
+ }
193
+ ```
194
+
195
+ ## Creating Payment URIs
196
+
197
+ Payment Kit provides helper functions to create and parse Payment Kit transaction URIs. These URIs
198
+ are useful for generating payment links, QR codes, or deep links in your application:
199
+
200
+ ```ts
201
+ // Create a payment URI
202
+ const paymentUri = createPaymentTransactionUri({
203
+ receiverAddress: '0x123...abc',
204
+ amount: 1000000000n, // 1 SUI in MIST
205
+ coinType: '0x2::sui::SUI',
206
+ nonce: crypto.randomUUID(),
207
+ label: 'Coffee Payment',
208
+ message: 'Payment for espresso',
209
+ registryName: 'my-registry', // Optional: specify a registry name
210
+ // Or use registryId: '0x...' for a specific registry object ID
211
+ });
212
+
213
+ console.log(paymentUri);
214
+ // Output: sui:pay?receiver=0x123...abc&amount=1000000000&coinType=0x2%3A%3Asui%3A%3ASUI&nonce=...&label=Coffee%20Payment&message=Payment%20for%20espresso&registry=my-registry
215
+ ```
216
+
217
+ The URI parameters include:
218
+
219
+ - **receiver**: The Sui address receiving the payment (required)
220
+ - **amount**: The payment amount as a positive bigint (required)
221
+ - **coinType**: The coin type being transferred (required)
222
+ - **nonce**: A unique identifier up to 36 characters (required)
223
+ - **registry**: Either a registry name or object ID (optional)
224
+ - **label**: A short label for the payment (optional)
225
+ - **message**: A longer description message (optional)
226
+ - **iconUrl**: URL to an icon for display purposes (optional)
227
+
228
+ You can then parse URIs back into payment parameters:
229
+
230
+ ```ts
231
+ // Parse a payment URI
232
+ const params = parsePaymentTransactionUri(paymentUri);
233
+ // Returns: { receiverAddress, amount, coinType, nonce, label?, message?, iconUrl?, registryName? | registryId? }
234
+
235
+ // Use the parsed parameters to create a transaction
236
+ const tx = client.paymentKit.tx.processRegistryPayment({
237
+ receiver: params.receiverAddress,
238
+ amount: params.amount,
239
+ coinType: params.coinType,
240
+ nonce: params.nonce,
241
+ registryName: params.registryName,
242
+ sender: sender,
243
+ });
244
+ ```
245
+
246
+ ## Next Steps
247
+
248
+ Now that you understand the basics, explore more advanced features:
249
+
250
+ - [Payment Processing](./payment-processing) - Deep dive into payment models
251
+ - [Registry Management](./registry-management) - Create and configure custom registries
252
+ - [SDK API Reference](./payment-kit-sdk) - Complete SDK API documentation
package/docs/index.md ADDED
@@ -0,0 +1,131 @@
1
+ # Payment Kit
2
+
3
+ > Accept payments in any coin type 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
+ The Sui Payment Kit SDK is a TypeScript library that provides a simple and secure way to process
10
+ blockchain payments on the Sui network. It offers flexible payment processing with built-in
11
+ duplicate prevention, configurable payment registries, and comprehensive receipt management.
12
+
13
+ ## Overview
14
+
15
+ Payment Kit enables developers to integrate secure payment processing into their Sui applications
16
+ with minimal setup. The SDK provides two payment models:
17
+
18
+ - **Registry-based payments**: Persistent payment records with duplicate prevention and configurable
19
+ expiration
20
+ - **Ephemeral payments**: Lightweight payment processing without persistent storage
21
+
22
+ All payments emit a `PaymentReceipt` that can be stored off-chain for verification and
23
+ record-keeping.
24
+
25
+ ## Key Features
26
+
27
+ - **Duplicate Prevention**: Registry-based payments automatically prevent duplicate transactions
28
+ - **Flexible Payment Models**: Choose between registry-based or ephemeral payment processing
29
+ - **Payment Registries**: Create and manage custom payment registries with configurable policies
30
+ - **Receipt Management**: Automatic receipt generation for all payments
31
+ - **Multi-coin Support**: Process payments with any Sui coin type
32
+ - **Configurable Expiration**: Set custom expiration policies for payment records
33
+ - **Fund Management**: Optional registry-managed funds for simplified coin handling
34
+
35
+ ## Installation
36
+
37
+ ```bash npm2yarn
38
+ npm install --save @mysten/payment-kit @mysten/sui
39
+ ```
40
+
41
+ ## Quick Start
42
+
43
+ ```ts
44
+ // Create a Sui client with a Payment Kit extension
45
+ const client = new SuiGrpcClient({
46
+ network: 'testnet',
47
+ baseUrl: 'https://fullnode.testnet.sui.io:443',
48
+ }).$extend(paymentKit());
49
+
50
+ // Process a registry-based payment
51
+ const tx = client.paymentKit.tx.processRegistryPayment({
52
+ nonce: crypto.randomUUID(),
53
+ coinType: '0x2::sui::SUI',
54
+ amount: 1n * MIST_PER_SUI, // 1 SUI in MIST
55
+ receiver: '0x123...abc',
56
+ sender: '0x456...def',
57
+ });
58
+
59
+ // Sign and execute the transaction
60
+ const result = await client.signAndExecuteTransaction({
61
+ transaction: tx,
62
+ signer: keypair,
63
+ });
64
+
65
+ // Check transaction status
66
+ if (result.$kind === 'FailedTransaction') {
67
+ throw new Error(`Payment failed: ${result.FailedTransaction.status.error?.message}`);
68
+ }
69
+ ```
70
+
71
+ ## Network Support
72
+
73
+ Payment Kit supports the following Sui networks:
74
+
75
+ - **Mainnet**: Production environment
76
+ - **Testnet**: Testing environment
77
+
78
+ The SDK automatically configures the correct package and object IDs based on the network specified
79
+ in your `SuiGrpcClient` configuration.
80
+
81
+ ## Core Concepts
82
+
83
+ ### Payment Processing
84
+
85
+ Payment Kit offers two distinct payment processing models to suit different application needs:
86
+
87
+ 1. **Registry-based Payments**: Creates a persistent `PaymentRecord` that prevents duplicate
88
+ payments and provides verifiable proof of payment
89
+ 2. **Ephemeral Payments**: Processes payments without persistent storage, suitable for scenarios
90
+ where duplicate prevention is handled externally
91
+
92
+ ### Payment Registries
93
+
94
+ A `PaymentRegistry` manages payment records and configurations. Benefits include:
95
+
96
+ - Centralized payment tracking
97
+ - Configurable expiration policies
98
+ - Optional fund management
99
+ - Custom naming for easy identification and indexing
100
+
101
+ ### Payment Records
102
+
103
+ When using registry-based payments, a `PaymentRecord` is created as a Dynamic Field on the registry.
104
+ Records are identified by a composite key derived from:
105
+
106
+ - Payment nonce (unique identifier)
107
+ - Payment amount
108
+ - Coin type
109
+ - Receiver address
110
+
111
+ ### Payment Receipts
112
+
113
+ Every payment (registry-based or ephemeral) emits a `PaymentReceipt` event containing:
114
+
115
+ ```ts
116
+ type PaymentReceipt = {
117
+ paymentType: 'Registry' | 'Ephemeral';
118
+ nonce: string;
119
+ amount: number;
120
+ receiver: string;
121
+ coinType: string;
122
+ timestampMs: number;
123
+ };
124
+ ```
125
+
126
+ ## Next Steps
127
+
128
+ - [Getting Started Guide](/payment-kit/getting-started) - Detailed setup and usage instructions
129
+ - [Payment Processing](/payment-kit/payment-processing) - Learn about different payment models
130
+ - [Registry Management](/payment-kit/registry-management) - Create and configure payment registries
131
+ - [SDK API Reference](/payment-kit/payment-kit-sdk) - Complete SDK API documentation
@@ -0,0 +1,9 @@
1
+ # Payment Kit
2
+
3
+ > Accept payments in any coin type on Sui
4
+
5
+ - [Payment Kit](./index.md): Accept payments in any coin type on Sui
6
+ - [Getting Started](./getting-started.md): Install and set up Payment Kit for your Sui dApp
7
+ - [Payment Kit SDK](./payment-kit-sdk.md): Payment Kit SDK API reference and configuration
8
+ - [Payment Processing](./payment-processing.md): Process payments and handle transaction results
9
+ - [Registry Management](./registry-management.md): Manage payment registries and accepted coin types