@zkp2p/sdk 0.0.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.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 ZKP2P Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
package/README.md ADDED
@@ -0,0 +1,547 @@
1
+ # @zkp2p/client-sdk
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@zkp2p/client-sdk.svg)](https://www.npmjs.com/package/@zkp2p/client-sdk)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.0%2B-blue)](https://www.typescriptlang.org/)
6
+
7
+ **ZKP2P Client SDK** - TypeScript SDK for **liquidity providers** who want to offer fiat off-ramp services on Base.
8
+
9
+ ## Who Is This For?
10
+
11
+ This SDK is designed for **liquidity providers (peers)** who want to:
12
+ - Create and manage USDC deposits that accept fiat payments
13
+ - Configure payment methods, currencies, and conversion rates
14
+ - Monitor deposit utilization and manage liquidity
15
+ - Earn fees by providing off-ramp services
16
+
17
+ ## RPC-First Architecture
18
+
19
+ This SDK uses **RPC-first queries** via ProtocolViewer for instant, real-time on-chain data:
20
+
21
+ - **No indexer lag**: Queries go directly to the blockchain
22
+ - **Always fresh**: See deposit/intent state immediately after transactions
23
+ - **Instant feedback**: Perfect for interactive UIs
24
+
25
+ Advanced historical queries (pagination, filtering, fulfillment records) are available via `client.indexer.*`.
26
+
27
+ ## Core Features (Deposit Management)
28
+
29
+ | Feature | Description |
30
+ |---------|-------------|
31
+ | **Create Deposits** | Lock USDC and define accepted payment methods |
32
+ | **Configure Rates** | Set conversion rates per currency and payment platform |
33
+ | **Manage Funds** | Add/remove funds, withdraw deposits |
34
+ | **Payment Methods** | Wise, Venmo, Revolut, CashApp, PayPal, Zelle, Monzo, MercadoPago |
35
+ | **Multi-Currency** | Support USD, EUR, GBP, and 25+ fiat currencies |
36
+ | **Query Deposits** | Real-time on-chain queries via ProtocolViewer |
37
+ | **React Hooks** | Full suite of React hooks for frontend integration |
38
+
39
+ ## Supporting Features
40
+
41
+ The SDK also includes supporting functionality for the broader ZKP2P ecosystem:
42
+
43
+ - **Intent Operations**: `signalIntent()`, `fulfillIntent()`, `cancelIntent()` (typically used by takers/buyers)
44
+ - **Quote API**: `getQuote()` (used by frontends to display available liquidity)
45
+ - **Indexer Queries**: Historical data, pagination, and advanced filtering via `client.indexer.*`
46
+
47
+ ## Installation
48
+
49
+ ```bash
50
+ npm install @zkp2p/client-sdk viem
51
+ # or
52
+ yarn add @zkp2p/client-sdk viem
53
+ # or
54
+ pnpm add @zkp2p/client-sdk viem
55
+ ```
56
+
57
+ ## Quick Start
58
+
59
+ ### Initialize the Client
60
+
61
+ ```typescript
62
+ import { OfframpClient } from '@zkp2p/client-sdk';
63
+ import { createWalletClient, custom } from 'viem';
64
+ import { base } from 'viem/chains';
65
+
66
+ const walletClient = createWalletClient({
67
+ chain: base,
68
+ transport: custom(window.ethereum),
69
+ });
70
+
71
+ const client = new OfframpClient({
72
+ walletClient,
73
+ chainId: base.id,
74
+ apiKey: 'YOUR_API_KEY', // Optional for API operations
75
+ });
76
+ ```
77
+
78
+ ## Core Operations
79
+
80
+ ### Creating a Deposit
81
+
82
+ Provide liquidity by creating a deposit with your preferred payment methods and currencies:
83
+
84
+ ```typescript
85
+ import { Currency } from '@zkp2p/client-sdk';
86
+
87
+ await client.createDeposit({
88
+ token: '0xUSDC_ADDRESS',
89
+ amount: 10000000000n, // 10,000 USDC (6 decimals)
90
+ intentAmountRange: { min: 100000n, max: 1000000000n },
91
+ processorNames: ['wise', 'revolut'],
92
+ depositData: [
93
+ { email: 'maker@example.com' }, // Wise payment details
94
+ { tag: '@maker' }, // Revolut payment details
95
+ ],
96
+ conversionRates: [
97
+ [{ currency: Currency.USD, conversionRate: '1020000000000000000' }], // 1.02 (18 decimals)
98
+ [{ currency: Currency.EUR, conversionRate: '950000000000000000' }], // 0.95 (18 decimals)
99
+ ],
100
+ onSuccess: ({ hash }) => console.log('Deposit created:', hash),
101
+ });
102
+ ```
103
+
104
+ ### Managing Deposit Settings
105
+
106
+ ```typescript
107
+ // Toggle accepting intents
108
+ await client.setAcceptingIntents({ depositId: 1n, accepting: true });
109
+
110
+ // Update intent amount range
111
+ await client.setIntentRange({ depositId: 1n, min: 50000n, max: 5000000n });
112
+
113
+ // Set minimum conversion rate for a currency
114
+ await client.setCurrencyMinRate({
115
+ depositId: 1n,
116
+ paymentMethod: '0x...',
117
+ fiatCurrency: '0x...',
118
+ minConversionRate: 1020000n, // 1.02 rate
119
+ });
120
+ ```
121
+
122
+ ### Fund Management
123
+
124
+ ```typescript
125
+ // Add more funds to your deposit
126
+ await client.addFunds({ depositId: 1n, amount: 5000000n });
127
+
128
+ // Remove funds from deposit
129
+ await client.removeFunds({ depositId: 1n, amount: 1000000n });
130
+
131
+ // Withdraw entire deposit
132
+ await client.withdrawDeposit({ depositId: 1n });
133
+ ```
134
+
135
+ ### Querying Deposits (RPC-first)
136
+
137
+ ```typescript
138
+ // Get all your deposits (instant on-chain query)
139
+ const deposits = await client.getDeposits();
140
+
141
+ // Get deposits for any address
142
+ const ownerDeposits = await client.getAccountDeposits('0xOwnerAddress');
143
+
144
+ // Get a specific deposit by ID
145
+ const deposit = await client.getDeposit(42n);
146
+ console.log(`Available liquidity: ${deposit.availableLiquidity}`);
147
+ console.log(`Payment methods: ${deposit.paymentMethods.length}`);
148
+
149
+ // Get multiple deposits by ID
150
+ const batch = await client.getDepositsById([1n, 2n, 3n]);
151
+ ```
152
+
153
+ ### Querying Intents (RPC-first)
154
+
155
+ ```typescript
156
+ // Get all your intents
157
+ const intents = await client.getIntents();
158
+
159
+ // Get intents for any address
160
+ const ownerIntents = await client.getAccountIntents('0xOwnerAddress');
161
+
162
+ // Get a specific intent by hash
163
+ const intent = await client.getIntent('0xIntentHash...');
164
+ ```
165
+
166
+ ### Advanced Indexer Queries
167
+
168
+ For historical data, pagination, and advanced filtering:
169
+
170
+ ```typescript
171
+ // Query with filters and pagination
172
+ const deposits = await client.indexer.getDeposits(
173
+ { status: 'ACTIVE', minLiquidity: '1000000', depositor: '0xYourAddress' }, // Note: use 'depositor', not 'owner'
174
+ { limit: 50, orderBy: 'remainingDeposits', orderDirection: 'desc' }
175
+ );
176
+
177
+ // Get deposits with related data
178
+ const depositsWithRelations = await client.indexer.getDepositsWithRelations(
179
+ { status: 'ACTIVE' },
180
+ { limit: 50 },
181
+ { includeIntents: true, intentStatuses: ['SIGNALED'] }
182
+ );
183
+
184
+ // Historical fulfillment records
185
+ const fulfillments = await client.indexer.getFulfilledIntentEvents(['0x...']);
186
+
187
+ // Find deposits by payee
188
+ const payeeDeposits = await client.indexer.getDepositsByPayeeHash('0x...');
189
+ ```
190
+
191
+ ### Supporting: Intent Operations
192
+
193
+ > **Note**: These methods are typically used by takers/buyers, not liquidity providers.
194
+
195
+ ```typescript
196
+ // Signal an intent to use a deposit
197
+ await client.signalIntent({
198
+ depositId: 1n,
199
+ amount: 1000000n,
200
+ toAddress: '0xRecipient',
201
+ processorName: 'wise',
202
+ fiatCurrencyCode: 'USD',
203
+ conversionRate: 1020000n,
204
+ payeeDetails: '0xPayeeHash',
205
+ });
206
+
207
+ // Fulfill an intent with a payment proof
208
+ await client.fulfillIntent({
209
+ intentHash: '0xIntentHash',
210
+ proof: attestationProof,
211
+ });
212
+
213
+ // Release funds back to deposit owner (liquidity providers may use this)
214
+ await client.releaseFundsToPayer({ intentHash: '0x...' });
215
+
216
+ // Cancel an intent
217
+ await client.cancelIntent({ intentHash: '0x...' });
218
+ ```
219
+
220
+ ### Supporting: Getting Quotes
221
+
222
+ > **Note**: Primarily used by frontend applications to display available liquidity.
223
+
224
+ ```typescript
225
+ const quote = await client.getQuote({
226
+ paymentPlatforms: ['wise', 'revolut'],
227
+ fiatCurrency: 'USD',
228
+ user: '0xUserAddress',
229
+ recipient: '0xRecipientAddress',
230
+ destinationChainId: 8453,
231
+ destinationToken: '0xUSDC',
232
+ amount: '100',
233
+ });
234
+ ```
235
+
236
+ ## React Hooks
237
+
238
+ The SDK provides React hooks for all deposit and intent operations via a dedicated subpath:
239
+
240
+ ```tsx
241
+ import {
242
+ useCreateDeposit,
243
+ useAddFunds,
244
+ useRemoveFunds,
245
+ useWithdrawDeposit,
246
+ useSetAcceptingIntents,
247
+ useSetIntentRange,
248
+ useSetCurrencyMinRate,
249
+ useAddPaymentMethods,
250
+ useRemovePaymentMethod,
251
+ useAddCurrencies,
252
+ useSignalIntent,
253
+ useFulfillIntent,
254
+ useReleaseFundsToPayer,
255
+ usePruneExpiredIntents,
256
+ useSetDelegate,
257
+ useRemoveDelegate,
258
+ } from '@zkp2p/client-sdk/react';
259
+
260
+ function DepositManager({ client }) {
261
+ const { createDeposit, isLoading, error } = useCreateDeposit({ client });
262
+ const { addFunds } = useAddFunds({ client });
263
+ const { setAcceptingIntents } = useSetAcceptingIntents({ client });
264
+
265
+ const handleCreate = async () => {
266
+ const result = await createDeposit({
267
+ token: '0xUSDC_ADDRESS',
268
+ amount: 10000000000n,
269
+ intentAmountRange: { min: 100000n, max: 1000000000n },
270
+ processorNames: ['wise'],
271
+ depositData: [{ email: 'maker@example.com' }],
272
+ conversionRates: [[{ currency: 'USD', conversionRate: '1020000000000000000' }]], // 1.02 (18 decimals)
273
+ });
274
+ console.log('Created deposit:', result.hash);
275
+ };
276
+
277
+ return (
278
+ <div>
279
+ <button disabled={isLoading} onClick={handleCreate}>
280
+ {isLoading ? 'Creating...' : 'Create Deposit'}
281
+ </button>
282
+ {error && <p>Error: {error.message}</p>}
283
+ </div>
284
+ );
285
+ }
286
+ ```
287
+
288
+ ## Payment Methods
289
+
290
+ Supported payment platforms:
291
+
292
+ | Platform | Key | Currencies |
293
+ |-------------|---------------|------------|
294
+ | Wise | `wise` | USD, EUR, GBP, etc. |
295
+ | Venmo | `venmo` | USD |
296
+ | Revolut | `revolut` | USD, EUR, GBP, etc. |
297
+ | CashApp | `cashapp` | USD |
298
+ | PayPal | `paypal` | USD, EUR, etc. |
299
+ | Zelle | `zelle` | USD |
300
+ | Monzo | `monzo` | GBP |
301
+ | MercadoPago | `mercadopago` | BRL, ARS, MXN |
302
+
303
+ ```typescript
304
+ import { getPaymentMethodsCatalog, PLATFORM_METADATA, PAYMENT_PLATFORMS } from '@zkp2p/client-sdk';
305
+
306
+ // Available payment platforms
307
+ console.log(PAYMENT_PLATFORMS); // ['wise', 'venmo', 'revolut', 'cashapp', 'mercadopago', 'zelle', 'paypal', 'monzo']
308
+
309
+ // Get payment method hashes
310
+ const methods = getPaymentMethodsCatalog(8453, 'production');
311
+ const wiseHash = methods['wise'].paymentMethodHash;
312
+
313
+ // Get platform metadata
314
+ const wiseInfo = PLATFORM_METADATA['wise'];
315
+ console.log(wiseInfo.displayName); // "Wise"
316
+ ```
317
+
318
+ ## Currency Utilities
319
+
320
+ ```typescript
321
+ import {
322
+ Currency,
323
+ currencyInfo,
324
+ getCurrencyInfoFromHash,
325
+ resolveFiatCurrencyBytes32
326
+ } from '@zkp2p/client-sdk';
327
+
328
+ // Use currency constants
329
+ const usd = Currency.USD;
330
+ const eur = Currency.EUR;
331
+
332
+ // Get currency info
333
+ const info = currencyInfo[Currency.USD];
334
+ console.log(info.currencySymbol); // "$"
335
+
336
+ // Convert to bytes32 for on-chain use
337
+ const usdBytes = resolveFiatCurrencyBytes32('USD');
338
+ ```
339
+
340
+ ## Contract Helpers
341
+
342
+ ```typescript
343
+ import { getContracts, getPaymentMethodsCatalog } from '@zkp2p/client-sdk';
344
+
345
+ // Get contract addresses and ABIs
346
+ const { addresses, abis } = getContracts(8453, 'production');
347
+ console.log(addresses.escrow); // Contract addresses use camelCase
348
+ console.log(addresses.orchestrator);
349
+
350
+ // Get payment methods catalog
351
+ const catalog = getPaymentMethodsCatalog(8453, 'production');
352
+ ```
353
+
354
+ ## Supported Networks
355
+
356
+ | Network | Chain ID | Environment |
357
+ |---------|----------|-------------|
358
+ | Base Mainnet | 8453 | `production` |
359
+ | Base Sepolia | 84532 | `staging` |
360
+
361
+ ## API Reference
362
+
363
+ ### Query Methods (RPC-first)
364
+
365
+ **Deposits (instant on-chain reads):**
366
+ - `getDeposits()` - Get connected wallet's deposits
367
+ - `getAccountDeposits(owner)` - Get deposits for any address
368
+ - `getDeposit(depositId)` - Get single deposit by ID
369
+ - `getDepositsById(ids)` - Batch fetch deposits
370
+
371
+ **Intents (instant on-chain reads):**
372
+ - `getIntents()` - Get connected wallet's intents
373
+ - `getAccountIntents(owner)` - Get intents for any address
374
+ - `getIntent(intentHash)` - Get single intent by hash
375
+
376
+ **Utilities:**
377
+ - `resolvePayeeHash(depositId, paymentMethodHash)` - Get payee details hash
378
+
379
+ **Token Allowance:**
380
+ - `ensureAllowance(params)` - Check/set ERC20 allowance for deposits
381
+
382
+ ### Core Methods (Deposit Management)
383
+
384
+ **Creating & Managing Deposits:**
385
+ - `createDeposit(params)` - Create a new liquidity deposit
386
+ - `addFunds(params)` - Add funds to deposit
387
+ - `removeFunds(params)` - Remove funds from deposit
388
+ - `withdrawDeposit(params)` - Withdraw entire deposit
389
+
390
+ **Configuring Deposits:**
391
+ - `setAcceptingIntents(params)` - Toggle intent acceptance
392
+ - `setIntentRange(params)` - Set min/max intent amounts
393
+ - `setCurrencyMinRate(params)` - Set minimum conversion rate
394
+ - `setDelegate(params)` / `removeDelegate(params)` - Manage delegates
395
+ - `addPaymentMethods(params)` - Add payment platforms
396
+ - `setPaymentMethodActive(params)` - Enable/disable payment methods
397
+ - `addCurrencies(params)` / `deactivateCurrency(params)` - Manage currencies
398
+
399
+ ### Indexer Methods (`client.indexer.*`)
400
+
401
+ For historical data, pagination, and advanced filtering:
402
+
403
+ - `indexer.getDeposits(filter?, pagination?)` - Query deposits with filters
404
+ - `indexer.getDepositsWithRelations(filter?, pagination?, options?)` - Include payment methods/intents
405
+ - `indexer.getDepositById(compositeId, options?)` - Get by composite ID
406
+ - `indexer.getDepositsByPayeeHash(hash, options?)` - Find by payee
407
+ - `indexer.getOwnerIntents(owner, statuses?)` - Get owner's intents
408
+ - `indexer.getExpiredIntents(params)` - Find expired intents
409
+ - `indexer.getFulfilledIntentEvents(intentHashes)` - Historical fulfillments
410
+ - `indexer.getFulfillmentAndPayment(intentHash)` - Verification records
411
+
412
+ ### Supporting Methods
413
+
414
+ **Intent Operations** (typically used by takers, not liquidity providers):
415
+ - `signalIntent(params)` - Signal an intent to use a deposit
416
+ - `fulfillIntent(params)` - Fulfill with attestation proof
417
+ - `cancelIntent(params)` - Cancel an intent
418
+ - `releaseFundsToPayer(params)` - Release funds back to deposit
419
+ - `pruneExpiredIntents(params)` - Clean up expired intents
420
+
421
+ **Quote API** (used by frontends):
422
+ - `getQuote(params)` - Get available exchange quotes
423
+
424
+ ## Token Allowance Management
425
+
426
+ Before creating deposits or adding funds, you may need to approve the escrow contract to spend your tokens:
427
+
428
+ ```typescript
429
+ // Check and set allowance if needed
430
+ const result = await client.ensureAllowance({
431
+ token: '0xUSDC_ADDRESS',
432
+ amount: 10000000000n, // Amount to approve
433
+ spender: addresses.escrow, // Optional: defaults to escrow contract
434
+ maxApprove: false, // Optional: set to true for unlimited approval
435
+ });
436
+
437
+ if (result.hadAllowance) {
438
+ console.log('Already had sufficient allowance');
439
+ } else {
440
+ console.log('Approval transaction:', result.hash);
441
+ }
442
+ ```
443
+
444
+ ## Low-Level Method Parameters
445
+
446
+ For methods that interact directly with on-chain data, parameters use bytes32 hex strings:
447
+
448
+ ```typescript
449
+ // addCurrencies - Add currencies to a payment method
450
+ await client.addCurrencies({
451
+ depositId: 1n,
452
+ paymentMethod: '0x...', // bytes32 payment method hash
453
+ currencies: [
454
+ { code: '0x...', minConversionRate: 1020000000000000000n }, // bytes32 currency code, 18 decimals
455
+ ],
456
+ });
457
+
458
+ // deactivateCurrency - Remove a currency from a payment method
459
+ await client.deactivateCurrency({
460
+ depositId: 1n,
461
+ paymentMethod: '0x...', // bytes32 payment method hash
462
+ currencyCode: '0x...', // bytes32 currency code
463
+ });
464
+
465
+ // setPaymentMethodActive - Enable/disable a payment method
466
+ await client.setPaymentMethodActive({
467
+ depositId: 1n,
468
+ paymentMethod: '0x...', // bytes32 payment method hash (not paymentMethodHash)
469
+ isActive: true,
470
+ });
471
+
472
+ // setCurrencyMinRate - Update minimum conversion rate
473
+ await client.setCurrencyMinRate({
474
+ depositId: 1n,
475
+ paymentMethod: '0x...', // bytes32 payment method hash
476
+ fiatCurrency: '0x...', // bytes32 currency code (not currencyCode)
477
+ minConversionRate: 1020000000000000000n, // 18 decimals
478
+ });
479
+ ```
480
+
481
+ ## Error Handling
482
+
483
+ ```typescript
484
+ import { ValidationError, NetworkError, ContractError } from '@zkp2p/client-sdk';
485
+
486
+ try {
487
+ await client.createDeposit({ /* ... */ });
488
+ } catch (error) {
489
+ if (error instanceof ValidationError) {
490
+ console.error('Invalid parameters:', error.message);
491
+ } else if (error instanceof NetworkError) {
492
+ console.error('Network issue:', error.message);
493
+ } else if (error instanceof ContractError) {
494
+ console.error('Contract error:', error.message);
495
+ }
496
+ }
497
+ ```
498
+
499
+ ## Logging
500
+
501
+ ```typescript
502
+ import { setLogLevel } from '@zkp2p/client-sdk';
503
+
504
+ // Set log level: 'debug' | 'info' | 'warn' | 'error' | 'none'
505
+ setLogLevel('debug');
506
+ ```
507
+
508
+ ## TypeScript Support
509
+
510
+ Full TypeScript support with exported types:
511
+
512
+ ```typescript
513
+ import type {
514
+ CreateDepositParams,
515
+ SignalIntentParams,
516
+ FulfillIntentParams,
517
+ IndexerDeposit,
518
+ IndexerIntent,
519
+ CurrencyType,
520
+ PaymentPlatformType,
521
+ } from '@zkp2p/client-sdk';
522
+ ```
523
+
524
+ ## Contributing
525
+
526
+ ```bash
527
+ cd packages/offramp-sdk
528
+ npm install
529
+ npm run build
530
+ npm run test
531
+ npm run lint
532
+ ```
533
+
534
+ ## License
535
+
536
+ MIT License - see [LICENSE](LICENSE) for details.
537
+
538
+ ## Links
539
+
540
+ - [NPM Package](https://www.npmjs.com/package/@zkp2p/client-sdk)
541
+ - [GitHub Repository](https://github.com/zkp2p/zkp2p-client-sdk)
542
+ - [Documentation](https://docs.zkp2p.xyz)
543
+
544
+ ## Support
545
+
546
+ - GitHub Issues: [Create an issue](https://github.com/zkp2p/zkp2p-client-sdk/issues)
547
+ - Email: support@zkp2p.xyz