@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,2708 @@
1
+ "use strict";
2
+ // Copyright (c) 2025 Palindrome Pay
3
+ // Licensed under the MIT License. See LICENSE file for details.
4
+ var __importDefault = (this && this.__importDefault) || function (mod) {
5
+ return (mod && mod.__esModule) ? mod : { "default": mod };
6
+ };
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.PalindromePaySDK = exports.SDKError = exports.SDKErrorCode = exports.Role = exports.DisputeResolution = exports.EscrowState = void 0;
9
+ /**
10
+ * PALINDROME Pay SDK
11
+ *
12
+ * Key contract functions:
13
+ * - createEscrow(token, buyer, amount, maturityDays, arbiter, title, ipfsHash, sellerWalletSig)
14
+ * - createEscrowAndDeposit(token, seller, amount, maturityDays, arbiter, title, ipfsHash, buyerWalletSig)
15
+ * - deposit(escrowId, buyerWalletSig)
16
+ * - acceptEscrow(escrowId, sellerWalletSig)
17
+ * - confirmDelivery(escrowId, buyerWalletSig)
18
+ * - confirmDeliverySigned(escrowId, coordSignature, deadline, nonce, buyerWalletSig)
19
+ * - requestCancel(escrowId, walletSig)
20
+ * - cancelByTimeout(escrowId)
21
+ * - autoRelease(escrowId)
22
+ * - startDispute(escrowId)
23
+ * - startDisputeSigned(escrowId, signature, deadline, nonce)
24
+ * - submitDisputeMessage(escrowId, role, ipfsHash)
25
+ * - submitArbiterDecision(escrowId, resolution, ipfsHash, arbiterWalletSig)
26
+ * - Wallet: withdraw()
27
+ */
28
+ const viem_1 = require("viem");
29
+ const actions_1 = require("viem/actions");
30
+ const PalindromePay_json_1 = __importDefault(require("./contract/PalindromePay.json"));
31
+ const PalindromePayWallet_json_1 = __importDefault(require("./contract/PalindromePayWallet.json"));
32
+ const USDT_json_1 = __importDefault(require("./contract/USDT.json"));
33
+ const client_1 = require("@apollo/client");
34
+ /** Type guard to check if error is a Viem error */
35
+ function isViemError(error) {
36
+ return (typeof error === 'object' &&
37
+ error !== null &&
38
+ 'message' in error &&
39
+ typeof error.message === 'string');
40
+ }
41
+ /** Type guard to check if error is a contract error */
42
+ function isContractError(error) {
43
+ return isViemError(error) && 'contractAddress' in error;
44
+ }
45
+ /** Type guard to check if error has a short message */
46
+ function hasShortMessage(error) {
47
+ return (isViemError(error) &&
48
+ 'shortMessage' in error &&
49
+ typeof error.shortMessage === 'string');
50
+ }
51
+ /** Default console logger */
52
+ const defaultLogger = {
53
+ debug: (msg, ctx) => ctx !== undefined ? console.debug(msg, ctx) : console.debug(msg),
54
+ info: (msg, ctx) => ctx !== undefined ? console.info(msg, ctx) : console.info(msg),
55
+ warn: (msg, ctx) => ctx !== undefined ? console.warn(msg, ctx) : console.warn(msg),
56
+ error: (msg, ctx) => ctx !== undefined ? console.error(msg, ctx) : console.error(msg),
57
+ };
58
+ /** No-op logger (disables all logging) */
59
+ const noOpLogger = {
60
+ debug: () => { },
61
+ info: () => { },
62
+ warn: () => { },
63
+ error: () => { },
64
+ };
65
+ // ==========================================================================
66
+ // IMPORTS CONTINUED
67
+ // ==========================================================================
68
+ const queries_1 = require("./subgraph/queries");
69
+ const chains_1 = require("viem/chains");
70
+ // ============================================================================
71
+ // ENUMS & TYPES
72
+ // ============================================================================
73
+ var EscrowState;
74
+ (function (EscrowState) {
75
+ EscrowState[EscrowState["AWAITING_PAYMENT"] = 0] = "AWAITING_PAYMENT";
76
+ EscrowState[EscrowState["AWAITING_DELIVERY"] = 1] = "AWAITING_DELIVERY";
77
+ EscrowState[EscrowState["DISPUTED"] = 2] = "DISPUTED";
78
+ EscrowState[EscrowState["COMPLETE"] = 3] = "COMPLETE";
79
+ EscrowState[EscrowState["REFUNDED"] = 4] = "REFUNDED";
80
+ EscrowState[EscrowState["CANCELED"] = 5] = "CANCELED";
81
+ })(EscrowState || (exports.EscrowState = EscrowState = {}));
82
+ var DisputeResolution;
83
+ (function (DisputeResolution) {
84
+ DisputeResolution[DisputeResolution["Complete"] = 3] = "Complete";
85
+ DisputeResolution[DisputeResolution["Refunded"] = 4] = "Refunded";
86
+ })(DisputeResolution || (exports.DisputeResolution = DisputeResolution = {}));
87
+ var Role;
88
+ (function (Role) {
89
+ Role[Role["None"] = 0] = "None";
90
+ Role[Role["Buyer"] = 1] = "Buyer";
91
+ Role[Role["Seller"] = 2] = "Seller";
92
+ Role[Role["Arbiter"] = 3] = "Arbiter";
93
+ })(Role || (exports.Role = Role = {}));
94
+ // ==========================================================================
95
+ // CONSTANTS
96
+ // ==========================================================================
97
+ /** Maximum length for string fields (title, IPFS hash) */
98
+ const MAX_STRING_LENGTH = 500;
99
+ /** User rejection error code from wallet */
100
+ const USER_REJECTION_CODE = 4001;
101
+ /** Seconds per day for maturity calculations */
102
+ const SECONDS_PER_DAY = 86400n;
103
+ /** Nonce bitmap word size in bits */
104
+ const NONCE_BITMAP_SIZE = 256;
105
+ /** Default cache TTL in milliseconds */
106
+ const DEFAULT_CACHE_TTL = 5000;
107
+ /** Default transaction receipt timeout in milliseconds */
108
+ const DEFAULT_RECEIPT_TIMEOUT = 60000;
109
+ /** Default polling interval in milliseconds */
110
+ const DEFAULT_POLLING_INTERVAL = 5000;
111
+ // ==========================================================================
112
+ // ERROR CODES
113
+ // ==========================================================================
114
+ var SDKErrorCode;
115
+ (function (SDKErrorCode) {
116
+ SDKErrorCode["WALLET_NOT_CONNECTED"] = "WALLET_NOT_CONNECTED";
117
+ SDKErrorCode["WALLET_ACCOUNT_MISSING"] = "WALLET_ACCOUNT_MISSING";
118
+ SDKErrorCode["NOT_BUYER"] = "NOT_BUYER";
119
+ SDKErrorCode["NOT_SELLER"] = "NOT_SELLER";
120
+ SDKErrorCode["NOT_ARBITER"] = "NOT_ARBITER";
121
+ SDKErrorCode["INVALID_STATE"] = "INVALID_STATE";
122
+ SDKErrorCode["INSUFFICIENT_BALANCE"] = "INSUFFICIENT_BALANCE";
123
+ SDKErrorCode["ALLOWANCE_FAILED"] = "ALLOWANCE_FAILED";
124
+ SDKErrorCode["SIGNATURE_EXPIRED"] = "SIGNATURE_EXPIRED";
125
+ SDKErrorCode["TRANSACTION_FAILED"] = "TRANSACTION_FAILED";
126
+ SDKErrorCode["INVALID_ROLE"] = "INVALID_ROLE";
127
+ SDKErrorCode["INVALID_TOKEN"] = "INVALID_TOKEN";
128
+ SDKErrorCode["VALIDATION_ERROR"] = "VALIDATION_ERROR";
129
+ SDKErrorCode["RPC_ERROR"] = "RPC_ERROR";
130
+ SDKErrorCode["EVIDENCE_ALREADY_SUBMITTED"] = "EVIDENCE_ALREADY_SUBMITTED";
131
+ SDKErrorCode["ESCROW_NOT_FOUND"] = "ESCROW_NOT_FOUND";
132
+ SDKErrorCode["ALREADY_ACCEPTED"] = "ALREADY_ACCEPTED";
133
+ })(SDKErrorCode || (exports.SDKErrorCode = SDKErrorCode = {}));
134
+ class SDKError extends Error {
135
+ constructor(message, code, details) {
136
+ super(message);
137
+ this.code = code;
138
+ this.details = details;
139
+ this.name = "SDKError";
140
+ }
141
+ }
142
+ exports.SDKError = SDKError;
143
+ // ============================================================================
144
+ // UTILITY FUNCTIONS
145
+ // ============================================================================
146
+ function assertWalletClient(client) {
147
+ if (!client) {
148
+ throw new SDKError("Wallet client is required", SDKErrorCode.WALLET_NOT_CONNECTED);
149
+ }
150
+ if (!client.account) {
151
+ throw new SDKError("Wallet account is required", SDKErrorCode.WALLET_ACCOUNT_MISSING);
152
+ }
153
+ }
154
+ /**
155
+ * Validate and normalize an Ethereum address using EIP-55 checksum.
156
+ * Throws SDKError if invalid.
157
+ */
158
+ function validateAddress(address, fieldName = "address") {
159
+ try {
160
+ return (0, viem_1.getAddress)(address);
161
+ }
162
+ catch {
163
+ throw new SDKError(`Invalid ${fieldName}: ${address}`, SDKErrorCode.VALIDATION_ERROR);
164
+ }
165
+ }
166
+ /**
167
+ * Check if address is the zero address
168
+ */
169
+ function isZeroAddress(address) {
170
+ return address === viem_1.zeroAddress;
171
+ }
172
+ /**
173
+ * Validate signature format (65 bytes = 130 hex chars + 0x prefix)
174
+ */
175
+ function validateSignature(signature, context = "signature") {
176
+ if (!/^0x[0-9a-fA-F]{130}$/.test(signature)) {
177
+ throw new SDKError(`Invalid ${context} format: expected 65-byte hex signature`, SDKErrorCode.VALIDATION_ERROR);
178
+ }
179
+ }
180
+ /**
181
+ * Compare two addresses for equality (case-insensitive, normalized).
182
+ * More efficient than repeated toLowerCase() calls.
183
+ */
184
+ function addressEquals(a, b) {
185
+ try {
186
+ return (0, viem_1.getAddress)(a) === (0, viem_1.getAddress)(b);
187
+ }
188
+ catch {
189
+ return false;
190
+ }
191
+ }
192
+ // ============================================================================
193
+ // MAIN SDK CLASS
194
+ // ============================================================================
195
+ class PalindromePaySDK {
196
+ constructor(config) {
197
+ /** LRU cache for escrow data with automatic eviction */
198
+ this.escrowCache = new Map();
199
+ /** Cache for token decimals (rarely changes, no eviction needed) */
200
+ this.tokenDecimalsCache = new Map();
201
+ /** Cache for immutable contract values */
202
+ this.walletBytecodeHashCache = null;
203
+ this.feeReceiverCache = null;
204
+ /** Cached multicall support status per chain (null = not yet detected) */
205
+ this.multicallSupported = null;
206
+ this.STATE_NAMES = [
207
+ "AWAITING_PAYMENT",
208
+ "AWAITING_DELIVERY",
209
+ "DISPUTED",
210
+ "COMPLETE",
211
+ "REFUNDED",
212
+ "CANCELED",
213
+ ];
214
+ this.walletAuthorizationTypes = {
215
+ WalletAuthorization: [
216
+ { name: "escrowId", type: "uint256" },
217
+ { name: "wallet", type: "address" },
218
+ { name: "participant", type: "address" },
219
+ ],
220
+ };
221
+ this.confirmDeliveryTypes = {
222
+ ConfirmDelivery: [
223
+ { name: "escrowId", type: "uint256" },
224
+ { name: "buyer", type: "address" },
225
+ { name: "seller", type: "address" },
226
+ { name: "arbiter", type: "address" },
227
+ { name: "token", type: "address" },
228
+ { name: "amount", type: "uint256" },
229
+ { name: "depositTime", type: "uint256" },
230
+ { name: "deadline", type: "uint256" },
231
+ { name: "nonce", type: "uint256" },
232
+ ],
233
+ };
234
+ this.startDisputeTypes = {
235
+ StartDispute: [
236
+ { name: "escrowId", type: "uint256" },
237
+ { name: "buyer", type: "address" },
238
+ { name: "seller", type: "address" },
239
+ { name: "arbiter", type: "address" },
240
+ { name: "token", type: "address" },
241
+ { name: "amount", type: "uint256" },
242
+ { name: "depositTime", type: "uint256" },
243
+ { name: "deadline", type: "uint256" },
244
+ { name: "nonce", type: "uint256" },
245
+ ],
246
+ };
247
+ /** Cached fee basis points (lazily computed from contract) */
248
+ this.cachedFeeBps = null;
249
+ if (!config.contractAddress) {
250
+ throw new SDKError("contractAddress is required", SDKErrorCode.VALIDATION_ERROR);
251
+ }
252
+ this.contractAddress = config.contractAddress;
253
+ this.abiEscrow = PalindromePay_json_1.default.abi;
254
+ this.abiWallet = PalindromePayWallet_json_1.default.abi;
255
+ this.abiERC20 = USDT_json_1.default.abi;
256
+ this.publicClient = config.publicClient;
257
+ this.walletClient = config.walletClient;
258
+ this.chain = config.chain ?? chains_1.hardhat;
259
+ this.cacheTTL = config.cacheTTL ?? DEFAULT_CACHE_TTL;
260
+ this.maxCacheSize = config.maxCacheSize ?? 1000;
261
+ this.enableRetry = config.enableRetry ?? true;
262
+ this.maxRetries = config.maxRetries ?? 3;
263
+ this.retryDelay = config.retryDelay ?? 1000;
264
+ this.gasBuffer = config.gasBuffer ?? 20;
265
+ this.receiptTimeout = config.receiptTimeout ?? DEFAULT_RECEIPT_TIMEOUT;
266
+ this.skipSimulation = config.skipSimulation ?? false;
267
+ this.defaultGasLimit = config.defaultGasLimit ?? 500000n;
268
+ this.logLevel = config.logLevel ?? 'info';
269
+ this.logger = config.logger ?? (this.logLevel === 'none' ? noOpLogger : defaultLogger);
270
+ this.apollo = config.apolloClient ?? new client_1.ApolloClient({
271
+ link: new client_1.HttpLink({
272
+ uri: config.subgraphUrl ?? "https://api.studio.thegraph.com/query/121986/palindrome-finance-subgraph/version/latest",
273
+ }),
274
+ cache: new client_1.InMemoryCache(),
275
+ });
276
+ }
277
+ // ==========================================================================
278
+ // PRIVATE HELPERS
279
+ // ==========================================================================
280
+ /**
281
+ * Internal logging helper that respects log level configuration
282
+ */
283
+ log(level, message, context) {
284
+ const levels = ['debug', 'info', 'warn', 'error', 'none'];
285
+ const currentLevelIndex = levels.indexOf(this.logLevel);
286
+ const messageLevelIndex = levels.indexOf(level);
287
+ if (messageLevelIndex >= currentLevelIndex && messageLevelIndex < 4) {
288
+ this.logger[level](message, context);
289
+ }
290
+ }
291
+ /**
292
+ * Execute a contract write with resilient simulation handling.
293
+ *
294
+ * This method handles unreliable RPC simulation on certain chains (e.g., Base Sepolia)
295
+ * by falling back to direct transaction sending when simulation fails.
296
+ *
297
+ * @param walletClient - The wallet client to use
298
+ * @param params - Contract call parameters
299
+ * @param params.address - Contract address
300
+ * @param params.abi - Contract ABI
301
+ * @param params.functionName - Function to call
302
+ * @param params.args - Function arguments
303
+ * @returns Transaction hash
304
+ */
305
+ async resilientWriteContract(walletClient, params) {
306
+ const { address, abi, functionName, args } = params;
307
+ // Path 1: Skip simulation entirely if configured
308
+ if (this.skipSimulation) {
309
+ this.log('debug', `Skipping simulation for ${functionName}, sending directly`);
310
+ return this.sendTransactionDirect(walletClient, params);
311
+ }
312
+ // Path 2: Try normal write with simulation
313
+ try {
314
+ return await walletClient.writeContract({
315
+ address,
316
+ abi,
317
+ functionName,
318
+ args,
319
+ account: walletClient.account,
320
+ chain: this.chain,
321
+ });
322
+ }
323
+ catch (error) {
324
+ // Path 3: Conditional fallback based on error type
325
+ if (!this.isSimulationErrorType(error)) {
326
+ throw error; // Not a simulation error, propagate
327
+ }
328
+ // Simulation failed - send directly as fallback
329
+ this.log('warn', `Simulation failed for ${functionName}, bypassing to send directly`, {
330
+ error: isViemError(error) ? error.message?.slice(0, 100) : String(error),
331
+ functionName,
332
+ });
333
+ return this.sendTransactionDirect(walletClient, params);
334
+ }
335
+ }
336
+ /**
337
+ * Wait for transaction receipt with timeout and retry logic.
338
+ */
339
+ async waitForReceipt(hash) {
340
+ return this.withRetry(async () => {
341
+ try {
342
+ return await this.publicClient.waitForTransactionReceipt({
343
+ hash,
344
+ timeout: this.receiptTimeout,
345
+ });
346
+ }
347
+ catch (error) {
348
+ const errorMessage = isViemError(error) ? error.message : String(error);
349
+ if (errorMessage.includes("timed out") || errorMessage.includes("timeout")) {
350
+ throw new SDKError(`Transaction receipt timeout after ${this.receiptTimeout}ms`, SDKErrorCode.TRANSACTION_FAILED, { hash });
351
+ }
352
+ throw error;
353
+ }
354
+ }, "waitForTransactionReceipt");
355
+ }
356
+ /**
357
+ * Execute an async operation with retry logic.
358
+ */
359
+ async withRetry(operation, operationName = "operation") {
360
+ let lastError;
361
+ for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
362
+ try {
363
+ return await operation();
364
+ }
365
+ catch (error) {
366
+ lastError = error;
367
+ // Don't retry on validation errors or user rejections
368
+ const errorCode = error?.code;
369
+ const errorName = error?.name;
370
+ if (errorCode === SDKErrorCode.VALIDATION_ERROR ||
371
+ errorCode === USER_REJECTION_CODE || // User rejected
372
+ errorName === "SDKError") {
373
+ throw error;
374
+ }
375
+ // Only retry if retries are enabled and we have attempts left
376
+ if (!this.enableRetry || attempt >= this.maxRetries) {
377
+ throw error;
378
+ }
379
+ // Wait before retrying with exponential backoff
380
+ const delay = this.retryDelay * Math.pow(2, attempt - 1);
381
+ await new Promise((resolve) => setTimeout(resolve, delay));
382
+ }
383
+ }
384
+ throw lastError ?? new SDKError(`${operationName} failed after ${this.maxRetries} attempts`, SDKErrorCode.RPC_ERROR);
385
+ }
386
+ /**
387
+ * Extract error message from unknown error type.
388
+ */
389
+ extractErrorMessage(error) {
390
+ if (error instanceof Error) {
391
+ return error.message;
392
+ }
393
+ if (isViemError(error)) {
394
+ return error.shortMessage || error.message;
395
+ }
396
+ if (typeof error === 'string') {
397
+ return error;
398
+ }
399
+ return String(error);
400
+ }
401
+ /**
402
+ * Validate common escrow creation parameters.
403
+ */
404
+ validateCreateEscrowParams(params) {
405
+ const { tokenAddress, buyerAddress, sellerAddress, amount, maturityDays, title } = params;
406
+ if (!tokenAddress || tokenAddress === viem_1.zeroAddress) {
407
+ throw new SDKError("Invalid token address", SDKErrorCode.VALIDATION_ERROR);
408
+ }
409
+ if (!buyerAddress || buyerAddress === viem_1.zeroAddress) {
410
+ throw new SDKError("Invalid buyer address", SDKErrorCode.VALIDATION_ERROR);
411
+ }
412
+ if (!sellerAddress || sellerAddress === viem_1.zeroAddress) {
413
+ throw new SDKError("Invalid seller address", SDKErrorCode.VALIDATION_ERROR);
414
+ }
415
+ // Note: arbiterAddress can be zeroAddress (no arbiter)
416
+ if (amount <= 0n) {
417
+ throw new SDKError("Amount must be greater than 0", SDKErrorCode.VALIDATION_ERROR);
418
+ }
419
+ if (maturityDays < 0n) {
420
+ throw new SDKError("Maturity days cannot be negative", SDKErrorCode.VALIDATION_ERROR);
421
+ }
422
+ if (!title || title.trim().length === 0) {
423
+ throw new SDKError("Title cannot be empty", SDKErrorCode.VALIDATION_ERROR);
424
+ }
425
+ if (title.length > MAX_STRING_LENGTH) {
426
+ throw new SDKError(`Title must be ${MAX_STRING_LENGTH} characters or less`, SDKErrorCode.VALIDATION_ERROR);
427
+ }
428
+ }
429
+ /**
430
+ * Verify caller is the buyer, throw if not.
431
+ */
432
+ verifyBuyer(caller, escrow) {
433
+ if (caller.toLowerCase() !== escrow.buyer.toLowerCase()) {
434
+ throw new SDKError("Only buyer can perform this action", SDKErrorCode.NOT_BUYER);
435
+ }
436
+ }
437
+ /**
438
+ * Verify caller is the seller, throw if not.
439
+ */
440
+ verifySeller(caller, escrow) {
441
+ if (caller.toLowerCase() !== escrow.seller.toLowerCase()) {
442
+ throw new SDKError("Only seller can perform this action", SDKErrorCode.NOT_SELLER);
443
+ }
444
+ }
445
+ /**
446
+ * Verify caller is the arbiter, throw if not.
447
+ */
448
+ verifyArbiter(caller, escrow) {
449
+ if (caller.toLowerCase() !== escrow.arbiter.toLowerCase()) {
450
+ throw new SDKError("Only arbiter can perform this action", SDKErrorCode.NOT_ARBITER);
451
+ }
452
+ }
453
+ /**
454
+ * Verify escrow is in expected state, throw if not.
455
+ */
456
+ verifyState(escrow, expectedState, actionName) {
457
+ if (escrow.state !== expectedState) {
458
+ throw new SDKError(`Cannot ${actionName}: escrow is in state ${escrow.state}, expected ${expectedState}`, SDKErrorCode.INVALID_STATE);
459
+ }
460
+ }
461
+ /**
462
+ * Send transaction directly without simulation.
463
+ * Encodes function data manually and sends with fixed gas limit.
464
+ *
465
+ * @param walletClient - The wallet client to send from
466
+ * @param params - Contract write parameters
467
+ * @returns Transaction hash
468
+ */
469
+ async sendTransactionDirect(walletClient, params) {
470
+ const { address, abi, functionName, args } = params;
471
+ const data = (0, viem_1.encodeFunctionData)({ abi, functionName, args });
472
+ return walletClient.sendTransaction({
473
+ to: address,
474
+ data,
475
+ account: walletClient.account,
476
+ chain: this.chain,
477
+ gas: this.defaultGasLimit,
478
+ });
479
+ }
480
+ /**
481
+ * Detect if error is a simulation failure (not user rejection or validation error).
482
+ *
483
+ * @param error - The error to check
484
+ * @returns True if error is from simulation failure
485
+ */
486
+ isSimulationErrorType(error) {
487
+ if (!isViemError(error)) {
488
+ return false;
489
+ }
490
+ // User rejection is NOT a simulation error
491
+ if (error.code === USER_REJECTION_CODE) {
492
+ return false;
493
+ }
494
+ // Check for simulation-specific error patterns
495
+ return !!(error.message?.includes("simulation") ||
496
+ error.message?.includes("eth_call") ||
497
+ error.message?.includes("execution reverted") ||
498
+ error.cause?.message?.includes("simulation"));
499
+ }
500
+ /**
501
+ * Set a value in the LRU cache with automatic eviction.
502
+ */
503
+ setCacheValue(key, data) {
504
+ // If at capacity, remove oldest entry (first in Map)
505
+ if (this.escrowCache.size >= this.maxCacheSize) {
506
+ const oldestKey = this.escrowCache.keys().next().value;
507
+ if (oldestKey) {
508
+ this.escrowCache.delete(oldestKey);
509
+ }
510
+ }
511
+ // Delete and re-add to move to end (most recently used)
512
+ this.escrowCache.delete(key);
513
+ this.escrowCache.set(key, { data, timestamp: Date.now() });
514
+ }
515
+ /**
516
+ * Get a value from the LRU cache, refreshing its position.
517
+ */
518
+ getCacheValue(key) {
519
+ const cached = this.escrowCache.get(key);
520
+ if (!cached)
521
+ return undefined;
522
+ // Check TTL
523
+ if (Date.now() - cached.timestamp > this.cacheTTL) {
524
+ this.escrowCache.delete(key);
525
+ return undefined;
526
+ }
527
+ // Move to end (most recently used)
528
+ this.escrowCache.delete(key);
529
+ this.escrowCache.set(key, cached);
530
+ return cached.data;
531
+ }
532
+ // ==========================================================================
533
+ // WALLET SIGNATURE HELPERS (EIP-712)
534
+ // ==========================================================================
535
+ /**
536
+ * Get the EIP-712 domain for wallet authorization signatures
537
+ */
538
+ getWalletDomain(walletAddress) {
539
+ return {
540
+ name: "PalindromePayWallet",
541
+ version: "1",
542
+ chainId: this.chain.id,
543
+ verifyingContract: walletAddress,
544
+ };
545
+ }
546
+ /**
547
+ * Get the EIP-712 domain for escrow contract signatures
548
+ */
549
+ getEscrowDomain() {
550
+ return {
551
+ name: "PalindromeCryptoEscrow",
552
+ version: "1",
553
+ chainId: this.chain.id,
554
+ verifyingContract: this.contractAddress,
555
+ };
556
+ }
557
+ /**
558
+ * Sign a wallet authorization for a participant
559
+ * Used for: deposit, confirmDelivery, requestCancel, submitArbiterDecision
560
+ */
561
+ async signWalletAuthorization(walletClient, walletAddress, escrowId) {
562
+ assertWalletClient(walletClient);
563
+ const signature = await walletClient.signTypedData({
564
+ account: walletClient.account,
565
+ domain: this.getWalletDomain(walletAddress),
566
+ types: this.walletAuthorizationTypes,
567
+ primaryType: "WalletAuthorization",
568
+ message: {
569
+ escrowId,
570
+ wallet: walletAddress,
571
+ participant: walletClient.account.address,
572
+ },
573
+ });
574
+ validateSignature(signature, "wallet authorization signature");
575
+ return signature;
576
+ }
577
+ /**
578
+ * Sign a confirm delivery message (for gasless meta-tx)
579
+ */
580
+ async signConfirmDelivery(walletClient, escrowId, deadline, nonce) {
581
+ assertWalletClient(walletClient);
582
+ const deal = await this.getEscrowByIdParsed(escrowId);
583
+ const signature = await walletClient.signTypedData({
584
+ account: walletClient.account,
585
+ domain: this.getEscrowDomain(),
586
+ types: this.confirmDeliveryTypes,
587
+ primaryType: "ConfirmDelivery",
588
+ message: {
589
+ escrowId,
590
+ buyer: deal.buyer,
591
+ seller: deal.seller,
592
+ arbiter: deal.arbiter,
593
+ token: deal.token,
594
+ amount: deal.amount,
595
+ depositTime: deal.depositTime,
596
+ deadline,
597
+ nonce,
598
+ },
599
+ });
600
+ validateSignature(signature, "confirm delivery signature");
601
+ return signature;
602
+ }
603
+ /**
604
+ * Sign a start dispute message (for gasless meta-tx)
605
+ */
606
+ async signStartDispute(walletClient, escrowId, deadline, nonce) {
607
+ assertWalletClient(walletClient);
608
+ const deal = await this.getEscrowByIdParsed(escrowId);
609
+ const signature = await walletClient.signTypedData({
610
+ account: walletClient.account,
611
+ domain: this.getEscrowDomain(),
612
+ types: this.startDisputeTypes,
613
+ primaryType: "StartDispute",
614
+ message: {
615
+ escrowId,
616
+ buyer: deal.buyer,
617
+ seller: deal.seller,
618
+ arbiter: deal.arbiter,
619
+ token: deal.token,
620
+ amount: deal.amount,
621
+ depositTime: deal.depositTime,
622
+ deadline,
623
+ nonce,
624
+ },
625
+ });
626
+ validateSignature(signature, "start dispute signature");
627
+ return signature;
628
+ }
629
+ /**
630
+ * Create a signature deadline (timestamp + minutes)
631
+ */
632
+ async createSignatureDeadline(minutesFromNow = 10) {
633
+ const block = await this.publicClient.getBlock();
634
+ return BigInt(Number(block.timestamp) + minutesFromNow * 60);
635
+ }
636
+ /**
637
+ * Check if signature deadline has expired
638
+ */
639
+ isSignatureDeadlineExpired(deadline, safetySeconds = 5) {
640
+ const now = Math.floor(Date.now() / 1000) + safetySeconds;
641
+ return BigInt(now) > deadline;
642
+ }
643
+ // ==========================================================================
644
+ // ADDRESS PREDICTION (CREATE2)
645
+ // ==========================================================================
646
+ /**
647
+ * Predict the wallet address for a given escrow ID (before creation)
648
+ */
649
+ async predictWalletAddress(escrowId) {
650
+ const salt = (0, viem_1.keccak256)((0, viem_1.pad)((0, viem_1.toBytes)(escrowId), { size: 32 }));
651
+ // Get wallet bytecode hash from contract (cached - immutable value)
652
+ if (!this.walletBytecodeHashCache) {
653
+ this.walletBytecodeHashCache = await this.publicClient.readContract({
654
+ address: this.contractAddress,
655
+ abi: this.abiEscrow,
656
+ functionName: "WALLET_BYTECODE_HASH",
657
+ });
658
+ }
659
+ // Compute CREATE2 address
660
+ const encodedArgs = (0, viem_1.encodeAbiParameters)([{ type: "address" }, { type: "uint256" }], [this.contractAddress, escrowId]);
661
+ // Note: For accurate prediction, need actual bytecode + args hash
662
+ // This is a simplified version - in production, use the contract's computation
663
+ const initCodeHash = (0, viem_1.keccak256)((PalindromePayWallet_json_1.default.bytecode + encodedArgs.slice(2)));
664
+ const raw = (0, viem_1.keccak256)((`0xff${this.contractAddress.slice(2)}${salt.slice(2)}${initCodeHash.slice(2)}`));
665
+ return (0, viem_1.getAddress)(`0x${raw.slice(26)}`);
666
+ }
667
+ // ==========================================================================
668
+ // ESCROW DATA READING
669
+ // ==========================================================================
670
+ /**
671
+ * Get raw escrow data from contract
672
+ */
673
+ async getEscrowById(escrowId) {
674
+ const raw = await (0, actions_1.readContract)(this.publicClient, {
675
+ address: this.contractAddress,
676
+ abi: this.abiEscrow,
677
+ functionName: "getEscrow",
678
+ args: [escrowId],
679
+ });
680
+ return raw;
681
+ }
682
+ /**
683
+ * Get parsed escrow data
684
+ */
685
+ async getEscrowByIdParsed(escrowId) {
686
+ const raw = await this.getEscrowById(escrowId);
687
+ return {
688
+ token: raw.token,
689
+ buyer: raw.buyer,
690
+ seller: raw.seller,
691
+ arbiter: raw.arbiter,
692
+ wallet: raw.wallet,
693
+ amount: raw.amount,
694
+ depositTime: raw.depositTime,
695
+ maturityTime: raw.maturityTime,
696
+ disputeStartTime: raw.disputeStartTime,
697
+ state: Number(raw.state),
698
+ buyerCancelRequested: raw.buyerCancelRequested,
699
+ sellerCancelRequested: raw.sellerCancelRequested,
700
+ tokenDecimals: Number(raw.tokenDecimals),
701
+ sellerWalletSig: raw.sellerWalletSig,
702
+ buyerWalletSig: raw.buyerWalletSig,
703
+ arbiterWalletSig: raw.arbiterWalletSig,
704
+ };
705
+ }
706
+ /**
707
+ * Get next escrow ID
708
+ */
709
+ async getNextEscrowId() {
710
+ return (0, actions_1.readContract)(this.publicClient, {
711
+ address: this.contractAddress,
712
+ abi: this.abiEscrow,
713
+ functionName: "nextEscrowId",
714
+ });
715
+ }
716
+ // ==========================================================================
717
+ // NONCE MANAGEMENT (Contract-Based)
718
+ // ==========================================================================
719
+ /**
720
+ * Get the nonce bitmap from the contract.
721
+ *
722
+ * Each bitmap word contains NONCE_BITMAP_SIZE nonce states. A set bit means the nonce is used.
723
+ *
724
+ * @param escrowId - The escrow ID
725
+ * @param signer - The signer's address
726
+ * @param wordIndex - The word index (nonce / NONCE_BITMAP_SIZE)
727
+ * @returns The bitmap as a bigint
728
+ */
729
+ async getNonceBitmap(escrowId, signer, wordIndex = 0n) {
730
+ return this.publicClient.readContract({
731
+ address: this.contractAddress,
732
+ abi: this.abiEscrow,
733
+ functionName: "getNonceBitmap",
734
+ args: [escrowId, signer, wordIndex],
735
+ });
736
+ }
737
+ /**
738
+ * Check if a specific nonce has been used.
739
+ *
740
+ * @param escrowId - The escrow ID
741
+ * @param signer - The signer's address
742
+ * @param nonce - The nonce to check
743
+ * @returns True if the nonce has been used
744
+ */
745
+ async isNonceUsed(escrowId, signer, nonce) {
746
+ const wordIndex = nonce / 256n;
747
+ const bitIndex = nonce % 256n;
748
+ const bitmap = await this.getNonceBitmap(escrowId, signer, wordIndex);
749
+ return (bitmap & (1n << bitIndex)) !== 0n;
750
+ }
751
+ /**
752
+ * Get the next available nonce for a signer.
753
+ *
754
+ * Queries the contract's nonce bitmap and finds the first unused nonce.
755
+ * This is the recommended way to get a nonce for signed transactions.
756
+ *
757
+ * @param escrowId - The escrow ID
758
+ * @param signer - The signer's address
759
+ * @returns The next available nonce
760
+ * @throws SDKError if nonce space is exhausted (> 25,600 nonces used)
761
+ */
762
+ async getUserNonce(escrowId, signer) {
763
+ // Start with word 0 (nonces 0-255)
764
+ let wordIndex = 0n;
765
+ while (wordIndex < PalindromePaySDK.MAX_NONCE_WORDS) {
766
+ const bitmap = await this.getNonceBitmap(escrowId, signer, wordIndex);
767
+ // If bitmap is all 1s (all NONCE_BITMAP_SIZE nonces used), check next word
768
+ if (bitmap === (1n << 256n) - 1n) {
769
+ wordIndex++;
770
+ continue;
771
+ }
772
+ // Find first zero bit (unused nonce)
773
+ for (let i = 0n; i < 256n; i++) {
774
+ if ((bitmap & (1n << i)) === 0n) {
775
+ return wordIndex * 256n + i;
776
+ }
777
+ }
778
+ // Shouldn't reach here, but just in case
779
+ wordIndex++;
780
+ }
781
+ throw new SDKError("Nonce space exhausted: too many nonces used for this escrow/signer", SDKErrorCode.VALIDATION_ERROR);
782
+ }
783
+ /**
784
+ * Calculate estimated number of bitmap words needed for nonce count.
785
+ * Uses conservative estimate with buffer to minimize round trips.
786
+ *
787
+ * @param count - Number of nonces needed
788
+ * @returns Estimated number of bitmap words to fetch
789
+ */
790
+ getEstimatedWordCount(count) {
791
+ return Math.min(Math.ceil(count / 128) + 1, // Conservative estimate with buffer
792
+ Number(PalindromePaySDK.MAX_NONCE_WORDS));
793
+ }
794
+ /**
795
+ * Detect if chain supports Multicall3 and cache result.
796
+ * Performs a test multicall on first invocation and caches the result.
797
+ *
798
+ * @param escrowId - Escrow ID for test call
799
+ * @param signer - Signer address for test call
800
+ */
801
+ async detectMulticallSupport(escrowId, signer) {
802
+ if (this.multicallSupported !== null) {
803
+ return; // Already detected
804
+ }
805
+ this.log('debug', 'Detecting multicall support...');
806
+ try {
807
+ await (0, actions_1.multicall)(this.publicClient, {
808
+ contracts: [{
809
+ address: this.contractAddress,
810
+ abi: this.abiEscrow,
811
+ functionName: "getNonceBitmap",
812
+ args: [escrowId, signer, 0n],
813
+ }],
814
+ });
815
+ this.multicallSupported = true;
816
+ this.log('info', 'Multicall3 supported on this chain');
817
+ }
818
+ catch (error) {
819
+ const message = this.extractErrorMessage(error);
820
+ if (message.includes("multicall") || message.includes("Chain")) {
821
+ this.multicallSupported = false;
822
+ this.log('info', 'Multicall3 not supported, using sequential calls');
823
+ }
824
+ else {
825
+ throw error; // Different error, re-throw
826
+ }
827
+ }
828
+ }
829
+ /**
830
+ * Fetch nonce bitmaps using either multicall or sequential calls.
831
+ * Automatically uses multicall if supported, otherwise falls back to sequential.
832
+ *
833
+ * @param escrowId - The escrow ID
834
+ * @param signer - The signer's address
835
+ * @param wordCount - Number of bitmap words to fetch
836
+ * @returns Array of bitmap results with status
837
+ */
838
+ async fetchNonceBitmaps(escrowId, signer, wordCount) {
839
+ if (this.multicallSupported) {
840
+ // Use multicall for efficiency
841
+ const results = await (0, actions_1.multicall)(this.publicClient, {
842
+ contracts: Array.from({ length: wordCount }, (_, i) => ({
843
+ address: this.contractAddress,
844
+ abi: this.abiEscrow,
845
+ functionName: "getNonceBitmap",
846
+ args: [escrowId, signer, BigInt(i)],
847
+ })),
848
+ });
849
+ return results;
850
+ }
851
+ else {
852
+ // Sequential fallback for chains without multicall
853
+ return Promise.all(Array.from({ length: wordCount }, async (_, i) => {
854
+ try {
855
+ const result = await this.getNonceBitmap(escrowId, signer, BigInt(i));
856
+ return { status: "success", result };
857
+ }
858
+ catch {
859
+ return { status: "failure" };
860
+ }
861
+ }));
862
+ }
863
+ }
864
+ /**
865
+ * Scan bitmap words for available (unused) nonces.
866
+ * Performs bit-level scanning with early exit when count is reached.
867
+ *
868
+ * @param bitmapResults - Array of bitmap words fetched from contract
869
+ * @param count - Maximum number of nonces to find
870
+ * @returns Array of available nonce values
871
+ */
872
+ scanBitmapsForNonces(bitmapResults, count) {
873
+ const nonces = [];
874
+ for (let wordIdx = 0; wordIdx < bitmapResults.length && nonces.length < count; wordIdx++) {
875
+ const wordResult = bitmapResults[wordIdx];
876
+ if (wordResult.status !== "success" || wordResult.result === undefined) {
877
+ continue; // Skip failed fetches
878
+ }
879
+ const bitmap = wordResult.result;
880
+ const baseNonce = BigInt(wordIdx) * BigInt(NONCE_BITMAP_SIZE);
881
+ // Scan each bit in the word (0 = available, 1 = used)
882
+ for (let bitPos = 0n; bitPos < BigInt(NONCE_BITMAP_SIZE) && nonces.length < count; bitPos++) {
883
+ if ((bitmap & (1n << bitPos)) === 0n) {
884
+ nonces.push(baseNonce + bitPos);
885
+ }
886
+ }
887
+ }
888
+ return nonces;
889
+ }
890
+ /**
891
+ * Get multiple available nonces at once (for batch operations).
892
+ *
893
+ * @param escrowId - The escrow ID
894
+ * @param signer - The signer's address
895
+ * @param count - Number of nonces to retrieve (max NONCE_BITMAP_SIZE)
896
+ * @returns Array of available nonces
897
+ * @throws SDKError if count exceeds limit or nonce space is exhausted
898
+ */
899
+ async getMultipleNonces(escrowId, signer, count) {
900
+ // 1. Input validation
901
+ if (count > NONCE_BITMAP_SIZE) {
902
+ throw new SDKError(`Cannot request more than ${NONCE_BITMAP_SIZE} nonces at once`, SDKErrorCode.VALIDATION_ERROR);
903
+ }
904
+ if (count <= 0) {
905
+ return [];
906
+ }
907
+ // 2. Detect multicall support (cached after first call)
908
+ await this.detectMulticallSupport(escrowId, signer);
909
+ // 3. Fetch bitmap words
910
+ const estimatedWords = this.getEstimatedWordCount(count);
911
+ const bitmapResults = await this.fetchNonceBitmaps(escrowId, signer, estimatedWords);
912
+ // 4. Scan bitmaps for available nonces
913
+ const nonces = this.scanBitmapsForNonces(bitmapResults, count);
914
+ // 5. Verify we found enough nonces
915
+ if (nonces.length < count) {
916
+ throw new SDKError(`Could only find ${nonces.length} available nonces out of ${count} requested`, SDKErrorCode.VALIDATION_ERROR);
917
+ }
918
+ return nonces;
919
+ }
920
+ /**
921
+ * @deprecated No longer needed - nonces are tracked by the contract
922
+ */
923
+ resetNonceTracker() {
924
+ // No-op: Contract tracks nonces now
925
+ }
926
+ /**
927
+ * Get dispute submission status
928
+ */
929
+ async getDisputeSubmissionStatus(escrowId) {
930
+ const status = await this.publicClient.readContract({
931
+ address: this.contractAddress,
932
+ abi: this.abiEscrow,
933
+ functionName: "disputeStatus",
934
+ args: [escrowId],
935
+ });
936
+ const buyer = (status & 1n) !== 0n;
937
+ const seller = (status & 2n) !== 0n;
938
+ const arbiter = (status & 4n) !== 0n;
939
+ return { buyer, seller, arbiter, allSubmitted: buyer && seller && arbiter };
940
+ }
941
+ // ==========================================================================
942
+ // TOKEN UTILITIES
943
+ // ==========================================================================
944
+ async getTokenDecimals(tokenAddress) {
945
+ if (this.tokenDecimalsCache.has(tokenAddress)) {
946
+ return this.tokenDecimalsCache.get(tokenAddress);
947
+ }
948
+ const decimals = await this.publicClient.readContract({
949
+ address: tokenAddress,
950
+ abi: this.abiERC20,
951
+ functionName: "decimals",
952
+ });
953
+ this.tokenDecimalsCache.set(tokenAddress, decimals);
954
+ return decimals;
955
+ }
956
+ async getTokenBalance(account, tokenAddress) {
957
+ return this.publicClient.readContract({
958
+ address: tokenAddress,
959
+ abi: this.abiERC20,
960
+ functionName: "balanceOf",
961
+ args: [account],
962
+ });
963
+ }
964
+ async getTokenAllowance(owner, spender, tokenAddress) {
965
+ return this.publicClient.readContract({
966
+ address: tokenAddress,
967
+ abi: this.abiERC20,
968
+ functionName: "allowance",
969
+ args: [owner, spender],
970
+ });
971
+ }
972
+ formatTokenAmount(amount, decimals) {
973
+ const divisor = 10n ** BigInt(decimals);
974
+ const integerPart = amount / divisor;
975
+ const fractionalPart = (amount % divisor).toString().padStart(decimals, "0");
976
+ return `${integerPart}.${fractionalPart}`;
977
+ }
978
+ /**
979
+ * Approve token spending if needed
980
+ */
981
+ async approveTokenIfNeeded(walletClient, token, spender, amount) {
982
+ assertWalletClient(walletClient);
983
+ const currentAllowance = await this.getTokenAllowance(walletClient.account.address, spender, token);
984
+ if (currentAllowance >= amount)
985
+ return null;
986
+ const hash = await this.resilientWriteContract(walletClient, {
987
+ address: token,
988
+ abi: this.abiERC20,
989
+ functionName: "approve",
990
+ args: [spender, amount],
991
+ });
992
+ await this.waitForReceipt(hash);
993
+ return hash;
994
+ }
995
+ // ==========================================================================
996
+ // ESCROW CREATION
997
+ // ==========================================================================
998
+ /**
999
+ * Create a new escrow as the seller
1000
+ *
1001
+ * This function creates a new escrow where the caller (seller) is offering goods/services
1002
+ * to a buyer. The escrow starts in AWAITING_PAYMENT state until the buyer deposits funds.
1003
+ *
1004
+ * The seller's wallet authorization signature is automatically generated and attached,
1005
+ * which will be used later for 2-of-3 multisig withdrawals from the escrow wallet.
1006
+ *
1007
+ * @param walletClient - The seller's wallet client (must have account connected)
1008
+ * @param params - Escrow creation parameters
1009
+ * @param params.token - ERC20 token address for payment
1010
+ * @param params.buyer - Buyer's wallet address
1011
+ * @param params.amount - Payment amount in token's smallest unit (e.g., wei for 18 decimals)
1012
+ * @param params.maturityTimeDays - Optional days until maturity (default: 1, min: 1, max: 3650)
1013
+ * @param params.arbiter - Optional arbiter address for dispute resolution
1014
+ * @param params.title - Escrow title/description (1-500 characters, supports encrypted hashes)
1015
+ * @param params.ipfsHash - Optional IPFS hash for additional details
1016
+ * @returns Object containing escrowId, transaction hash, and wallet address
1017
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
1018
+ * @throws {SDKError} VALIDATION_ERROR - If parameters are invalid
1019
+ * @throws {SDKError} TRANSACTION_FAILED - If the transaction fails
1020
+ */
1021
+ async createEscrow(walletClient, params) {
1022
+ assertWalletClient(walletClient);
1023
+ // Validate and normalize addresses
1024
+ const token = validateAddress(params.token, "token");
1025
+ const buyer = validateAddress(params.buyer, "buyer");
1026
+ const arbiter = params.arbiter
1027
+ ? validateAddress(params.arbiter, "arbiter")
1028
+ : viem_1.zeroAddress;
1029
+ const sellerAddress = walletClient.account.address;
1030
+ const maturityDays = params.maturityTimeDays ?? 1n;
1031
+ // Validate using helper
1032
+ this.validateCreateEscrowParams({
1033
+ tokenAddress: token,
1034
+ buyerAddress: buyer,
1035
+ sellerAddress,
1036
+ arbiterAddress: arbiter,
1037
+ amount: params.amount,
1038
+ maturityDays,
1039
+ title: params.title,
1040
+ });
1041
+ // Validate arbiter is not buyer or seller
1042
+ if (!isZeroAddress(arbiter)) {
1043
+ if ((0, viem_1.getAddress)(arbiter) === (0, viem_1.getAddress)(buyer)) {
1044
+ throw new SDKError("Arbiter cannot be the buyer", SDKErrorCode.VALIDATION_ERROR);
1045
+ }
1046
+ if ((0, viem_1.getAddress)(arbiter) === (0, viem_1.getAddress)(sellerAddress)) {
1047
+ throw new SDKError("Arbiter cannot be the seller", SDKErrorCode.VALIDATION_ERROR);
1048
+ }
1049
+ }
1050
+ const ipfsHash = params.ipfsHash ?? "";
1051
+ // Predict next escrow ID and wallet address
1052
+ const nextId = await this.getNextEscrowId();
1053
+ const predictedWallet = await this.predictWalletAddress(nextId);
1054
+ // Sign wallet authorization
1055
+ const sellerWalletSig = await this.signWalletAuthorization(walletClient, predictedWallet, nextId);
1056
+ // Create escrow
1057
+ const hash = await this.resilientWriteContract(walletClient, {
1058
+ address: this.contractAddress,
1059
+ abi: this.abiEscrow,
1060
+ functionName: "createEscrow",
1061
+ args: [
1062
+ token,
1063
+ buyer,
1064
+ params.amount,
1065
+ maturityDays,
1066
+ arbiter,
1067
+ params.title,
1068
+ ipfsHash,
1069
+ sellerWalletSig,
1070
+ ],
1071
+ });
1072
+ const receipt = await this.waitForReceipt(hash);
1073
+ if (receipt.status !== "success") {
1074
+ throw new SDKError("Transaction failed", SDKErrorCode.TRANSACTION_FAILED, { txHash: hash });
1075
+ }
1076
+ // Parse event to get escrow ID
1077
+ const events = (0, viem_1.parseEventLogs)({
1078
+ abi: this.abiEscrow,
1079
+ eventName: "EscrowCreated",
1080
+ logs: receipt.logs,
1081
+ });
1082
+ const escrowId = events[0]?.args?.escrowId ?? nextId;
1083
+ const deal = await this.getEscrowByIdParsed(escrowId);
1084
+ return { escrowId, txHash: hash, walletAddress: deal.wallet };
1085
+ }
1086
+ /**
1087
+ * Create a new escrow and deposit funds as the buyer (single transaction)
1088
+ *
1089
+ * This function creates a new escrow and immediately deposits the payment in one transaction.
1090
+ * The escrow starts in AWAITING_DELIVERY state. The seller must call `acceptEscrow` to
1091
+ * provide their wallet signature before funds can be released.
1092
+ *
1093
+ * Token approval is automatically handled if needed.
1094
+ *
1095
+ * @param walletClient - The buyer's wallet client (must have account connected)
1096
+ * @param params - Escrow creation parameters
1097
+ * @param params.token - ERC20 token address for payment
1098
+ * @param params.seller - Seller's wallet address
1099
+ * @param params.amount - Payment amount in token's smallest unit (e.g., wei for 18 decimals)
1100
+ * @param params.maturityTimeDays - Optional days until maturity (default: 1, min: 1, max: 3650)
1101
+ * @param params.arbiter - Optional arbiter address for dispute resolution
1102
+ * @param params.title - Escrow title/description (1-500 characters, supports encrypted hashes)
1103
+ * @param params.ipfsHash - Optional IPFS hash for additional details
1104
+ * @returns Object containing escrowId, transaction hash, and wallet address
1105
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
1106
+ * @throws {SDKError} VALIDATION_ERROR - If parameters are invalid
1107
+ * @throws {SDKError} INSUFFICIENT_BALANCE - If buyer has insufficient token balance
1108
+ * @throws {SDKError} TRANSACTION_FAILED - If the transaction fails
1109
+ */
1110
+ async createEscrowAndDeposit(walletClient, params) {
1111
+ assertWalletClient(walletClient);
1112
+ // Validate and normalize addresses
1113
+ const token = validateAddress(params.token, "token");
1114
+ const seller = validateAddress(params.seller, "seller");
1115
+ const arbiter = params.arbiter
1116
+ ? validateAddress(params.arbiter, "arbiter")
1117
+ : viem_1.zeroAddress;
1118
+ const buyerAddress = walletClient.account.address;
1119
+ const maturityDays = params.maturityTimeDays ?? 1n;
1120
+ // Validate using helper
1121
+ this.validateCreateEscrowParams({
1122
+ tokenAddress: token,
1123
+ buyerAddress,
1124
+ sellerAddress: seller,
1125
+ arbiterAddress: arbiter,
1126
+ amount: params.amount,
1127
+ maturityDays,
1128
+ title: params.title,
1129
+ });
1130
+ // Validate arbiter is not buyer or seller
1131
+ if (!isZeroAddress(arbiter)) {
1132
+ if ((0, viem_1.getAddress)(arbiter) === (0, viem_1.getAddress)(seller)) {
1133
+ throw new SDKError("Arbiter cannot be the seller", SDKErrorCode.VALIDATION_ERROR);
1134
+ }
1135
+ if ((0, viem_1.getAddress)(arbiter) === (0, viem_1.getAddress)(buyerAddress)) {
1136
+ throw new SDKError("Arbiter cannot be the buyer", SDKErrorCode.VALIDATION_ERROR);
1137
+ }
1138
+ }
1139
+ const ipfsHash = params.ipfsHash ?? "";
1140
+ // Approve token spending
1141
+ await this.approveTokenIfNeeded(walletClient, token, this.contractAddress, params.amount);
1142
+ // Predict next escrow ID and wallet address
1143
+ const nextId = await this.getNextEscrowId();
1144
+ const predictedWallet = await this.predictWalletAddress(nextId);
1145
+ // Sign wallet authorization
1146
+ const buyerWalletSig = await this.signWalletAuthorization(walletClient, predictedWallet, nextId);
1147
+ // Create escrow and deposit
1148
+ const hash = await this.resilientWriteContract(walletClient, {
1149
+ address: this.contractAddress,
1150
+ abi: this.abiEscrow,
1151
+ functionName: "createEscrowAndDeposit",
1152
+ args: [
1153
+ token,
1154
+ seller,
1155
+ params.amount,
1156
+ maturityDays,
1157
+ arbiter,
1158
+ params.title,
1159
+ ipfsHash,
1160
+ buyerWalletSig,
1161
+ ],
1162
+ });
1163
+ const receipt = await this.waitForReceipt(hash);
1164
+ if (receipt.status !== "success") {
1165
+ throw new SDKError("Transaction failed", SDKErrorCode.TRANSACTION_FAILED, { txHash: hash });
1166
+ }
1167
+ // Parse event to get escrow ID
1168
+ const events = (0, viem_1.parseEventLogs)({
1169
+ abi: this.abiEscrow,
1170
+ eventName: "EscrowCreated",
1171
+ logs: receipt.logs,
1172
+ });
1173
+ const escrowId = events[0]?.args?.escrowId ?? nextId;
1174
+ const deal = await this.getEscrowByIdParsed(escrowId);
1175
+ return { escrowId, txHash: hash, walletAddress: deal.wallet };
1176
+ }
1177
+ // ==========================================================================
1178
+ // DEPOSIT
1179
+ // ==========================================================================
1180
+ /**
1181
+ * Deposit funds into an existing escrow as the buyer
1182
+ *
1183
+ * This function is used when the seller created the escrow via `createEscrow`.
1184
+ * The buyer deposits the required payment amount, transitioning the escrow from
1185
+ * AWAITING_PAYMENT to AWAITING_DELIVERY state.
1186
+ *
1187
+ * Token approval is automatically handled if needed.
1188
+ * The buyer's wallet authorization signature is automatically generated.
1189
+ *
1190
+ * @param walletClient - The buyer's wallet client (must have account connected)
1191
+ * @param escrowId - The escrow ID to deposit into
1192
+ * @returns Transaction hash
1193
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
1194
+ * @throws {SDKError} NOT_BUYER - If caller is not the designated buyer
1195
+ * @throws {SDKError} INVALID_STATE - If escrow is not in AWAITING_PAYMENT state
1196
+ * @throws {SDKError} INSUFFICIENT_BALANCE - If buyer has insufficient token balance
1197
+ */
1198
+ async deposit(walletClient, escrowId) {
1199
+ assertWalletClient(walletClient);
1200
+ const deal = await this.getEscrowByIdParsed(escrowId);
1201
+ // Verify caller and state using helpers
1202
+ this.verifyBuyer(walletClient.account.address, deal);
1203
+ this.verifyState(deal, EscrowState.AWAITING_PAYMENT, "deposit");
1204
+ // Approve token spending
1205
+ await this.approveTokenIfNeeded(walletClient, deal.token, this.contractAddress, deal.amount);
1206
+ // Sign wallet authorization
1207
+ const buyerWalletSig = await this.signWalletAuthorization(walletClient, deal.wallet, escrowId);
1208
+ // Deposit
1209
+ const hash = await this.resilientWriteContract(walletClient, {
1210
+ address: this.contractAddress,
1211
+ abi: this.abiEscrow,
1212
+ functionName: "deposit",
1213
+ args: [escrowId, buyerWalletSig],
1214
+ });
1215
+ await this.waitForReceipt(hash);
1216
+ return hash;
1217
+ }
1218
+ // ==========================================================================
1219
+ // ACCEPT ESCROW (for buyer-created escrows)
1220
+ // ==========================================================================
1221
+ /**
1222
+ * Accept an escrow as the seller (for buyer-created escrows)
1223
+ *
1224
+ * This function is required when the buyer created the escrow via `createEscrowAndDeposit`.
1225
+ * The seller must accept to provide their wallet authorization signature, which is
1226
+ * required for the 2-of-3 multisig withdrawal mechanism.
1227
+ *
1228
+ * Without accepting, the seller cannot receive funds even if the buyer confirms delivery.
1229
+ *
1230
+ * @param walletClient - The seller's wallet client (must have account connected)
1231
+ * @param escrowId - The escrow ID to accept
1232
+ * @returns Transaction hash
1233
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
1234
+ * @throws {SDKError} NOT_SELLER - If caller is not the designated seller
1235
+ * @throws {SDKError} INVALID_STATE - If escrow is not in AWAITING_DELIVERY state
1236
+ * @throws {SDKError} ALREADY_ACCEPTED - If escrow was already accepted
1237
+ */
1238
+ async acceptEscrow(walletClient, escrowId) {
1239
+ assertWalletClient(walletClient);
1240
+ const deal = await this.getEscrowByIdParsed(escrowId);
1241
+ // Verify caller and state using helpers
1242
+ this.verifySeller(walletClient.account.address, deal);
1243
+ this.verifyState(deal, EscrowState.AWAITING_DELIVERY, "accept");
1244
+ // Check if already accepted (seller sig already exists)
1245
+ if (deal.sellerWalletSig && deal.sellerWalletSig !== "0x") {
1246
+ throw new SDKError("Escrow already accepted", SDKErrorCode.ALREADY_ACCEPTED);
1247
+ }
1248
+ // Sign wallet authorization
1249
+ const sellerWalletSig = await this.signWalletAuthorization(walletClient, deal.wallet, escrowId);
1250
+ // Accept escrow
1251
+ const hash = await this.resilientWriteContract(walletClient, {
1252
+ address: this.contractAddress,
1253
+ abi: this.abiEscrow,
1254
+ functionName: "acceptEscrow",
1255
+ args: [escrowId, sellerWalletSig],
1256
+ });
1257
+ await this.waitForReceipt(hash);
1258
+ return hash;
1259
+ }
1260
+ // ==========================================================================
1261
+ // CONFIRM DELIVERY
1262
+ // ==========================================================================
1263
+ /**
1264
+ * Confirm delivery and release funds to the seller
1265
+ *
1266
+ * This function is called by the buyer after receiving the goods/services.
1267
+ * It transitions the escrow to COMPLETE state and authorizes payment release to the seller.
1268
+ *
1269
+ * After confirmation, anyone can call `withdraw` on the escrow wallet to execute
1270
+ * the actual token transfer (requires 2-of-3 signatures: buyer + seller).
1271
+ *
1272
+ * A 1% fee is deducted from the payment amount.
1273
+ *
1274
+ * @param walletClient - The buyer's wallet client (must have account connected)
1275
+ * @param escrowId - The escrow ID to confirm
1276
+ * @returns Transaction hash
1277
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
1278
+ * @throws {SDKError} NOT_BUYER - If caller is not the designated buyer
1279
+ * @throws {SDKError} INVALID_STATE - If escrow is not in AWAITING_DELIVERY state
1280
+ */
1281
+ async confirmDelivery(walletClient, escrowId) {
1282
+ assertWalletClient(walletClient);
1283
+ const deal = await this.getEscrowByIdParsed(escrowId);
1284
+ // Verify caller and state using helpers
1285
+ this.verifyBuyer(walletClient.account.address, deal);
1286
+ this.verifyState(deal, EscrowState.AWAITING_DELIVERY, "confirm delivery");
1287
+ // Sign wallet authorization
1288
+ const buyerWalletSig = await this.signWalletAuthorization(walletClient, deal.wallet, escrowId);
1289
+ // Confirm delivery
1290
+ const hash = await this.resilientWriteContract(walletClient, {
1291
+ address: this.contractAddress,
1292
+ abi: this.abiEscrow,
1293
+ functionName: "confirmDelivery",
1294
+ args: [escrowId, buyerWalletSig],
1295
+ });
1296
+ await this.waitForReceipt(hash);
1297
+ return hash;
1298
+ }
1299
+ /**
1300
+ * Confirm delivery via meta-transaction (gasless for buyer)
1301
+ *
1302
+ * This function allows a relayer to submit the confirm delivery transaction on behalf
1303
+ * of the buyer. The buyer signs the confirmation off-chain, and the relayer pays the gas.
1304
+ *
1305
+ * Use `prepareConfirmDeliverySigned` to generate the required signatures.
1306
+ *
1307
+ * @param walletClient - The relayer's wallet client (pays gas)
1308
+ * @param escrowId - The escrow ID to confirm
1309
+ * @param coordSignature - Buyer's EIP-712 signature for the confirmation
1310
+ * @param deadline - Signature expiration timestamp (must be within 24 hours)
1311
+ * @param nonce - Buyer's nonce for replay protection
1312
+ * @param buyerWalletSig - Buyer's wallet authorization signature
1313
+ * @returns Transaction hash
1314
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
1315
+ * @throws {SDKError} SIGNATURE_EXPIRED - If deadline has passed
1316
+ */
1317
+ async confirmDeliverySigned(walletClient, escrowId, coordSignature, deadline, nonce, buyerWalletSig) {
1318
+ assertWalletClient(walletClient);
1319
+ if (this.isSignatureDeadlineExpired(deadline)) {
1320
+ throw new SDKError("Signature deadline expired", SDKErrorCode.SIGNATURE_EXPIRED);
1321
+ }
1322
+ // Anyone can submit (typically relayer)
1323
+ const hash = await this.resilientWriteContract(walletClient, {
1324
+ address: this.contractAddress,
1325
+ abi: this.abiEscrow,
1326
+ functionName: "confirmDeliverySigned",
1327
+ args: [escrowId, coordSignature, deadline, nonce, buyerWalletSig],
1328
+ });
1329
+ await this.waitForReceipt(hash);
1330
+ return hash;
1331
+ }
1332
+ /**
1333
+ * Prepare signatures for gasless confirm delivery
1334
+ *
1335
+ * This helper function generates all the signatures needed for a gasless confirm delivery.
1336
+ * The buyer signs off-chain, and the resulting data can be sent to a relayer who will
1337
+ * submit the transaction and pay the gas.
1338
+ *
1339
+ * The deadline is set to 60 minutes from the current block timestamp.
1340
+ *
1341
+ * @param buyerWalletClient - The buyer's wallet client (must have account connected)
1342
+ * @param escrowId - The escrow ID to confirm
1343
+ * @returns Object containing coordSignature, buyerWalletSig, deadline, and nonce
1344
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
1345
+ * @throws {SDKError} NOT_BUYER - If caller is not the designated buyer
1346
+ */
1347
+ async prepareConfirmDeliverySigned(buyerWalletClient, escrowId) {
1348
+ assertWalletClient(buyerWalletClient);
1349
+ const deal = await this.getEscrowByIdParsed(escrowId);
1350
+ // Verify caller using helper
1351
+ this.verifyBuyer(buyerWalletClient.account.address, deal);
1352
+ // Parallelize deadline and nonce fetching
1353
+ const [deadline, nonce] = await Promise.all([
1354
+ this.createSignatureDeadline(60), // 60 minutes
1355
+ this.getUserNonce(escrowId, buyerWalletClient.account.address),
1356
+ ]);
1357
+ // Sign coordinator message and wallet authorization in parallel
1358
+ const [coordSignature, buyerWalletSig] = await Promise.all([
1359
+ this.signConfirmDelivery(buyerWalletClient, escrowId, deadline, nonce),
1360
+ this.signWalletAuthorization(buyerWalletClient, deal.wallet, escrowId),
1361
+ ]);
1362
+ return { coordSignature, buyerWalletSig, deadline, nonce };
1363
+ }
1364
+ // ==========================================================================
1365
+ // CANCEL FLOWS
1366
+ // ==========================================================================
1367
+ /**
1368
+ * Request cancellation of an escrow
1369
+ *
1370
+ * This function allows either the buyer or seller to request cancellation.
1371
+ * Both parties must call this function for a mutual cancellation to occur.
1372
+ *
1373
+ * - If only one party requests: The request is recorded, awaiting the other party
1374
+ * - If both parties request: The escrow is automatically canceled and funds returned to buyer
1375
+ *
1376
+ * Use `getCancelRequestStatus` to check if the other party has already requested.
1377
+ *
1378
+ * @param walletClient - The buyer's or seller's wallet client
1379
+ * @param escrowId - The escrow ID to cancel
1380
+ * @returns Transaction hash
1381
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
1382
+ * @throws {SDKError} INVALID_ROLE - If caller is not buyer or seller
1383
+ * @throws {SDKError} INVALID_STATE - If escrow is not in AWAITING_DELIVERY state
1384
+ */
1385
+ async requestCancel(walletClient, escrowId) {
1386
+ assertWalletClient(walletClient);
1387
+ const deal = await this.getEscrowByIdParsed(escrowId);
1388
+ // Verify caller is buyer or seller
1389
+ const isBuyer = addressEquals(walletClient.account.address, deal.buyer);
1390
+ const isSeller = addressEquals(walletClient.account.address, deal.seller);
1391
+ if (!isBuyer && !isSeller) {
1392
+ throw new SDKError("Only buyer or seller can request cancel", SDKErrorCode.INVALID_ROLE);
1393
+ }
1394
+ // Verify state
1395
+ if (deal.state !== EscrowState.AWAITING_DELIVERY) {
1396
+ throw new SDKError(`Invalid state: ${this.STATE_NAMES[deal.state]}. Expected: AWAITING_DELIVERY`, SDKErrorCode.INVALID_STATE);
1397
+ }
1398
+ // Sign wallet authorization
1399
+ const walletSig = await this.signWalletAuthorization(walletClient, deal.wallet, escrowId);
1400
+ // Request cancel
1401
+ const hash = await this.resilientWriteContract(walletClient, {
1402
+ address: this.contractAddress,
1403
+ abi: this.abiEscrow,
1404
+ functionName: "requestCancel",
1405
+ args: [escrowId, walletSig],
1406
+ });
1407
+ await this.waitForReceipt(hash);
1408
+ return hash;
1409
+ }
1410
+ /**
1411
+ * Cancel escrow by timeout (unilateral cancellation by buyer)
1412
+ *
1413
+ * This function allows the buyer to cancel the escrow unilaterally if:
1414
+ * - The buyer has already requested cancellation via `requestCancel`
1415
+ * - The maturity time has passed
1416
+ * - The seller has not agreed to mutual cancellation
1417
+ * - No dispute is active
1418
+ * - An arbiter is assigned to the escrow
1419
+ *
1420
+ * Funds are returned to the buyer without any fee deduction.
1421
+ *
1422
+ * @param walletClient - The buyer's wallet client (must have account connected)
1423
+ * @param escrowId - The escrow ID to cancel
1424
+ * @returns Transaction hash
1425
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
1426
+ * @throws {SDKError} NOT_BUYER - If caller is not the designated buyer
1427
+ * @throws {SDKError} INVALID_STATE - If conditions for timeout cancel are not met
1428
+ */
1429
+ async cancelByTimeout(walletClient, escrowId) {
1430
+ assertWalletClient(walletClient);
1431
+ const deal = await this.getEscrowByIdParsed(escrowId);
1432
+ // Verify caller using helper
1433
+ this.verifyBuyer(walletClient.account.address, deal);
1434
+ // Cancel by timeout
1435
+ const hash = await this.resilientWriteContract(walletClient, {
1436
+ address: this.contractAddress,
1437
+ abi: this.abiEscrow,
1438
+ functionName: "cancelByTimeout",
1439
+ args: [escrowId],
1440
+ });
1441
+ await this.waitForReceipt(hash);
1442
+ return hash;
1443
+ }
1444
+ /**
1445
+ * Auto-release funds to seller after maturity time
1446
+ *
1447
+ * This function allows the seller to claim funds unilaterally after the maturity time
1448
+ * has passed. This protects sellers when buyers become unresponsive after receiving
1449
+ * goods/services.
1450
+ *
1451
+ * Requirements:
1452
+ * - Escrow must be in AWAITING_DELIVERY state
1453
+ * - No dispute has been started
1454
+ * - Buyer has not requested cancellation
1455
+ * - maturityTime has passed
1456
+ * - Seller has already provided wallet signature (via createEscrow or acceptEscrow)
1457
+ *
1458
+ * A 1% fee is deducted from the payment amount.
1459
+ *
1460
+ * @param walletClient - The seller's wallet client (must have account connected)
1461
+ * @param escrowId - The escrow ID to auto-release
1462
+ * @returns Transaction hash
1463
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
1464
+ * @throws {SDKError} NOT_SELLER - If caller is not the designated seller
1465
+ * @throws {SDKError} INVALID_STATE - If escrow is not in AWAITING_DELIVERY state
1466
+ * @throws {SDKError} INVALID_STATE - If dispute is active or buyer requested cancel
1467
+ * @throws {SDKError} VALIDATION_ERROR - If seller wallet signature is missing
1468
+ */
1469
+ async autoRelease(walletClient, escrowId) {
1470
+ assertWalletClient(walletClient);
1471
+ const deal = await this.getEscrowByIdParsed(escrowId);
1472
+ // Verify caller and state using helpers
1473
+ this.verifySeller(walletClient.account.address, deal);
1474
+ this.verifyState(deal, EscrowState.AWAITING_DELIVERY, "auto-release");
1475
+ // Verify no dispute is active
1476
+ if (deal.disputeStartTime > 0n) {
1477
+ throw new SDKError("Cannot auto-release: dispute is active", SDKErrorCode.INVALID_STATE);
1478
+ }
1479
+ // Verify buyer hasn't requested cancellation
1480
+ if (deal.buyerCancelRequested) {
1481
+ throw new SDKError("Cannot auto-release: buyer has requested cancellation", SDKErrorCode.INVALID_STATE);
1482
+ }
1483
+ // Verify deposit exists
1484
+ if (deal.depositTime === 0n) {
1485
+ throw new SDKError("Cannot auto-release: no deposit made", SDKErrorCode.INVALID_STATE);
1486
+ }
1487
+ // Verify seller signature exists
1488
+ if (!deal.sellerWalletSig || deal.sellerWalletSig === "0x" || deal.sellerWalletSig.length !== 132) {
1489
+ throw new SDKError("Cannot auto-release: seller wallet signature missing. Call acceptEscrow first if buyer created the escrow.", SDKErrorCode.VALIDATION_ERROR);
1490
+ }
1491
+ // Auto-release
1492
+ const hash = await this.resilientWriteContract(walletClient, {
1493
+ address: this.contractAddress,
1494
+ abi: this.abiEscrow,
1495
+ functionName: "autoRelease",
1496
+ args: [escrowId],
1497
+ });
1498
+ await this.waitForReceipt(hash);
1499
+ return hash;
1500
+ }
1501
+ // ==========================================================================
1502
+ // DISPUTE FLOWS
1503
+ // ==========================================================================
1504
+ /**
1505
+ * Start a dispute for an escrow
1506
+ *
1507
+ * This function initiates a dispute when there's a disagreement between buyer and seller.
1508
+ * Once started, the escrow enters DISPUTED state and requires arbiter resolution.
1509
+ *
1510
+ * Either the buyer or seller can start a dispute. An arbiter must be assigned to the
1511
+ * escrow for disputes to be possible.
1512
+ *
1513
+ * After starting a dispute:
1514
+ * 1. Both parties should submit evidence via `submitDisputeMessage`
1515
+ * 2. The arbiter reviews evidence and makes a decision via `submitArbiterDecision`
1516
+ * 3. The arbiter can rule in favor of buyer (REFUNDED) or seller (COMPLETE)
1517
+ *
1518
+ * @param walletClient - The buyer's or seller's wallet client
1519
+ * @param escrowId - The escrow ID to dispute
1520
+ * @returns Transaction hash
1521
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
1522
+ * @throws {SDKError} INVALID_STATE - If escrow is not in AWAITING_DELIVERY state
1523
+ */
1524
+ async startDispute(walletClient, escrowId) {
1525
+ assertWalletClient(walletClient);
1526
+ // Start dispute
1527
+ const hash = await this.resilientWriteContract(walletClient, {
1528
+ address: this.contractAddress,
1529
+ abi: this.abiEscrow,
1530
+ functionName: "startDispute",
1531
+ args: [escrowId],
1532
+ });
1533
+ await this.waitForReceipt(hash);
1534
+ return hash;
1535
+ }
1536
+ /**
1537
+ * Start a dispute via meta-transaction (gasless for buyer/seller)
1538
+ *
1539
+ * This function allows a relayer to submit the start dispute transaction on behalf
1540
+ * of the buyer or seller. The initiator signs off-chain, and the relayer pays the gas.
1541
+ *
1542
+ * Use `signStartDispute` to generate the required signature.
1543
+ *
1544
+ * @param walletClient - The relayer's wallet client (pays gas)
1545
+ * @param escrowId - The escrow ID to dispute
1546
+ * @param signature - Buyer's or seller's EIP-712 signature
1547
+ * @param deadline - Signature expiration timestamp (must be within 24 hours)
1548
+ * @param nonce - Signer's nonce for replay protection
1549
+ * @returns Transaction hash
1550
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
1551
+ * @throws {SDKError} SIGNATURE_EXPIRED - If deadline has passed
1552
+ */
1553
+ async startDisputeSigned(walletClient, escrowId, signature, deadline, nonce) {
1554
+ assertWalletClient(walletClient);
1555
+ if (this.isSignatureDeadlineExpired(deadline)) {
1556
+ throw new SDKError("Signature deadline expired", SDKErrorCode.SIGNATURE_EXPIRED);
1557
+ }
1558
+ // Anyone can submit (typically relayer)
1559
+ const hash = await this.resilientWriteContract(walletClient, {
1560
+ address: this.contractAddress,
1561
+ abi: this.abiEscrow,
1562
+ functionName: "startDisputeSigned",
1563
+ args: [escrowId, signature, deadline, nonce],
1564
+ });
1565
+ await this.waitForReceipt(hash);
1566
+ return hash;
1567
+ }
1568
+ /**
1569
+ * Submit evidence for a dispute
1570
+ *
1571
+ * This function allows the buyer or seller to submit evidence supporting their case.
1572
+ * Each party can only submit evidence once. Evidence is stored on IPFS and the hash
1573
+ * is recorded on-chain.
1574
+ *
1575
+ * The arbiter will review submitted evidence before making a decision. Both parties
1576
+ * should submit evidence for a fair resolution. After 30 days, the arbiter can make
1577
+ * a decision even without complete evidence.
1578
+ *
1579
+ * @param walletClient - The buyer's or seller's wallet client
1580
+ * @param escrowId - The escrow ID
1581
+ * @param role - The caller's role (Role.Buyer or Role.Seller)
1582
+ * @param ipfsHash - IPFS hash containing the evidence (max 500 characters)
1583
+ * @returns Transaction hash
1584
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
1585
+ * @throws {SDKError} EVIDENCE_ALREADY_SUBMITTED - If caller already submitted evidence
1586
+ * @throws {SDKError} INVALID_STATE - If escrow is not in DISPUTED state
1587
+ */
1588
+ async submitDisputeMessage(walletClient, escrowId, role, ipfsHash) {
1589
+ assertWalletClient(walletClient);
1590
+ // Check if already submitted
1591
+ const hasSubmitted = await this.hasSubmittedEvidence(escrowId, role);
1592
+ if (hasSubmitted) {
1593
+ throw new SDKError(`${role === Role.Buyer ? "Buyer" : "Seller"} has already submitted evidence`, SDKErrorCode.EVIDENCE_ALREADY_SUBMITTED);
1594
+ }
1595
+ // Submit dispute message
1596
+ const hash = await this.resilientWriteContract(walletClient, {
1597
+ address: this.contractAddress,
1598
+ abi: this.abiEscrow,
1599
+ functionName: "submitDisputeMessage",
1600
+ args: [escrowId, role, ipfsHash],
1601
+ });
1602
+ await this.waitForReceipt(hash);
1603
+ return hash;
1604
+ }
1605
+ /**
1606
+ * Submit arbiter's decision to resolve a dispute
1607
+ *
1608
+ * This function is called by the designated arbiter to resolve a dispute.
1609
+ * The arbiter reviews evidence submitted by both parties and makes a final decision.
1610
+ *
1611
+ * The arbiter can rule:
1612
+ * - DisputeResolution.Complete (3): Funds go to seller (with 1% fee)
1613
+ * - DisputeResolution.Refunded (4): Funds go to buyer (no fee)
1614
+ *
1615
+ * Requirements:
1616
+ * - Both parties must have submitted evidence, OR
1617
+ * - 30 days + 1 hour timeout has passed since dispute started
1618
+ *
1619
+ * The arbiter's wallet signature is automatically generated for the multisig.
1620
+ *
1621
+ * @param walletClient - The arbiter's wallet client (must have account connected)
1622
+ * @param escrowId - The escrow ID to resolve
1623
+ * @param resolution - DisputeResolution.Complete or DisputeResolution.Refunded
1624
+ * @param ipfsHash - IPFS hash containing the decision explanation
1625
+ * @returns Transaction hash
1626
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
1627
+ * @throws {SDKError} NOT_ARBITER - If caller is not the designated arbiter
1628
+ * @throws {SDKError} INVALID_STATE - If escrow is not in DISPUTED state
1629
+ */
1630
+ async submitArbiterDecision(walletClient, escrowId, resolution, ipfsHash) {
1631
+ assertWalletClient(walletClient);
1632
+ const deal = await this.getEscrowByIdParsed(escrowId);
1633
+ // Verify caller using helper
1634
+ this.verifyArbiter(walletClient.account.address, deal);
1635
+ // Sign wallet authorization
1636
+ const arbiterWalletSig = await this.signWalletAuthorization(walletClient, deal.wallet, escrowId);
1637
+ // Submit decision
1638
+ const hash = await this.resilientWriteContract(walletClient, {
1639
+ address: this.contractAddress,
1640
+ abi: this.abiEscrow,
1641
+ functionName: "submitArbiterDecision",
1642
+ args: [escrowId, resolution, ipfsHash, arbiterWalletSig],
1643
+ });
1644
+ await this.waitForReceipt(hash);
1645
+ return hash;
1646
+ }
1647
+ // ==========================================================================
1648
+ // WALLET WITHDRAWAL
1649
+ // ==========================================================================
1650
+ /**
1651
+ * Withdraw funds from the escrow wallet
1652
+ *
1653
+ * This function executes the actual token transfer from the escrow wallet to the
1654
+ * designated recipient. The wallet contract uses a 2-of-3 multisig mechanism:
1655
+ *
1656
+ * - COMPLETE state: Requires buyer + seller signatures → funds go to seller
1657
+ * - REFUNDED state: Requires buyer + arbiter signatures → funds go to buyer
1658
+ * - CANCELED state: Requires buyer + seller signatures → funds go to buyer
1659
+ *
1660
+ * Anyone can call this function (typically the recipient), as the signatures
1661
+ * were already collected during the escrow lifecycle. The wallet contract
1662
+ * automatically reads and verifies signatures from the escrow contract.
1663
+ *
1664
+ * @param walletClient - Any wallet client (typically the recipient)
1665
+ * @param escrowId - The escrow ID to withdraw from
1666
+ * @returns Transaction hash
1667
+ * @throws {SDKError} WALLET_NOT_CONNECTED - If wallet client is not connected
1668
+ * @throws {SDKError} INVALID_STATE - If escrow is not in a final state (COMPLETE/REFUNDED/CANCELED)
1669
+ */
1670
+ async withdraw(walletClient, escrowId) {
1671
+ assertWalletClient(walletClient);
1672
+ const deal = await this.getEscrowByIdParsed(escrowId);
1673
+ // Verify final state
1674
+ if (![EscrowState.COMPLETE, EscrowState.REFUNDED, EscrowState.CANCELED].includes(deal.state)) {
1675
+ throw new SDKError(`Cannot withdraw in state: ${this.STATE_NAMES[deal.state]}`, SDKErrorCode.INVALID_STATE);
1676
+ }
1677
+ // Withdraw from wallet
1678
+ const hash = await this.resilientWriteContract(walletClient, {
1679
+ address: deal.wallet,
1680
+ abi: this.abiWallet,
1681
+ functionName: "withdraw",
1682
+ args: [],
1683
+ });
1684
+ await this.waitForReceipt(hash);
1685
+ return hash;
1686
+ }
1687
+ /**
1688
+ * Get valid signature count for wallet
1689
+ */
1690
+ async getWalletSignatureCount(escrowId) {
1691
+ const deal = await this.getEscrowByIdParsed(escrowId);
1692
+ const count = await this.publicClient.readContract({
1693
+ address: deal.wallet,
1694
+ abi: this.abiWallet,
1695
+ functionName: "getValidSignatureCount",
1696
+ });
1697
+ return Number(count);
1698
+ }
1699
+ /**
1700
+ * Get wallet balance
1701
+ */
1702
+ async getWalletBalance(escrowId) {
1703
+ const deal = await this.getEscrowByIdParsed(escrowId);
1704
+ return this.publicClient.readContract({
1705
+ address: deal.wallet,
1706
+ abi: this.abiWallet,
1707
+ functionName: "getBalance",
1708
+ });
1709
+ }
1710
+ // ==========================================================================
1711
+ // SUBGRAPH QUERIES
1712
+ // ==========================================================================
1713
+ async getEscrows() {
1714
+ const { data } = await this.apollo.query({
1715
+ query: queries_1.ALL_ESCROWS_QUERY,
1716
+ fetchPolicy: "network-only",
1717
+ });
1718
+ return data?.escrows ?? [];
1719
+ }
1720
+ async getEscrowsByBuyer(buyer) {
1721
+ const { data } = await this.apollo.query({
1722
+ query: queries_1.ESCROWS_BY_BUYER_QUERY,
1723
+ variables: { buyer: buyer.toLowerCase() },
1724
+ fetchPolicy: "network-only",
1725
+ });
1726
+ return data?.escrows ?? [];
1727
+ }
1728
+ async getEscrowsBySeller(seller) {
1729
+ const { data } = await this.apollo.query({
1730
+ query: queries_1.ESCROWS_BY_SELLER_QUERY,
1731
+ variables: { seller: seller.toLowerCase() },
1732
+ fetchPolicy: "network-only",
1733
+ });
1734
+ return data?.escrows ?? [];
1735
+ }
1736
+ async getEscrowDetail(id) {
1737
+ const { data } = await this.apollo.query({
1738
+ query: queries_1.ESCROW_DETAIL_QUERY,
1739
+ variables: { id },
1740
+ fetchPolicy: "network-only",
1741
+ });
1742
+ return data?.escrow;
1743
+ }
1744
+ async getDisputeMessages(escrowId) {
1745
+ const { data } = await this.apollo.query({
1746
+ query: queries_1.DISPUTE_MESSAGES_BY_ESCROW_QUERY,
1747
+ variables: { escrowId },
1748
+ fetchPolicy: "network-only",
1749
+ });
1750
+ return data?.escrow?.disputeMessages ?? [];
1751
+ }
1752
+ // ==========================================================================
1753
+ // UTILITY METHODS
1754
+ // ==========================================================================
1755
+ /**
1756
+ * Get a human-readable status label with color and description for an escrow state.
1757
+ * This is useful for displaying escrow status in UIs.
1758
+ *
1759
+ * @param state - The escrow state enum value
1760
+ * @returns An object containing:
1761
+ * - label: Human-readable status name
1762
+ * - color: Suggested UI color (orange, blue, red, green, gray)
1763
+ * - description: Detailed explanation of what this state means
1764
+ *
1765
+ * @example
1766
+ * ```typescript
1767
+ * const sdk = new PalindromePaySDK(...);
1768
+ * const escrow = await sdk.getEscrowByIdParsed(1n);
1769
+ * const status = sdk.getStatusLabel(escrow.state);
1770
+ * console.log(status.label); // "Awaiting Payment"
1771
+ * console.log(status.color); // "orange"
1772
+ * console.log(status.description); // "Buyer needs to deposit funds"
1773
+ * ```
1774
+ */
1775
+ getStatusLabel(state) {
1776
+ const labels = {
1777
+ [EscrowState.AWAITING_PAYMENT]: {
1778
+ label: "Awaiting Payment",
1779
+ color: "orange",
1780
+ description: "Buyer needs to deposit funds",
1781
+ },
1782
+ [EscrowState.AWAITING_DELIVERY]: {
1783
+ label: "Awaiting Delivery",
1784
+ color: "blue",
1785
+ description: "Seller should deliver product/service",
1786
+ },
1787
+ [EscrowState.DISPUTED]: {
1788
+ label: "Disputed",
1789
+ color: "red",
1790
+ description: "Dispute in progress - arbiter will resolve",
1791
+ },
1792
+ [EscrowState.COMPLETE]: {
1793
+ label: "Complete",
1794
+ color: "green",
1795
+ description: "Transaction completed successfully",
1796
+ },
1797
+ [EscrowState.REFUNDED]: {
1798
+ label: "Refunded",
1799
+ color: "gray",
1800
+ description: "Funds returned to buyer",
1801
+ },
1802
+ [EscrowState.CANCELED]: {
1803
+ label: "Canceled",
1804
+ color: "gray",
1805
+ description: "Escrow was canceled",
1806
+ },
1807
+ };
1808
+ return labels[state];
1809
+ }
1810
+ /**
1811
+ * Get user role for an escrow
1812
+ */
1813
+ getUserRole(userAddress, escrow) {
1814
+ if (addressEquals(userAddress, escrow.buyer))
1815
+ return Role.Buyer;
1816
+ if (addressEquals(userAddress, escrow.seller))
1817
+ return Role.Seller;
1818
+ if (addressEquals(userAddress, escrow.arbiter))
1819
+ return Role.Arbiter;
1820
+ return Role.None;
1821
+ }
1822
+ // ==========================================================================
1823
+ // SIMULATION & GAS ESTIMATION
1824
+ // ==========================================================================
1825
+ /**
1826
+ * Simulate a transaction before executing
1827
+ * Returns success status, gas estimate, and revert reason if failed
1828
+ */
1829
+ async simulateTransaction(walletClient, functionName, args, contractAddress) {
1830
+ assertWalletClient(walletClient);
1831
+ const target = contractAddress ?? this.contractAddress;
1832
+ try {
1833
+ // Simulate the call
1834
+ const { result } = await this.publicClient.simulateContract({
1835
+ address: target,
1836
+ abi: this.abiEscrow,
1837
+ functionName,
1838
+ args,
1839
+ account: walletClient.account,
1840
+ });
1841
+ // Estimate gas
1842
+ const gasEstimate = await this.publicClient.estimateContractGas({
1843
+ address: target,
1844
+ abi: this.abiEscrow,
1845
+ functionName,
1846
+ args,
1847
+ account: walletClient.account,
1848
+ });
1849
+ return {
1850
+ success: true,
1851
+ gasEstimate,
1852
+ result,
1853
+ };
1854
+ }
1855
+ catch (error) {
1856
+ // Extract revert reason
1857
+ let revertReason = "Unknown error";
1858
+ if (isViemError(error)) {
1859
+ if (error.cause?.reason) {
1860
+ revertReason = error.cause.reason;
1861
+ }
1862
+ else if (hasShortMessage(error)) {
1863
+ revertReason = error.shortMessage;
1864
+ }
1865
+ else if (error.message) {
1866
+ // Try to parse revert reason from error message
1867
+ const match = error.message.match(/reverted with reason string '([^']+)'/);
1868
+ if (match) {
1869
+ revertReason = match[1];
1870
+ }
1871
+ else {
1872
+ revertReason = error.message.slice(0, 200);
1873
+ }
1874
+ }
1875
+ }
1876
+ return {
1877
+ success: false,
1878
+ revertReason,
1879
+ };
1880
+ }
1881
+ }
1882
+ /**
1883
+ * Simulate deposit before executing
1884
+ */
1885
+ async simulateDeposit(walletClient, escrowId) {
1886
+ assertWalletClient(walletClient);
1887
+ const deal = await this.getEscrowByIdParsed(escrowId);
1888
+ // Check approval first
1889
+ const allowance = await this.getTokenAllowance(walletClient.account.address, this.contractAddress, deal.token);
1890
+ const needsApproval = allowance < deal.amount;
1891
+ // Simulate the deposit (without actual wallet sig for simulation)
1892
+ const result = await this.simulateTransaction(walletClient, "deposit", [escrowId, "0x"]);
1893
+ return {
1894
+ ...result,
1895
+ needsApproval,
1896
+ approvalAmount: needsApproval ? deal.amount - allowance : 0n,
1897
+ };
1898
+ }
1899
+ /**
1900
+ * Simulate confirm delivery before executing
1901
+ */
1902
+ async simulateConfirmDelivery(walletClient, escrowId) {
1903
+ return this.simulateTransaction(walletClient, "confirmDelivery", [escrowId, "0x"]);
1904
+ }
1905
+ /**
1906
+ * Simulate withdraw before executing
1907
+ */
1908
+ async simulateWithdraw(walletClient, escrowId) {
1909
+ assertWalletClient(walletClient);
1910
+ const deal = await this.getEscrowByIdParsed(escrowId);
1911
+ const signatureCount = await this.getWalletSignatureCount(escrowId);
1912
+ try {
1913
+ const gasEstimate = await this.publicClient.estimateContractGas({
1914
+ address: deal.wallet,
1915
+ abi: this.abiWallet,
1916
+ functionName: "withdraw",
1917
+ args: [],
1918
+ account: walletClient.account,
1919
+ });
1920
+ return {
1921
+ success: true,
1922
+ gasEstimate,
1923
+ signatureCount,
1924
+ };
1925
+ }
1926
+ catch (error) {
1927
+ let revertReason = "Unknown error";
1928
+ if (error?.shortMessage) {
1929
+ revertReason = error.shortMessage;
1930
+ }
1931
+ else if (error?.message) {
1932
+ revertReason = error.message.slice(0, 200);
1933
+ }
1934
+ return {
1935
+ success: false,
1936
+ revertReason,
1937
+ signatureCount,
1938
+ };
1939
+ }
1940
+ }
1941
+ /**
1942
+ * Estimate gas for a transaction with buffer
1943
+ */
1944
+ async estimateGasWithBuffer(walletClient, functionName, args, contractAddress) {
1945
+ assertWalletClient(walletClient);
1946
+ const target = contractAddress ?? this.contractAddress;
1947
+ const gasEstimate = await this.publicClient.estimateContractGas({
1948
+ address: target,
1949
+ abi: this.abiEscrow,
1950
+ functionName,
1951
+ args,
1952
+ account: walletClient.account,
1953
+ });
1954
+ // Add buffer (default 20%)
1955
+ return gasEstimate + (gasEstimate * BigInt(this.gasBuffer)) / 100n;
1956
+ }
1957
+ // ==========================================================================
1958
+ // HEALTH CHECK
1959
+ // ==========================================================================
1960
+ /**
1961
+ * Health check
1962
+ */
1963
+ async healthCheck() {
1964
+ const errors = [];
1965
+ let rpcConnected = false;
1966
+ let contractDeployed = false;
1967
+ let subgraphConnected = false;
1968
+ try {
1969
+ await this.publicClient.getBlockNumber();
1970
+ rpcConnected = true;
1971
+ }
1972
+ catch (e) {
1973
+ const message = this.extractErrorMessage(e);
1974
+ errors.push(`RPC error: ${message}`);
1975
+ }
1976
+ try {
1977
+ await this.getNextEscrowId();
1978
+ contractDeployed = true;
1979
+ }
1980
+ catch (e) {
1981
+ const message = this.extractErrorMessage(e);
1982
+ errors.push(`Contract error: ${message}`);
1983
+ }
1984
+ try {
1985
+ await this.getEscrows();
1986
+ subgraphConnected = true;
1987
+ }
1988
+ catch (e) {
1989
+ const message = this.extractErrorMessage(e);
1990
+ errors.push(`Subgraph error: ${message}`);
1991
+ }
1992
+ return { rpcConnected, contractDeployed, subgraphConnected, errors };
1993
+ }
1994
+ // ==========================================================================
1995
+ // CACHE MANAGEMENT
1996
+ // ==========================================================================
1997
+ /**
1998
+ * Get escrow status with optional caching
1999
+ */
2000
+ async getEscrowStatus(escrowId, forceRefresh = false) {
2001
+ const cacheKey = `status-${escrowId}`;
2002
+ if (!forceRefresh) {
2003
+ const cached = this.getCacheValue(cacheKey);
2004
+ if (cached)
2005
+ return cached;
2006
+ }
2007
+ const deal = await this.getEscrowByIdParsed(escrowId);
2008
+ const statusInfo = this.getStatusLabel(deal.state);
2009
+ const result = {
2010
+ state: deal.state,
2011
+ stateName: this.STATE_NAMES[deal.state],
2012
+ ...statusInfo,
2013
+ };
2014
+ this.setCacheValue(cacheKey, result);
2015
+ return result;
2016
+ }
2017
+ /**
2018
+ * Get cache statistics
2019
+ */
2020
+ getCacheStats() {
2021
+ return {
2022
+ escrowCacheSize: this.escrowCache.size,
2023
+ tokenDecimalsCacheSize: this.tokenDecimalsCache.size,
2024
+ };
2025
+ }
2026
+ /**
2027
+ * Clear all caches
2028
+ */
2029
+ clearAllCaches() {
2030
+ this.escrowCache.clear();
2031
+ this.tokenDecimalsCache.clear();
2032
+ this.feeReceiverCache = null;
2033
+ this.cachedFeeBps = null;
2034
+ this.multicallSupported = null;
2035
+ // Note: walletBytecodeHashCache is immutable and never needs clearing
2036
+ }
2037
+ /**
2038
+ * Clear escrow cache only
2039
+ */
2040
+ clearEscrowCache() {
2041
+ this.escrowCache.clear();
2042
+ }
2043
+ /**
2044
+ * Clear multicall cache (useful when switching chains)
2045
+ */
2046
+ clearMulticallCache() {
2047
+ this.multicallSupported = null;
2048
+ }
2049
+ // ==========================================================================
2050
+ // EVENT WATCHING
2051
+ // ==========================================================================
2052
+ /**
2053
+ * Watch for escrow events related to a user
2054
+ */
2055
+ watchUserEscrows(userAddress, callback, options) {
2056
+ const unwatch = this.publicClient.watchContractEvent({
2057
+ address: this.contractAddress,
2058
+ abi: this.abiEscrow,
2059
+ eventName: "EscrowCreated",
2060
+ fromBlock: options?.fromBlock,
2061
+ onLogs: (logs) => {
2062
+ for (const log of logs) {
2063
+ const parsedLog = log;
2064
+ if (!parsedLog.args) {
2065
+ continue; // Skip logs without args
2066
+ }
2067
+ const args = parsedLog.args;
2068
+ if (addressEquals(args.buyer, userAddress) ||
2069
+ addressEquals(args.seller, userAddress)) {
2070
+ callback(args.escrowId, args);
2071
+ }
2072
+ }
2073
+ },
2074
+ });
2075
+ return { dispose: unwatch };
2076
+ }
2077
+ /**
2078
+ * Watch for state changes on a specific escrow
2079
+ */
2080
+ watchEscrowStateChanges(escrowId, callback, options) {
2081
+ let lastState = null;
2082
+ const interval = options?.pollingInterval ?? DEFAULT_POLLING_INTERVAL;
2083
+ const poll = async () => {
2084
+ try {
2085
+ const deal = await this.getEscrowByIdParsed(escrowId);
2086
+ if (lastState !== null && deal.state !== lastState) {
2087
+ callback(deal.state, lastState);
2088
+ }
2089
+ lastState = deal.state;
2090
+ }
2091
+ catch (e) {
2092
+ const message = this.extractErrorMessage(e);
2093
+ this.log('error', 'Error polling escrow state', {
2094
+ escrowId: escrowId.toString(),
2095
+ error: message
2096
+ });
2097
+ }
2098
+ };
2099
+ // Initial poll
2100
+ poll();
2101
+ // Set up interval
2102
+ const intervalId = setInterval(poll, interval);
2103
+ return {
2104
+ dispose: () => clearInterval(intervalId),
2105
+ };
2106
+ }
2107
+ // ==========================================================================
2108
+ // ADDITIONAL HELPERS
2109
+ // ==========================================================================
2110
+ /**
2111
+ * Check if user has submitted evidence for a dispute
2112
+ */
2113
+ async hasSubmittedEvidence(escrowId, role) {
2114
+ const status = await this.getDisputeSubmissionStatus(escrowId);
2115
+ switch (role) {
2116
+ case Role.Buyer:
2117
+ return status.buyer;
2118
+ case Role.Seller:
2119
+ return status.seller;
2120
+ case Role.Arbiter:
2121
+ return status.arbiter;
2122
+ default:
2123
+ return false;
2124
+ }
2125
+ }
2126
+ /**
2127
+ * Get cancellation request status for an escrow
2128
+ *
2129
+ * This helper function checks whether the buyer and/or seller have requested
2130
+ * cancellation. Use this to determine if mutual cancellation is pending or complete.
2131
+ *
2132
+ * Cancellation flow:
2133
+ * - Either party calls `requestCancel` to initiate
2134
+ * - If only one party requested, the other must also call `requestCancel` for mutual cancel
2135
+ * - When both request, the escrow is automatically canceled and funds return to buyer
2136
+ * - Alternatively, buyer can use `cancelByTimeout` after maturity time (if arbiter is set)
2137
+ *
2138
+ * @param escrowId - The escrow ID to check
2139
+ * @returns Object with buyer/seller cancel request status and whether mutual cancel is complete
2140
+ */
2141
+ async getCancelRequestStatus(escrowId) {
2142
+ const deal = await this.getEscrowByIdParsed(escrowId);
2143
+ return {
2144
+ buyerRequested: deal.buyerCancelRequested,
2145
+ sellerRequested: deal.sellerCancelRequested,
2146
+ mutualCancelComplete: deal.buyerCancelRequested && deal.sellerCancelRequested,
2147
+ };
2148
+ }
2149
+ /**
2150
+ * Get user balances for multiple tokens (batched for performance).
2151
+ * Uses Promise.all to fetch all balances and decimals in parallel.
2152
+ */
2153
+ async getUserBalances(userAddress, tokens) {
2154
+ if (tokens.length === 0) {
2155
+ return new Map();
2156
+ }
2157
+ // Batch fetch all balances and decimals in parallel
2158
+ const [balances, decimalsArray] = await Promise.all([
2159
+ Promise.all(tokens.map((token) => this.getTokenBalance(userAddress, token))),
2160
+ Promise.all(tokens.map((token) => this.getTokenDecimals(token))),
2161
+ ]);
2162
+ const result = new Map();
2163
+ for (let i = 0; i < tokens.length; i++) {
2164
+ const token = tokens[i];
2165
+ const balance = balances[i];
2166
+ const decimals = decimalsArray[i];
2167
+ const formatted = this.formatTokenAmount(balance, decimals);
2168
+ result.set(token, { balance, decimals, formatted });
2169
+ }
2170
+ return result;
2171
+ }
2172
+ /**
2173
+ * Get maturity info for an escrow
2174
+ */
2175
+ getMaturityInfo(depositTime, maturityDays) {
2176
+ const hasDeadline = maturityDays > 0n;
2177
+ const maturityTimestamp = depositTime + maturityDays * 86400n;
2178
+ const now = BigInt(Math.floor(Date.now() / 1000));
2179
+ const isPassed = now >= maturityTimestamp;
2180
+ const remainingSeconds = isPassed ? 0 : Number(maturityTimestamp - now);
2181
+ return {
2182
+ hasDeadline,
2183
+ maturityDays: Number(maturityDays),
2184
+ maturityTimestamp,
2185
+ isPassed,
2186
+ remainingSeconds,
2187
+ };
2188
+ }
2189
+ /**
2190
+ * Get all escrows for a user (as buyer or seller)
2191
+ */
2192
+ async getUserEscrows(userAddress) {
2193
+ const [buyerEscrows, sellerEscrows] = await Promise.all([
2194
+ this.getEscrowsByBuyer(userAddress),
2195
+ this.getEscrowsBySeller(userAddress),
2196
+ ]);
2197
+ // Merge and deduplicate by ID
2198
+ const escrowMap = new Map();
2199
+ for (const escrow of [...buyerEscrows, ...sellerEscrows]) {
2200
+ escrowMap.set(escrow.id, escrow);
2201
+ }
2202
+ return Array.from(escrowMap.values());
2203
+ }
2204
+ // ============================================================================
2205
+ // STATE & ROLE VALIDATION HELPERS
2206
+ // ============================================================================
2207
+ /**
2208
+ * Check if a user can deposit to an escrow.
2209
+ * A user can deposit if:
2210
+ * - The escrow exists and is in AWAITING_PAYMENT state
2211
+ * - The user is either the buyer or seller
2212
+ *
2213
+ * @param userAddress - The address of the user to check
2214
+ * @param escrowId - The escrow ID to check
2215
+ * @returns True if the user can deposit, false otherwise
2216
+ */
2217
+ async canUserDeposit(userAddress, escrowId) {
2218
+ try {
2219
+ const escrow = await this.getEscrowByIdParsed(escrowId);
2220
+ // Must be in AWAITING_PAYMENT state
2221
+ if (escrow.state !== EscrowState.AWAITING_PAYMENT) {
2222
+ return false;
2223
+ }
2224
+ // Must be buyer or seller
2225
+ return addressEquals(userAddress, escrow.buyer) ||
2226
+ addressEquals(userAddress, escrow.seller);
2227
+ }
2228
+ catch {
2229
+ return false;
2230
+ }
2231
+ }
2232
+ /**
2233
+ * Check if a user can accept an escrow (seller accepting after buyer deposit).
2234
+ * A user can accept if:
2235
+ * - The escrow is in AWAITING_DELIVERY state
2236
+ * - The user is the seller
2237
+ *
2238
+ * @param userAddress - The address of the user to check
2239
+ * @param escrowId - The escrow ID to check
2240
+ * @returns True if the user can accept, false otherwise
2241
+ */
2242
+ async canUserAcceptEscrow(userAddress, escrowId) {
2243
+ try {
2244
+ const escrow = await this.getEscrowByIdParsed(escrowId);
2245
+ // Must be in AWAITING_DELIVERY state
2246
+ if (escrow.state !== EscrowState.AWAITING_DELIVERY) {
2247
+ return false;
2248
+ }
2249
+ // Must be seller
2250
+ return addressEquals(userAddress, escrow.seller);
2251
+ }
2252
+ catch {
2253
+ return false;
2254
+ }
2255
+ }
2256
+ /**
2257
+ * Check if a user can confirm delivery (buyer confirming receipt).
2258
+ * A user can confirm delivery if:
2259
+ * - The escrow is in AWAITING_DELIVERY or DISPUTED state
2260
+ * - The user is the buyer
2261
+ *
2262
+ * @param userAddress - The address of the user to check
2263
+ * @param escrowId - The escrow ID to check
2264
+ * @returns True if the user can confirm delivery, false otherwise
2265
+ */
2266
+ async canUserConfirmDelivery(userAddress, escrowId) {
2267
+ try {
2268
+ const escrow = await this.getEscrowByIdParsed(escrowId);
2269
+ // Must be in AWAITING_DELIVERY or DISPUTED state
2270
+ if (escrow.state !== EscrowState.AWAITING_DELIVERY &&
2271
+ escrow.state !== EscrowState.DISPUTED) {
2272
+ return false;
2273
+ }
2274
+ // Must be buyer
2275
+ return addressEquals(userAddress, escrow.buyer);
2276
+ }
2277
+ catch {
2278
+ return false;
2279
+ }
2280
+ }
2281
+ /**
2282
+ * Check if a user can start a dispute.
2283
+ * A user can start a dispute if:
2284
+ * - The escrow is in AWAITING_DELIVERY state
2285
+ * - The escrow has an arbiter set
2286
+ * - The user is either the buyer or seller
2287
+ *
2288
+ * @param userAddress - The address of the user to check
2289
+ * @param escrowId - The escrow ID to check
2290
+ * @returns True if the user can start a dispute, false otherwise
2291
+ */
2292
+ async canUserStartDispute(userAddress, escrowId) {
2293
+ try {
2294
+ const escrow = await this.getEscrowByIdParsed(escrowId);
2295
+ // Must be in AWAITING_DELIVERY state
2296
+ if (escrow.state !== EscrowState.AWAITING_DELIVERY) {
2297
+ return false;
2298
+ }
2299
+ // Must have arbiter
2300
+ if (!this.hasArbiter(escrow)) {
2301
+ return false;
2302
+ }
2303
+ // Must be buyer or seller
2304
+ return addressEquals(userAddress, escrow.buyer) ||
2305
+ addressEquals(userAddress, escrow.seller);
2306
+ }
2307
+ catch {
2308
+ return false;
2309
+ }
2310
+ }
2311
+ /**
2312
+ * Check if an escrow can be withdrawn (auto-release check).
2313
+ * An escrow can be withdrawn if:
2314
+ * - It's in AWAITING_DELIVERY state
2315
+ * - The maturity time has passed (if deadline is set)
2316
+ *
2317
+ * @param escrowId - The escrow ID to check
2318
+ * @returns True if the escrow can be withdrawn, false otherwise
2319
+ */
2320
+ async canUserWithdraw(escrowId) {
2321
+ try {
2322
+ const escrow = await this.getEscrowByIdParsed(escrowId);
2323
+ // Must be in AWAITING_DELIVERY state
2324
+ if (escrow.state !== EscrowState.AWAITING_DELIVERY) {
2325
+ return false;
2326
+ }
2327
+ // Check if maturity time has passed (if deadline is set)
2328
+ if (escrow.maturityTime > 0n) {
2329
+ const now = BigInt(Math.floor(Date.now() / 1000));
2330
+ return now >= escrow.maturityTime;
2331
+ }
2332
+ // No deadline set, cannot auto-withdraw
2333
+ return false;
2334
+ }
2335
+ catch {
2336
+ return false;
2337
+ }
2338
+ }
2339
+ /**
2340
+ * Check if a seller can perform auto-release.
2341
+ * A seller can auto-release if:
2342
+ * - The escrow is in AWAITING_DELIVERY state
2343
+ * - The maturity time has passed (if deadline is set)
2344
+ * - The user is the seller
2345
+ *
2346
+ * @param userAddress - The address of the user to check
2347
+ * @param escrowId - The escrow ID to check
2348
+ * @returns True if the seller can auto-release, false otherwise
2349
+ */
2350
+ async canSellerAutoRelease(userAddress, escrowId) {
2351
+ try {
2352
+ const escrow = await this.getEscrowByIdParsed(escrowId);
2353
+ // Must be seller
2354
+ if (!addressEquals(userAddress, escrow.seller)) {
2355
+ return false;
2356
+ }
2357
+ // Must be in AWAITING_DELIVERY state
2358
+ if (escrow.state !== EscrowState.AWAITING_DELIVERY) {
2359
+ return false;
2360
+ }
2361
+ // Check if maturity time has passed (if deadline is set)
2362
+ if (escrow.maturityTime > 0n) {
2363
+ const now = BigInt(Math.floor(Date.now() / 1000));
2364
+ return now >= escrow.maturityTime;
2365
+ }
2366
+ // No deadline set, cannot auto-release
2367
+ return false;
2368
+ }
2369
+ catch {
2370
+ return false;
2371
+ }
2372
+ }
2373
+ /**
2374
+ * Check if an address is the buyer in an escrow.
2375
+ *
2376
+ * @param userAddress - The address to check
2377
+ * @param escrow - The escrow data
2378
+ * @returns True if the address is the buyer
2379
+ */
2380
+ isBuyer(userAddress, escrow) {
2381
+ return addressEquals(userAddress, escrow.buyer);
2382
+ }
2383
+ /**
2384
+ * Check if an address is the seller in an escrow.
2385
+ *
2386
+ * @param userAddress - The address to check
2387
+ * @param escrow - The escrow data
2388
+ * @returns True if the address is the seller
2389
+ */
2390
+ isSeller(userAddress, escrow) {
2391
+ return addressEquals(userAddress, escrow.seller);
2392
+ }
2393
+ /**
2394
+ * Check if an address is the arbiter in an escrow.
2395
+ *
2396
+ * @param userAddress - The address to check
2397
+ * @param escrow - The escrow data
2398
+ * @returns True if the address is the arbiter
2399
+ */
2400
+ isArbiter(userAddress, escrow) {
2401
+ return addressEquals(userAddress, escrow.arbiter);
2402
+ }
2403
+ /**
2404
+ * Check if an escrow has an arbiter set.
2405
+ *
2406
+ * @param escrow - The escrow data
2407
+ * @returns True if the escrow has an arbiter (non-zero address)
2408
+ */
2409
+ hasArbiter(escrow) {
2410
+ return escrow.arbiter !== viem_1.zeroAddress;
2411
+ }
2412
+ /**
2413
+ * Compare two addresses for equality (case-insensitive, normalized).
2414
+ * This is a public utility method that can be used to compare Ethereum addresses.
2415
+ *
2416
+ * @param a - First address to compare
2417
+ * @param b - Second address to compare
2418
+ * @returns True if the addresses are equal (case-insensitive)
2419
+ *
2420
+ * @example
2421
+ * ```typescript
2422
+ * const sdk = new PalindromePaySDK(...);
2423
+ * const areEqual = sdk.addressEquals(
2424
+ * "0xabc...",
2425
+ * "0xABC..."
2426
+ * ); // true
2427
+ * ```
2428
+ */
2429
+ addressEquals(a, b) {
2430
+ return addressEquals(a, b);
2431
+ }
2432
+ // ============================================================================
2433
+ // GAS ESTIMATION HELPERS
2434
+ // ============================================================================
2435
+ /**
2436
+ * Get current gas price information from the network.
2437
+ * Returns standard, fast, and instant gas price estimates in gwei.
2438
+ *
2439
+ * @returns Object containing gas price estimates
2440
+ *
2441
+ * @example
2442
+ * ```typescript
2443
+ * const gasPrice = await sdk.getCurrentGasPrice();
2444
+ * console.log(`Standard: ${gasPrice.standard} gwei`);
2445
+ * console.log(`Fast: ${gasPrice.fast} gwei`);
2446
+ * console.log(`Instant: ${gasPrice.instant} gwei`);
2447
+ * ```
2448
+ */
2449
+ async getCurrentGasPrice() {
2450
+ const gasPrice = await this.publicClient.getGasPrice();
2451
+ // Estimate different speed tiers (standard, fast, instant)
2452
+ // Standard: base price
2453
+ // Fast: +20%
2454
+ // Instant: +50%
2455
+ const standard = gasPrice;
2456
+ const fast = (gasPrice * 120n) / 100n;
2457
+ const instant = (gasPrice * 150n) / 100n;
2458
+ return {
2459
+ standard,
2460
+ fast,
2461
+ instant,
2462
+ wei: gasPrice
2463
+ };
2464
+ }
2465
+ /**
2466
+ * Estimate gas cost for creating an escrow.
2467
+ *
2468
+ * @param params - Create escrow parameters
2469
+ * @returns Gas estimation details
2470
+ *
2471
+ * @example
2472
+ * ```typescript
2473
+ * const estimate = await sdk.estimateGasForCreateEscrow({
2474
+ * token: tokenAddress,
2475
+ * buyer: buyerAddress,
2476
+ * amount: 1000000n,
2477
+ * maturityDays: 7n,
2478
+ * arbiter: zeroAddress,
2479
+ * title: 'Test',
2480
+ * ipfsHash: ''
2481
+ * });
2482
+ * console.log(`Gas limit: ${estimate.gasLimit}`);
2483
+ * console.log(`Cost: ${estimate.estimatedCostEth} ETH`);
2484
+ * ```
2485
+ */
2486
+ async estimateGasForCreateEscrow(params) {
2487
+ if (!this.walletClient) {
2488
+ throw new Error('Wallet client required for gas estimation');
2489
+ }
2490
+ try {
2491
+ const gasLimit = await this.publicClient.estimateContractGas({
2492
+ address: this.contractAddress,
2493
+ abi: this.abiEscrow,
2494
+ functionName: 'createEscrow',
2495
+ args: [
2496
+ params.token,
2497
+ params.buyer,
2498
+ params.amount,
2499
+ params.maturityDays,
2500
+ params.arbiter,
2501
+ params.title,
2502
+ params.ipfsHash,
2503
+ (0, viem_1.pad)('0x00', { size: 65 }) // Empty seller wallet sig
2504
+ ],
2505
+ account: this.walletClient.account
2506
+ });
2507
+ const gasPrice = await this.publicClient.getGasPrice();
2508
+ const estimatedCostWei = gasLimit * gasPrice;
2509
+ const estimatedCostEth = (Number(estimatedCostWei) / 1e18).toFixed(6);
2510
+ return {
2511
+ gasLimit,
2512
+ estimatedCostWei,
2513
+ estimatedCostEth
2514
+ };
2515
+ }
2516
+ catch (error) {
2517
+ // If estimation fails, return conservative estimate
2518
+ const gasLimit = 300000n; // Conservative estimate
2519
+ const gasPrice = await this.publicClient.getGasPrice();
2520
+ const estimatedCostWei = gasLimit * gasPrice;
2521
+ const estimatedCostEth = (Number(estimatedCostWei) / 1e18).toFixed(6);
2522
+ return {
2523
+ gasLimit,
2524
+ estimatedCostWei,
2525
+ estimatedCostEth
2526
+ };
2527
+ }
2528
+ }
2529
+ /**
2530
+ * Estimate gas cost for depositing to an escrow.
2531
+ *
2532
+ * @param escrowId - The escrow ID
2533
+ * @returns Gas estimation details
2534
+ *
2535
+ * @example
2536
+ * ```typescript
2537
+ * const estimate = await sdk.estimateGasForDeposit(escrowId);
2538
+ * console.log(`Gas limit: ${estimate.gasLimit}`);
2539
+ * ```
2540
+ */
2541
+ async estimateGasForDeposit(escrowId) {
2542
+ if (!this.walletClient) {
2543
+ throw new Error('Wallet client required for gas estimation');
2544
+ }
2545
+ try {
2546
+ const gasLimit = await this.publicClient.estimateContractGas({
2547
+ address: this.contractAddress,
2548
+ abi: this.abiEscrow,
2549
+ functionName: 'deposit',
2550
+ args: [escrowId, (0, viem_1.pad)('0x00', { size: 65 })],
2551
+ account: this.walletClient.account
2552
+ });
2553
+ const gasPrice = await this.publicClient.getGasPrice();
2554
+ const estimatedCostWei = gasLimit * gasPrice;
2555
+ const estimatedCostEth = (Number(estimatedCostWei) / 1e18).toFixed(6);
2556
+ return {
2557
+ gasLimit,
2558
+ estimatedCostWei,
2559
+ estimatedCostEth
2560
+ };
2561
+ }
2562
+ catch {
2563
+ const gasLimit = 200000n;
2564
+ const gasPrice = await this.publicClient.getGasPrice();
2565
+ const estimatedCostWei = gasLimit * gasPrice;
2566
+ const estimatedCostEth = (Number(estimatedCostWei) / 1e18).toFixed(6);
2567
+ return {
2568
+ gasLimit,
2569
+ estimatedCostWei,
2570
+ estimatedCostEth
2571
+ };
2572
+ }
2573
+ }
2574
+ /**
2575
+ * Estimate gas cost for confirming delivery.
2576
+ *
2577
+ * @param escrowId - The escrow ID
2578
+ * @returns Gas estimation details
2579
+ *
2580
+ * @example
2581
+ * ```typescript
2582
+ * const estimate = await sdk.estimateGasForConfirmDelivery(escrowId);
2583
+ * console.log(`Cost: ${estimate.estimatedCostEth} ETH`);
2584
+ * ```
2585
+ */
2586
+ async estimateGasForConfirmDelivery(escrowId) {
2587
+ if (!this.walletClient) {
2588
+ throw new Error('Wallet client required for gas estimation');
2589
+ }
2590
+ try {
2591
+ const gasLimit = await this.publicClient.estimateContractGas({
2592
+ address: this.contractAddress,
2593
+ abi: this.abiEscrow,
2594
+ functionName: 'confirmDelivery',
2595
+ args: [escrowId, (0, viem_1.pad)('0x00', { size: 65 })],
2596
+ account: this.walletClient.account
2597
+ });
2598
+ const gasPrice = await this.publicClient.getGasPrice();
2599
+ const estimatedCostWei = gasLimit * gasPrice;
2600
+ const estimatedCostEth = (Number(estimatedCostWei) / 1e18).toFixed(6);
2601
+ return {
2602
+ gasLimit,
2603
+ estimatedCostWei,
2604
+ estimatedCostEth
2605
+ };
2606
+ }
2607
+ catch {
2608
+ const gasLimit = 150000n;
2609
+ const gasPrice = await this.publicClient.getGasPrice();
2610
+ const estimatedCostWei = gasLimit * gasPrice;
2611
+ const estimatedCostEth = (Number(estimatedCostWei) / 1e18).toFixed(6);
2612
+ return {
2613
+ gasLimit,
2614
+ estimatedCostWei,
2615
+ estimatedCostEth
2616
+ };
2617
+ }
2618
+ }
2619
+ /**
2620
+ * Estimate gas cost for withdrawing from escrow wallet.
2621
+ *
2622
+ * @returns Gas estimation details
2623
+ *
2624
+ * @example
2625
+ * ```typescript
2626
+ * const estimate = await sdk.estimateGasForWithdraw();
2627
+ * ```
2628
+ */
2629
+ async estimateGasForWithdraw() {
2630
+ const gasLimit = 100000n; // Withdraw is typically cheaper
2631
+ const gasPrice = await this.publicClient.getGasPrice();
2632
+ const estimatedCostWei = gasLimit * gasPrice;
2633
+ const estimatedCostEth = (Number(estimatedCostWei) / 1e18).toFixed(6);
2634
+ return {
2635
+ gasLimit,
2636
+ estimatedCostWei,
2637
+ estimatedCostEth
2638
+ };
2639
+ }
2640
+ // ============================================================================
2641
+ // FEE UTILITIES
2642
+ // ============================================================================
2643
+ /**
2644
+ * Get fee receiver address (cached - rarely changes)
2645
+ * @param forceRefresh - Set to true to bypass cache and fetch fresh value
2646
+ */
2647
+ async getFeeReceiver(forceRefresh = false) {
2648
+ if (!forceRefresh && this.feeReceiverCache) {
2649
+ return this.feeReceiverCache;
2650
+ }
2651
+ this.feeReceiverCache = await this.publicClient.readContract({
2652
+ address: this.contractAddress,
2653
+ abi: this.abiEscrow,
2654
+ functionName: "feeReceiver",
2655
+ });
2656
+ return this.feeReceiverCache;
2657
+ }
2658
+ /**
2659
+ * Get fee percentage in basis points.
2660
+ * Tries to read FEE_BPS from contract, falls back to default (100 = 1%).
2661
+ * Result is cached for performance.
2662
+ */
2663
+ async getFeeBps() {
2664
+ if (this.cachedFeeBps !== null) {
2665
+ return this.cachedFeeBps;
2666
+ }
2667
+ try {
2668
+ // Try to read FEE_BPS if it's public in the contract
2669
+ const feeBps = await this.publicClient.readContract({
2670
+ address: this.contractAddress,
2671
+ abi: this.abiEscrow,
2672
+ functionName: "FEE_BPS",
2673
+ });
2674
+ this.cachedFeeBps = feeBps;
2675
+ return feeBps;
2676
+ }
2677
+ catch (e) {
2678
+ // Fall back to default if not readable (private constant)
2679
+ const message = this.extractErrorMessage(e);
2680
+ this.log('warn', 'Could not read FEE_BPS from contract, using default', {
2681
+ error: message
2682
+ });
2683
+ this.cachedFeeBps = 100n; // 1% fee
2684
+ return this.cachedFeeBps;
2685
+ }
2686
+ }
2687
+ /**
2688
+ * Calculate fee for an amount.
2689
+ * Uses the same logic as the contract's _computeFeeAndNet.
2690
+ */
2691
+ async calculateFee(amount, tokenDecimals = 6) {
2692
+ const feeBps = await this.getFeeBps();
2693
+ const minFee = 10n ** BigInt(tokenDecimals > 2 ? tokenDecimals - 2 : 0);
2694
+ const calculatedFee = (amount * feeBps) / 10000n;
2695
+ const fee = calculatedFee >= minFee ? calculatedFee : minFee;
2696
+ return { fee, net: amount - fee };
2697
+ }
2698
+ }
2699
+ exports.PalindromePaySDK = PalindromePaySDK;
2700
+ /**
2701
+ * Maximum nonce word index to prevent infinite loops.
2702
+ * 100 words = 25,600 nonces per escrow per signer.
2703
+ */
2704
+ PalindromePaySDK.MAX_NONCE_WORDS = 100n;
2705
+ // ============================================================================
2706
+ // EXPORT DEFAULT
2707
+ // ============================================================================
2708
+ exports.default = PalindromePaySDK;