@owney/sdk 0.7.37 → 0.8.0-beta.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.cjs CHANGED
@@ -211,7 +211,7 @@ var P_SUPPORTED_CHAINS = {
211
211
  chainIds: [8453, 42161, 1],
212
212
  chains: ["BASE", "ARBITRUM", "ETHEREUM"]
213
213
  };
214
- var SUPPORTED_TOKENS = ["USDC", "WETH"];
214
+ var SUPPORTED_TOKENS = ["USDC", "WETH", "EURC", "USDT"];
215
215
  var SUPPORTED_CHAIN_IDS = P_SUPPORTED_CHAINS.chainIds;
216
216
  var SUPPORTED_CHAINS = P_SUPPORTED_CHAINS.chains;
217
217
  var SupportedAssets = [
@@ -250,8 +250,31 @@ var SupportedAssets = [
250
250
  symbol: "WETH",
251
251
  chainId: 1,
252
252
  decimals: 18
253
+ },
254
+ {
255
+ address: `0x1aBaEA1f7C830bD89Acc67eC4af516284b1bC33c`,
256
+ symbol: "EURC",
257
+ chainId: 1,
258
+ decimals: 6
259
+ },
260
+ {
261
+ address: `0x60a3E35Cc302bFA44Cb288Bc5a4F316Fdb1adb42`,
262
+ symbol: "EURC",
263
+ chainId: 8453,
264
+ decimals: 6
265
+ },
266
+ {
267
+ address: `0xdAC17F958D2ee523a2206206994597C13D831ec7`,
268
+ symbol: "USDT",
269
+ chainId: 1,
270
+ decimals: 6
253
271
  }
254
272
  ];
273
+ function tokenAddress(symbol, chainId) {
274
+ return SupportedAssets.find(
275
+ (a) => a.symbol === symbol && a.chainId === chainId
276
+ )?.address;
277
+ }
255
278
 
256
279
  // src/lib/debug.ts
257
280
  var configuredDebug = false;
@@ -316,6 +339,8 @@ function matchesAsset(symbol, asset) {
316
339
  // src/agents/zyfai/zyfai.mapper.ts
317
340
  var DECIMALS_BY_SYMBOL = {
318
341
  usdc: 6,
342
+ eurc: 6,
343
+ usdt: 6,
319
344
  weth: 18,
320
345
  eth: 18,
321
346
  cbeth: 18,
@@ -512,7 +537,7 @@ function netApy(net, gross, field) {
512
537
  }
513
538
  function usdPerUnit(tokenSymbol, prices) {
514
539
  const symbol = tokenSymbol?.toUpperCase();
515
- if (symbol === "USDC") return 1;
540
+ if (symbol === "USDC" || symbol === "USDT") return 1;
516
541
  const price = symbol ? prices?.[symbol] : void 0;
517
542
  return typeof price === "number" && Number.isFinite(price) && price > 0 ? price : void 0;
518
543
  }
@@ -917,7 +942,7 @@ var isJwtExpired = (token) => {
917
942
  }
918
943
  };
919
944
  var memorySessions = /* @__PURE__ */ new Map();
920
- var isFreshSession = (session) => typeof session === "object" && session !== null && typeof session.isPredeployed === "boolean" && !!session.token && !isJwtExpired(session.token);
945
+ var isFreshSession = (session) => !!session && typeof session.isPredeployed === "boolean" && !!session.token && !isJwtExpired(session.token);
921
946
  var readLegacySession = (store, address) => {
922
947
  if (!store) return null;
923
948
  const prefix = legacyKeyPrefix(address);
@@ -999,17 +1024,6 @@ var clearSession = (address, _chainId) => {
999
1024
  }
1000
1025
  readLegacySession(store, address);
1001
1026
  };
1002
- var BrowserSessionStore = class {
1003
- read(_agentId, address) {
1004
- return readSession(address, 0);
1005
- }
1006
- write(_agentId, address, session) {
1007
- writeSession(address, 0, session);
1008
- }
1009
- clear(_agentId, address) {
1010
- clearSession(address, 0);
1011
- }
1012
- };
1013
1027
 
1014
1028
  // src/agents/zyfai/autoSelect.ts
1015
1029
  function buildAutoSelectUpdate(current, asset, chainId) {
@@ -1222,6 +1236,7 @@ var CHAINLINK_ETH_USD_FEED = {
1222
1236
  42161: "0x639Fe6ab55C921f74e7fac1ee960C0B6293ba612",
1223
1237
  1: "0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419"
1224
1238
  };
1239
+ var CHAINLINK_EUR_USD_FEED = "0xb49f677943BC038e9857d61E7d053CaA2C1734C1";
1225
1240
  var CHAINLINK_ABI = (0, import_viem.parseAbi)([
1226
1241
  "function latestRoundData() view returns (uint80, int256, uint256, uint256, uint80)"
1227
1242
  ]);
@@ -1231,13 +1246,8 @@ var DEFAULT_ZYFAI_RPC_URLS = {
1231
1246
  42161: "https://arb-mainnet.g.alchemy.com/v2/ZWyVU-9XfS3z8Rn-xkq7V",
1232
1247
  1: "https://eth-mainnet.g.alchemy.com/v2/ZWyVU-9XfS3z8Rn-xkq7V"
1233
1248
  };
1234
- var WETH_ADDRESS_BY_CHAIN = {
1235
- 8453: "0x4200000000000000000000000000000000000006",
1236
- 42161: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
1237
- 1: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
1238
- };
1239
1249
  var VIEM_CHAIN = { 8453: import_chains.base, 42161: import_chains.arbitrum, 1: import_chains.mainnet };
1240
- var SPLITTING_ASSETS = ["USDC", "WETH"];
1250
+ var SPLITTING_ASSETS = SUPPORTED_TOKENS;
1241
1251
  var POOL_POLICY_CHAIN_IDS = [8453, 42161, 1];
1242
1252
  var EARNINGS_REFRESH_COOLDOWN_MS = 60 * 60 * 1e3;
1243
1253
  var ZyfaiAgent = class _ZyfaiAgent {
@@ -1249,7 +1259,8 @@ var ZyfaiAgent = class _ZyfaiAgent {
1249
1259
  chain: "BASE",
1250
1260
  assets: [
1251
1261
  { symbol: "USDC", minDepositAmount: "1500000" },
1252
- { symbol: "WETH", minDepositAmount: "500000000000000" }
1262
+ { symbol: "WETH", minDepositAmount: "500000000000000" },
1263
+ { symbol: "EURC", minDepositAmount: "1500000" }
1253
1264
  ]
1254
1265
  },
1255
1266
  {
@@ -1270,7 +1281,12 @@ var ZyfaiAgent = class _ZyfaiAgent {
1270
1281
  // the shipped code enforces 0.005 WETH, so match it or deposits reject on-chain.
1271
1282
  assets: [
1272
1283
  { symbol: "USDC", minDepositAmount: "100000000" },
1273
- { symbol: "WETH", minDepositAmount: "5000000000000000" }
1284
+ { symbol: "WETH", minDepositAmount: "5000000000000000" },
1285
+ // ROUT-308: same floor as USDC (6 decimals). Zyfai's own
1286
+ // MIN_PORTFOLIO_BALANCE says 10,000 here, but that is only enforced by
1287
+ // its sendDeposit, which we don't use. Confirm with Zyfai before release.
1288
+ { symbol: "EURC", minDepositAmount: "100000000" },
1289
+ { symbol: "USDT", minDepositAmount: "100000000" }
1274
1290
  ]
1275
1291
  }
1276
1292
  ];
@@ -1292,13 +1308,12 @@ var ZyfaiAgent = class _ZyfaiAgent {
1292
1308
  // RPC error retries on the next fetch.
1293
1309
  withdrawAmountCache = /* @__PURE__ */ new Map();
1294
1310
  ethUsd = null;
1311
+ eurUsd = null;
1295
1312
  earningsReads = /* @__PURE__ */ new Map();
1296
1313
  earningsRefreshes = /* @__PURE__ */ new Map();
1297
1314
  earningsSnapshot = null;
1298
1315
  earningsGeneration = 0;
1299
- sessionStore;
1300
- constructor(apiKey, rpcUrls, referralSource, sessionStore = new BrowserSessionStore()) {
1301
- this.sessionStore = sessionStore;
1316
+ constructor(apiKey, rpcUrls, referralSource) {
1302
1317
  this.rpcUrls = rpcUrls ?? DEFAULT_ZYFAI_RPC_URLS;
1303
1318
  this.sdk = new import_sdk.ZyfaiSDK({
1304
1319
  apiKey,
@@ -1389,36 +1404,21 @@ var ZyfaiAgent = class _ZyfaiAgent {
1389
1404
  * (Zyfai dist line 1374). At that point `walletClient` + `currentChainId`
1390
1405
  * are populated, so the cache lookup has both keys it needs.
1391
1406
  *
1392
- * The session lives in `sessionStore`: localStorage in the browser (a no-op
1393
- * on the server), or whatever the host passed in `OwneySDKConfig`.
1407
+ * No-op on the server (no `window`) — the SDK is constructed during SSR
1408
+ * for some apps and the patch only matters in the browser anyway.
1394
1409
  */
1395
- /**
1396
- * The session store is a cache: an unavailable store must never block
1397
- * authentication or teardown. Failures read as a cache miss.
1398
- */
1399
- async storeOp(op) {
1400
- try {
1401
- return await op();
1402
- } catch (error) {
1403
- console.warn(
1404
- "owney-sdk: agent session store failed, continuing without it",
1405
- error
1406
- );
1407
- return null;
1408
- }
1409
- }
1410
1410
  installAuthCache() {
1411
+ if (typeof window === "undefined") return;
1411
1412
  const internals = this.sdk;
1412
1413
  const original = internals.authenticateUser.bind(internals);
1413
1414
  let inFlight = null;
1414
1415
  const authenticate = async () => {
1415
1416
  if (internals.authenticatedUserId !== null) return;
1416
1417
  const address = internals.walletClient?.account?.address;
1418
+ const chainId = internals.currentChainId ?? 0;
1417
1419
  if (address) {
1418
- const cached = await this.storeOp(
1419
- () => this.sessionStore.read(this.id, address)
1420
- );
1421
- if (isFreshSession(cached)) {
1420
+ const cached = readSession(address, chainId);
1421
+ if (cached) {
1422
1422
  internals.httpClient.setAuthToken(cached.token);
1423
1423
  internals.authenticatedUserId = cached.userId;
1424
1424
  internals.hasActiveSessionKey = cached.hasActiveSessionKey;
@@ -1428,16 +1428,15 @@ var ZyfaiAgent = class _ZyfaiAgent {
1428
1428
  }
1429
1429
  await original();
1430
1430
  const newAddress = internals.walletClient?.account?.address;
1431
+ const newChainId = internals.currentChainId ?? 0;
1431
1432
  const newToken = internals.httpClient.authToken;
1432
1433
  if (newAddress && newToken) {
1433
- await this.storeOp(
1434
- () => this.sessionStore.write(this.id, newAddress, {
1435
- token: newToken,
1436
- userId: internals.authenticatedUserId,
1437
- hasActiveSessionKey: internals.hasActiveSessionKey,
1438
- isPredeployed: internals.isPredeployed
1439
- })
1440
- );
1434
+ writeSession(newAddress, newChainId, {
1435
+ token: newToken,
1436
+ userId: internals.authenticatedUserId,
1437
+ hasActiveSessionKey: internals.hasActiveSessionKey,
1438
+ isPredeployed: internals.isPredeployed
1439
+ });
1441
1440
  }
1442
1441
  };
1443
1442
  internals.authenticateUser = () => {
@@ -1503,9 +1502,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
1503
1502
  if (!message.toLowerCase().includes("unauthorized")) throw error;
1504
1503
  const internals = this.sdk;
1505
1504
  const address = internals.walletClient?.account?.address;
1506
- if (address) {
1507
- await this.storeOp(() => this.sessionStore.clear(this.id, address));
1508
- }
1505
+ if (address) clearSession(address, chainId);
1509
1506
  return await this.sdk.connectAccount(provider, chainId);
1510
1507
  }
1511
1508
  }
@@ -1533,15 +1530,15 @@ var ZyfaiAgent = class _ZyfaiAgent {
1533
1530
  * it diffs available-vs-enabled by protocol id and writes the full union
1534
1531
  * back, or does nothing when none are missing.
1535
1532
  *
1536
- * Non-fatal: a sync failure must never block activation. Only "USDC" / "WETH"
1537
- * are modeled per-asset by the Zyfai profile API, so other assets are skipped.
1533
+ * Non-fatal: a sync failure must never block activation. Assets that do not
1534
+ * exist on `chainId` (no token address there) are skipped.
1538
1535
  */
1539
- async ensureProtocolsSynced(chainId, asset) {
1540
- if (asset !== "USDC" && asset !== "WETH") return;
1536
+ async ensureProtocolsSynced(chainId, asset, availableProtocols) {
1537
+ if (!tokenAddress(asset, chainId)) return;
1541
1538
  try {
1542
1539
  const [current, { protocols: available }] = await Promise.all([
1543
1540
  this.sdk.getUserDetails(asset),
1544
- this.sdk.getAvailableProtocols(chainId)
1541
+ availableProtocols
1545
1542
  ]);
1546
1543
  debugLog("zyfai:protocol-sync", `${asset}: profile before sync`, {
1547
1544
  chains: current.chains,
@@ -1589,9 +1586,8 @@ var ZyfaiAgent = class _ZyfaiAgent {
1589
1586
  this.earningsReads.clear();
1590
1587
  this.earningsRefreshes.clear();
1591
1588
  this.earningsSnapshot = null;
1592
- if (this.connectedAddress) {
1593
- const address = this.connectedAddress;
1594
- await this.storeOp(() => this.sessionStore.clear(this.id, address));
1589
+ if (this.connectedAddress && this.connectedChainId !== null) {
1590
+ clearSession(this.connectedAddress, this.connectedChainId);
1595
1591
  }
1596
1592
  await this.sdk.disconnectAccount();
1597
1593
  this.connectedAddress = null;
@@ -1611,9 +1607,15 @@ var ZyfaiAgent = class _ZyfaiAgent {
1611
1607
  ms: Date.now() - startedAt
1612
1608
  });
1613
1609
  const validChainId = isValidChainId(chainId);
1610
+ const availableProtocols = Promise.resolve().then(
1611
+ () => this.sdk.getAvailableProtocols(validChainId)
1612
+ );
1613
+ availableProtocols.catch(() => {
1614
+ });
1614
1615
  await Promise.all([
1615
- this.ensureProtocolsSynced(validChainId, "USDC"),
1616
- this.ensureProtocolsSynced(validChainId, "WETH"),
1616
+ ...SUPPORTED_TOKENS.map(
1617
+ (asset) => this.ensureProtocolsSynced(validChainId, asset, availableProtocols)
1618
+ ),
1617
1619
  // Retrofit a session key for old wallets that are already deployed and
1618
1620
  // funded but never got one — otherwise their balance stays idle until
1619
1621
  // they happen to deposit again. Only touches Safes that are missing the
@@ -1727,34 +1729,41 @@ var ZyfaiAgent = class _ZyfaiAgent {
1727
1729
  );
1728
1730
  const desiredAutoSelect = policy.autoApproveProtocols;
1729
1731
  for (const asset of SPLITTING_ASSETS) {
1730
- const current = await this.sdk.getUserDetails(asset);
1731
- if (strategy === void 0 && (current.strategy === "conservative" || current.strategy === "aggressive")) {
1732
- strategy = current.strategy;
1733
- }
1734
- const needsUpdate = protocolsPolicyNeedsUpdate(
1735
- current,
1736
- desiredProtocols,
1737
- desiredAutoSelect
1738
- );
1739
- debugLog("zyfai:pools", `${asset}: comparing protocols`, {
1740
- current: {
1741
- protocols: current.protocols,
1742
- autoSelectProtocols: current.autoSelectProtocols
1743
- },
1744
- desired: {
1745
- protocols: desiredProtocols,
1732
+ try {
1733
+ const current = await this.sdk.getUserDetails(asset);
1734
+ if (strategy === void 0 && (current.strategy === "conservative" || current.strategy === "aggressive")) {
1735
+ strategy = current.strategy;
1736
+ }
1737
+ const needsUpdate = protocolsPolicyNeedsUpdate(
1738
+ current,
1739
+ desiredProtocols,
1740
+ desiredAutoSelect
1741
+ );
1742
+ debugLog("zyfai:pools", `${asset}: comparing protocols`, {
1743
+ current: {
1744
+ protocols: current.protocols,
1745
+ autoSelectProtocols: current.autoSelectProtocols
1746
+ },
1747
+ desired: {
1748
+ protocols: desiredProtocols,
1749
+ autoSelectProtocols: desiredAutoSelect
1750
+ },
1751
+ decision: needsUpdate ? "will write \u2014 profile differs from the org policy" : "skipping \u2014 profile already matches"
1752
+ });
1753
+ if (!needsUpdate) continue;
1754
+ const update = {
1755
+ asset,
1746
1756
  autoSelectProtocols: desiredAutoSelect
1747
- },
1748
- decision: needsUpdate ? "will write \u2014 profile differs from the org policy" : "skipping \u2014 profile already matches"
1749
- });
1750
- if (!needsUpdate) continue;
1751
- const update = {
1752
- asset,
1753
- autoSelectProtocols: desiredAutoSelect
1754
- };
1755
- if (desiredProtocols !== null) update.protocols = desiredProtocols;
1756
- await this.sdk.updateUserProfile(update);
1757
- debugLog("zyfai:pools", `${asset}: wrote protocols update`, update);
1757
+ };
1758
+ if (desiredProtocols !== null) update.protocols = desiredProtocols;
1759
+ await this.sdk.updateUserProfile(update);
1760
+ debugLog("zyfai:pools", `${asset}: wrote protocols update`, update);
1761
+ } catch (error) {
1762
+ console.warn(
1763
+ `[zyfai] applyPoolPolicy(${asset}) failed (non-fatal):`,
1764
+ error instanceof Error ? error.message : String(error)
1765
+ );
1766
+ }
1758
1767
  }
1759
1768
  const poolResults = await Promise.all(
1760
1769
  universe.map(async (protocol) => {
@@ -1880,9 +1889,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
1880
1889
  await Promise.all(
1881
1890
  selection.strategies.map(async ({ asset, strategy }) => {
1882
1891
  const current = await this.sdk.getUserDetails(asset);
1883
- const selectedProtocols = selection.selections.filter(
1884
- (entry) => entry.asset === asset && entry.pools.length > 0
1885
- ).map((entry) => entry.protocolId);
1892
+ const selectedProtocols = selection.selections.filter((entry) => entry.asset === asset && entry.pools.length > 0).map((entry) => entry.protocolId);
1886
1893
  const protocols = [
1887
1894
  .../* @__PURE__ */ new Set([...current.protocols ?? [], ...selectedProtocols])
1888
1895
  ];
@@ -2241,11 +2248,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
2241
2248
  requestedStrategy: "aggressive",
2242
2249
  setupResult
2243
2250
  });
2251
+ await this.syncAutoSelect(validChainId, asset);
2244
2252
  if (isOwneyDebug()) {
2245
2253
  try {
2246
- const profileAfterSetup = await this.sdk.getUserDetails(
2247
- asset === "WETH" ? "WETH" : "USDC"
2248
- );
2254
+ const profileAfterSetup = await this.sdk.getUserDetails(asset);
2249
2255
  debugLog("zyfai:first-deposit", "profile immediately after setup", {
2250
2256
  asset,
2251
2257
  strategy: profileAfterSetup.strategy,
@@ -2263,9 +2269,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
2263
2269
  validChainId
2264
2270
  );
2265
2271
  const txHash = await depositCallback(smartWallet, validChainId, amount);
2266
- const tokenAddress = asset === "WETH" ? WETH_ADDRESS_BY_CHAIN[validChainId] : void 0;
2272
+ const tokenAddress2 = asset === "USDC" ? void 0 : tokenAddress(asset, validChainId);
2267
2273
  try {
2268
- await (tokenAddress ? this.sdk.logDeposit(validChainId, txHash, amount, tokenAddress) : this.sdk.logDeposit(validChainId, txHash, amount));
2274
+ await (tokenAddress2 ? this.sdk.logDeposit(validChainId, txHash, amount, tokenAddress2) : this.sdk.logDeposit(validChainId, txHash, amount));
2269
2275
  } catch (logError) {
2270
2276
  console.warn(
2271
2277
  "[owney-sdk] Deposit landed on-chain but logDeposit failed (non-fatal):",
@@ -2371,13 +2377,22 @@ var ZyfaiAgent = class _ZyfaiAgent {
2371
2377
  }
2372
2378
  async getAccountApy(state, chainId, days, tokenSymbol, scopeChainId) {
2373
2379
  const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
2374
- const [raw, ethUsd] = await Promise.all([
2380
+ const [raw, ethUsd, eurUsd] = await Promise.all([
2375
2381
  this.sdk.getDailyApyHistory(smartWallet, days),
2376
- tokenSymbol ? void 0 : this.readEthUsd(validChainId)
2382
+ tokenSymbol ? void 0 : this.readEthUsd(validChainId),
2383
+ tokenSymbol ? void 0 : this.readEurUsd()
2377
2384
  ]);
2378
2385
  const scope = scopeChainId === null ? void 0 : scopeChainId ?? chainId;
2379
- const usdPrices = ethUsd ? { WETH: ethUsd, ETH: ethUsd } : void 0;
2380
- return mapApyHistory(raw, scope, tokenSymbol, usdPrices);
2386
+ const usdPrices = {
2387
+ ...ethUsd ? { WETH: ethUsd, ETH: ethUsd } : {},
2388
+ ...eurUsd ? { EURC: eurUsd } : {}
2389
+ };
2390
+ return mapApyHistory(
2391
+ raw,
2392
+ scope,
2393
+ tokenSymbol,
2394
+ Object.keys(usdPrices).length ? usdPrices : void 0
2395
+ );
2381
2396
  }
2382
2397
  /**
2383
2398
  * Today's ETH/USD from Chainlink, cached for a minute. Every day of the
@@ -2385,24 +2400,38 @@ var ZyfaiAgent = class _ZyfaiAgent {
2385
2400
  * move over the window is not reflected (ROUT-682). Undefined on failure,
2386
2401
  * which leaves the series on token-amount weighting rather than failing it.
2387
2402
  */
2388
- async readEthUsd(chainId) {
2389
- if (this.ethUsd && Date.now() - this.ethUsd.at < ETH_USD_TTL_MS) {
2390
- return this.ethUsd.price;
2403
+ readEthUsd(chainId) {
2404
+ return this.readChainlinkUsd(
2405
+ chainId,
2406
+ CHAINLINK_ETH_USD_FEED[chainId],
2407
+ "ethUsd"
2408
+ );
2409
+ }
2410
+ /** Today's EUR/USD from Chainlink on Ethereum, for pricing EURC (ROUT-308). */
2411
+ readEurUsd() {
2412
+ return this.readChainlinkUsd(1, CHAINLINK_EUR_USD_FEED, "eurUsd");
2413
+ }
2414
+ async readChainlinkUsd(chainId, feed, cache) {
2415
+ const cached = this[cache];
2416
+ if (cached && Date.now() - cached.at < ETH_USD_TTL_MS) {
2417
+ return cached.price;
2391
2418
  }
2392
2419
  try {
2393
2420
  const [, answer] = await this.getPublicClient(chainId).readContract({
2394
- address: CHAINLINK_ETH_USD_FEED[chainId],
2421
+ address: feed,
2395
2422
  abi: CHAINLINK_ABI,
2396
2423
  functionName: "latestRoundData"
2397
2424
  });
2398
2425
  const price = Number(answer) / 1e8;
2399
2426
  if (!Number.isFinite(price) || price <= 0) return void 0;
2400
- this.ethUsd = { price, at: Date.now() };
2427
+ this[cache] = { price, at: Date.now() };
2401
2428
  return price;
2402
2429
  } catch (err) {
2403
- debugLog("zyfai:apy", "ETH/USD read failed; token-amount weighting", {
2404
- err
2405
- });
2430
+ debugLog(
2431
+ "zyfai:apy",
2432
+ `${cache === "ethUsd" ? "ETH/USD" : "EUR/USD"} read failed; token-amount weighting`,
2433
+ { err }
2434
+ );
2406
2435
  return void 0;
2407
2436
  }
2408
2437
  }
@@ -2433,6 +2462,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
2433
2462
  return "eth";
2434
2463
  case "EURC":
2435
2464
  return "eurc";
2465
+ // Zyfai has no "usdt" history filter, so USDT is filtered client-side.
2436
2466
  default:
2437
2467
  return void 0;
2438
2468
  }
@@ -2441,6 +2471,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
2441
2471
  const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
2442
2472
  const limit = options?.limit ?? 10;
2443
2473
  const assetType = _ZyfaiAgent.toZyfaiAssetType(options?.tokenSymbol);
2474
+ const clientSideAsset = !assetType && options?.tokenSymbol && SUPPORTED_TOKENS.includes(
2475
+ options.tokenSymbol.toUpperCase()
2476
+ ) ? options.tokenSymbol : void 0;
2444
2477
  const cursor = options?.cursor ? decodeHistoryCursor(options.cursor) : null;
2445
2478
  const toDate = cursor?.toDate ?? options?.toDate ?? (/* @__PURE__ */ new Date()).toISOString();
2446
2479
  let offset = cursor?.rawOffset ?? 0;
@@ -2462,6 +2495,12 @@ var ZyfaiAgent = class _ZyfaiAgent {
2462
2495
  assetType
2463
2496
  });
2464
2497
  raw.data.forEach((entry, idx) => {
2498
+ if (clientSideAsset && !matchesAsset(
2499
+ entry.positions?.[0]?.token_symbol ?? "",
2500
+ clientSideAsset
2501
+ )) {
2502
+ return;
2503
+ }
2465
2504
  if (entry.chainId === validChainId) {
2466
2505
  matched.push({ entry, rawIdx: offset + idx });
2467
2506
  }
@@ -2504,6 +2543,20 @@ var ZyfaiAgent = class _ZyfaiAgent {
2504
2543
  }
2505
2544
  async ensureAutoSelectProtocols(state, chainId, asset) {
2506
2545
  await this.connectAuth(state, chainId);
2546
+ return this.syncAutoSelect(chainId, asset);
2547
+ }
2548
+ /**
2549
+ * Zyfai's first-deposit setup keys off the USDC profile alone: once USDC is
2550
+ * configured it reports `{ applied: false }` for every asset, so an existing
2551
+ * user's first EURC/USDT keeps a chainless profile and the deposit sits as
2552
+ * an idle stale balance (ROUT-308). Configured USDC is what marks such a
2553
+ * user; a brand-new one is still left to first-deposit setup.
2554
+ */
2555
+ async isExistingZyfaiUser() {
2556
+ const usdc = await this.sdk.getUserDetails("USDC");
2557
+ return (usdc.chains?.length ?? 0) > 0 && (usdc.protocols?.length ?? 0) > 0;
2558
+ }
2559
+ async syncAutoSelect(chainId, asset) {
2507
2560
  const current = await this.sdk.getUserDetails(asset);
2508
2561
  debugLog("zyfai:auto-select", `${asset}: profile before check`, {
2509
2562
  autoSelectProtocols: current.autoSelectProtocols,
@@ -2511,7 +2564,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
2511
2564
  protocols: current.protocols,
2512
2565
  strategy: current.strategy
2513
2566
  });
2514
- if ((current.chains?.length ?? 0) === 0) {
2567
+ if ((current.chains?.length ?? 0) === 0 && (asset === "USDC" || !await this.isExistingZyfaiUser())) {
2515
2568
  debugLog(
2516
2569
  "zyfai:auto-select",
2517
2570
  `${asset}: skipping untouched profile until first deposit`
@@ -3396,6 +3449,20 @@ async function readErc20Balance(publicClient, token, owner) {
3396
3449
  });
3397
3450
  }
3398
3451
 
3452
+ // src/lib/erc20-approve.ts
3453
+ var ZERO_RESET_TOKENS = /* @__PURE__ */ new Set([
3454
+ "0xdac17f958d2ee523a2206206994597c13d831ec7"
3455
+ ]);
3456
+ function needsAllowanceReset(token) {
3457
+ return ZERO_RESET_TOKENS.has(token.toLowerCase());
3458
+ }
3459
+ async function approveWithResetIfNeeded(input) {
3460
+ if (input.currentAllowance > 0n && needsAllowanceReset(input.token)) {
3461
+ await input.approve(input.spender, 0n);
3462
+ }
3463
+ return input.approve(input.spender, input.amount);
3464
+ }
3465
+
3399
3466
  // src/lib/swap/swap.secrets.ts
3400
3467
  var import_viem4 = require("viem");
3401
3468
  var SECRET_BYTES = 32;
@@ -3754,6 +3821,15 @@ async function executeSwap(deps, options) {
3754
3821
  }
3755
3822
  return { received: arrived.toString(), ...result ?? {} };
3756
3823
  }
3824
+ function approveMax(deps, token, current, spender) {
3825
+ return approveWithResetIfNeeded({
3826
+ token,
3827
+ currentAllowance: current,
3828
+ spender,
3829
+ amount: MAX_UINT256,
3830
+ approve: deps.approve
3831
+ });
3832
+ }
3757
3833
  async function runClassic(deps, options) {
3758
3834
  const {
3759
3835
  quote,
@@ -3790,7 +3866,7 @@ async function runClassic(deps, options) {
3790
3866
  if (current < needed) {
3791
3867
  onStage?.("approving");
3792
3868
  await deps.ensureChain(quote.src.chainId);
3793
- await deps.approve(tx.to, MAX_UINT256);
3869
+ await approveMax(deps, quote.src.address, current, tx.to);
3794
3870
  debugLog(
3795
3871
  "owney-sdk",
3796
3872
  "swap: re-fetching classic calldata after approval"
@@ -3879,7 +3955,7 @@ async function authoriseSpend(deps, options, amount, isNativeSource) {
3879
3955
  });
3880
3956
  return permit;
3881
3957
  }
3882
- await deps.approve(quote.spender, MAX_UINT256);
3958
+ await approveMax(deps, quote.src.address, current, quote.spender);
3883
3959
  debugLog("owney-sdk", "swap: approved limit order protocol");
3884
3960
  return void 0;
3885
3961
  }
@@ -3975,6 +4051,66 @@ async function runFusion(deps, options, walletAddress) {
3975
4051
  return { orderHash: built.orderHash };
3976
4052
  }
3977
4053
 
4054
+ // src/lib/swap/swap.approve.ts
4055
+ var APPROVE_WATCH_INTERVAL_MS = 4e3;
4056
+ var APPROVE_PROMPT_TIMEOUT_MS = 5 * 60 * 1e3;
4057
+ async function approveWatched(deps, options) {
4058
+ const { amount, symbol, chainId } = options;
4059
+ const landed = (allowance) => amount === 0n ? allowance === 0n : allowance >= amount;
4060
+ const sleep2 = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
4061
+ return new Promise((resolve, reject) => {
4062
+ let done = false;
4063
+ const finish = (settle) => {
4064
+ if (done) return;
4065
+ done = true;
4066
+ clearTimeout(timer);
4067
+ settle();
4068
+ };
4069
+ const timer = setTimeout(
4070
+ () => finish(
4071
+ () => reject(
4072
+ new OwneyError(
4073
+ "SWAP_WALLET_PROMPT_TIMEOUT",
4074
+ // Hedged: a wallet that never answered may still have sent it.
4075
+ `Your wallet didn't answer the request to approve your ${symbol}. Check your wallet before trying again.`,
4076
+ {
4077
+ chainId,
4078
+ prompt: "approve",
4079
+ timeoutMs: APPROVE_PROMPT_TIMEOUT_MS
4080
+ }
4081
+ )
4082
+ )
4083
+ ),
4084
+ APPROVE_PROMPT_TIMEOUT_MS
4085
+ );
4086
+ deps.send().then(async (hash) => {
4087
+ clearTimeout(timer);
4088
+ await deps.waitForReceipt(hash);
4089
+ return hash;
4090
+ }).then(
4091
+ (hash) => finish(() => resolve(hash)),
4092
+ (error) => finish(() => reject(error))
4093
+ );
4094
+ void (async () => {
4095
+ while (!done) {
4096
+ await sleep2(APPROVE_WATCH_INTERVAL_MS);
4097
+ if (done) return;
4098
+ try {
4099
+ if (landed(await deps.readAllowance())) {
4100
+ debugLog(
4101
+ "owney-sdk",
4102
+ "approve: landed on chain before the wallet answered"
4103
+ );
4104
+ finish(() => resolve(void 0));
4105
+ return;
4106
+ }
4107
+ } catch {
4108
+ }
4109
+ }
4110
+ })();
4111
+ });
4112
+ }
4113
+
3978
4114
  // src/lib/swap/swap.permit.ts
3979
4115
  var import_viem5 = require("viem");
3980
4116
  var PERMIT_ABI = (0, import_viem5.parseAbi)([
@@ -4693,6 +4829,7 @@ function makeSponsoredDepositCallback(deps) {
4693
4829
  // src/lib/walletconnect-switch.ts
4694
4830
  var WALLET_SWITCH_TIMEOUT_MS = 12e4;
4695
4831
  var HOLD_CHAIN_MS = 15e3;
4832
+ var MAX_RESENDS = 2;
4696
4833
  var holds = /* @__PURE__ */ new Map();
4697
4834
  function parseChainId(raw) {
4698
4835
  if (typeof raw === "number") return raw;
@@ -4701,76 +4838,28 @@ function parseChainId(raw) {
4701
4838
  const id = ref.startsWith("0x") ? Number.parseInt(ref, 16) : Number(ref);
4702
4839
  return Number.isFinite(id) ? id : void 0;
4703
4840
  }
4704
- function walletConnectSession(provider) {
4841
+ function walletConnectCore(provider) {
4705
4842
  const p = provider;
4706
4843
  const core = p?.signer ?? p;
4707
- if (typeof core?.request !== "function" || typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
4844
+ if (typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
4708
4845
  return null;
4709
4846
  }
4710
4847
  const peer = core.session.peer?.metadata?.name ?? "";
4711
- if (/metamask/i.test(peer)) {
4712
- return { core, strategy: "remote-wallet" };
4713
- }
4714
- if (/fireblocks/i.test(peer)) {
4715
- return { core, strategy: "session-default" };
4716
- }
4717
- return null;
4718
- }
4719
- function approvedChains(core) {
4720
- const approved = /* @__PURE__ */ new Set();
4721
- for (const namespace of Object.values(core.session.namespaces ?? {})) {
4722
- for (const chain of namespace.chains ?? []) approved.add(chain);
4723
- for (const account of namespace.accounts ?? []) {
4724
- const [namespaceName, reference] = account.split(":");
4725
- if (namespaceName && reference) {
4726
- approved.add(`${namespaceName}:${reference}`);
4727
- }
4728
- }
4729
- }
4730
- return approved;
4731
- }
4732
- async function selectSessionDefaultChain(core, chainId) {
4733
- const target = `eip155:${chainId}`;
4734
- if (!approvedChains(core).has(target)) {
4735
- throw new Error(
4736
- `The WalletConnect session has not approved ${target}. Reconnect the wallet and try again.`
4737
- );
4738
- }
4739
- core.setDefaultChain(target);
4740
- const selected = parseChainId(
4741
- await core.request({ method: "eth_chainId" })
4742
- );
4743
- debugLog("wc-switch", "selected WalletConnect session default", {
4744
- peer: core.session.peer?.metadata?.name,
4745
- target: chainId,
4746
- selected
4747
- });
4748
- if (selected !== chainId) {
4749
- throw new Error(
4750
- `WalletConnect stayed on chain ${selected ?? "unknown"}; expected ${chainId}.`
4751
- );
4752
- }
4848
+ if (!/metamask/i.test(peer)) return null;
4849
+ return core;
4753
4850
  }
4754
4851
  async function switchWalletConnectChain(provider, chainId, timeoutMs = WALLET_SWITCH_TIMEOUT_MS) {
4755
- const session = walletConnectSession(provider);
4756
- if (!session) return false;
4757
- const { core, strategy } = session;
4852
+ const core = walletConnectCore(provider);
4853
+ if (!core) return false;
4758
4854
  holds.get(core.session.topic)?.();
4759
- if (strategy === "session-default") {
4760
- await selectSessionDefaultChain(core, chainId);
4761
- return true;
4762
- }
4763
4855
  await requestSwitch(core, provider, chainId, timeoutMs);
4764
- holdChain(core, chainId);
4856
+ holdChain(core, provider, chainId);
4765
4857
  return true;
4766
4858
  }
4767
4859
  async function requestSwitch(core, provider, chainId, timeoutMs) {
4768
- const current = parseChainId(
4860
+ const current = Number(
4769
4861
  await provider.request({ method: "eth_chainId" })
4770
4862
  );
4771
- if (current === void 0) {
4772
- throw new Error("WalletConnect could not report its current chain.");
4773
- }
4774
4863
  const hexChainId = `0x${chainId.toString(16)}`;
4775
4864
  let timer;
4776
4865
  try {
@@ -4800,27 +4889,26 @@ async function requestSwitch(core, provider, chainId, timeoutMs) {
4800
4889
  } catch {
4801
4890
  }
4802
4891
  }
4803
- function holdChain(core, chainId) {
4892
+ function holdChain(core, provider, chainId) {
4804
4893
  if (typeof core.on !== "function" || typeof core.removeListener !== "function") {
4805
4894
  return;
4806
4895
  }
4807
- let repins = 0;
4896
+ let resends = 0;
4808
4897
  const listener = (raw) => {
4809
4898
  const reported = parseChainId(raw);
4810
4899
  debugLog("wc-switch", "wallet reported chain", {
4811
4900
  reported,
4812
4901
  holding: chainId,
4813
- repins
4902
+ resends
4814
4903
  });
4815
4904
  if (reported === void 0 || reported === chainId) return;
4816
- repins += 1;
4817
- try {
4818
- core.setDefaultChain(`eip155:${chainId}`);
4819
- } catch (error) {
4820
- debugLog("wc-switch", "session re-pin failed", {
4905
+ if (resends >= MAX_RESENDS) return;
4906
+ resends += 1;
4907
+ void requestSwitch(core, provider, chainId, WALLET_SWITCH_TIMEOUT_MS).catch(
4908
+ (error) => debugLog("wc-switch", "re-switch failed", {
4821
4909
  error: error instanceof Error ? error.message : String(error)
4822
- });
4823
- }
4910
+ })
4911
+ );
4824
4912
  };
4825
4913
  const release = () => {
4826
4914
  clearTimeout(timer);
@@ -4834,7 +4922,7 @@ function holdChain(core, chainId) {
4834
4922
  holds.set(core.session.topic, release);
4835
4923
  }
4836
4924
  function withWalletConnectSwitch(provider) {
4837
- if (!walletConnectSession(provider)) return provider;
4925
+ if (!walletConnectCore(provider)) return provider;
4838
4926
  const target = provider;
4839
4927
  const request2 = async (args) => {
4840
4928
  if (args?.method !== "wallet_switchEthereumChain") {
@@ -4866,7 +4954,7 @@ function makeSponsoredWethCallback(deps) {
4866
4954
  if (!token) {
4867
4955
  throw new OwneyError(
4868
4956
  "CHAIN_UNSUPPORTED",
4869
- `No sponsored WETH configured for chain ${chainId}`
4957
+ `No sponsored ${deps.assetSymbol} configured for chain ${chainId}`
4870
4958
  );
4871
4959
  }
4872
4960
  const amountWei = BigInt(amount);
@@ -4879,14 +4967,14 @@ function makeSponsoredWethCallback(deps) {
4879
4967
  if (balance < amountWei) {
4880
4968
  throw new OwneyError(
4881
4969
  "DEPOSIT_INSUFFICIENT_BALANCE",
4882
- "Insufficient WETH balance for this deposit.",
4970
+ `Insufficient ${deps.assetSymbol} balance for this deposit.`,
4883
4971
  { token, chainId: cid, balance: balance.toString(), amount }
4884
4972
  );
4885
4973
  }
4886
4974
  } catch (err) {
4887
4975
  if (err instanceof OwneyError) throw err;
4888
4976
  console.warn(
4889
- "[owney-sdk] WETH balance pre-check failed (non-fatal):",
4977
+ `[owney-sdk] ${deps.assetSymbol} balance pre-check failed (non-fatal):`,
4890
4978
  err instanceof Error ? err.message : String(err)
4891
4979
  );
4892
4980
  }
@@ -4898,7 +4986,7 @@ function makeSponsoredWethCallback(deps) {
4898
4986
  if (allowance < amountWei) {
4899
4987
  throw new OwneyError(
4900
4988
  "PERMIT2_APPROVAL_REQUIRED",
4901
- "WETH gasless deposits need a one-time Permit2 approval; call approvePermit2() first",
4989
+ `${deps.assetSymbol} gasless deposits need a one-time Permit2 approval; call approvePermit2() first`,
4902
4990
  { token, chainId: cid, allowance: allowance.toString(), amount }
4903
4991
  );
4904
4992
  }
@@ -5085,8 +5173,22 @@ var SPONSORED_WETH_BY_CHAIN = {
5085
5173
  42161: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
5086
5174
  1: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
5087
5175
  };
5176
+ function sponsoredTokenMap(asset) {
5177
+ if (asset === "USDC") return SPONSORED_USDC_BY_CHAIN;
5178
+ if (asset === "WETH") return SPONSORED_WETH_BY_CHAIN;
5179
+ return Object.fromEntries(
5180
+ SUPPORTED_CHAIN_IDS.flatMap((id) => {
5181
+ const a = tokenAddress(asset, id);
5182
+ return a ? [[id, a]] : [];
5183
+ })
5184
+ );
5185
+ }
5186
+ var PERMIT2_ASSETS = /* @__PURE__ */ new Set(["WETH", "USDT"]);
5187
+ function isPermit2Asset(asset) {
5188
+ return PERMIT2_ASSETS.has(asset);
5189
+ }
5088
5190
  function shouldFallbackToUserPaid(error, asset, appCallback) {
5089
- return (asset === "WETH" || asset === "USDC") && appCallback === void 0 && error instanceof OwneyError && error.code === "SPONSOR_REQUEST_FAILED" && error.details?.safeToFallback === true;
5191
+ return SUPPORTED_TOKENS.includes(asset) && appCallback === void 0 && error instanceof OwneyError && error.code === "SPONSOR_REQUEST_FAILED" && error.details?.safeToFallback === true;
5090
5192
  }
5091
5193
  var OwneySDK = class {
5092
5194
  agents = /* @__PURE__ */ new Map();
@@ -5109,9 +5211,8 @@ var OwneySDK = class {
5109
5211
  userPoolCustomization = false;
5110
5212
  routingApiBaseUrl;
5111
5213
  referralSource;
5112
- sessionStore;
5113
- cachedSponsoredCallback = null;
5114
- cachedWethSponsoredCallback = null;
5214
+ cachedSponsoredCallbacks = /* @__PURE__ */ new Map();
5215
+ cachedPermit2SponsoredCallbacks = /* @__PURE__ */ new Map();
5115
5216
  paymasterServiceUrl;
5116
5217
  cachedSponsoredCallsCallbacks = /* @__PURE__ */ new Map();
5117
5218
  agentReads = new AgentReads();
@@ -5133,7 +5234,6 @@ var OwneySDK = class {
5133
5234
  this.routingApiBaseUrl = config.routingApiBaseUrl;
5134
5235
  this.paymasterServiceUrl = config.paymasterServiceUrl;
5135
5236
  this.referralSource = config.referralSource;
5136
- this.sessionStore = config.sessionStore;
5137
5237
  this.userPoolCustomization = config.userPoolCustomization ?? false;
5138
5238
  }
5139
5239
  /**
@@ -5160,8 +5260,8 @@ var OwneySDK = class {
5160
5260
  walletAddress,
5161
5261
  chainId: null
5162
5262
  };
5163
- this.cachedSponsoredCallback = null;
5164
- this.cachedWethSponsoredCallback = null;
5263
+ this.cachedSponsoredCallbacks.clear();
5264
+ this.cachedPermit2SponsoredCallbacks.clear();
5165
5265
  this.cachedSponsoredCallsCallbacks.clear();
5166
5266
  }
5167
5267
  /**
@@ -5177,8 +5277,8 @@ var OwneySDK = class {
5177
5277
  this.agentReads.clearInFlight();
5178
5278
  this.activationChecks.clear();
5179
5279
  this.state = null;
5180
- this.cachedSponsoredCallback = null;
5181
- this.cachedWethSponsoredCallback = null;
5280
+ this.cachedSponsoredCallbacks.clear();
5281
+ this.cachedPermit2SponsoredCallbacks.clear();
5182
5282
  this.cachedSponsoredCallsCallbacks.clear();
5183
5283
  }
5184
5284
  isAgentDisabled(agentId) {
@@ -5228,9 +5328,9 @@ var OwneySDK = class {
5228
5328
  * provider with viem `custom(provider)` to read token meta and sign the
5229
5329
  * `TransferWithAuthorization`, then POSTs to the sponsor API.
5230
5330
  */
5231
- getDefaultSponsoredCallback(onApproved) {
5232
- if (!onApproved && this.cachedSponsoredCallback)
5233
- return this.cachedSponsoredCallback;
5331
+ getDefaultSponsoredCallback(asset, onApproved) {
5332
+ const cached = this.cachedSponsoredCallbacks.get(asset);
5333
+ if (!onApproved && cached) return cached;
5234
5334
  const provider = this.requireConnectedProvider();
5235
5335
  const owner = this.state.walletAddress;
5236
5336
  const callback = makeSponsoredDepositCallback({
@@ -5238,7 +5338,7 @@ var OwneySDK = class {
5238
5338
  baseUrl: this.routingApiBaseUrl,
5239
5339
  ownerAddress: owner,
5240
5340
  onApproved,
5241
- tokenAddressByChain: SPONSORED_USDC_BY_CHAIN,
5341
+ tokenAddressByChain: sponsoredTokenMap(asset),
5242
5342
  // Casts work around viem's chain-narrowed Client vs the generic
5243
5343
  // PublicClient/WalletClient param types — structurally identical at
5244
5344
  // runtime, but the two share a name TS treats as unrelated.
@@ -5255,14 +5355,13 @@ var OwneySDK = class {
5255
5355
  transport: (0, import_viem9.custom)(provider)
5256
5356
  })
5257
5357
  });
5258
- if (!onApproved) this.cachedSponsoredCallback = callback;
5358
+ if (!onApproved) this.cachedSponsoredCallbacks.set(asset, callback);
5259
5359
  return callback;
5260
5360
  }
5261
5361
  /**
5262
- * Lazily builds (and caches) the default Permit2 sponsored WETH deposit
5263
- * callback used when the caller omits `depositCallback` for a WETH
5264
- * deposit. Mirrors `getDefaultSponsoredCallback()` but signs a Permit2
5265
- * `PermitTransferFrom` instead of an EIP-3009 authorization.
5362
+ * Lazily builds (and caches, per asset) the default paymaster-sponsored
5363
+ * deposit callback used when the caller omits `depositCallback` and a
5364
+ * `paymasterServiceUrl` is configured. One rail serves every asset.
5266
5365
  */
5267
5366
  getDefaultSponsoredCallsCallback(asset, onApproved) {
5268
5367
  const cached = this.cachedSponsoredCallsCallbacks.get(asset);
@@ -5273,20 +5372,20 @@ var OwneySDK = class {
5273
5372
  ownerAddress: this.state.walletAddress,
5274
5373
  paymasterServiceUrl: this.paymasterServiceUrl,
5275
5374
  onApproved,
5276
- tokenAddressByChain: asset === "WETH" ? SPONSORED_WETH_BY_CHAIN : SPONSORED_USDC_BY_CHAIN
5375
+ tokenAddressByChain: sponsoredTokenMap(asset)
5277
5376
  });
5278
5377
  if (!onApproved) this.cachedSponsoredCallsCallbacks.set(asset, callback);
5279
5378
  return callback;
5280
5379
  }
5281
5380
  /**
5282
- * Lazily builds (and caches) the default Permit2 sponsored WETH deposit
5283
- * callback used when the caller omits `depositCallback` for a WETH deposit.
5284
- * Mirrors `getDefaultSponsoredCallback()` but signs a Permit2
5285
- * `PermitTransferFrom` instead of an EIP-3009 authorization.
5381
+ * Lazily builds (and caches, per asset) the default Permit2 sponsored
5382
+ * deposit callback used when the caller omits `depositCallback` for a
5383
+ * Permit2 asset (WETH, USDT). Mirrors `getDefaultSponsoredCallback()` but
5384
+ * signs a Permit2 `PermitTransferFrom` instead of an EIP-3009 authorization.
5286
5385
  */
5287
- getDefaultWethSponsoredCallback(onApproved) {
5288
- if (!onApproved && this.cachedWethSponsoredCallback)
5289
- return this.cachedWethSponsoredCallback;
5386
+ getDefaultPermit2SponsoredCallback(asset, onApproved) {
5387
+ const cached = this.cachedPermit2SponsoredCallbacks.get(asset);
5388
+ if (!onApproved && cached) return cached;
5290
5389
  const provider = this.requireConnectedProvider();
5291
5390
  const owner = this.state.walletAddress;
5292
5391
  const callback = makeSponsoredWethCallback({
@@ -5294,7 +5393,8 @@ var OwneySDK = class {
5294
5393
  baseUrl: this.routingApiBaseUrl,
5295
5394
  ownerAddress: owner,
5296
5395
  onApproved,
5297
- tokenAddressByChain: SPONSORED_WETH_BY_CHAIN,
5396
+ tokenAddressByChain: sponsoredTokenMap(asset),
5397
+ assetSymbol: asset,
5298
5398
  // Casts work around viem's chain-narrowed Client vs the generic
5299
5399
  // PublicClient/WalletClient param types — structurally identical at
5300
5400
  // runtime, but the two share a name TS treats as unrelated.
@@ -5311,7 +5411,7 @@ var OwneySDK = class {
5311
5411
  transport: (0, import_viem9.custom)(provider)
5312
5412
  })
5313
5413
  });
5314
- if (!onApproved) this.cachedWethSponsoredCallback = callback;
5414
+ if (!onApproved) this.cachedPermit2SponsoredCallbacks.set(asset, callback);
5315
5415
  return callback;
5316
5416
  }
5317
5417
  getAgent(agentId) {
@@ -5407,12 +5507,7 @@ var OwneySDK = class {
5407
5507
  }
5408
5508
  createAgent(agentId, key2) {
5409
5509
  if (agentId === "zyfai") {
5410
- return new ZyfaiAgent(
5411
- key2,
5412
- this.zyfaiRpcUrls,
5413
- this.referralSource,
5414
- this.sessionStore
5415
- );
5510
+ return new ZyfaiAgent(key2, this.zyfaiRpcUrls, this.referralSource);
5416
5511
  }
5417
5512
  return null;
5418
5513
  }
@@ -5574,7 +5669,8 @@ var OwneySDK = class {
5574
5669
  }
5575
5670
  const state = this.requireState();
5576
5671
  const chainId = options.chainId ?? this.requireChainId();
5577
- const effectiveCallback = depositCallback ?? (this.paymasterServiceUrl ? this.getDefaultSponsoredCallsCallback(asset, onApproved) : asset === "WETH" ? this.getDefaultWethSponsoredCallback(onApproved) : this.getDefaultSponsoredCallback(onApproved));
5672
+ const sponsoredAsset = asset;
5673
+ const effectiveCallback = depositCallback ?? (this.paymasterServiceUrl ? this.getDefaultSponsoredCallsCallback(sponsoredAsset, onApproved) : isPermit2Asset(sponsoredAsset) ? this.getDefaultPermit2SponsoredCallback(sponsoredAsset, onApproved) : this.getDefaultSponsoredCallback(sponsoredAsset, onApproved));
5578
5674
  if (agentId) {
5579
5675
  if (this.isAgentDisabled(agentId)) {
5580
5676
  throw new OwneyError(
@@ -5688,15 +5784,16 @@ var OwneySDK = class {
5688
5784
  *
5689
5785
  * 1. Missing Permit2 allowance: when the app did not supply its own
5690
5786
  * callback and the attempt fails with `PERMIT2_APPROVAL_REQUIRED` on a
5691
- * WETH deposit, this is the wallet's first gasless WETH deposit. We send
5692
- * the one-time (user-paid) Permit2 approval via `approvePermit2()` and
5693
- * retry the SAME sponsored attempt once. Bounded to one approval attempt
5694
- * per call so a wallet/agent that keeps reporting the allowance as
5695
- * missing can't loop forever. If `approvePermit2()` itself throws (e.g.
5787
+ * Permit2 asset (WETH, USDT), this is the wallet's first gasless deposit
5788
+ * of that asset on this chain. We send the one-time (user-paid) Permit2
5789
+ * approval via `approvePermit2(asset)` and retry the SAME sponsored
5790
+ * attempt once. Bounded to one approval attempt per call so a
5791
+ * wallet/agent that keeps reporting the allowance as missing can't loop
5792
+ * forever. If `approvePermit2()` itself throws (e.g.
5696
5793
  * the user rejects the wallet prompt), that error propagates as-is —
5697
5794
  * the user said no to a transaction, so we must not turn around and ask
5698
5795
  * them to pay for a different one via the fallback below.
5699
- * 2. `shouldFallbackToUserPaid`: the SDK's own WETH sponsor path failed at
5796
+ * 2. `shouldFallbackToUserPaid`: the SDK's own sponsor path failed at
5700
5797
  * the infrastructure layer in a provably safe-to-retry way, so we warn
5701
5798
  * and retry once with `undefined`, falling through to a user-paid
5702
5799
  * native deposit. This still applies after a successful Permit2
@@ -5725,12 +5822,12 @@ var OwneySDK = class {
5725
5822
  try {
5726
5823
  return await attempt(effectiveCallback);
5727
5824
  } catch (error) {
5728
- if (!approvalAttempted && appCallback === void 0 && asset === "WETH" && error instanceof OwneyError && error.code === "PERMIT2_APPROVAL_REQUIRED") {
5825
+ if (!approvalAttempted && appCallback === void 0 && isPermit2Asset(asset) && error instanceof OwneyError && error.code === "PERMIT2_APPROVAL_REQUIRED") {
5729
5826
  approvalAttempted = true;
5730
5827
  console.warn(
5731
- "[owney-sdk] First WETH deposit: sending one-time Permit2 approval..."
5828
+ `[owney-sdk] First ${asset} deposit: sending one-time Permit2 approval...`
5732
5829
  );
5733
- await this.approvePermit2();
5830
+ await this.approvePermit2(asset);
5734
5831
  continue;
5735
5832
  }
5736
5833
  if (!shouldFallbackToUserPaid(error, asset, appCallback)) throw error;
@@ -6167,22 +6264,45 @@ var OwneySDK = class {
6167
6264
  functionName: "allowance",
6168
6265
  args: [state.walletAddress, spender]
6169
6266
  }),
6170
- approve: async (spender, amount) => {
6171
- const hash = await wallet.writeContract({
6172
- address: quote.src.address,
6173
- abi: ERC20_ALLOWANCE_ABI,
6174
- functionName: "approve",
6175
- args: [spender, amount],
6176
- account: state.walletAddress,
6177
- chain: srcChain
6178
- });
6179
- await srcPublic.waitForTransactionReceipt({
6180
- hash,
6181
- confirmations: 1,
6182
- timeout: receiptTimeoutMs(quote.src.chainId)
6183
- });
6184
- return hash;
6185
- },
6267
+ // Watched on chain as well as through the wallet: Trust's extension can
6268
+ // land the approval and never return its hash (ROUT-759).
6269
+ approve: (spender, amount) => approveWatched(
6270
+ {
6271
+ send: () => wallet.writeContract({
6272
+ address: quote.src.address,
6273
+ abi: ERC20_ALLOWANCE_ABI,
6274
+ functionName: "approve",
6275
+ args: [spender, amount],
6276
+ account: state.walletAddress,
6277
+ chain: srcChain
6278
+ }),
6279
+ waitForReceipt: async (hash) => {
6280
+ const receipt = await srcPublic.waitForTransactionReceipt({
6281
+ hash,
6282
+ confirmations: 1,
6283
+ timeout: receiptTimeoutMs(quote.src.chainId)
6284
+ });
6285
+ if (receipt.status !== "success") {
6286
+ throw new OwneyError(
6287
+ "SWAP_REQUEST_FAILED",
6288
+ `Approval transaction reverted (tx ${hash})`,
6289
+ { hash }
6290
+ );
6291
+ }
6292
+ },
6293
+ readAllowance: () => srcPublic.readContract({
6294
+ address: quote.src.address,
6295
+ abi: ERC20_ALLOWANCE_ABI,
6296
+ functionName: "allowance",
6297
+ args: [state.walletAddress, spender]
6298
+ })
6299
+ },
6300
+ {
6301
+ amount,
6302
+ symbol: quote.src.symbol,
6303
+ chainId: quote.src.chainId
6304
+ }
6305
+ ),
6186
6306
  ensureChain: (chainId) => this.ensureSwapChain(chainId),
6187
6307
  /**
6188
6308
  * Sign the approval instead of paying for it. Null means the token
@@ -6270,30 +6390,33 @@ var OwneySDK = class {
6270
6390
  * figure directly. It is the entire arrival, so there is no slack: anything
6271
6391
  * that spends the target asset between the two fails the deposit outright.
6272
6392
  *
6273
- * Something does. A first WETH deposit needs a one-time Permit2 approval,
6274
- * and that approval is a transaction. A wallet holding no native gas token -
6275
- * the normal state of someone who just swapped everything INTO WETH - pays
6276
- * for it out of the WETH. The deposit then asked for ~2e12 wei more than was
6277
- * left and refused with DEPOSIT_INSUFFICIENT_BALANCE, under a wrapper saying
6278
- * the funds were safe but unadded (ROUT-242).
6393
+ * Something does. A first deposit of a Permit2 asset (WETH, USDT) needs a
6394
+ * one-time Permit2 approval, and that approval is a transaction. For WETH,
6395
+ * a wallet holding no native gas token - the normal state of someone who
6396
+ * just swapped everything INTO WETH - pays for it out of the WETH. The
6397
+ * deposit then asked for ~2e12 wei more than was left and refused with
6398
+ * DEPOSIT_INSUFFICIENT_BALANCE, under a wrapper saying the funds were safe
6399
+ * but unadded (ROUT-242). For USDT the gas cannot come out of the token, so
6400
+ * this step only adds the one-time approval and the read changes nothing.
6279
6401
  *
6280
6402
  * So the approval happens here, before the amount is settled, and the amount
6281
6403
  * comes from a read taken after it. Two things this deliberately is not:
6282
6404
  *
6283
6405
  * - It is not a balance sweep. `received` is a DELTA over the pre-swap
6284
- * balance, so a wallet already holding WETH reads far above it; depositing
6285
- * the balance would move funds the user never offered. The arrival is the
6286
- * ceiling and the balance is only ever allowed to lower it.
6287
- * - It does not touch USDC, which moves on signed typed data and so spends
6288
- * nothing of the user's in between, nor a paymaster-configured client,
6289
- * where the sponsor covers the transfer and Permit2 never applies.
6406
+ * balance, so a wallet already holding the asset reads far above it;
6407
+ * depositing the balance would move funds the user never offered. The
6408
+ * arrival is the ceiling and the balance is only ever allowed to lower it.
6409
+ * - It does not touch USDC or EURC, which move on signed typed data
6410
+ * (EIP-3009) and so spend nothing of the user's in between, nor a
6411
+ * paymaster-configured client, where the sponsor covers the transfer and
6412
+ * Permit2 never applies.
6290
6413
  */
6291
6414
  async settleSwapDepositAmount(chainId, token, symbol, received) {
6292
- if (symbol !== "WETH" || this.paymasterServiceUrl) {
6415
+ if (!isPermit2Asset(symbol) || this.paymasterServiceUrl) {
6293
6416
  return received.toString();
6294
6417
  }
6295
6418
  const allowance = await this.readTokenPermit2Allowance(chainId, token);
6296
- if (allowance < received) await this.approvePermit2();
6419
+ if (allowance < received) await this.approvePermit2(symbol);
6297
6420
  const balance = await this.readTokenBalance(chainId, token);
6298
6421
  return (balance < received ? balance : received).toString();
6299
6422
  }
@@ -6458,7 +6581,10 @@ var OwneySDK = class {
6458
6581
  );
6459
6582
  }
6460
6583
  await this.ensureSwapChain(entry.chainId);
6461
- const token = entry.symbol === "WETH" ? SPONSORED_WETH_BY_CHAIN[entry.chainId] : void 0;
6584
+ const supported = SUPPORTED_TOKENS.includes(
6585
+ entry.symbol
6586
+ );
6587
+ const token = supported ? sponsoredTokenMap(entry.symbol)[entry.chainId] : void 0;
6462
6588
  const amount = token ? await this.settleSwapDepositAmount(
6463
6589
  entry.chainId,
6464
6590
  token,
@@ -7611,7 +7737,7 @@ var OwneySDK = class {
7611
7737
  /**
7612
7738
  * Ensure the given asset uses backend protocol auto-selection for the active
7613
7739
  * chain's account. No-op (returns false) for agents that don't support it.
7614
- * @param asset - "USDC" or "WETH".
7740
+ * @param asset - Asset symbol (e.g. "USDC").
7615
7741
  * @param agentId - Agent to target. Defaults to "zyfai".
7616
7742
  * @returns whether a profile write occurred.
7617
7743
  */
@@ -7636,23 +7762,28 @@ var OwneySDK = class {
7636
7762
  return pending;
7637
7763
  }
7638
7764
  /**
7639
- * One-time, user-paid approval of Permit2 on the sponsored WETH token for
7640
- * the active chain. Required once per wallet per chain before gasless WETH
7641
- * deposits; afterwards deposit() is signature-only. Resolves only after the
7642
- * approval transaction is mined (1 confirmation), so a subsequent deposit()
7643
- * will see the new allowance; throws if the transaction reverted.
7765
+ * One-time, user-paid approval of Permit2 on the sponsored WETH (default) or
7766
+ * USDT token for the active chain. Required once per wallet per chain before
7767
+ * gasless deposits of that asset; afterwards deposit() is signature-only.
7768
+ * Resolves only after the approval transaction is mined (1 confirmation), so
7769
+ * a subsequent deposit() will see the new allowance; throws if the
7770
+ * transaction reverted.
7771
+ *
7772
+ * On mainnet USDT only (`needsAllowanceReset`), a non-zero existing allowance
7773
+ * is first zeroed in its own transaction. If the user rejects the second
7774
+ * prompt, the previous Permit2 allowance stays zeroed; calling this again
7775
+ * approves from zero in a single transaction.
7644
7776
  * @returns the approval transaction hash.
7645
7777
  */
7646
7778
  async approvePermit2(asset = "WETH") {
7647
- void asset;
7648
7779
  const state = this.requireState();
7649
7780
  const chainId = this.requireChainId();
7650
- this.validateAssetSupport(this.getAgent("zyfai"), chainId, "WETH");
7651
- const token = SPONSORED_WETH_BY_CHAIN[chainId];
7781
+ this.validateAssetSupport(this.getAgent("zyfai"), chainId, asset);
7782
+ const token = sponsoredTokenMap(asset)[chainId];
7652
7783
  if (!token) {
7653
7784
  throw new OwneyError(
7654
7785
  "CHAIN_UNSUPPORTED",
7655
- `No sponsored WETH on chain ${chainId}`
7786
+ `No sponsored ${asset} on chain ${chainId}`
7656
7787
  );
7657
7788
  }
7658
7789
  const provider = this.requireConnectedProvider();
@@ -7670,22 +7801,52 @@ var OwneySDK = class {
7670
7801
  wallet,
7671
7802
  chainId
7672
7803
  );
7673
- const hash = await wallet.writeContract({
7674
- address: token,
7675
- abi: ERC20_ALLOWANCE_ABI,
7676
- functionName: "approve",
7677
- args: [PERMIT2_ADDRESS, MAX_UINT256],
7678
- account: state.walletAddress,
7679
- chain: VIEM_CHAIN2[chainId]
7804
+ const currentAllowance = await this.readTokenPermit2Allowance(
7805
+ chainId,
7806
+ token
7807
+ ).catch(
7808
+ () => readPermit2Allowance(
7809
+ publicClient,
7810
+ token,
7811
+ state.walletAddress
7812
+ )
7813
+ ).catch((err) => {
7814
+ if (!needsAllowanceReset(token)) return 0n;
7815
+ throw new OwneyError(
7816
+ "PERMIT2_APPROVAL_REQUIRED",
7817
+ `Could not read the current ${asset} allowance for Permit2; please try again.`,
7818
+ {
7819
+ token,
7820
+ chainId,
7821
+ reason: "ALLOWANCE_UNREADABLE",
7822
+ cause: err instanceof Error ? err.message : String(err)
7823
+ }
7824
+ );
7680
7825
  });
7681
- const receipt = await publicClient.waitForTransactionReceipt({
7682
- hash,
7683
- confirmations: 1
7826
+ return approveWithResetIfNeeded({
7827
+ token,
7828
+ currentAllowance,
7829
+ spender: PERMIT2_ADDRESS,
7830
+ amount: MAX_UINT256,
7831
+ approve: async (spender, amount) => {
7832
+ const hash = await wallet.writeContract({
7833
+ address: token,
7834
+ abi: ERC20_ALLOWANCE_ABI,
7835
+ functionName: "approve",
7836
+ args: [spender, amount],
7837
+ account: state.walletAddress,
7838
+ chain: VIEM_CHAIN2[chainId]
7839
+ });
7840
+ const receipt = await publicClient.waitForTransactionReceipt({
7841
+ hash,
7842
+ confirmations: 1
7843
+ });
7844
+ if (receipt.status !== "success") {
7845
+ throw new Error(`Permit2 approval reverted (tx ${hash})`);
7846
+ }
7847
+ return hash;
7848
+ }
7684
7849
  });
7685
- if (receipt.status !== "success") {
7686
- throw new Error(`Permit2 approval reverted (tx ${hash})`);
7687
- }
7688
- return hash;
7689
7850
  }
7690
7851
  // --- Discovery (no wallet required) ---
7691
7852
  /**