@palindromepay/sdk 1.9.7 → 1.9.9

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