@palindromepay/sdk 1.9.7 → 1.9.8

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,1215 @@
1
+ /**
2
+ * PALINDROME Pay SDK
3
+ *
4
+ * Key contract functions:
5
+ * - createEscrow(token, buyer, amount, maturityDays, arbiter, title, ipfsHash, sellerWalletSig)
6
+ * - createEscrowAndDeposit(token, seller, amount, maturityDays, arbiter, title, ipfsHash, buyerWalletSig)
7
+ * - deposit(escrowId, buyerWalletSig)
8
+ * - acceptEscrow(escrowId, sellerWalletSig)
9
+ * - confirmDelivery(escrowId, buyerWalletSig)
10
+ * - confirmDeliverySigned(escrowId, coordSignature, deadline, nonce, buyerWalletSig)
11
+ * - requestCancel(escrowId, walletSig)
12
+ * - cancelByTimeout(escrowId)
13
+ * - autoRelease(escrowId)
14
+ * - startDispute(escrowId)
15
+ * - startDisputeSigned(escrowId, signature, deadline, nonce)
16
+ * - submitDisputeMessage(escrowId, role, ipfsHash)
17
+ * - submitArbiterDecision(escrowId, resolution, ipfsHash, arbiterWalletSig)
18
+ * - Wallet: withdraw()
19
+ */
20
+ import { Address, Abi, PublicClient, WalletClient, Hex, Transport, Account, Chain } from "viem";
21
+ import { ApolloClient } from "@apollo/client";
22
+ export type ViemError = {
23
+ message: string;
24
+ shortMessage?: string;
25
+ cause?: {
26
+ reason?: string;
27
+ message?: string;
28
+ };
29
+ code?: number;
30
+ stack?: string;
31
+ };
32
+ export type ContractError = ViemError & {
33
+ contractAddress?: Address;
34
+ functionName?: string;
35
+ args?: readonly unknown[];
36
+ };
37
+ export type RPCError = {
38
+ message: string;
39
+ code?: number;
40
+ data?: unknown;
41
+ };
42
+ export type UnknownError = {
43
+ message?: string;
44
+ toString(): string;
45
+ };
46
+ export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'none';
47
+ export interface SDKLogger {
48
+ debug(message: string, context?: unknown): void;
49
+ info(message: string, context?: unknown): void;
50
+ warn(message: string, context?: unknown): void;
51
+ error(message: string, context?: unknown): void;
52
+ }
53
+ import { Escrow } from "./types/escrow";
54
+ export declare enum EscrowState {
55
+ AWAITING_PAYMENT = 0,
56
+ AWAITING_DELIVERY = 1,
57
+ DISPUTED = 2,
58
+ COMPLETE = 3,
59
+ REFUNDED = 4,
60
+ CANCELED = 5
61
+ }
62
+ export declare enum DisputeResolution {
63
+ Complete = 3,
64
+ Refunded = 4
65
+ }
66
+ export declare enum Role {
67
+ None = 0,
68
+ Buyer = 1,
69
+ Seller = 2,
70
+ Arbiter = 3
71
+ }
72
+ export declare enum SDKErrorCode {
73
+ WALLET_NOT_CONNECTED = "WALLET_NOT_CONNECTED",
74
+ WALLET_ACCOUNT_MISSING = "WALLET_ACCOUNT_MISSING",
75
+ NOT_BUYER = "NOT_BUYER",
76
+ NOT_SELLER = "NOT_SELLER",
77
+ NOT_ARBITER = "NOT_ARBITER",
78
+ INVALID_STATE = "INVALID_STATE",
79
+ INSUFFICIENT_BALANCE = "INSUFFICIENT_BALANCE",
80
+ ALLOWANCE_FAILED = "ALLOWANCE_FAILED",
81
+ SIGNATURE_EXPIRED = "SIGNATURE_EXPIRED",
82
+ TRANSACTION_FAILED = "TRANSACTION_FAILED",
83
+ INVALID_ROLE = "INVALID_ROLE",
84
+ INVALID_TOKEN = "INVALID_TOKEN",
85
+ VALIDATION_ERROR = "VALIDATION_ERROR",
86
+ RPC_ERROR = "RPC_ERROR",
87
+ EVIDENCE_ALREADY_SUBMITTED = "EVIDENCE_ALREADY_SUBMITTED",
88
+ ESCROW_NOT_FOUND = "ESCROW_NOT_FOUND",
89
+ ALREADY_ACCEPTED = "ALREADY_ACCEPTED"
90
+ }
91
+ export type EscrowWalletClient = WalletClient<Transport, Chain, Account>;
92
+ export declare class SDKError extends Error {
93
+ code: SDKErrorCode;
94
+ details?: ViemError | RPCError | UnknownError | Record<string, unknown>;
95
+ constructor(message: string, code: SDKErrorCode, details?: ViemError | RPCError | UnknownError | Record<string, unknown>);
96
+ }
97
+ export interface PalindromePaySDKConfig {
98
+ publicClient: PublicClient;
99
+ contractAddress: Address;
100
+ walletClient?: EscrowWalletClient;
101
+ apolloClient?: ApolloClient;
102
+ chain?: Chain;
103
+ /** Cache TTL in milliseconds (default: 5000) */
104
+ cacheTTL?: number;
105
+ /** Maximum cache entries before LRU eviction (default: 1000) */
106
+ maxCacheSize?: number;
107
+ /** Enable automatic retry on RPC failures (default: true) */
108
+ enableRetry?: boolean;
109
+ /** Maximum retry attempts (default: 3) */
110
+ maxRetries?: number;
111
+ /** Retry delay in milliseconds (default: 1000) */
112
+ retryDelay?: number;
113
+ /** Gas buffer percentage (default: 20) */
114
+ gasBuffer?: number;
115
+ /** Transaction receipt timeout in milliseconds (default: 60000) */
116
+ receiptTimeout?: number;
117
+ subgraphUrl?: string;
118
+ /**
119
+ * Skip eth_call simulation before sending transactions (default: false)
120
+ * Enable this for chains with unreliable RPC simulation (e.g., Base Sepolia)
121
+ * When true, transactions are sent directly without pre-flight simulation
122
+ */
123
+ skipSimulation?: boolean;
124
+ /**
125
+ * Default gas limit when simulation is skipped (default: 500000n)
126
+ * Only used when skipSimulation is true
127
+ */
128
+ defaultGasLimit?: bigint;
129
+ /**
130
+ * Logger instance for SDK events and errors (default: console)
131
+ * Set to custom logger or use noOpLogger to disable
132
+ */
133
+ logger?: SDKLogger;
134
+ /**
135
+ * Minimum log level to output (default: 'info')
136
+ * 'debug' shows all logs, 'none' disables all logging
137
+ */
138
+ logLevel?: LogLevel;
139
+ }
140
+ export interface CreateEscrowParams {
141
+ token: Address;
142
+ buyer: Address;
143
+ amount: bigint;
144
+ maturityTimeDays?: bigint;
145
+ arbiter?: Address;
146
+ title: string;
147
+ ipfsHash?: string;
148
+ }
149
+ export interface CreateEscrowAndDepositParams {
150
+ token: Address;
151
+ seller: Address;
152
+ amount: bigint;
153
+ maturityTimeDays?: bigint;
154
+ arbiter?: Address;
155
+ title: string;
156
+ ipfsHash?: string;
157
+ }
158
+ /** Raw escrow data from contract (before type narrowing to Address/Hex) */
159
+ export interface RawEscrowData {
160
+ token: `0x${string}`;
161
+ buyer: `0x${string}`;
162
+ seller: `0x${string}`;
163
+ arbiter: `0x${string}`;
164
+ wallet: `0x${string}`;
165
+ amount: bigint;
166
+ depositTime: bigint;
167
+ maturityTime: bigint;
168
+ disputeStartTime: bigint;
169
+ state: number;
170
+ buyerCancelRequested: boolean;
171
+ sellerCancelRequested: boolean;
172
+ tokenDecimals: number;
173
+ sellerWalletSig: `0x${string}`;
174
+ buyerWalletSig: `0x${string}`;
175
+ arbiterWalletSig: `0x${string}`;
176
+ }
177
+ /** Parsed escrow data with proper types */
178
+ export interface EscrowData {
179
+ token: Address;
180
+ buyer: Address;
181
+ seller: Address;
182
+ arbiter: Address;
183
+ wallet: Address;
184
+ amount: bigint;
185
+ depositTime: bigint;
186
+ maturityTime: bigint;
187
+ disputeStartTime: bigint;
188
+ state: EscrowState;
189
+ buyerCancelRequested: boolean;
190
+ sellerCancelRequested: boolean;
191
+ tokenDecimals: number;
192
+ sellerWalletSig: Hex;
193
+ buyerWalletSig: Hex;
194
+ arbiterWalletSig: Hex;
195
+ }
196
+ export interface EscrowCreatedEvent {
197
+ escrowId: bigint;
198
+ buyer: Address;
199
+ seller: Address;
200
+ token: Address;
201
+ amount: bigint;
202
+ arbiter: Address;
203
+ maturityTime: bigint;
204
+ title: string;
205
+ ipfsHash: string;
206
+ }
207
+ export interface DisputeSubmissionStatus {
208
+ buyer: boolean;
209
+ seller: boolean;
210
+ arbiter: boolean;
211
+ allSubmitted: boolean;
212
+ }
213
+ export declare class PalindromePaySDK {
214
+ readonly contractAddress: Address;
215
+ readonly abiEscrow: Abi;
216
+ readonly abiWallet: Abi;
217
+ readonly abiERC20: Abi;
218
+ readonly publicClient: PublicClient;
219
+ readonly walletClient?: EscrowWalletClient;
220
+ readonly apollo: ApolloClient;
221
+ readonly chain: Chain;
222
+ private readonly cacheTTL;
223
+ private readonly maxCacheSize;
224
+ private readonly enableRetry;
225
+ private readonly maxRetries;
226
+ private readonly retryDelay;
227
+ private readonly gasBuffer;
228
+ private readonly receiptTimeout;
229
+ private readonly skipSimulation;
230
+ private readonly defaultGasLimit;
231
+ private readonly logger;
232
+ private readonly logLevel;
233
+ /** LRU cache for escrow data with automatic eviction */
234
+ private escrowCache;
235
+ /** Cache for token decimals (rarely changes, no eviction needed) */
236
+ private tokenDecimalsCache;
237
+ /** Cache for immutable contract values */
238
+ private walletBytecodeHashCache;
239
+ private feeReceiverCache;
240
+ /** Cached multicall support status per chain (null = not yet detected) */
241
+ private multicallSupported;
242
+ private readonly STATE_NAMES;
243
+ constructor(config: PalindromePaySDKConfig);
244
+ /**
245
+ * Internal logging helper that respects log level configuration
246
+ */
247
+ private log;
248
+ /**
249
+ * Execute a contract write with resilient simulation handling.
250
+ *
251
+ * This method handles unreliable RPC simulation on certain chains (e.g., Base Sepolia)
252
+ * by falling back to direct transaction sending when simulation fails.
253
+ *
254
+ * @param walletClient - The wallet client to use
255
+ * @param params - Contract call parameters
256
+ * @param params.address - Contract address
257
+ * @param params.abi - Contract ABI
258
+ * @param params.functionName - Function to call
259
+ * @param params.args - Function arguments
260
+ * @returns Transaction hash
261
+ */
262
+ private resilientWriteContract;
263
+ /**
264
+ * Wait for transaction receipt with timeout and retry logic.
265
+ */
266
+ private waitForReceipt;
267
+ /**
268
+ * Execute an async operation with retry logic.
269
+ */
270
+ private withRetry;
271
+ /**
272
+ * Extract error message from unknown error type.
273
+ */
274
+ private extractErrorMessage;
275
+ /**
276
+ * Validate common escrow creation parameters.
277
+ */
278
+ private validateCreateEscrowParams;
279
+ /**
280
+ * Verify caller is the buyer, throw if not.
281
+ */
282
+ private verifyBuyer;
283
+ /**
284
+ * Verify caller is the seller, throw if not.
285
+ */
286
+ private verifySeller;
287
+ /**
288
+ * Verify caller is the arbiter, throw if not.
289
+ */
290
+ private verifyArbiter;
291
+ /**
292
+ * Verify escrow is in expected state, throw if not.
293
+ */
294
+ private verifyState;
295
+ /**
296
+ * Send transaction directly without simulation.
297
+ * Encodes function data manually and sends with fixed gas limit.
298
+ *
299
+ * @param walletClient - The wallet client to send from
300
+ * @param params - Contract write parameters
301
+ * @returns Transaction hash
302
+ */
303
+ private sendTransactionDirect;
304
+ /**
305
+ * Detect if error is a simulation failure (not user rejection or validation error).
306
+ *
307
+ * @param error - The error to check
308
+ * @returns True if error is from simulation failure
309
+ */
310
+ private isSimulationErrorType;
311
+ /**
312
+ * Set a value in the LRU cache with automatic eviction.
313
+ */
314
+ private setCacheValue;
315
+ /**
316
+ * Get a value from the LRU cache, refreshing its position.
317
+ */
318
+ private getCacheValue;
319
+ /**
320
+ * Get the EIP-712 domain for wallet authorization signatures
321
+ */
322
+ private getWalletDomain;
323
+ /**
324
+ * Get the EIP-712 domain for escrow contract signatures
325
+ */
326
+ private getEscrowDomain;
327
+ private readonly walletAuthorizationTypes;
328
+ private readonly confirmDeliveryTypes;
329
+ private readonly startDisputeTypes;
330
+ /**
331
+ * Sign a wallet authorization for a participant
332
+ * Used for: deposit, confirmDelivery, requestCancel, submitArbiterDecision
333
+ */
334
+ signWalletAuthorization(walletClient: EscrowWalletClient, walletAddress: Address, escrowId: bigint): Promise<Hex>;
335
+ /**
336
+ * Sign a confirm delivery message (for gasless meta-tx)
337
+ */
338
+ signConfirmDelivery(walletClient: EscrowWalletClient, escrowId: bigint, deadline: bigint, nonce: bigint): Promise<Hex>;
339
+ /**
340
+ * Sign a start dispute message (for gasless meta-tx)
341
+ */
342
+ signStartDispute(walletClient: EscrowWalletClient, escrowId: bigint, deadline: bigint, nonce: bigint): Promise<Hex>;
343
+ /**
344
+ * Create a signature deadline (timestamp + minutes)
345
+ */
346
+ createSignatureDeadline(minutesFromNow?: number): Promise<bigint>;
347
+ /**
348
+ * Check if signature deadline has expired
349
+ */
350
+ isSignatureDeadlineExpired(deadline: bigint, safetySeconds?: number): boolean;
351
+ /**
352
+ * Predict the wallet address for a given escrow ID (before creation)
353
+ */
354
+ predictWalletAddress(escrowId: bigint): Promise<Address>;
355
+ /**
356
+ * Get raw escrow data from contract
357
+ */
358
+ getEscrowById(escrowId: bigint): Promise<RawEscrowData>;
359
+ /**
360
+ * Get parsed escrow data
361
+ */
362
+ getEscrowByIdParsed(escrowId: bigint): Promise<EscrowData>;
363
+ /**
364
+ * Get next escrow ID
365
+ */
366
+ getNextEscrowId(): Promise<bigint>;
367
+ /**
368
+ * Get the nonce bitmap from the contract.
369
+ *
370
+ * Each bitmap word contains NONCE_BITMAP_SIZE nonce states. A set bit means the nonce is used.
371
+ *
372
+ * @param escrowId - The escrow ID
373
+ * @param signer - The signer's address
374
+ * @param wordIndex - The word index (nonce / NONCE_BITMAP_SIZE)
375
+ * @returns The bitmap as a bigint
376
+ */
377
+ getNonceBitmap(escrowId: bigint, signer: Address, wordIndex?: bigint): Promise<bigint>;
378
+ /**
379
+ * Check if a specific nonce has been used.
380
+ *
381
+ * @param escrowId - The escrow ID
382
+ * @param signer - The signer's address
383
+ * @param nonce - The nonce to check
384
+ * @returns True if the nonce has been used
385
+ */
386
+ isNonceUsed(escrowId: bigint, signer: Address, nonce: bigint): Promise<boolean>;
387
+ /**
388
+ * Maximum nonce word index to prevent infinite loops.
389
+ * 100 words = 25,600 nonces per escrow per signer.
390
+ */
391
+ private static readonly MAX_NONCE_WORDS;
392
+ /**
393
+ * Get the next available nonce for a signer.
394
+ *
395
+ * Queries the contract's nonce bitmap and finds the first unused nonce.
396
+ * This is the recommended way to get a nonce for signed transactions.
397
+ *
398
+ * @param escrowId - The escrow ID
399
+ * @param signer - The signer's address
400
+ * @returns The next available nonce
401
+ * @throws SDKError if nonce space is exhausted (> 25,600 nonces used)
402
+ */
403
+ getUserNonce(escrowId: bigint, signer: Address): Promise<bigint>;
404
+ /**
405
+ * Calculate estimated number of bitmap words needed for nonce count.
406
+ * Uses conservative estimate with buffer to minimize round trips.
407
+ *
408
+ * @param count - Number of nonces needed
409
+ * @returns Estimated number of bitmap words to fetch
410
+ */
411
+ private getEstimatedWordCount;
412
+ /**
413
+ * Detect if chain supports Multicall3 and cache result.
414
+ * Performs a test multicall on first invocation and caches the result.
415
+ *
416
+ * @param escrowId - Escrow ID for test call
417
+ * @param signer - Signer address for test call
418
+ */
419
+ private detectMulticallSupport;
420
+ /**
421
+ * Fetch nonce bitmaps using either multicall or sequential calls.
422
+ * Automatically uses multicall if supported, otherwise falls back to sequential.
423
+ *
424
+ * @param escrowId - The escrow ID
425
+ * @param signer - The signer's address
426
+ * @param wordCount - Number of bitmap words to fetch
427
+ * @returns Array of bitmap results with status
428
+ */
429
+ private fetchNonceBitmaps;
430
+ /**
431
+ * Scan bitmap words for available (unused) nonces.
432
+ * Performs bit-level scanning with early exit when count is reached.
433
+ *
434
+ * @param bitmapResults - Array of bitmap words fetched from contract
435
+ * @param count - Maximum number of nonces to find
436
+ * @returns Array of available nonce values
437
+ */
438
+ private scanBitmapsForNonces;
439
+ /**
440
+ * Get multiple available nonces at once (for batch operations).
441
+ *
442
+ * @param escrowId - The escrow ID
443
+ * @param signer - The signer's address
444
+ * @param count - Number of nonces to retrieve (max NONCE_BITMAP_SIZE)
445
+ * @returns Array of available nonces
446
+ * @throws SDKError if count exceeds limit or nonce space is exhausted
447
+ */
448
+ getMultipleNonces(escrowId: bigint, signer: Address, count: number): Promise<bigint[]>;
449
+ /**
450
+ * @deprecated No longer needed - nonces are tracked by the contract
451
+ */
452
+ resetNonceTracker(): void;
453
+ /**
454
+ * Get dispute submission status
455
+ */
456
+ getDisputeSubmissionStatus(escrowId: bigint): Promise<DisputeSubmissionStatus>;
457
+ getTokenDecimals(tokenAddress: Address): Promise<number>;
458
+ getTokenBalance(account: Address, tokenAddress: Address): Promise<bigint>;
459
+ getTokenAllowance(owner: Address, spender: Address, tokenAddress: Address): Promise<bigint>;
460
+ formatTokenAmount(amount: bigint, decimals: number): string;
461
+ /**
462
+ * Approve token spending if needed
463
+ */
464
+ approveTokenIfNeeded(walletClient: EscrowWalletClient, token: Address, spender: Address, amount: bigint): Promise<Hex | null>;
465
+ /**
466
+ * Create a new escrow as the seller
467
+ *
468
+ * This function creates a new escrow where the caller (seller) is offering goods/services
469
+ * to a buyer. The escrow starts in AWAITING_PAYMENT state until the buyer deposits funds.
470
+ *
471
+ * The seller's wallet authorization signature is automatically generated and attached,
472
+ * which will be used later for 2-of-3 multisig withdrawals from the escrow wallet.
473
+ *
474
+ * @param walletClient - The seller's wallet client (must have account connected)
475
+ * @param params - Escrow creation parameters
476
+ * @param params.token - ERC20 token address for payment
477
+ * @param params.buyer - Buyer's wallet address
478
+ * @param params.amount - Payment amount in token's smallest unit (e.g., wei for 18 decimals)
479
+ * @param params.maturityTimeDays - Optional days until maturity (default: 1, min: 1, max: 3650)
480
+ * @param params.arbiter - Optional arbiter address for dispute resolution
481
+ * @param params.title - Escrow title/description (1-500 characters, supports encrypted hashes)
482
+ * @param params.ipfsHash - Optional IPFS hash for additional details
483
+ * @returns Object containing escrowId, transaction hash, and wallet address
484
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
485
+ * @throws {SDKError} VALIDATION_ERROR - If parameters are invalid
486
+ * @throws {SDKError} TRANSACTION_FAILED - If the transaction fails
487
+ */
488
+ createEscrow(walletClient: EscrowWalletClient, params: CreateEscrowParams): Promise<{
489
+ escrowId: bigint;
490
+ txHash: Hex;
491
+ walletAddress: Address;
492
+ }>;
493
+ /**
494
+ * Create a new escrow and deposit funds as the buyer (single transaction)
495
+ *
496
+ * This function creates a new escrow and immediately deposits the payment in one transaction.
497
+ * The escrow starts in AWAITING_DELIVERY state. The seller must call `acceptEscrow` to
498
+ * provide their wallet signature before funds can be released.
499
+ *
500
+ * Token approval is automatically handled if needed.
501
+ *
502
+ * @param walletClient - The buyer's wallet client (must have account connected)
503
+ * @param params - Escrow creation parameters
504
+ * @param params.token - ERC20 token address for payment
505
+ * @param params.seller - Seller's wallet address
506
+ * @param params.amount - Payment amount in token's smallest unit (e.g., wei for 18 decimals)
507
+ * @param params.maturityTimeDays - Optional days until maturity (default: 1, min: 1, max: 3650)
508
+ * @param params.arbiter - Optional arbiter address for dispute resolution
509
+ * @param params.title - Escrow title/description (1-500 characters, supports encrypted hashes)
510
+ * @param params.ipfsHash - Optional IPFS hash for additional details
511
+ * @returns Object containing escrowId, transaction hash, and wallet address
512
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
513
+ * @throws {SDKError} VALIDATION_ERROR - If parameters are invalid
514
+ * @throws {SDKError} INSUFFICIENT_BALANCE - If buyer has insufficient token balance
515
+ * @throws {SDKError} TRANSACTION_FAILED - If the transaction fails
516
+ */
517
+ createEscrowAndDeposit(walletClient: EscrowWalletClient, params: CreateEscrowAndDepositParams): Promise<{
518
+ escrowId: bigint;
519
+ txHash: Hex;
520
+ walletAddress: Address;
521
+ }>;
522
+ /**
523
+ * Deposit funds into an existing escrow as the buyer
524
+ *
525
+ * This function is used when the seller created the escrow via `createEscrow`.
526
+ * The buyer deposits the required payment amount, transitioning the escrow from
527
+ * AWAITING_PAYMENT to AWAITING_DELIVERY state.
528
+ *
529
+ * Token approval is automatically handled if needed.
530
+ * The buyer's wallet authorization signature is automatically generated.
531
+ *
532
+ * @param walletClient - The buyer's wallet client (must have account connected)
533
+ * @param escrowId - The escrow ID to deposit into
534
+ * @returns Transaction hash
535
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
536
+ * @throws {SDKError} NOT_BUYER - If caller is not the designated buyer
537
+ * @throws {SDKError} INVALID_STATE - If escrow is not in AWAITING_PAYMENT state
538
+ * @throws {SDKError} INSUFFICIENT_BALANCE - If buyer has insufficient token balance
539
+ */
540
+ deposit(walletClient: EscrowWalletClient, escrowId: bigint): Promise<Hex>;
541
+ /**
542
+ * Accept an escrow as the seller (for buyer-created escrows)
543
+ *
544
+ * This function is required when the buyer created the escrow via `createEscrowAndDeposit`.
545
+ * The seller must accept to provide their wallet authorization signature, which is
546
+ * required for the 2-of-3 multisig withdrawal mechanism.
547
+ *
548
+ * Without accepting, the seller cannot receive funds even if the buyer confirms delivery.
549
+ *
550
+ * @param walletClient - The seller's wallet client (must have account connected)
551
+ * @param escrowId - The escrow ID to accept
552
+ * @returns Transaction hash
553
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
554
+ * @throws {SDKError} NOT_SELLER - If caller is not the designated seller
555
+ * @throws {SDKError} INVALID_STATE - If escrow is not in AWAITING_DELIVERY state
556
+ * @throws {SDKError} ALREADY_ACCEPTED - If escrow was already accepted
557
+ */
558
+ acceptEscrow(walletClient: EscrowWalletClient, escrowId: bigint): Promise<Hex>;
559
+ /**
560
+ * Confirm delivery and release funds to the seller
561
+ *
562
+ * This function is called by the buyer after receiving the goods/services.
563
+ * It transitions the escrow to COMPLETE state and authorizes payment release to the seller.
564
+ *
565
+ * After confirmation, anyone can call `withdraw` on the escrow wallet to execute
566
+ * the actual token transfer (requires 2-of-3 signatures: buyer + seller).
567
+ *
568
+ * A 1% fee is deducted from the payment amount.
569
+ *
570
+ * @param walletClient - The buyer's wallet client (must have account connected)
571
+ * @param escrowId - The escrow ID to confirm
572
+ * @returns Transaction hash
573
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
574
+ * @throws {SDKError} NOT_BUYER - If caller is not the designated buyer
575
+ * @throws {SDKError} INVALID_STATE - If escrow is not in AWAITING_DELIVERY state
576
+ */
577
+ confirmDelivery(walletClient: EscrowWalletClient, escrowId: bigint): Promise<Hex>;
578
+ /**
579
+ * Confirm delivery via meta-transaction (gasless for buyer)
580
+ *
581
+ * This function allows a relayer to submit the confirm delivery transaction on behalf
582
+ * of the buyer. The buyer signs the confirmation off-chain, and the relayer pays the gas.
583
+ *
584
+ * Use `prepareConfirmDeliverySigned` to generate the required signatures.
585
+ *
586
+ * @param walletClient - The relayer's wallet client (pays gas)
587
+ * @param escrowId - The escrow ID to confirm
588
+ * @param coordSignature - Buyer's EIP-712 signature for the confirmation
589
+ * @param deadline - Signature expiration timestamp (must be within 24 hours)
590
+ * @param nonce - Buyer's nonce for replay protection
591
+ * @param buyerWalletSig - Buyer's wallet authorization signature
592
+ * @returns Transaction hash
593
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
594
+ * @throws {SDKError} SIGNATURE_EXPIRED - If deadline has passed
595
+ */
596
+ confirmDeliverySigned(walletClient: EscrowWalletClient, escrowId: bigint, coordSignature: Hex, deadline: bigint, nonce: bigint, buyerWalletSig: Hex): Promise<Hex>;
597
+ /**
598
+ * Prepare signatures for gasless confirm delivery
599
+ *
600
+ * This helper function generates all the signatures needed for a gasless confirm delivery.
601
+ * The buyer signs off-chain, and the resulting data can be sent to a relayer who will
602
+ * submit the transaction and pay the gas.
603
+ *
604
+ * The deadline is set to 60 minutes from the current block timestamp.
605
+ *
606
+ * @param buyerWalletClient - The buyer's wallet client (must have account connected)
607
+ * @param escrowId - The escrow ID to confirm
608
+ * @returns Object containing coordSignature, buyerWalletSig, deadline, and nonce
609
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
610
+ * @throws {SDKError} NOT_BUYER - If caller is not the designated buyer
611
+ */
612
+ prepareConfirmDeliverySigned(buyerWalletClient: EscrowWalletClient, escrowId: bigint): Promise<{
613
+ coordSignature: Hex;
614
+ buyerWalletSig: Hex;
615
+ deadline: bigint;
616
+ nonce: bigint;
617
+ }>;
618
+ /**
619
+ * Request cancellation of an escrow
620
+ *
621
+ * This function allows either the buyer or seller to request cancellation.
622
+ * Both parties must call this function for a mutual cancellation to occur.
623
+ *
624
+ * - If only one party requests: The request is recorded, awaiting the other party
625
+ * - If both parties request: The escrow is automatically canceled and funds returned to buyer
626
+ *
627
+ * Use `getCancelRequestStatus` to check if the other party has already requested.
628
+ *
629
+ * @param walletClient - The buyer's or seller's wallet client
630
+ * @param escrowId - The escrow ID to cancel
631
+ * @returns Transaction hash
632
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
633
+ * @throws {SDKError} INVALID_ROLE - If caller is not buyer or seller
634
+ * @throws {SDKError} INVALID_STATE - If escrow is not in AWAITING_DELIVERY state
635
+ */
636
+ requestCancel(walletClient: EscrowWalletClient, escrowId: bigint): Promise<Hex>;
637
+ /**
638
+ * Cancel escrow by timeout (unilateral cancellation by buyer)
639
+ *
640
+ * This function allows the buyer to cancel the escrow unilaterally if:
641
+ * - The buyer has already requested cancellation via `requestCancel`
642
+ * - The maturity time has passed
643
+ * - The seller has not agreed to mutual cancellation
644
+ * - No dispute is active
645
+ * - An arbiter is assigned to the escrow
646
+ *
647
+ * Funds are returned to the buyer without any fee deduction.
648
+ *
649
+ * @param walletClient - The buyer's wallet client (must have account connected)
650
+ * @param escrowId - The escrow ID to cancel
651
+ * @returns Transaction hash
652
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
653
+ * @throws {SDKError} NOT_BUYER - If caller is not the designated buyer
654
+ * @throws {SDKError} INVALID_STATE - If conditions for timeout cancel are not met
655
+ */
656
+ cancelByTimeout(walletClient: EscrowWalletClient, escrowId: bigint): Promise<Hex>;
657
+ /**
658
+ * Auto-release funds to seller after maturity time
659
+ *
660
+ * This function allows the seller to claim funds unilaterally after the maturity time
661
+ * has passed. This protects sellers when buyers become unresponsive after receiving
662
+ * goods/services.
663
+ *
664
+ * Requirements:
665
+ * - Escrow must be in AWAITING_DELIVERY state
666
+ * - No dispute has been started
667
+ * - Buyer has not requested cancellation
668
+ * - maturityTime has passed
669
+ * - Seller has already provided wallet signature (via createEscrow or acceptEscrow)
670
+ *
671
+ * A 1% fee is deducted from the payment amount.
672
+ *
673
+ * @param walletClient - The seller's wallet client (must have account connected)
674
+ * @param escrowId - The escrow ID to auto-release
675
+ * @returns Transaction hash
676
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
677
+ * @throws {SDKError} NOT_SELLER - If caller is not the designated seller
678
+ * @throws {SDKError} INVALID_STATE - If escrow is not in AWAITING_DELIVERY state
679
+ * @throws {SDKError} INVALID_STATE - If dispute is active or buyer requested cancel
680
+ * @throws {SDKError} VALIDATION_ERROR - If seller wallet signature is missing
681
+ */
682
+ autoRelease(walletClient: EscrowWalletClient, escrowId: bigint): Promise<Hex>;
683
+ /**
684
+ * Start a dispute for an escrow
685
+ *
686
+ * This function initiates a dispute when there's a disagreement between buyer and seller.
687
+ * Once started, the escrow enters DISPUTED state and requires arbiter resolution.
688
+ *
689
+ * Either the buyer or seller can start a dispute. An arbiter must be assigned to the
690
+ * escrow for disputes to be possible.
691
+ *
692
+ * After starting a dispute:
693
+ * 1. Both parties should submit evidence via `submitDisputeMessage`
694
+ * 2. The arbiter reviews evidence and makes a decision via `submitArbiterDecision`
695
+ * 3. The arbiter can rule in favor of buyer (REFUNDED) or seller (COMPLETE)
696
+ *
697
+ * @param walletClient - The buyer's or seller's wallet client
698
+ * @param escrowId - The escrow ID to dispute
699
+ * @returns Transaction hash
700
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
701
+ * @throws {SDKError} INVALID_STATE - If escrow is not in AWAITING_DELIVERY state
702
+ */
703
+ startDispute(walletClient: EscrowWalletClient, escrowId: bigint): Promise<Hex>;
704
+ /**
705
+ * Start a dispute via meta-transaction (gasless for buyer/seller)
706
+ *
707
+ * This function allows a relayer to submit the start dispute transaction on behalf
708
+ * of the buyer or seller. The initiator signs off-chain, and the relayer pays the gas.
709
+ *
710
+ * Use `signStartDispute` to generate the required signature.
711
+ *
712
+ * @param walletClient - The relayer's wallet client (pays gas)
713
+ * @param escrowId - The escrow ID to dispute
714
+ * @param signature - Buyer's or seller's EIP-712 signature
715
+ * @param deadline - Signature expiration timestamp (must be within 24 hours)
716
+ * @param nonce - Signer's nonce for replay protection
717
+ * @returns Transaction hash
718
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
719
+ * @throws {SDKError} SIGNATURE_EXPIRED - If deadline has passed
720
+ */
721
+ startDisputeSigned(walletClient: EscrowWalletClient, escrowId: bigint, signature: Hex, deadline: bigint, nonce: bigint): Promise<Hex>;
722
+ /**
723
+ * Submit evidence for a dispute
724
+ *
725
+ * This function allows the buyer or seller to submit evidence supporting their case.
726
+ * Each party can only submit evidence once. Evidence is stored on IPFS and the hash
727
+ * is recorded on-chain.
728
+ *
729
+ * The arbiter will review submitted evidence before making a decision. Both parties
730
+ * should submit evidence for a fair resolution. After 30 days, the arbiter can make
731
+ * a decision even without complete evidence.
732
+ *
733
+ * @param walletClient - The buyer's or seller's wallet client
734
+ * @param escrowId - The escrow ID
735
+ * @param role - The caller's role (Role.Buyer or Role.Seller)
736
+ * @param ipfsHash - IPFS hash containing the evidence (max 500 characters)
737
+ * @returns Transaction hash
738
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
739
+ * @throws {SDKError} EVIDENCE_ALREADY_SUBMITTED - If caller already submitted evidence
740
+ * @throws {SDKError} INVALID_STATE - If escrow is not in DISPUTED state
741
+ */
742
+ submitDisputeMessage(walletClient: EscrowWalletClient, escrowId: bigint, role: Role.Buyer | Role.Seller, ipfsHash: string): Promise<Hex>;
743
+ /**
744
+ * Submit arbiter's decision to resolve a dispute
745
+ *
746
+ * This function is called by the designated arbiter to resolve a dispute.
747
+ * The arbiter reviews evidence submitted by both parties and makes a final decision.
748
+ *
749
+ * The arbiter can rule:
750
+ * - DisputeResolution.Complete (3): Funds go to seller (with 1% fee)
751
+ * - DisputeResolution.Refunded (4): Funds go to buyer (no fee)
752
+ *
753
+ * Requirements:
754
+ * - Both parties must have submitted evidence, OR
755
+ * - 30 days + 1 hour timeout has passed since dispute started
756
+ *
757
+ * The arbiter's wallet signature is automatically generated for the multisig.
758
+ *
759
+ * @param walletClient - The arbiter's wallet client (must have account connected)
760
+ * @param escrowId - The escrow ID to resolve
761
+ * @param resolution - DisputeResolution.Complete or DisputeResolution.Refunded
762
+ * @param ipfsHash - IPFS hash containing the decision explanation
763
+ * @returns Transaction hash
764
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
765
+ * @throws {SDKError} NOT_ARBITER - If caller is not the designated arbiter
766
+ * @throws {SDKError} INVALID_STATE - If escrow is not in DISPUTED state
767
+ */
768
+ submitArbiterDecision(walletClient: EscrowWalletClient, escrowId: bigint, resolution: DisputeResolution, ipfsHash: string): Promise<Hex>;
769
+ /**
770
+ * Withdraw funds from the escrow wallet
771
+ *
772
+ * This function executes the actual token transfer from the escrow wallet to the
773
+ * designated recipient. The wallet contract uses a 2-of-3 multisig mechanism:
774
+ *
775
+ * - COMPLETE state: Requires buyer + seller signatures → funds go to seller
776
+ * - REFUNDED state: Requires buyer + arbiter signatures → funds go to buyer
777
+ * - CANCELED state: Requires buyer + seller signatures → funds go to buyer
778
+ *
779
+ * Anyone can call this function (typically the recipient), as the signatures
780
+ * were already collected during the escrow lifecycle. The wallet contract
781
+ * automatically reads and verifies signatures from the escrow contract.
782
+ *
783
+ * @param walletClient - Any wallet client (typically the recipient)
784
+ * @param escrowId - The escrow ID to withdraw from
785
+ * @returns Transaction hash
786
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
787
+ * @throws {SDKError} INVALID_STATE - If escrow is not in a final state (COMPLETE/REFUNDED/CANCELED)
788
+ */
789
+ withdraw(walletClient: EscrowWalletClient, escrowId: bigint): Promise<Hex>;
790
+ /**
791
+ * Get valid signature count for wallet
792
+ */
793
+ getWalletSignatureCount(escrowId: bigint): Promise<number>;
794
+ /**
795
+ * Get wallet balance
796
+ */
797
+ getWalletBalance(escrowId: bigint): Promise<bigint>;
798
+ getEscrows(): Promise<Escrow[]>;
799
+ getEscrowsByBuyer(buyer: string): Promise<Escrow[]>;
800
+ getEscrowsBySeller(seller: string): Promise<Escrow[]>;
801
+ getEscrowDetail(id: string): Promise<Escrow | undefined>;
802
+ getDisputeMessages(escrowId: string): Promise<any[]>;
803
+ /**
804
+ * Get a human-readable status label with color and description for an escrow state.
805
+ * This is useful for displaying escrow status in UIs.
806
+ *
807
+ * @param state - The escrow state enum value
808
+ * @returns An object containing:
809
+ * - label: Human-readable status name
810
+ * - color: Suggested UI color (orange, blue, red, green, gray)
811
+ * - description: Detailed explanation of what this state means
812
+ *
813
+ * @example
814
+ * ```typescript
815
+ * const sdk = new PalindromePaySDK(...);
816
+ * const escrow = await sdk.getEscrowByIdParsed(1n);
817
+ * const status = sdk.getStatusLabel(escrow.state);
818
+ * console.log(status.label); // "Awaiting Payment"
819
+ * console.log(status.color); // "orange"
820
+ * console.log(status.description); // "Buyer needs to deposit funds"
821
+ * ```
822
+ */
823
+ getStatusLabel(state: EscrowState): {
824
+ label: string;
825
+ color: string;
826
+ description: string;
827
+ };
828
+ /**
829
+ * Get user role for an escrow
830
+ */
831
+ getUserRole(userAddress: Address, escrow: EscrowData): Role;
832
+ /**
833
+ * Simulate a transaction before executing
834
+ * Returns success status, gas estimate, and revert reason if failed
835
+ */
836
+ simulateTransaction(walletClient: EscrowWalletClient, functionName: string, args: any[], contractAddress?: Address): Promise<{
837
+ success: boolean;
838
+ gasEstimate?: bigint;
839
+ revertReason?: string;
840
+ result?: any;
841
+ }>;
842
+ /**
843
+ * Simulate deposit before executing
844
+ */
845
+ simulateDeposit(walletClient: EscrowWalletClient, escrowId: bigint): Promise<{
846
+ success: boolean;
847
+ gasEstimate?: bigint;
848
+ revertReason?: string;
849
+ needsApproval?: boolean;
850
+ approvalAmount?: bigint;
851
+ }>;
852
+ /**
853
+ * Simulate confirm delivery before executing
854
+ */
855
+ simulateConfirmDelivery(walletClient: EscrowWalletClient, escrowId: bigint): Promise<{
856
+ success: boolean;
857
+ gasEstimate?: bigint;
858
+ revertReason?: string;
859
+ }>;
860
+ /**
861
+ * Simulate withdraw before executing
862
+ */
863
+ simulateWithdraw(walletClient: EscrowWalletClient, escrowId: bigint): Promise<{
864
+ success: boolean;
865
+ gasEstimate?: bigint;
866
+ revertReason?: string;
867
+ signatureCount?: number;
868
+ }>;
869
+ /**
870
+ * Estimate gas for a transaction with buffer
871
+ */
872
+ estimateGasWithBuffer(walletClient: EscrowWalletClient, functionName: string, args: any[], contractAddress?: Address): Promise<bigint>;
873
+ /**
874
+ * Health check
875
+ */
876
+ healthCheck(): Promise<{
877
+ rpcConnected: boolean;
878
+ contractDeployed: boolean;
879
+ subgraphConnected: boolean;
880
+ errors: string[];
881
+ }>;
882
+ /**
883
+ * Get escrow status with optional caching
884
+ */
885
+ getEscrowStatus(escrowId: bigint, forceRefresh?: boolean): Promise<{
886
+ state: EscrowState;
887
+ stateName: string;
888
+ label: string;
889
+ color: string;
890
+ description: string;
891
+ }>;
892
+ /**
893
+ * Get cache statistics
894
+ */
895
+ getCacheStats(): {
896
+ escrowCacheSize: number;
897
+ tokenDecimalsCacheSize: number;
898
+ };
899
+ /**
900
+ * Clear all caches
901
+ */
902
+ clearAllCaches(): void;
903
+ /**
904
+ * Clear escrow cache only
905
+ */
906
+ clearEscrowCache(): void;
907
+ /**
908
+ * Clear multicall cache (useful when switching chains)
909
+ */
910
+ clearMulticallCache(): void;
911
+ /**
912
+ * Watch for escrow events related to a user
913
+ */
914
+ watchUserEscrows(userAddress: Address, callback: (escrowId: bigint, event: EscrowCreatedEvent) => void, options?: {
915
+ fromBlock?: bigint;
916
+ }): {
917
+ dispose: () => void;
918
+ };
919
+ /**
920
+ * Watch for state changes on a specific escrow
921
+ */
922
+ watchEscrowStateChanges(escrowId: bigint, callback: (newState: EscrowState, previousState: EscrowState) => void, options?: {
923
+ pollingInterval?: number;
924
+ }): {
925
+ dispose: () => void;
926
+ };
927
+ /**
928
+ * Check if user has submitted evidence for a dispute
929
+ */
930
+ hasSubmittedEvidence(escrowId: bigint, role: Role): Promise<boolean>;
931
+ /**
932
+ * Get cancellation request status for an escrow
933
+ *
934
+ * This helper function checks whether the buyer and/or seller have requested
935
+ * cancellation. Use this to determine if mutual cancellation is pending or complete.
936
+ *
937
+ * Cancellation flow:
938
+ * - Either party calls `requestCancel` to initiate
939
+ * - If only one party requested, the other must also call `requestCancel` for mutual cancel
940
+ * - When both request, the escrow is automatically canceled and funds return to buyer
941
+ * - Alternatively, buyer can use `cancelByTimeout` after maturity time (if arbiter is set)
942
+ *
943
+ * @param escrowId - The escrow ID to check
944
+ * @returns Object with buyer/seller cancel request status and whether mutual cancel is complete
945
+ */
946
+ getCancelRequestStatus(escrowId: bigint): Promise<{
947
+ buyerRequested: boolean;
948
+ sellerRequested: boolean;
949
+ mutualCancelComplete: boolean;
950
+ }>;
951
+ /**
952
+ * Get user balances for multiple tokens (batched for performance).
953
+ * Uses Promise.all to fetch all balances and decimals in parallel.
954
+ */
955
+ getUserBalances(userAddress: Address, tokens: Address[]): Promise<Map<Address, {
956
+ balance: bigint;
957
+ decimals: number;
958
+ formatted: string;
959
+ }>>;
960
+ /**
961
+ * Get maturity info for an escrow
962
+ */
963
+ getMaturityInfo(depositTime: bigint, maturityDays: bigint): {
964
+ hasDeadline: boolean;
965
+ maturityDays: number;
966
+ maturityTimestamp: bigint;
967
+ isPassed: boolean;
968
+ remainingSeconds: number;
969
+ };
970
+ /**
971
+ * Get all escrows for a user (as buyer or seller)
972
+ */
973
+ getUserEscrows(userAddress: Address): Promise<Escrow[]>;
974
+ /**
975
+ * Check if a user can deposit to an escrow.
976
+ * A user can deposit if:
977
+ * - The escrow exists and is in AWAITING_PAYMENT state
978
+ * - The user is either the buyer or seller
979
+ *
980
+ * @param userAddress - The address of the user to check
981
+ * @param escrowId - The escrow ID to check
982
+ * @returns True if the user can deposit, false otherwise
983
+ */
984
+ canUserDeposit(userAddress: Address, escrowId: bigint): Promise<boolean>;
985
+ /**
986
+ * Check if a user can accept an escrow (seller accepting after buyer deposit).
987
+ * A user can accept if:
988
+ * - The escrow is in AWAITING_DELIVERY state
989
+ * - The user is the seller
990
+ *
991
+ * @param userAddress - The address of the user to check
992
+ * @param escrowId - The escrow ID to check
993
+ * @returns True if the user can accept, false otherwise
994
+ */
995
+ canUserAcceptEscrow(userAddress: Address, escrowId: bigint): Promise<boolean>;
996
+ /**
997
+ * Check if a user can confirm delivery (buyer confirming receipt).
998
+ * A user can confirm delivery if:
999
+ * - The escrow is in AWAITING_DELIVERY or DISPUTED state
1000
+ * - The user is the buyer
1001
+ *
1002
+ * @param userAddress - The address of the user to check
1003
+ * @param escrowId - The escrow ID to check
1004
+ * @returns True if the user can confirm delivery, false otherwise
1005
+ */
1006
+ canUserConfirmDelivery(userAddress: Address, escrowId: bigint): Promise<boolean>;
1007
+ /**
1008
+ * Check if a user can start a dispute.
1009
+ * A user can start a dispute if:
1010
+ * - The escrow is in AWAITING_DELIVERY state
1011
+ * - The escrow has an arbiter set
1012
+ * - The user is either the buyer or seller
1013
+ *
1014
+ * @param userAddress - The address of the user to check
1015
+ * @param escrowId - The escrow ID to check
1016
+ * @returns True if the user can start a dispute, false otherwise
1017
+ */
1018
+ canUserStartDispute(userAddress: Address, escrowId: bigint): Promise<boolean>;
1019
+ /**
1020
+ * Check if an escrow can be withdrawn (auto-release check).
1021
+ * An escrow can be withdrawn if:
1022
+ * - It's in AWAITING_DELIVERY state
1023
+ * - The maturity time has passed (if deadline is set)
1024
+ *
1025
+ * @param escrowId - The escrow ID to check
1026
+ * @returns True if the escrow can be withdrawn, false otherwise
1027
+ */
1028
+ canUserWithdraw(escrowId: bigint): Promise<boolean>;
1029
+ /**
1030
+ * Check if a seller can perform auto-release.
1031
+ * A seller can auto-release if:
1032
+ * - The escrow is in AWAITING_DELIVERY state
1033
+ * - The maturity time has passed (if deadline is set)
1034
+ * - The user is the seller
1035
+ *
1036
+ * @param userAddress - The address of the user to check
1037
+ * @param escrowId - The escrow ID to check
1038
+ * @returns True if the seller can auto-release, false otherwise
1039
+ */
1040
+ canSellerAutoRelease(userAddress: Address, escrowId: bigint): Promise<boolean>;
1041
+ /**
1042
+ * Check if an address is the buyer in an escrow.
1043
+ *
1044
+ * @param userAddress - The address to check
1045
+ * @param escrow - The escrow data
1046
+ * @returns True if the address is the buyer
1047
+ */
1048
+ isBuyer(userAddress: Address, escrow: EscrowData): boolean;
1049
+ /**
1050
+ * Check if an address is the seller in an escrow.
1051
+ *
1052
+ * @param userAddress - The address to check
1053
+ * @param escrow - The escrow data
1054
+ * @returns True if the address is the seller
1055
+ */
1056
+ isSeller(userAddress: Address, escrow: EscrowData): boolean;
1057
+ /**
1058
+ * Check if an address is the arbiter in an escrow.
1059
+ *
1060
+ * @param userAddress - The address to check
1061
+ * @param escrow - The escrow data
1062
+ * @returns True if the address is the arbiter
1063
+ */
1064
+ isArbiter(userAddress: Address, escrow: EscrowData): boolean;
1065
+ /**
1066
+ * Check if an escrow has an arbiter set.
1067
+ *
1068
+ * @param escrow - The escrow data
1069
+ * @returns True if the escrow has an arbiter (non-zero address)
1070
+ */
1071
+ hasArbiter(escrow: EscrowData): boolean;
1072
+ /**
1073
+ * Compare two addresses for equality (case-insensitive, normalized).
1074
+ * This is a public utility method that can be used to compare Ethereum addresses.
1075
+ *
1076
+ * @param a - First address to compare
1077
+ * @param b - Second address to compare
1078
+ * @returns True if the addresses are equal (case-insensitive)
1079
+ *
1080
+ * @example
1081
+ * ```typescript
1082
+ * const sdk = new PalindromePaySDK(...);
1083
+ * const areEqual = sdk.addressEquals(
1084
+ * "0xabc...",
1085
+ * "0xABC..."
1086
+ * ); // true
1087
+ * ```
1088
+ */
1089
+ addressEquals(a: Address | string, b: Address | string): boolean;
1090
+ /**
1091
+ * Get current gas price information from the network.
1092
+ * Returns standard, fast, and instant gas price estimates in gwei.
1093
+ *
1094
+ * @returns Object containing gas price estimates
1095
+ *
1096
+ * @example
1097
+ * ```typescript
1098
+ * const gasPrice = await sdk.getCurrentGasPrice();
1099
+ * console.log(`Standard: ${gasPrice.standard} gwei`);
1100
+ * console.log(`Fast: ${gasPrice.fast} gwei`);
1101
+ * console.log(`Instant: ${gasPrice.instant} gwei`);
1102
+ * ```
1103
+ */
1104
+ getCurrentGasPrice(): Promise<{
1105
+ standard: bigint;
1106
+ fast: bigint;
1107
+ instant: bigint;
1108
+ wei: bigint;
1109
+ }>;
1110
+ /**
1111
+ * Estimate gas cost for creating an escrow.
1112
+ *
1113
+ * @param params - Create escrow parameters
1114
+ * @returns Gas estimation details
1115
+ *
1116
+ * @example
1117
+ * ```typescript
1118
+ * const estimate = await sdk.estimateGasForCreateEscrow({
1119
+ * token: tokenAddress,
1120
+ * buyer: buyerAddress,
1121
+ * amount: 1000000n,
1122
+ * maturityDays: 7n,
1123
+ * arbiter: zeroAddress,
1124
+ * title: 'Test',
1125
+ * ipfsHash: ''
1126
+ * });
1127
+ * console.log(`Gas limit: ${estimate.gasLimit}`);
1128
+ * console.log(`Cost: ${estimate.estimatedCostEth} ETH`);
1129
+ * ```
1130
+ */
1131
+ estimateGasForCreateEscrow(params: {
1132
+ token: Address;
1133
+ buyer: Address;
1134
+ amount: bigint;
1135
+ maturityDays: bigint;
1136
+ arbiter: Address;
1137
+ title: string;
1138
+ ipfsHash: string;
1139
+ }): Promise<{
1140
+ gasLimit: bigint;
1141
+ estimatedCostWei: bigint;
1142
+ estimatedCostEth: string;
1143
+ }>;
1144
+ /**
1145
+ * Estimate gas cost for depositing to an escrow.
1146
+ *
1147
+ * @param escrowId - The escrow ID
1148
+ * @returns Gas estimation details
1149
+ *
1150
+ * @example
1151
+ * ```typescript
1152
+ * const estimate = await sdk.estimateGasForDeposit(escrowId);
1153
+ * console.log(`Gas limit: ${estimate.gasLimit}`);
1154
+ * ```
1155
+ */
1156
+ estimateGasForDeposit(escrowId: bigint): Promise<{
1157
+ gasLimit: bigint;
1158
+ estimatedCostWei: bigint;
1159
+ estimatedCostEth: string;
1160
+ }>;
1161
+ /**
1162
+ * Estimate gas cost for confirming delivery.
1163
+ *
1164
+ * @param escrowId - The escrow ID
1165
+ * @returns Gas estimation details
1166
+ *
1167
+ * @example
1168
+ * ```typescript
1169
+ * const estimate = await sdk.estimateGasForConfirmDelivery(escrowId);
1170
+ * console.log(`Cost: ${estimate.estimatedCostEth} ETH`);
1171
+ * ```
1172
+ */
1173
+ estimateGasForConfirmDelivery(escrowId: bigint): Promise<{
1174
+ gasLimit: bigint;
1175
+ estimatedCostWei: bigint;
1176
+ estimatedCostEth: string;
1177
+ }>;
1178
+ /**
1179
+ * Estimate gas cost for withdrawing from escrow wallet.
1180
+ *
1181
+ * @returns Gas estimation details
1182
+ *
1183
+ * @example
1184
+ * ```typescript
1185
+ * const estimate = await sdk.estimateGasForWithdraw();
1186
+ * ```
1187
+ */
1188
+ estimateGasForWithdraw(): Promise<{
1189
+ gasLimit: bigint;
1190
+ estimatedCostWei: bigint;
1191
+ estimatedCostEth: string;
1192
+ }>;
1193
+ /**
1194
+ * Get fee receiver address (cached - rarely changes)
1195
+ * @param forceRefresh - Set to true to bypass cache and fetch fresh value
1196
+ */
1197
+ getFeeReceiver(forceRefresh?: boolean): Promise<Address>;
1198
+ /** Cached fee basis points (lazily computed from contract) */
1199
+ private cachedFeeBps;
1200
+ /**
1201
+ * Get fee percentage in basis points.
1202
+ * Tries to read FEE_BPS from contract, falls back to default (100 = 1%).
1203
+ * Result is cached for performance.
1204
+ */
1205
+ getFeeBps(): Promise<bigint>;
1206
+ /**
1207
+ * Calculate fee for an amount.
1208
+ * Uses the same logic as the contract's _computeFeeAndNet.
1209
+ */
1210
+ calculateFee(amount: bigint, tokenDecimals?: number): Promise<{
1211
+ fee: bigint;
1212
+ net: bigint;
1213
+ }>;
1214
+ }
1215
+ export default PalindromePaySDK;