@zkp2p/cash 0.1.9 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { MARKET_SPREAD_BPS, ORACLE_MIN_CONVERSION_RATE_SENTINEL, CASH_RETAIN_ON_EMPTY, BASE_USDC_ADDRESS, USDC_DECIMALS, BASE_CHAIN_ID, errors, isCashError, CASH_ORDER_STATUSES, mapChainError, CashError } from './chunk-TR6JVYYF.js';
2
- export { BASE_CHAIN_ID, BASE_USDC_ADDRESS, CASH_ORDER_POLL_INTERVAL_MS, CASH_ORDER_STATUSES, CASH_RETAIN_ON_EMPTY, CashError, MARKET_SPREAD_BPS, ORACLE_MIN_CONVERSION_RATE_SENTINEL, USDC_DECIMALS, errors, isCashError } from './chunk-TR6JVYYF.js';
1
+ import { MARKET_SPREAD_BPS, ORACLE_MIN_CONVERSION_RATE_SENTINEL, CASH_RETAIN_ON_EMPTY, BASE_USDC_ADDRESS, USDC_DECIMALS, BASE_CHAIN_ID, errors, isCashError, CASH_ORDER_STATUSES, mapChainError, CashError } from './chunk-5VBP3IWK.js';
2
+ export { BASE_CHAIN_ID, BASE_USDC_ADDRESS, CASH_ORDER_POLL_INTERVAL_MS, CASH_ORDER_STATUSES, CASH_RETAIN_ON_EMPTY, CashError, MARKET_SPREAD_BPS, ORACLE_MIN_CONVERSION_RATE_SENTINEL, USDC_DECIMALS, errors, isCashError, isUserRejectedError } from './chunk-5VBP3IWK.js';
3
3
  import { parseAbi, parseEventLogs, isAddress, http, createWalletClient, encodeFunctionData } from 'viem';
4
4
  import { base } from 'viem/chains';
5
5
  import { getSpreadOracleConfig, currencyInfo, getPaymentMethodsCatalog, getGatingServiceAddress, resolvePaymentMethodHashFromCatalog, resolvePaymentMethodNameFromHash, getCurrencyCodeFromHash, createCompositeDepositId, appendAttributionToCalldata, Zkp2pClient, CHAINLINK_ORACLE_FEEDS } from '@zkp2p/sdk';
@@ -7,6 +7,12 @@ import { createClient, MAINNET_RELAY_API } from '@relayprotocol/relay-sdk';
7
7
  import { fetchChainConfigs, configureDynamicChains } from '@relayprotocol/relay-sdk/chain-utils';
8
8
  import { z } from 'zod';
9
9
 
10
+ function payoutCurrencies(payout) {
11
+ if (payout.currency === void 0 === (payout.currencies === void 0)) {
12
+ throw new Error("Pass exactly one of payout currency or currencies");
13
+ }
14
+ return payout.currencies ?? [payout.currency];
15
+ }
10
16
  function isMarketRateSupported(currency, adapters) {
11
17
  return getSpreadOracleConfig(currency, adapters) != null;
12
18
  }
@@ -38,14 +44,32 @@ async function prepareCashDepositParams(client, input, adapters) {
38
44
  const runtimeEnv = client.runtimeEnv;
39
45
  const catalog = getPaymentMethodsCatalog(chainId, runtimeEnv);
40
46
  const intentGatingService = getGatingServiceAddress(chainId, runtimeEnv);
47
+ const processorNames = payouts.map((p) => p.processorName);
48
+ const paymentMethodsOverride = processorNames.map(
49
+ (name) => resolvePaymentMethodHashFromCatalog(name, catalog)
50
+ );
41
51
  for (const payout of payouts) {
42
- if (!isMarketRateSupported(payout.currency, adapters)) {
43
- throw new Error(
44
- `${payout.currency} has no live market-rate oracle feed; Peer Cash supports market-rate currencies only.`
45
- );
52
+ const currencies = payoutCurrencies(payout);
53
+ if (currencies.length === 0 || new Set(currencies).size !== currencies.length) {
54
+ throw new Error("Payout currencies must be non-empty and unique");
55
+ }
56
+ const supportedCurrencyHashes = new Set(
57
+ (catalog[payout.processorName.toLowerCase()]?.currencies ?? []).map(
58
+ (hash) => hash.toLowerCase()
59
+ )
60
+ );
61
+ for (const currency of currencies) {
62
+ if (!isMarketRateSupported(currency, adapters)) {
63
+ throw new Error(
64
+ `${currency} has no live market-rate oracle feed; Peer Cash supports market-rate currencies only.`
65
+ );
66
+ }
67
+ const currencyHash = currencyInfo[currency]?.currencyCodeHash;
68
+ if (!currencyHash || !supportedCurrencyHashes.has(currencyHash.toLowerCase())) {
69
+ throw new Error(`${payout.processorName} does not support ${currency}`);
70
+ }
46
71
  }
47
72
  }
48
- const processorNames = payouts.map((p) => p.processorName);
49
73
  const { hashedOnchainIds } = await client.registerPayeeDetails({
50
74
  processorNames,
51
75
  payeeData: payouts.map((p) => p.payeeData)
@@ -53,22 +77,24 @@ async function prepareCashDepositParams(client, input, adapters) {
53
77
  if (hashedOnchainIds.length !== payouts.length) {
54
78
  throw new Error("Payee registration returned an unexpected number of hashes");
55
79
  }
56
- const paymentMethodsOverride = processorNames.map(
57
- (name) => resolvePaymentMethodHashFromCatalog(name, catalog)
58
- );
59
80
  const paymentMethodDataOverride = hashedOnchainIds.map((hid) => ({
60
81
  intentGatingService,
61
82
  payeeDetails: hid,
62
83
  data: "0x"
63
84
  }));
64
- const currenciesOverride = payouts.map((p) => {
65
- const tuple = buildMarketRateCurrencyOverride(p.currency, adapters);
66
- if (!tuple) throw new Error(`Failed to build market-rate config for ${p.currency}`);
67
- return [tuple];
68
- });
69
- const conversionRates = payouts.map((p) => [
70
- { currency: p.currency, conversionRate: ORACLE_MIN_CONVERSION_RATE_SENTINEL.toString() }
71
- ]);
85
+ const currenciesOverride = payouts.map(
86
+ (payout) => payoutCurrencies(payout).map((currency) => {
87
+ const tuple = buildMarketRateCurrencyOverride(currency, adapters);
88
+ if (!tuple) throw new Error(`Failed to build market-rate config for ${currency}`);
89
+ return tuple;
90
+ })
91
+ );
92
+ const conversionRates = payouts.map(
93
+ (payout) => payoutCurrencies(payout).map((currency) => ({
94
+ currency,
95
+ conversionRate: ORACLE_MIN_CONVERSION_RATE_SENTINEL.toString()
96
+ }))
97
+ );
72
98
  const intentAmountRange = input.intentAmountRange ?? buildIntentAmountRange(input.amount);
73
99
  return {
74
100
  token: input.token ?? BASE_USDC_ADDRESS,
@@ -287,35 +313,41 @@ function toPricing(tuple) {
287
313
  };
288
314
  }
289
315
  function derivePayouts(paymentMethods, currencies, catalog) {
290
- return paymentMethods.flatMap((method) => {
316
+ const payouts = [];
317
+ for (const method of paymentMethods) {
291
318
  const platformHash = method.paymentMethodHash ?? "";
292
319
  if (!platformHash) return [];
293
320
  let platform;
294
321
  try {
295
322
  platform = resolvePaymentMethodNameFromHash(platformHash, catalog);
296
323
  } catch {
297
- platform = void 0;
324
+ return [];
298
325
  }
326
+ if (!platform) return [];
299
327
  const tuples = currencies.filter(
300
328
  (c) => (c.paymentMethodHash ?? "").toLowerCase() === platformHash.toLowerCase()
301
329
  );
302
330
  const base2 = {
303
- ...platform !== void 0 ? { platform } : {},
331
+ platform,
304
332
  platformHash,
305
333
  payeeHash: method.payeeDetailsHash ?? "",
306
334
  active: method.active ?? true
307
335
  };
308
- if (tuples.length === 0) return [{ ...base2, pricing: toPricing(void 0) }];
309
- return tuples.map((tuple) => {
336
+ if (tuples.length === 0) {
337
+ payouts.push({ ...base2, pricing: toPricing(void 0) });
338
+ continue;
339
+ }
340
+ for (const tuple of tuples) {
310
341
  const currency = tuple.currencyCode != null ? getCurrencyCodeFromHash(tuple.currencyCode) : void 0;
311
- return {
342
+ payouts.push({
312
343
  ...base2,
313
344
  ...currency !== void 0 ? { currency } : {},
314
345
  ...tuple.currencyCode != null ? { currencyHash: tuple.currencyCode } : {},
315
346
  pricing: toPricing(tuple)
316
- };
317
- });
318
- });
347
+ });
348
+ }
349
+ }
350
+ return payouts;
319
351
  }
320
352
 
321
353
  // src/engine/buyerProfile.ts
@@ -359,21 +391,33 @@ function resolveCashDepositId(params) {
359
391
  events = parseEventLogs({
360
392
  abi: params.abi,
361
393
  eventName: "DepositReceived",
362
- logs: params.logs
394
+ logs: [...params.logs]
363
395
  });
364
396
  } catch {
365
397
  return null;
366
398
  }
367
- const event = events[0];
368
- if (!event) return null;
399
+ const matchingEvents = events.filter((event2) => {
400
+ if (params.expectedEscrowAddress !== void 0 && event2.address.toLowerCase() !== params.expectedEscrowAddress.toLowerCase()) {
401
+ return false;
402
+ }
403
+ if (params.expectedToken !== void 0 && String(event2.args.token ?? "").toLowerCase() !== params.expectedToken.toLowerCase()) {
404
+ return false;
405
+ }
406
+ return true;
407
+ });
408
+ if (matchingEvents.length !== 1) return null;
409
+ const event = matchingEvents[0];
369
410
  const rawId = event.args.depositId;
370
411
  if (rawId === void 0 || rawId === null) return null;
371
412
  const onchainDepositId = BigInt(rawId);
413
+ const rawAmount = event.args.amount;
414
+ const amount = rawAmount === void 0 || rawAmount === null ? void 0 : BigInt(rawAmount);
372
415
  const escrowAddress = event.address.toLowerCase();
373
416
  return {
374
417
  onchainDepositId,
375
418
  escrowAddress,
376
- compositeId: createCompositeDepositId(escrowAddress, onchainDepositId)
419
+ compositeId: createCompositeDepositId(escrowAddress, onchainDepositId),
420
+ ...amount === void 0 ? {} : { amount }
377
421
  };
378
422
  }
379
423
  function parseCompositeDepositId(compositeId) {
@@ -387,26 +431,6 @@ function parseCompositeDepositId(compositeId) {
387
431
  const onchainDepositId = BigInt(rawDepositId);
388
432
  return { escrowAddress: canonicalEscrowAddress, onchainDepositId };
389
433
  }
390
-
391
- // src/client/platformGroups.ts
392
- var PLATFORM_METHOD_GROUPS = {
393
- zelle: ["zelle", "zelle-chase", "zelle-bofa", "zelle-citi"]
394
- };
395
- var METHOD_TO_BASE_PLATFORM = new Map(
396
- Object.entries(PLATFORM_METHOD_GROUPS).flatMap(
397
- ([platform, methods]) => methods.map((method) => [method, platform])
398
- )
399
- );
400
- function basePlatformForMethod(method) {
401
- return METHOD_TO_BASE_PLATFORM.get(method) ?? method;
402
- }
403
- function paymentMethodsForPlatform(platform, catalog) {
404
- const configured = PLATFORM_METHOD_GROUPS[platform];
405
- const methods = configured ?? [platform];
406
- return methods.filter((method) => catalog[method] !== void 0);
407
- }
408
-
409
- // src/client/capabilities.ts
410
434
  var MIN_CASHOUT_AMOUNT = 10000n;
411
435
  var RECOMMENDED_MIN_CASHOUT_AMOUNT = 1000000n;
412
436
  var PAYEE_HINTS = {
@@ -425,20 +449,13 @@ var PAYEE_HINTS = {
425
449
  var IDENTITY_ATTESTATION_PLATFORMS = /* @__PURE__ */ new Set(["wise", "paypal"]);
426
450
  function buildCapabilities(environment) {
427
451
  const catalog = getPaymentMethodsCatalog(BASE_CHAIN_ID, environment);
428
- const currenciesByPlatform = /* @__PURE__ */ new Map();
429
- for (const [method, entry] of Object.entries(catalog)) {
430
- const platform = basePlatformForMethod(method);
452
+ const platforms = Object.entries(catalog).map(([platform, entry]) => {
431
453
  const currencies2 = (entry.currencies ?? []).map((hash) => getCurrencyCodeFromHash(hash)).filter(
432
454
  (code) => code != null && isMarketRateSupported(code)
433
455
  );
434
- const aggregate = currenciesByPlatform.get(platform) ?? /* @__PURE__ */ new Set();
435
- for (const currency of currencies2) aggregate.add(currency);
436
- currenciesByPlatform.set(platform, aggregate);
437
- }
438
- const platforms = [...currenciesByPlatform.entries()].map(([platform, currencies2]) => {
439
456
  return {
440
457
  platform,
441
- currencies: [...currencies2].sort(),
458
+ currencies: [...new Set(currencies2)].sort(),
442
459
  payeeHint: PAYEE_HINTS[platform] ?? "Your payment handle for this platform",
443
460
  requiresIdentityAttestation: IDENTITY_ATTESTATION_PLATFORMS.has(platform)
444
461
  };
@@ -517,7 +534,7 @@ function computeFillStatsSample(deposits, nowSeconds, environment) {
517
534
  }
518
535
  const currency = normalizeCurrencyCode(intent.fiatCurrency);
519
536
  if (!method || !currency) continue;
520
- const pair = `${basePlatformForMethod(method)}:${currency}`;
537
+ const pair = `${method}:${currency}`;
521
538
  fillCounts.set(pair, (fillCounts.get(pair) ?? 0) + 1);
522
539
  if (createdAt === void 0 || createdAt < windowStart || fulfilledAt < createdAt) continue;
523
540
  const previousPairFill = firstFillByPair.get(pair);
@@ -582,7 +599,7 @@ async function readFillStatsSample(client, environment) {
582
599
  }
583
600
  function fillEtaFromSample(sample, input) {
584
601
  const currency = input.currency.toUpperCase();
585
- const seconds = input.platform ? sample.stats[`${basePlatformForMethod(input.platform)}:${currency}`]?.medianFillSeconds : sample.medianFillSecondsByCurrency.get(currency);
602
+ const seconds = input.platform ? sample.stats[`${input.platform}:${currency}`]?.medianFillSeconds : sample.medianFillSecondsByCurrency.get(currency);
586
603
  return {
587
604
  ...seconds !== void 0 ? { seconds } : {},
588
605
  label: etaLabel(seconds)
@@ -1145,6 +1162,36 @@ async function readEstimate(publicClient, input, context = {}) {
1145
1162
  return estimate;
1146
1163
  }
1147
1164
 
1165
+ // src/client/payee.ts
1166
+ function normalizePaypalHandle(value) {
1167
+ const withoutProtocol = value.replace(/^https?:\/\//i, "").replace(/^www\./i, "");
1168
+ if (/^paypal\.me(?:[?#].*)?$/i.test(withoutProtocol)) return "";
1169
+ const withoutDomain = withoutProtocol.replace(/^paypal\.me\//i, "");
1170
+ const [pathWithoutQuery = ""] = withoutDomain.split(/[?#]/, 1);
1171
+ const [username = ""] = pathWithoutQuery.replace(/^\/+/, "").split("/", 1);
1172
+ return username.replace(/^@+/, "").trim().toLowerCase();
1173
+ }
1174
+ function normalizeCashPayee(platform, payee) {
1175
+ if (typeof payee !== "string") return payee;
1176
+ const trimmed = payee.trim();
1177
+ switch (platform) {
1178
+ case "venmo":
1179
+ return { offchainId: trimmed.replace(/^@+/, "") };
1180
+ case "cashapp":
1181
+ return { offchainId: trimmed.replace(/^\$+/, "") };
1182
+ case "chime":
1183
+ return { offchainId: trimmed.toLowerCase() };
1184
+ case "n26":
1185
+ return { offchainId: trimmed.replace(/\s/g, "") };
1186
+ case "paypal":
1187
+ return { offchainId: normalizePaypalHandle(trimmed) };
1188
+ case "zelle":
1189
+ return { offchainId: trimmed.toLowerCase() };
1190
+ default:
1191
+ return { offchainId: trimmed };
1192
+ }
1193
+ }
1194
+
1148
1195
  // src/client/createCashClient.ts
1149
1196
  var DEFAULT_RPC_URL = "https://mainnet.base.org";
1150
1197
  var FILL_STATS_CACHE_MS = 15 * 60 * 1e3;
@@ -1186,7 +1233,7 @@ async function submitAndConfirm(client, verb, send) {
1186
1233
  hash = await send();
1187
1234
  } catch (err) {
1188
1235
  const mapped = mapChainError(verb, err);
1189
- if (isKnownPreBroadcastFailure(err, mapped)) throw mapped;
1236
+ if (isKnownPreBroadcastFailure(mapped)) throw mapped;
1190
1237
  throw errors.transactionSubmissionUnknown(verb, err, {
1191
1238
  kind: "inspect-base-operation-submission",
1192
1239
  operation: verb
@@ -1201,12 +1248,8 @@ async function submitAndConfirm(client, verb, send) {
1201
1248
  if (receipt.status === "reverted") throw errors.transactionFailed(hash);
1202
1249
  return hash;
1203
1250
  }
1204
- function isKnownPreBroadcastFailure(err, mapped) {
1205
- if (mapped.code === "INSUFFICIENT_TOKEN_BALANCE" || mapped.code === "ALLOWANCE_NOT_VISIBLE" || mapped.code === "ESCROW_PAUSED") {
1206
- return true;
1207
- }
1208
- const message = err instanceof Error ? err.message : String(err);
1209
- return /user rejected|user denied|rejected request|action_rejected/i.test(message);
1251
+ function isKnownPreBroadcastFailure(mapped) {
1252
+ return mapped.code === "TRANSACTION_REJECTED" || mapped.code === "INSUFFICIENT_TOKEN_BALANCE" || mapped.code === "ALLOWANCE_NOT_VISIBLE" || mapped.code === "ESCROW_PAUSED";
1210
1253
  }
1211
1254
  function depositOrderOptions(deposit) {
1212
1255
  const remaining = toBigIntOrUndefined(deposit.remainingDeposits);
@@ -1279,24 +1322,39 @@ function createCashClient(options) {
1279
1322
  }
1280
1323
  function validatePayout(input) {
1281
1324
  const { receive } = input;
1282
- const catalog = getPaymentMethodsCatalog(BASE_CHAIN_ID, environment);
1283
1325
  const platform = buildCapabilities(environment).platforms.find(
1284
1326
  (capability) => capability.platform === receive.platform
1285
1327
  );
1286
1328
  if (!platform) throw errors.unsupportedPlatform(receive.platform);
1287
- if (!isMarketRateSupported(receive.currency)) {
1288
- throw errors.oracleUnsupportedCurrency(receive.currency);
1329
+ if (receive.currency === void 0 === (receive.currencies === void 0)) {
1330
+ throw errors.invalidPayoutCurrencies(
1331
+ receive.platform,
1332
+ "pass exactly one of currency or currencies"
1333
+ );
1289
1334
  }
1290
- if (!platform.currencies.includes(receive.currency)) {
1291
- throw errors.unsupportedPlatformCurrency(receive.platform, receive.currency);
1335
+ const currencies = receive.currencies !== void 0 ? [...receive.currencies] : [receive.currency];
1336
+ if (currencies.length === 0) {
1337
+ throw errors.invalidPayoutCurrencies(receive.platform, "at least one currency is required");
1338
+ }
1339
+ if (new Set(currencies).size !== currencies.length) {
1340
+ throw errors.invalidPayoutCurrencies(receive.platform, "currencies must be unique");
1341
+ }
1342
+ for (const currency of currencies) {
1343
+ if (!isMarketRateSupported(currency)) {
1344
+ throw errors.oracleUnsupportedCurrency(currency);
1345
+ }
1346
+ if (!platform.currencies.includes(currency)) {
1347
+ throw errors.unsupportedPlatformCurrency(receive.platform, currency);
1348
+ }
1292
1349
  }
1293
- const paymentMethods = paymentMethodsForPlatform(receive.platform, catalog);
1294
1350
  return {
1295
- payouts: paymentMethods.map((processorName) => ({
1296
- processorName,
1297
- currency: receive.currency,
1298
- payeeData: receive.payee
1299
- }))
1351
+ payouts: [
1352
+ {
1353
+ processorName: receive.platform,
1354
+ ...currencies.length === 1 ? { currency: currencies[0] } : { currencies },
1355
+ payeeData: normalizeCashPayee(receive.platform, receive.payee)
1356
+ }
1357
+ ]
1300
1358
  };
1301
1359
  }
1302
1360
  function validateDepositInput(amount, input, payoutInput = validatePayout(input)) {
@@ -1313,6 +1371,14 @@ function createCashClient(options) {
1313
1371
  ...range ? { intentAmountRange: range } : {}
1314
1372
  };
1315
1373
  }
1374
+ function isCashPayoutSet(payouts) {
1375
+ const first = payouts[0];
1376
+ return Boolean(
1377
+ first && payouts.every(
1378
+ (payout) => payout.platformHash.toLowerCase() === first.platformHash.toLowerCase() && payout.payeeHash.toLowerCase() === first.payeeHash.toLowerCase() && payout.pricing.marketRate && payout.pricing.spreadBps === 0
1379
+ )
1380
+ );
1381
+ }
1316
1382
  async function buildDepositParams(client, depositInput) {
1317
1383
  try {
1318
1384
  return await prepareCashDepositParams(client, depositInput);
@@ -1367,9 +1433,10 @@ function createCashClient(options) {
1367
1433
  deposit.currencies ?? [],
1368
1434
  getPaymentMethodsCatalog(BASE_CHAIN_ID, environment)
1369
1435
  );
1436
+ if (!isCashPayoutSet(payouts)) throw errors.orderNotFound(compositeId);
1370
1437
  return deriveCashOrder(compositeId, deposit.intents ?? [], {
1371
1438
  ...depositOrderOptions(deposit),
1372
- ...payouts.length > 0 ? { payouts } : {}
1439
+ payouts
1373
1440
  });
1374
1441
  }
1375
1442
  function escrowContext(depositId) {
@@ -1583,9 +1650,9 @@ function createCashClient(options) {
1583
1650
  }
1584
1651
  },
1585
1652
  async cashout(input, opts) {
1653
+ const payoutInput = validatePayout(input);
1586
1654
  const client = await signingClient("cashout", opts);
1587
1655
  const owner = opts.signer.account.address;
1588
- const payoutInput = validatePayout(input);
1589
1656
  let sourceResult;
1590
1657
  let cashoutAmount = input.amount;
1591
1658
  if (input.source) {
@@ -1661,7 +1728,7 @@ function createCashClient(options) {
1661
1728
  const mapped = mapChainError("createDeposit", err, {
1662
1729
  requiredAmount: depositInput2.amount
1663
1730
  });
1664
- if (isKnownPreBroadcastFailure(err, mapped)) {
1731
+ if (isKnownPreBroadcastFailure(mapped)) {
1665
1732
  throw errors.sourceRouteCompletedCashoutFailed(routedSource, mapped);
1666
1733
  }
1667
1734
  throw errors.sourceCashoutSubmissionUnknown(routedSource, owner, mapped);
@@ -1717,7 +1784,7 @@ function createCashClient(options) {
1717
1784
  const mapped = mapChainError("createDeposit", err, {
1718
1785
  requiredAmount: depositInput.amount
1719
1786
  });
1720
- if (isKnownPreBroadcastFailure(err, mapped)) throw mapped;
1787
+ if (isKnownPreBroadcastFailure(mapped)) throw mapped;
1721
1788
  throw errors.transactionSubmissionUnknown("cashout", err, {
1722
1789
  kind: "inspect-base-cashout-submission",
1723
1790
  amount: depositInput.amount.toString(),
@@ -1785,6 +1852,32 @@ function createCashClient(options) {
1785
1852
  register: { hashedOnchainIds }
1786
1853
  };
1787
1854
  },
1855
+ finalizePreparedCashout(receipt) {
1856
+ if (receipt.status === "reverted") {
1857
+ throw errors.transactionFailed(receipt.transactionHash);
1858
+ }
1859
+ const abi = readClient.escrowV2Abi ?? readClient.escrowAbi;
1860
+ const expectedEscrowAddress = readClient.escrowV2Address ?? readClient.escrowAddress;
1861
+ const resolved = resolveCashDepositId({
1862
+ logs: receipt.logs,
1863
+ abi,
1864
+ expectedEscrowAddress,
1865
+ expectedToken: BASE_USDC_ADDRESS
1866
+ });
1867
+ if (!resolved || resolved.amount === void 0) {
1868
+ throw errors.depositResolutionFailed(receipt.transactionHash);
1869
+ }
1870
+ return {
1871
+ depositId: resolved.compositeId,
1872
+ txHash: receipt.transactionHash,
1873
+ escrowAddress: resolved.escrowAddress,
1874
+ onchainDepositId: resolved.onchainDepositId,
1875
+ order: deriveCashOrder(resolved.compositeId, [], {
1876
+ remainingAmount: resolved.amount,
1877
+ status: "ACTIVE"
1878
+ })
1879
+ };
1880
+ },
1788
1881
  async order(depositId) {
1789
1882
  return fetchOrder(depositId);
1790
1883
  },
@@ -1816,7 +1909,7 @@ function createCashClient(options) {
1816
1909
  deposit.currencies ?? [],
1817
1910
  catalog
1818
1911
  );
1819
- if (payouts.length !== 1 || !payouts.every((payout) => payout.pricing.marketRate && payout.pricing.spreadBps === 0)) {
1912
+ if (!isCashPayoutSet(payouts)) {
1820
1913
  return [];
1821
1914
  }
1822
1915
  return [
@@ -2085,7 +2178,7 @@ var cashPayoutPricingJsonSchema = z.object({
2085
2178
  marketRate: z.boolean()
2086
2179
  });
2087
2180
  var cashPayoutInfoJsonSchema = z.object({
2088
- platform: z.string().optional(),
2181
+ platform: z.string(),
2089
2182
  platformHash: z.string(),
2090
2183
  currency: z.string().optional(),
2091
2184
  currencyHash: z.string().optional(),
@@ -2301,6 +2394,7 @@ var CASH_ERROR_CODES = defineCashErrorCodes([
2301
2394
  "UNSUPPORTED_PLATFORM_CURRENCY",
2302
2395
  "AMOUNT_BELOW_MINIMUM",
2303
2396
  "INVALID_INTENT_AMOUNT_RANGE",
2397
+ "INVALID_PAYOUT_CURRENCIES",
2304
2398
  "ACTIVE_INTENT_BLOCKS_WITHDRAWAL",
2305
2399
  "NOTHING_TO_WITHDRAW",
2306
2400
  "INSUFFICIENT_AVAILABLE_FUNDS",
@@ -2329,6 +2423,7 @@ var CASH_ERROR_CODES = defineCashErrorCodes([
2329
2423
  "SIGNER_CHAIN_MISMATCH",
2330
2424
  "SIGNER_CHAIN_UNAVAILABLE",
2331
2425
  "WATCH_TIMEOUT",
2426
+ "TRANSACTION_REJECTED",
2332
2427
  "TRANSACTION_FAILED",
2333
2428
  "TRANSACTION_SUBMISSION_UNKNOWN",
2334
2429
  "TRANSACTION_STATUS_UNKNOWN"
@@ -2782,4 +2877,4 @@ function cashErrorFromJson(json) {
2782
2877
  });
2783
2878
  }
2784
2879
 
2785
- export { CASH_ATTRIBUTION_CODE, MIN_CASHOUT_AMOUNT, RATE_PRECISION, RECOMMENDED_MIN_CASHOUT_AMOUNT, bigintString, buildCapabilities, buildIntentAmountRange, buildMarketRateCurrencyOverride, buyerProfileFromJson, buyerProfileToJson, capabilitiesFromJson, capabilitiesToJson, cashAssetJsonSchema, cashBuyerProfileJsonSchema, cashCapabilitiesJsonSchema, cashChainJsonSchema, cashErrorFromJson, cashErrorJsonSchema, cashErrorRecoveryJsonSchema, cashErrorToJson, cashEstimateJsonSchema, cashFillJsonSchema, cashFillStatsJsonSchema, cashNextActionSchema, cashOrderJsonSchema, cashOrderStateSchema, cashPairFillStatsJsonSchema, cashPayoutInfoJsonSchema, cashPayoutPricingJsonSchema, cashPreparedStepJsonSchema, cashSourceCapabilitiesJsonSchema, cashoutResultFromJson, cashoutResultJsonSchema, cashoutResultToJson, centsToNumber, createCashClient, deriveBuyerProfile, deriveCashOrder, derivePayouts, estimateFromJson, estimateToJson, explainOrder, fiatFromUsdc, fiatToNumber, fillFromJson, fillStatsFromJson, fillStatsToJson, fillToJson, formatUsdc, intentStatusSchema, isFillLive, isMarketRateSupported, nonNegativeBigintString, orderFromJson, orderToJson, parseCompositeDepositId, prepareCashDepositParams, prepareResultFromJson, prepareResultJsonSchema, prepareResultToJson, preparedStepFromJson, preparedStepToJson, preparedTransactionJsonSchema, preparedTxFromJson, preparedTxToJson, rateToNumber, relayExecutionResultFromJson, relayExecutionResultJsonSchema, relayExecutionResultToJson, relayQuoteFromJson, relayQuoteJsonSchema, relayQuoteToJson, relayStatusFromJson, relayStatusJsonSchema, relayStatusToJson, relayTransactionJsonSchema, relayTransactionsJsonSchema, resolveCashDepositId, sourceCapabilitiesFromJson, sourceCapabilitiesToJson, topUpResultFromJson, topUpResultJsonSchema, topUpResultToJson, usdc, withExplain, withdrawResultFromJson, withdrawResultJsonSchema, withdrawResultToJson };
2880
+ export { CASH_ATTRIBUTION_CODE, MIN_CASHOUT_AMOUNT, RATE_PRECISION, RECOMMENDED_MIN_CASHOUT_AMOUNT, bigintString, buildCapabilities, buildIntentAmountRange, buildMarketRateCurrencyOverride, buyerProfileFromJson, buyerProfileToJson, capabilitiesFromJson, capabilitiesToJson, cashAssetJsonSchema, cashBuyerProfileJsonSchema, cashCapabilitiesJsonSchema, cashChainJsonSchema, cashErrorFromJson, cashErrorJsonSchema, cashErrorRecoveryJsonSchema, cashErrorToJson, cashEstimateJsonSchema, cashFillJsonSchema, cashFillStatsJsonSchema, cashNextActionSchema, cashOrderJsonSchema, cashOrderStateSchema, cashPairFillStatsJsonSchema, cashPayoutInfoJsonSchema, cashPayoutPricingJsonSchema, cashPreparedStepJsonSchema, cashSourceCapabilitiesJsonSchema, cashoutResultFromJson, cashoutResultJsonSchema, cashoutResultToJson, centsToNumber, createCashClient, deriveBuyerProfile, deriveCashOrder, derivePayouts, estimateFromJson, estimateToJson, explainOrder, fiatFromUsdc, fiatToNumber, fillFromJson, fillStatsFromJson, fillStatsToJson, fillToJson, formatUsdc, intentStatusSchema, isFillLive, isMarketRateSupported, nonNegativeBigintString, normalizeCashPayee, orderFromJson, orderToJson, parseCompositeDepositId, prepareCashDepositParams, prepareResultFromJson, prepareResultJsonSchema, prepareResultToJson, preparedStepFromJson, preparedStepToJson, preparedTransactionJsonSchema, preparedTxFromJson, preparedTxToJson, rateToNumber, relayExecutionResultFromJson, relayExecutionResultJsonSchema, relayExecutionResultToJson, relayQuoteFromJson, relayQuoteJsonSchema, relayQuoteToJson, relayStatusFromJson, relayStatusJsonSchema, relayStatusToJson, relayTransactionJsonSchema, relayTransactionsJsonSchema, resolveCashDepositId, sourceCapabilitiesFromJson, sourceCapabilitiesToJson, topUpResultFromJson, topUpResultJsonSchema, topUpResultToJson, usdc, withExplain, withdrawResultFromJson, withdrawResultJsonSchema, withdrawResultToJson };
package/dist/react.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { CurrencyType } from '@zkp2p/sdk';
2
- import { r as CashClient, G as EstimateInput, i as CashEstimate, E as CashoutOptions, h as CashoutResult, D as CashoutInput, T as TopUpResult, W as WithdrawResult, e as CashOrder } from './createCashClient-BhOytyHE.cjs';
2
+ import { r as CashClient, J as EstimateInput, i as CashEstimate, G as CashoutOptions, h as CashoutResult, F as CashoutInput, T as TopUpResult, W as WithdrawResult, e as CashOrder } from './createCashClient-Clg5Fa1H.cjs';
3
3
  import { WalletClient } from 'viem';
4
4
  import '@relayprotocol/relay-sdk';
5
5
 
package/dist/react.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { CurrencyType } from '@zkp2p/sdk';
2
- import { r as CashClient, G as EstimateInput, i as CashEstimate, E as CashoutOptions, h as CashoutResult, D as CashoutInput, T as TopUpResult, W as WithdrawResult, e as CashOrder } from './createCashClient-BhOytyHE.js';
2
+ import { r as CashClient, J as EstimateInput, i as CashEstimate, G as CashoutOptions, h as CashoutResult, F as CashoutInput, T as TopUpResult, W as WithdrawResult, e as CashOrder } from './createCashClient-Clg5Fa1H.js';
3
3
  import { WalletClient } from 'viem';
4
4
  import '@relayprotocol/relay-sdk';
5
5
 
package/dist/react.js CHANGED
@@ -1,4 +1,4 @@
1
- import { isCashError, CASH_ORDER_POLL_INTERVAL_MS } from './chunk-TR6JVYYF.js';
1
+ import { isCashError, CASH_ORDER_POLL_INTERVAL_MS } from './chunk-5VBP3IWK.js';
2
2
  import { useState, useRef, useCallback, useEffect, useMemo } from 'react';
3
3
 
4
4
  function useEstimate({
package/dist/tools.cjs CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  // package.json
4
4
  var package_default = {
5
- version: "0.1.9"};
5
+ version: "0.2.1"};
6
6
 
7
7
  // src/tools/index.ts
8
8
  var bigintString = {
@@ -137,20 +137,36 @@ var builtInCashTools = [
137
137
  description: 'Platform id from cash_capabilities, e.g. "venmo"'
138
138
  },
139
139
  currency: { type: "string", description: 'Fiat currency code, e.g. "USD"' },
140
+ currencies: {
141
+ type: "array",
142
+ minItems: 1,
143
+ uniqueItems: true,
144
+ items: { type: "string" },
145
+ description: 'Fiat currency choices for one payment method, e.g. ["EUR", "GBP"]'
146
+ },
140
147
  payee: {
141
- type: "object",
142
- description: "Payee handle for the platform",
143
- properties: {
144
- offchainId: {
148
+ description: "Raw payee handle or structured curator payee data",
149
+ oneOf: [
150
+ {
145
151
  type: "string",
146
- description: 'The handle, e.g. "@andrew" for Venmo - see payeeHint in cash_capabilities'
152
+ description: 'User-entered handle, e.g. "@andrew" for Venmo; Peer Cash normalizes it for the selected platform'
153
+ },
154
+ {
155
+ type: "object",
156
+ properties: {
157
+ offchainId: {
158
+ type: "string",
159
+ description: "Already-normalized handle for the platform"
160
+ }
161
+ },
162
+ required: ["offchainId"],
163
+ additionalProperties: true
147
164
  }
148
- },
149
- required: ["offchainId"],
150
- additionalProperties: true
165
+ ]
151
166
  }
152
167
  },
153
- required: ["platform", "currency", "payee"],
168
+ required: ["platform", "payee"],
169
+ oneOf: [{ required: ["currency"] }, { required: ["currencies"] }],
154
170
  additionalProperties: false
155
171
  }
156
172
  },
package/dist/tools.d.cts CHANGED
@@ -166,20 +166,39 @@ declare const builtInCashTools: readonly [{
166
166
  readonly type: "string";
167
167
  readonly description: "Fiat currency code, e.g. \"USD\"";
168
168
  };
169
+ readonly currencies: {
170
+ readonly type: "array";
171
+ readonly minItems: 1;
172
+ readonly uniqueItems: true;
173
+ readonly items: {
174
+ readonly type: "string";
175
+ };
176
+ readonly description: "Fiat currency choices for one payment method, e.g. [\"EUR\", \"GBP\"]";
177
+ };
169
178
  readonly payee: {
170
- readonly type: "object";
171
- readonly description: "Payee handle for the platform";
172
- readonly properties: {
173
- readonly offchainId: {
174
- readonly type: "string";
175
- readonly description: "The handle, e.g. \"@andrew\" for Venmo - see payeeHint in cash_capabilities";
179
+ readonly description: "Raw payee handle or structured curator payee data";
180
+ readonly oneOf: readonly [{
181
+ readonly type: "string";
182
+ readonly description: "User-entered handle, e.g. \"@andrew\" for Venmo; Peer Cash normalizes it for the selected platform";
183
+ }, {
184
+ readonly type: "object";
185
+ readonly properties: {
186
+ readonly offchainId: {
187
+ readonly type: "string";
188
+ readonly description: "Already-normalized handle for the platform";
189
+ };
176
190
  };
177
- };
178
- readonly required: readonly ["offchainId"];
179
- readonly additionalProperties: true;
191
+ readonly required: readonly ["offchainId"];
192
+ readonly additionalProperties: true;
193
+ }];
180
194
  };
181
195
  };
182
- readonly required: readonly ["platform", "currency", "payee"];
196
+ readonly required: readonly ["platform", "payee"];
197
+ readonly oneOf: readonly [{
198
+ readonly required: readonly ["currency"];
199
+ }, {
200
+ readonly required: readonly ["currencies"];
201
+ }];
183
202
  readonly additionalProperties: false;
184
203
  };
185
204
  };