@palindromepay/sdk 1.9.4 → 1.9.6

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/LICENCE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2025 Palindrome Finance
3
+ Copyright (c) 2025 Palindrome Pay
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,10 +1,10 @@
1
- # PalindromeEscrowSDK
1
+ # PalindromePay SDK
2
2
 
3
- [![npm version](https://img.shields.io/npm/v/@palindromecryptoescrow/sdk.svg)](https://www.npmjs.com/package/@palindromecryptoescrow/sdk)
3
+ [![npm version](https://img.shields.io/npm/v/@palindromepay/sdk.svg)](https://www.npmjs.com/package/@palindromepay/sdk)
4
4
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
5
  [![Documentation](https://img.shields.io/badge/docs-sdk.palindromefinance.com-blue)](https://sdk.palindromefinance.com)
6
6
 
7
- A TypeScript/Node SDK for interacting with the PalindromeCryptoEscrow smart contract and subgraph, including signature flows, event utilities, token helpers, and robust error handling.
7
+ A TypeScript/Node SDK for interacting with the PalindromePay escrow smart contract and subgraph, including signature flows, event utilities, token helpers, and robust error handling.
8
8
 
9
9
  ---
10
10
 
@@ -25,273 +25,14 @@ A TypeScript/Node SDK for interacting with the PalindromeCryptoEscrow smart cont
25
25
  - Flexible error classes and codes for wallet/client state
26
26
  - Utilities for fee calculation, token formatting, deadlines, and maturity times
27
27
  - Gas estimation helpers for transaction planning
28
- - Comprehensive state and role validation helpers (v1.9.3+)
28
+ - Comprehensive state and role validation helpers
29
29
 
30
30
  ---
31
31
 
32
32
  ## 📦 Installation
33
33
 
34
34
  ```bash
35
- npm install @palindromecryptoescrow/sdk
36
- ```
37
-
38
- ## 🚀 Quick Start
39
-
40
- ```typescript
41
- import { PalindromeEscrowSDK } from '@palindromecryptoescrow/sdk';
42
- import { createPublicClient, createWalletClient, http } from 'viem';
43
-
44
- // Create clients
45
- const publicClient = createPublicClient({
46
- chain: yourChain,
47
- transport: http()
48
- });
49
-
50
- const walletClient = createWalletClient({
51
- chain: yourChain,
52
- transport: http(),
53
- account: yourAccount
54
- });
55
-
56
- // Initialize SDK
57
- const sdk = new PalindromeEscrowSDK({
58
- publicClient,
59
- walletClient,
60
- contractAddress: '0x...',
61
- subgraphUrl: 'https://...'
62
- });
63
-
64
- // Create an escrow
65
- const escrow = await sdk.createEscrow({
66
- token: '0x...', // ERC20 token address
67
- buyer: '0x...', // Buyer address
68
- amount: 1000000n, // Amount in smallest unit
69
- maturityDays: 7n, // 7 days until auto-release
70
- arbiter: '0x...', // Optional arbiter
71
- title: 'Purchase of Product X',
72
- ipfsHash: 'Qm...' // Optional IPFS metadata
73
- });
74
- ```
75
-
76
- ---
77
-
78
- ## ⚠️ Token Compatibility
79
-
80
- **CRITICAL: Not all ERC20 tokens are compatible with this escrow system.**
81
-
82
- ### ✅ Supported Tokens
83
-
84
- The escrow contract works correctly with **standard ERC20 tokens** that:
85
- - Transfer the exact amount specified (no fees on transfer)
86
- - Have fixed supply (no rebasing)
87
- - Cannot be paused by admin once deposited
88
- - Do not have address blocklists
89
-
90
- **Examples of Safe Tokens:**
91
- - DAI
92
- - WETH
93
- - Standard ERC20 tokens without special features
94
-
95
- ### ❌ Unsupported Tokens
96
-
97
- **1. Fee-on-Transfer Tokens**
98
- - **What:** Tokens that deduct a fee during transfers
99
- - **Why Unsafe:** Escrow will receive less than the deposit amount, breaking accounting
100
- - **Examples:** SafeMoon, PAXG, some tax tokens
101
- - **Risk Level:** 🔴 CRITICAL - Will cause fund loss
102
-
103
- **2. Rebasing Tokens**
104
- - **What:** Tokens whose balance changes automatically over time
105
- - **Why Unsafe:** Escrow balance will change unexpectedly, breaking release amounts
106
- - **Examples:** stETH, AMPL, OHM
107
- - **Risk Level:** 🔴 CRITICAL - Unpredictable outcomes
108
-
109
- **3. Pausable Tokens**
110
- - **What:** Tokens that can be paused by admin, freezing all transfers
111
- - **Why Unsafe:** Escrow may become permanently locked if token is paused
112
- - **Examples:** USDC, USDT (admin can pause)
113
- - **Risk Level:** 🟡 MEDIUM - Temporary freeze possible
114
- - **Mitigation:** Only use with trusted token issuers
115
-
116
- **4. Blocklist Tokens**
117
- - **What:** Tokens where admin can blocklist specific addresses
118
- - **Why Unsafe:** Escrow wallet could be blocklisted, freezing funds
119
- - **Examples:** USDC, USDT (admin can blocklist)
120
- - **Risk Level:** 🟡 MEDIUM - Funds could be frozen
121
- - **Mitigation:** Only use with trusted token issuers
122
-
123
- ### 🔍 How to Check Token Compatibility
124
-
125
- ```typescript
126
- // Use the SDK to verify token decimals and basic functionality
127
- const decimals = await sdk.getTokenDecimals(tokenAddress);
128
- const balance = await sdk.getTokenBalance(userAddress, tokenAddress);
129
-
130
- // For production, additionally check:
131
- // 1. Token contract source code for transfer fees
132
- // 2. Token documentation for rebasing mechanics
133
- // 3. Token admin capabilities (pause, blocklist)
134
- ```
135
-
136
- **Best Practice:** Always test with small amounts first on mainnet or use testnet for new tokens.
137
-
138
- ---
139
-
140
- ## 🌐 Rate Limiting Best Practices
141
-
142
- ### RPC Provider Limits
143
-
144
- The SDK makes multiple RPC calls for operations like:
145
- - Creating escrows (3-5 calls)
146
- - Fetching multiple nonces (1-20+ calls depending on count)
147
- - Batch operations (N calls per item)
148
-
149
- **Recommended RPC Providers & Limits:**
150
-
151
- | Provider | Free Tier | Recommended Plan | Notes |
152
- |----------|-----------|------------------|-------|
153
- | Alchemy | 300M CU/month | Growth ($49/mo) | Best for production |
154
- | Infura | 100k req/day | Developer ($50/mo) | Good reliability |
155
- | QuickNode | 10M credits | Pro ($49/mo) | Low latency |
156
-
157
- ### SDK Rate Limiting Features
158
-
159
- The SDK includes built-in optimizations:
160
- - **Multicall support:** Batches multiple reads into one RPC call (when supported)
161
- - **Caching:** Fee receiver, decimals, multicall support cached
162
- - **Efficient nonce fetching:** Automatically uses multicall for bulk nonce queries
163
-
164
- ### Implementing Your Own Rate Limiting
165
-
166
- ```typescript
167
- // Example: Rate limit with p-queue
168
- import PQueue from 'p-queue';
169
-
170
- const queue = new PQueue({
171
- concurrency: 5, // Max 5 concurrent requests
172
- interval: 1000, // Per second
173
- intervalCap: 10 // Max 10 requests per interval
174
- });
175
-
176
- // Wrap SDK calls
177
- const escrow = await queue.add(() =>
178
- sdk.getEscrowByIdParsed(escrowId)
179
- );
180
- ```
181
-
182
- ### Monitoring RPC Usage
183
-
184
- ```typescript
185
- // Enable debug logging to monitor RPC calls
186
- const sdk = new PalindromeEscrowSDK({
187
- // ... other config
188
- logger: customLogger, // Implement custom logger to track calls
189
- logLevel: 'debug'
190
- });
191
- ```
192
-
193
- **Production Tip:** Use a dedicated RPC endpoint with higher limits for user-facing applications.
194
-
195
- ---
196
-
197
- ## ⛽ Gas Estimation
198
-
199
- The SDK provides gas estimation helpers to help users plan transaction costs:
200
-
201
- ### Estimating Gas for Operations
202
-
203
- ```typescript
204
- // Estimate gas for creating an escrow
205
- const gasEstimate = await sdk.estimateGasForCreateEscrow({
206
- token: tokenAddress,
207
- buyer: buyerAddress,
208
- amount: 1000000n,
209
- maturityDays: 7n,
210
- arbiter: arbiterAddress,
211
- title: 'Test Escrow',
212
- ipfsHash: ''
213
- });
214
-
215
- console.log(`Estimated gas: ${gasEstimate.gasLimit}`);
216
- console.log(`Estimated cost: ${gasEstimate.estimatedCostWei} wei`);
217
- console.log(`Estimated cost: ${gasEstimate.estimatedCostEth} ETH`);
218
-
219
- // Estimate gas for deposit
220
- const depositGas = await sdk.estimateGasForDeposit(escrowId);
221
-
222
- // Estimate gas for confirm delivery
223
- const confirmGas = await sdk.estimateGasForConfirmDelivery(escrowId);
224
- ```
225
-
226
- ### Gas Price Information
227
-
228
- ```typescript
229
- // Get current gas prices
230
- const gasPrice = await sdk.getCurrentGasPrice();
231
- console.log(`Current gas price: ${gasPrice.standard} gwei`);
232
- console.log(`Fast: ${gasPrice.fast} gwei`);
233
- console.log(`Instant: ${gasPrice.instant} gwei`);
234
- ```
235
-
236
- ### Setting Custom Gas Limits
237
-
238
- ```typescript
239
- const sdk = new PalindromeEscrowSDK({
240
- // ... other config
241
- defaultGasLimit: 500000n // Custom gas limit for all transactions
242
- });
243
- ```
244
-
245
- ---
246
-
247
- ## 🛡️ Security Best Practices
248
-
249
- 1. **Always validate addresses** before creating escrows
250
- 2. **Use arbiter for high-value transactions**
251
- 3. **Set appropriate maturity times** (7-30 days recommended)
252
- 4. **Test with small amounts first**
253
- 5. **Verify token compatibility** before using (see Token Compatibility section)
254
- 6. **Monitor for pausable/blocklist tokens**
255
-
256
- ---
257
-
258
- ## 📚 API Reference
259
-
260
- ### Helper Methods (New in v1.9.3)
261
-
262
- #### State Validation Helpers
263
- ```typescript
264
- // Check if user can deposit
265
- const canDeposit = await sdk.canUserDeposit(userAddress, escrowId);
266
-
267
- // Check if user can accept escrow
268
- const canAccept = await sdk.canUserAcceptEscrow(userAddress, escrowId);
269
-
270
- // Check if user can confirm delivery
271
- const canConfirm = await sdk.canUserConfirmDelivery(userAddress, escrowId);
272
-
273
- // Check if user can start dispute
274
- const canDispute = await sdk.canUserStartDispute(userAddress, escrowId);
275
-
276
- // Check if escrow can be auto-released
277
- const canWithdraw = await sdk.canUserWithdraw(escrowId);
278
-
279
- // Check if seller can auto-release
280
- const canAutoRelease = await sdk.canSellerAutoRelease(userAddress, escrowId);
281
- ```
282
-
283
- #### Role Validation Helpers
284
- ```typescript
285
- const escrow = await sdk.getEscrowByIdParsed(escrowId);
286
-
287
- // Check roles
288
- const isBuyer = sdk.isBuyer(userAddress, escrow);
289
- const isSeller = sdk.isSeller(userAddress, escrow);
290
- const isArbiter = sdk.isArbiter(userAddress, escrow);
291
- const hasArbiter = sdk.hasArbiter(escrow);
292
-
293
- // Compare addresses safely
294
- const areEqual = sdk.addressEquals(address1, address2);
35
+ npm install @palindromepay/sdk
295
36
  ```
296
37
 
297
38
  ---
@@ -1,7 +1,5 @@
1
1
  /**
2
- * PALINDROME CRYPTO ESCROW SDK
3
- *
4
- * Corrected and optimized SDK matching the actual smart contract interfaces.
2
+ * PALINDROME Pay SDK
5
3
  *
6
4
  * Key contract functions:
7
5
  * - createEscrow(token, buyer, amount, maturityDays, arbiter, title, ipfsHash, sellerWalletSig)
@@ -96,7 +94,7 @@ export declare class SDKError extends Error {
96
94
  details?: ViemError | RPCError | UnknownError | Record<string, unknown>;
97
95
  constructor(message: string, code: SDKErrorCode, details?: ViemError | RPCError | UnknownError | Record<string, unknown>);
98
96
  }
99
- export interface PalindromeEscrowSDKConfig {
97
+ export interface PalindromePaySDKConfig {
100
98
  publicClient: PublicClient;
101
99
  contractAddress: Address;
102
100
  walletClient?: EscrowWalletClient;
@@ -212,7 +210,7 @@ export interface DisputeSubmissionStatus {
212
210
  arbiter: boolean;
213
211
  allSubmitted: boolean;
214
212
  }
215
- export declare class PalindromeEscrowSDK {
213
+ export declare class PalindromePaySDK {
216
214
  readonly contractAddress: Address;
217
215
  readonly abiEscrow: Abi;
218
216
  readonly abiWallet: Abi;
@@ -242,7 +240,7 @@ export declare class PalindromeEscrowSDK {
242
240
  /** Cached multicall support status per chain (null = not yet detected) */
243
241
  private multicallSupported;
244
242
  private readonly STATE_NAMES;
245
- constructor(config: PalindromeEscrowSDKConfig);
243
+ constructor(config: PalindromePaySDKConfig);
246
244
  /**
247
245
  * Internal logging helper that respects log level configuration
248
246
  */
@@ -814,7 +812,7 @@ export declare class PalindromeEscrowSDK {
814
812
  *
815
813
  * @example
816
814
  * ```typescript
817
- * const sdk = new PalindromeEscrowSDK(...);
815
+ * const sdk = new PalindromePaySDK(...);
818
816
  * const escrow = await sdk.getEscrowByIdParsed(1n);
819
817
  * const status = sdk.getStatusLabel(escrow.state);
820
818
  * console.log(status.label); // "Awaiting Payment"
@@ -1081,7 +1079,7 @@ export declare class PalindromeEscrowSDK {
1081
1079
  *
1082
1080
  * @example
1083
1081
  * ```typescript
1084
- * const sdk = new PalindromeEscrowSDK(...);
1082
+ * const sdk = new PalindromePaySDK(...);
1085
1083
  * const areEqual = sdk.addressEquals(
1086
1084
  * "0xabc...",
1087
1085
  * "0xABC..."
@@ -1214,4 +1212,4 @@ export declare class PalindromeEscrowSDK {
1214
1212
  net: bigint;
1215
1213
  }>;
1216
1214
  }
1217
- export default PalindromeEscrowSDK;
1215
+ export default PalindromePaySDK;
@@ -1,15 +1,13 @@
1
1
  "use strict";
2
- // Copyright (c) 2025 Palindrome Finance
2
+ // Copyright (c) 2025 Palindrome Pay
3
3
  // Licensed under the MIT License. See LICENSE file for details.
4
4
  var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  return (mod && mod.__esModule) ? mod : { "default": mod };
6
6
  };
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
- exports.PalindromeEscrowSDK = exports.SDKError = exports.SDKErrorCode = exports.Role = exports.DisputeResolution = exports.EscrowState = void 0;
8
+ exports.PalindromePaySDK = exports.SDKError = exports.SDKErrorCode = exports.Role = exports.DisputeResolution = exports.EscrowState = void 0;
9
9
  /**
10
- * PALINDROME CRYPTO ESCROW SDK
11
- *
12
- * Corrected and optimized SDK matching the actual smart contract interfaces.
10
+ * PALINDROME Pay SDK
13
11
  *
14
12
  * Key contract functions:
15
13
  * - createEscrow(token, buyer, amount, maturityDays, arbiter, title, ipfsHash, sellerWalletSig)
@@ -29,8 +27,8 @@ exports.PalindromeEscrowSDK = exports.SDKError = exports.SDKErrorCode = exports.
29
27
  */
30
28
  const viem_1 = require("viem");
31
29
  const actions_1 = require("viem/actions");
32
- const PalindromeCryptoEscrow_json_1 = __importDefault(require("./contract/PalindromeCryptoEscrow.json"));
33
- const PalindromeEscrowWallet_json_1 = __importDefault(require("./contract/PalindromeEscrowWallet.json"));
30
+ const PalindromePay_json_1 = __importDefault(require("./contract/PalindromePay.json"));
31
+ const PalindromePayWallet_json_1 = __importDefault(require("./contract/PalindromePayWallet.json"));
34
32
  const USDT_json_1 = __importDefault(require("./contract/USDT.json"));
35
33
  const client_1 = require("@apollo/client");
36
34
  /** Type guard to check if error is a Viem error */
@@ -194,7 +192,7 @@ function addressEquals(a, b) {
194
192
  // ============================================================================
195
193
  // MAIN SDK CLASS
196
194
  // ============================================================================
197
- class PalindromeEscrowSDK {
195
+ class PalindromePaySDK {
198
196
  constructor(config) {
199
197
  /** LRU cache for escrow data with automatic eviction */
200
198
  this.escrowCache = new Map();
@@ -252,8 +250,8 @@ class PalindromeEscrowSDK {
252
250
  throw new SDKError("contractAddress is required", SDKErrorCode.VALIDATION_ERROR);
253
251
  }
254
252
  this.contractAddress = config.contractAddress;
255
- this.abiEscrow = PalindromeCryptoEscrow_json_1.default.abi;
256
- this.abiWallet = PalindromeEscrowWallet_json_1.default.abi;
253
+ this.abiEscrow = PalindromePay_json_1.default.abi;
254
+ this.abiWallet = PalindromePayWallet_json_1.default.abi;
257
255
  this.abiERC20 = USDT_json_1.default.abi;
258
256
  this.publicClient = config.publicClient;
259
257
  this.walletClient = config.walletClient;
@@ -539,7 +537,7 @@ class PalindromeEscrowSDK {
539
537
  */
540
538
  getWalletDomain(walletAddress) {
541
539
  return {
542
- name: "PalindromeEscrowWallet",
540
+ name: "PalindromePayWallet",
543
541
  version: "1",
544
542
  chainId: this.chain.id,
545
543
  verifyingContract: walletAddress,
@@ -662,7 +660,7 @@ class PalindromeEscrowSDK {
662
660
  const encodedArgs = (0, viem_1.encodeAbiParameters)([{ type: "address" }, { type: "uint256" }], [this.contractAddress, escrowId]);
663
661
  // Note: For accurate prediction, need actual bytecode + args hash
664
662
  // This is a simplified version - in production, use the contract's computation
665
- const initCodeHash = (0, viem_1.keccak256)((PalindromeEscrowWallet_json_1.default.bytecode + encodedArgs.slice(2)));
663
+ const initCodeHash = (0, viem_1.keccak256)((PalindromePayWallet_json_1.default.bytecode + encodedArgs.slice(2)));
666
664
  const raw = (0, viem_1.keccak256)((`0xff${this.contractAddress.slice(2)}${salt.slice(2)}${initCodeHash.slice(2)}`));
667
665
  return (0, viem_1.getAddress)(`0x${raw.slice(26)}`);
668
666
  }
@@ -764,7 +762,7 @@ class PalindromeEscrowSDK {
764
762
  async getUserNonce(escrowId, signer) {
765
763
  // Start with word 0 (nonces 0-255)
766
764
  let wordIndex = 0n;
767
- while (wordIndex < PalindromeEscrowSDK.MAX_NONCE_WORDS) {
765
+ while (wordIndex < PalindromePaySDK.MAX_NONCE_WORDS) {
768
766
  const bitmap = await this.getNonceBitmap(escrowId, signer, wordIndex);
769
767
  // If bitmap is all 1s (all NONCE_BITMAP_SIZE nonces used), check next word
770
768
  if (bitmap === (1n << 256n) - 1n) {
@@ -791,7 +789,7 @@ class PalindromeEscrowSDK {
791
789
  */
792
790
  getEstimatedWordCount(count) {
793
791
  return Math.min(Math.ceil(count / 128) + 1, // Conservative estimate with buffer
794
- Number(PalindromeEscrowSDK.MAX_NONCE_WORDS));
792
+ Number(PalindromePaySDK.MAX_NONCE_WORDS));
795
793
  }
796
794
  /**
797
795
  * Detect if chain supports Multicall3 and cache result.
@@ -1766,7 +1764,7 @@ class PalindromeEscrowSDK {
1766
1764
  *
1767
1765
  * @example
1768
1766
  * ```typescript
1769
- * const sdk = new PalindromeEscrowSDK(...);
1767
+ * const sdk = new PalindromePaySDK(...);
1770
1768
  * const escrow = await sdk.getEscrowByIdParsed(1n);
1771
1769
  * const status = sdk.getStatusLabel(escrow.state);
1772
1770
  * console.log(status.label); // "Awaiting Payment"
@@ -2421,7 +2419,7 @@ class PalindromeEscrowSDK {
2421
2419
  *
2422
2420
  * @example
2423
2421
  * ```typescript
2424
- * const sdk = new PalindromeEscrowSDK(...);
2422
+ * const sdk = new PalindromePaySDK(...);
2425
2423
  * const areEqual = sdk.addressEquals(
2426
2424
  * "0xabc...",
2427
2425
  * "0xABC..."
@@ -2698,13 +2696,13 @@ class PalindromeEscrowSDK {
2698
2696
  return { fee, net: amount - fee };
2699
2697
  }
2700
2698
  }
2701
- exports.PalindromeEscrowSDK = PalindromeEscrowSDK;
2699
+ exports.PalindromePaySDK = PalindromePaySDK;
2702
2700
  /**
2703
2701
  * Maximum nonce word index to prevent infinite loops.
2704
2702
  * 100 words = 25,600 nonces per escrow per signer.
2705
2703
  */
2706
- PalindromeEscrowSDK.MAX_NONCE_WORDS = 100n;
2704
+ PalindromePaySDK.MAX_NONCE_WORDS = 100n;
2707
2705
  // ============================================================================
2708
2706
  // EXPORT DEFAULT
2709
2707
  // ============================================================================
2710
- exports.default = PalindromeEscrowSDK;
2708
+ exports.default = PalindromePaySDK;