@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.js CHANGED
@@ -170,7 +170,7 @@ var P_SUPPORTED_CHAINS = {
170
170
  chainIds: [8453, 42161, 1],
171
171
  chains: ["BASE", "ARBITRUM", "ETHEREUM"]
172
172
  };
173
- var SUPPORTED_TOKENS = ["USDC", "WETH"];
173
+ var SUPPORTED_TOKENS = ["USDC", "WETH", "EURC", "USDT"];
174
174
  var SUPPORTED_CHAIN_IDS = P_SUPPORTED_CHAINS.chainIds;
175
175
  var SUPPORTED_CHAINS = P_SUPPORTED_CHAINS.chains;
176
176
  var SupportedAssets = [
@@ -209,8 +209,31 @@ var SupportedAssets = [
209
209
  symbol: "WETH",
210
210
  chainId: 1,
211
211
  decimals: 18
212
+ },
213
+ {
214
+ address: `0x1aBaEA1f7C830bD89Acc67eC4af516284b1bC33c`,
215
+ symbol: "EURC",
216
+ chainId: 1,
217
+ decimals: 6
218
+ },
219
+ {
220
+ address: `0x60a3E35Cc302bFA44Cb288Bc5a4F316Fdb1adb42`,
221
+ symbol: "EURC",
222
+ chainId: 8453,
223
+ decimals: 6
224
+ },
225
+ {
226
+ address: `0xdAC17F958D2ee523a2206206994597C13D831ec7`,
227
+ symbol: "USDT",
228
+ chainId: 1,
229
+ decimals: 6
212
230
  }
213
231
  ];
232
+ function tokenAddress(symbol, chainId) {
233
+ return SupportedAssets.find(
234
+ (a) => a.symbol === symbol && a.chainId === chainId
235
+ )?.address;
236
+ }
214
237
 
215
238
  // src/lib/debug.ts
216
239
  var configuredDebug = false;
@@ -275,6 +298,8 @@ function matchesAsset(symbol, asset) {
275
298
  // src/agents/zyfai/zyfai.mapper.ts
276
299
  var DECIMALS_BY_SYMBOL = {
277
300
  usdc: 6,
301
+ eurc: 6,
302
+ usdt: 6,
278
303
  weth: 18,
279
304
  eth: 18,
280
305
  cbeth: 18,
@@ -471,7 +496,7 @@ function netApy(net, gross, field) {
471
496
  }
472
497
  function usdPerUnit(tokenSymbol, prices) {
473
498
  const symbol = tokenSymbol?.toUpperCase();
474
- if (symbol === "USDC") return 1;
499
+ if (symbol === "USDC" || symbol === "USDT") return 1;
475
500
  const price = symbol ? prices?.[symbol] : void 0;
476
501
  return typeof price === "number" && Number.isFinite(price) && price > 0 ? price : void 0;
477
502
  }
@@ -876,7 +901,7 @@ var isJwtExpired = (token) => {
876
901
  }
877
902
  };
878
903
  var memorySessions = /* @__PURE__ */ new Map();
879
- var isFreshSession = (session) => typeof session === "object" && session !== null && typeof session.isPredeployed === "boolean" && !!session.token && !isJwtExpired(session.token);
904
+ var isFreshSession = (session) => !!session && typeof session.isPredeployed === "boolean" && !!session.token && !isJwtExpired(session.token);
880
905
  var readLegacySession = (store, address) => {
881
906
  if (!store) return null;
882
907
  const prefix = legacyKeyPrefix(address);
@@ -958,17 +983,6 @@ var clearSession = (address, _chainId) => {
958
983
  }
959
984
  readLegacySession(store, address);
960
985
  };
961
- var BrowserSessionStore = class {
962
- read(_agentId, address) {
963
- return readSession(address, 0);
964
- }
965
- write(_agentId, address, session) {
966
- writeSession(address, 0, session);
967
- }
968
- clear(_agentId, address) {
969
- clearSession(address, 0);
970
- }
971
- };
972
986
 
973
987
  // src/agents/zyfai/autoSelect.ts
974
988
  function buildAutoSelectUpdate(current, asset, chainId) {
@@ -1181,6 +1195,7 @@ var CHAINLINK_ETH_USD_FEED = {
1181
1195
  42161: "0x639Fe6ab55C921f74e7fac1ee960C0B6293ba612",
1182
1196
  1: "0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419"
1183
1197
  };
1198
+ var CHAINLINK_EUR_USD_FEED = "0xb49f677943BC038e9857d61E7d053CaA2C1734C1";
1184
1199
  var CHAINLINK_ABI = parseAbi([
1185
1200
  "function latestRoundData() view returns (uint80, int256, uint256, uint256, uint80)"
1186
1201
  ]);
@@ -1190,13 +1205,8 @@ var DEFAULT_ZYFAI_RPC_URLS = {
1190
1205
  42161: "https://arb-mainnet.g.alchemy.com/v2/ZWyVU-9XfS3z8Rn-xkq7V",
1191
1206
  1: "https://eth-mainnet.g.alchemy.com/v2/ZWyVU-9XfS3z8Rn-xkq7V"
1192
1207
  };
1193
- var WETH_ADDRESS_BY_CHAIN = {
1194
- 8453: "0x4200000000000000000000000000000000000006",
1195
- 42161: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
1196
- 1: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
1197
- };
1198
1208
  var VIEM_CHAIN = { 8453: base, 42161: arbitrum, 1: mainnet };
1199
- var SPLITTING_ASSETS = ["USDC", "WETH"];
1209
+ var SPLITTING_ASSETS = SUPPORTED_TOKENS;
1200
1210
  var POOL_POLICY_CHAIN_IDS = [8453, 42161, 1];
1201
1211
  var EARNINGS_REFRESH_COOLDOWN_MS = 60 * 60 * 1e3;
1202
1212
  var ZyfaiAgent = class _ZyfaiAgent {
@@ -1208,7 +1218,8 @@ var ZyfaiAgent = class _ZyfaiAgent {
1208
1218
  chain: "BASE",
1209
1219
  assets: [
1210
1220
  { symbol: "USDC", minDepositAmount: "1500000" },
1211
- { symbol: "WETH", minDepositAmount: "500000000000000" }
1221
+ { symbol: "WETH", minDepositAmount: "500000000000000" },
1222
+ { symbol: "EURC", minDepositAmount: "1500000" }
1212
1223
  ]
1213
1224
  },
1214
1225
  {
@@ -1229,7 +1240,12 @@ var ZyfaiAgent = class _ZyfaiAgent {
1229
1240
  // the shipped code enforces 0.005 WETH, so match it or deposits reject on-chain.
1230
1241
  assets: [
1231
1242
  { symbol: "USDC", minDepositAmount: "100000000" },
1232
- { symbol: "WETH", minDepositAmount: "5000000000000000" }
1243
+ { symbol: "WETH", minDepositAmount: "5000000000000000" },
1244
+ // ROUT-308: same floor as USDC (6 decimals). Zyfai's own
1245
+ // MIN_PORTFOLIO_BALANCE says 10,000 here, but that is only enforced by
1246
+ // its sendDeposit, which we don't use. Confirm with Zyfai before release.
1247
+ { symbol: "EURC", minDepositAmount: "100000000" },
1248
+ { symbol: "USDT", minDepositAmount: "100000000" }
1233
1249
  ]
1234
1250
  }
1235
1251
  ];
@@ -1251,13 +1267,12 @@ var ZyfaiAgent = class _ZyfaiAgent {
1251
1267
  // RPC error retries on the next fetch.
1252
1268
  withdrawAmountCache = /* @__PURE__ */ new Map();
1253
1269
  ethUsd = null;
1270
+ eurUsd = null;
1254
1271
  earningsReads = /* @__PURE__ */ new Map();
1255
1272
  earningsRefreshes = /* @__PURE__ */ new Map();
1256
1273
  earningsSnapshot = null;
1257
1274
  earningsGeneration = 0;
1258
- sessionStore;
1259
- constructor(apiKey, rpcUrls, referralSource, sessionStore = new BrowserSessionStore()) {
1260
- this.sessionStore = sessionStore;
1275
+ constructor(apiKey, rpcUrls, referralSource) {
1261
1276
  this.rpcUrls = rpcUrls ?? DEFAULT_ZYFAI_RPC_URLS;
1262
1277
  this.sdk = new ZyfaiSDK({
1263
1278
  apiKey,
@@ -1348,36 +1363,21 @@ var ZyfaiAgent = class _ZyfaiAgent {
1348
1363
  * (Zyfai dist line 1374). At that point `walletClient` + `currentChainId`
1349
1364
  * are populated, so the cache lookup has both keys it needs.
1350
1365
  *
1351
- * The session lives in `sessionStore`: localStorage in the browser (a no-op
1352
- * on the server), or whatever the host passed in `OwneySDKConfig`.
1366
+ * No-op on the server (no `window`) — the SDK is constructed during SSR
1367
+ * for some apps and the patch only matters in the browser anyway.
1353
1368
  */
1354
- /**
1355
- * The session store is a cache: an unavailable store must never block
1356
- * authentication or teardown. Failures read as a cache miss.
1357
- */
1358
- async storeOp(op) {
1359
- try {
1360
- return await op();
1361
- } catch (error) {
1362
- console.warn(
1363
- "owney-sdk: agent session store failed, continuing without it",
1364
- error
1365
- );
1366
- return null;
1367
- }
1368
- }
1369
1369
  installAuthCache() {
1370
+ if (typeof window === "undefined") return;
1370
1371
  const internals = this.sdk;
1371
1372
  const original = internals.authenticateUser.bind(internals);
1372
1373
  let inFlight = null;
1373
1374
  const authenticate = async () => {
1374
1375
  if (internals.authenticatedUserId !== null) return;
1375
1376
  const address = internals.walletClient?.account?.address;
1377
+ const chainId = internals.currentChainId ?? 0;
1376
1378
  if (address) {
1377
- const cached = await this.storeOp(
1378
- () => this.sessionStore.read(this.id, address)
1379
- );
1380
- if (isFreshSession(cached)) {
1379
+ const cached = readSession(address, chainId);
1380
+ if (cached) {
1381
1381
  internals.httpClient.setAuthToken(cached.token);
1382
1382
  internals.authenticatedUserId = cached.userId;
1383
1383
  internals.hasActiveSessionKey = cached.hasActiveSessionKey;
@@ -1387,16 +1387,15 @@ var ZyfaiAgent = class _ZyfaiAgent {
1387
1387
  }
1388
1388
  await original();
1389
1389
  const newAddress = internals.walletClient?.account?.address;
1390
+ const newChainId = internals.currentChainId ?? 0;
1390
1391
  const newToken = internals.httpClient.authToken;
1391
1392
  if (newAddress && newToken) {
1392
- await this.storeOp(
1393
- () => this.sessionStore.write(this.id, newAddress, {
1394
- token: newToken,
1395
- userId: internals.authenticatedUserId,
1396
- hasActiveSessionKey: internals.hasActiveSessionKey,
1397
- isPredeployed: internals.isPredeployed
1398
- })
1399
- );
1393
+ writeSession(newAddress, newChainId, {
1394
+ token: newToken,
1395
+ userId: internals.authenticatedUserId,
1396
+ hasActiveSessionKey: internals.hasActiveSessionKey,
1397
+ isPredeployed: internals.isPredeployed
1398
+ });
1400
1399
  }
1401
1400
  };
1402
1401
  internals.authenticateUser = () => {
@@ -1462,9 +1461,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
1462
1461
  if (!message.toLowerCase().includes("unauthorized")) throw error;
1463
1462
  const internals = this.sdk;
1464
1463
  const address = internals.walletClient?.account?.address;
1465
- if (address) {
1466
- await this.storeOp(() => this.sessionStore.clear(this.id, address));
1467
- }
1464
+ if (address) clearSession(address, chainId);
1468
1465
  return await this.sdk.connectAccount(provider, chainId);
1469
1466
  }
1470
1467
  }
@@ -1492,15 +1489,15 @@ var ZyfaiAgent = class _ZyfaiAgent {
1492
1489
  * it diffs available-vs-enabled by protocol id and writes the full union
1493
1490
  * back, or does nothing when none are missing.
1494
1491
  *
1495
- * Non-fatal: a sync failure must never block activation. Only "USDC" / "WETH"
1496
- * are modeled per-asset by the Zyfai profile API, so other assets are skipped.
1492
+ * Non-fatal: a sync failure must never block activation. Assets that do not
1493
+ * exist on `chainId` (no token address there) are skipped.
1497
1494
  */
1498
- async ensureProtocolsSynced(chainId, asset) {
1499
- if (asset !== "USDC" && asset !== "WETH") return;
1495
+ async ensureProtocolsSynced(chainId, asset, availableProtocols) {
1496
+ if (!tokenAddress(asset, chainId)) return;
1500
1497
  try {
1501
1498
  const [current, { protocols: available }] = await Promise.all([
1502
1499
  this.sdk.getUserDetails(asset),
1503
- this.sdk.getAvailableProtocols(chainId)
1500
+ availableProtocols
1504
1501
  ]);
1505
1502
  debugLog("zyfai:protocol-sync", `${asset}: profile before sync`, {
1506
1503
  chains: current.chains,
@@ -1548,9 +1545,8 @@ var ZyfaiAgent = class _ZyfaiAgent {
1548
1545
  this.earningsReads.clear();
1549
1546
  this.earningsRefreshes.clear();
1550
1547
  this.earningsSnapshot = null;
1551
- if (this.connectedAddress) {
1552
- const address = this.connectedAddress;
1553
- await this.storeOp(() => this.sessionStore.clear(this.id, address));
1548
+ if (this.connectedAddress && this.connectedChainId !== null) {
1549
+ clearSession(this.connectedAddress, this.connectedChainId);
1554
1550
  }
1555
1551
  await this.sdk.disconnectAccount();
1556
1552
  this.connectedAddress = null;
@@ -1570,9 +1566,15 @@ var ZyfaiAgent = class _ZyfaiAgent {
1570
1566
  ms: Date.now() - startedAt
1571
1567
  });
1572
1568
  const validChainId = isValidChainId(chainId);
1569
+ const availableProtocols = Promise.resolve().then(
1570
+ () => this.sdk.getAvailableProtocols(validChainId)
1571
+ );
1572
+ availableProtocols.catch(() => {
1573
+ });
1573
1574
  await Promise.all([
1574
- this.ensureProtocolsSynced(validChainId, "USDC"),
1575
- this.ensureProtocolsSynced(validChainId, "WETH"),
1575
+ ...SUPPORTED_TOKENS.map(
1576
+ (asset) => this.ensureProtocolsSynced(validChainId, asset, availableProtocols)
1577
+ ),
1576
1578
  // Retrofit a session key for old wallets that are already deployed and
1577
1579
  // funded but never got one — otherwise their balance stays idle until
1578
1580
  // they happen to deposit again. Only touches Safes that are missing the
@@ -1686,34 +1688,41 @@ var ZyfaiAgent = class _ZyfaiAgent {
1686
1688
  );
1687
1689
  const desiredAutoSelect = policy.autoApproveProtocols;
1688
1690
  for (const asset of SPLITTING_ASSETS) {
1689
- const current = await this.sdk.getUserDetails(asset);
1690
- if (strategy === void 0 && (current.strategy === "conservative" || current.strategy === "aggressive")) {
1691
- strategy = current.strategy;
1692
- }
1693
- const needsUpdate = protocolsPolicyNeedsUpdate(
1694
- current,
1695
- desiredProtocols,
1696
- desiredAutoSelect
1697
- );
1698
- debugLog("zyfai:pools", `${asset}: comparing protocols`, {
1699
- current: {
1700
- protocols: current.protocols,
1701
- autoSelectProtocols: current.autoSelectProtocols
1702
- },
1703
- desired: {
1704
- protocols: desiredProtocols,
1691
+ try {
1692
+ const current = await this.sdk.getUserDetails(asset);
1693
+ if (strategy === void 0 && (current.strategy === "conservative" || current.strategy === "aggressive")) {
1694
+ strategy = current.strategy;
1695
+ }
1696
+ const needsUpdate = protocolsPolicyNeedsUpdate(
1697
+ current,
1698
+ desiredProtocols,
1699
+ desiredAutoSelect
1700
+ );
1701
+ debugLog("zyfai:pools", `${asset}: comparing protocols`, {
1702
+ current: {
1703
+ protocols: current.protocols,
1704
+ autoSelectProtocols: current.autoSelectProtocols
1705
+ },
1706
+ desired: {
1707
+ protocols: desiredProtocols,
1708
+ autoSelectProtocols: desiredAutoSelect
1709
+ },
1710
+ decision: needsUpdate ? "will write \u2014 profile differs from the org policy" : "skipping \u2014 profile already matches"
1711
+ });
1712
+ if (!needsUpdate) continue;
1713
+ const update = {
1714
+ asset,
1705
1715
  autoSelectProtocols: desiredAutoSelect
1706
- },
1707
- decision: needsUpdate ? "will write \u2014 profile differs from the org policy" : "skipping \u2014 profile already matches"
1708
- });
1709
- if (!needsUpdate) continue;
1710
- const update = {
1711
- asset,
1712
- autoSelectProtocols: desiredAutoSelect
1713
- };
1714
- if (desiredProtocols !== null) update.protocols = desiredProtocols;
1715
- await this.sdk.updateUserProfile(update);
1716
- debugLog("zyfai:pools", `${asset}: wrote protocols update`, update);
1716
+ };
1717
+ if (desiredProtocols !== null) update.protocols = desiredProtocols;
1718
+ await this.sdk.updateUserProfile(update);
1719
+ debugLog("zyfai:pools", `${asset}: wrote protocols update`, update);
1720
+ } catch (error) {
1721
+ console.warn(
1722
+ `[zyfai] applyPoolPolicy(${asset}) failed (non-fatal):`,
1723
+ error instanceof Error ? error.message : String(error)
1724
+ );
1725
+ }
1717
1726
  }
1718
1727
  const poolResults = await Promise.all(
1719
1728
  universe.map(async (protocol) => {
@@ -1839,9 +1848,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
1839
1848
  await Promise.all(
1840
1849
  selection.strategies.map(async ({ asset, strategy }) => {
1841
1850
  const current = await this.sdk.getUserDetails(asset);
1842
- const selectedProtocols = selection.selections.filter(
1843
- (entry) => entry.asset === asset && entry.pools.length > 0
1844
- ).map((entry) => entry.protocolId);
1851
+ const selectedProtocols = selection.selections.filter((entry) => entry.asset === asset && entry.pools.length > 0).map((entry) => entry.protocolId);
1845
1852
  const protocols = [
1846
1853
  .../* @__PURE__ */ new Set([...current.protocols ?? [], ...selectedProtocols])
1847
1854
  ];
@@ -2200,11 +2207,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
2200
2207
  requestedStrategy: "aggressive",
2201
2208
  setupResult
2202
2209
  });
2210
+ await this.syncAutoSelect(validChainId, asset);
2203
2211
  if (isOwneyDebug()) {
2204
2212
  try {
2205
- const profileAfterSetup = await this.sdk.getUserDetails(
2206
- asset === "WETH" ? "WETH" : "USDC"
2207
- );
2213
+ const profileAfterSetup = await this.sdk.getUserDetails(asset);
2208
2214
  debugLog("zyfai:first-deposit", "profile immediately after setup", {
2209
2215
  asset,
2210
2216
  strategy: profileAfterSetup.strategy,
@@ -2222,9 +2228,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
2222
2228
  validChainId
2223
2229
  );
2224
2230
  const txHash = await depositCallback(smartWallet, validChainId, amount);
2225
- const tokenAddress = asset === "WETH" ? WETH_ADDRESS_BY_CHAIN[validChainId] : void 0;
2231
+ const tokenAddress2 = asset === "USDC" ? void 0 : tokenAddress(asset, validChainId);
2226
2232
  try {
2227
- await (tokenAddress ? this.sdk.logDeposit(validChainId, txHash, amount, tokenAddress) : this.sdk.logDeposit(validChainId, txHash, amount));
2233
+ await (tokenAddress2 ? this.sdk.logDeposit(validChainId, txHash, amount, tokenAddress2) : this.sdk.logDeposit(validChainId, txHash, amount));
2228
2234
  } catch (logError) {
2229
2235
  console.warn(
2230
2236
  "[owney-sdk] Deposit landed on-chain but logDeposit failed (non-fatal):",
@@ -2330,13 +2336,22 @@ var ZyfaiAgent = class _ZyfaiAgent {
2330
2336
  }
2331
2337
  async getAccountApy(state, chainId, days, tokenSymbol, scopeChainId) {
2332
2338
  const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
2333
- const [raw, ethUsd] = await Promise.all([
2339
+ const [raw, ethUsd, eurUsd] = await Promise.all([
2334
2340
  this.sdk.getDailyApyHistory(smartWallet, days),
2335
- tokenSymbol ? void 0 : this.readEthUsd(validChainId)
2341
+ tokenSymbol ? void 0 : this.readEthUsd(validChainId),
2342
+ tokenSymbol ? void 0 : this.readEurUsd()
2336
2343
  ]);
2337
2344
  const scope = scopeChainId === null ? void 0 : scopeChainId ?? chainId;
2338
- const usdPrices = ethUsd ? { WETH: ethUsd, ETH: ethUsd } : void 0;
2339
- return mapApyHistory(raw, scope, tokenSymbol, usdPrices);
2345
+ const usdPrices = {
2346
+ ...ethUsd ? { WETH: ethUsd, ETH: ethUsd } : {},
2347
+ ...eurUsd ? { EURC: eurUsd } : {}
2348
+ };
2349
+ return mapApyHistory(
2350
+ raw,
2351
+ scope,
2352
+ tokenSymbol,
2353
+ Object.keys(usdPrices).length ? usdPrices : void 0
2354
+ );
2340
2355
  }
2341
2356
  /**
2342
2357
  * Today's ETH/USD from Chainlink, cached for a minute. Every day of the
@@ -2344,24 +2359,38 @@ var ZyfaiAgent = class _ZyfaiAgent {
2344
2359
  * move over the window is not reflected (ROUT-682). Undefined on failure,
2345
2360
  * which leaves the series on token-amount weighting rather than failing it.
2346
2361
  */
2347
- async readEthUsd(chainId) {
2348
- if (this.ethUsd && Date.now() - this.ethUsd.at < ETH_USD_TTL_MS) {
2349
- return this.ethUsd.price;
2362
+ readEthUsd(chainId) {
2363
+ return this.readChainlinkUsd(
2364
+ chainId,
2365
+ CHAINLINK_ETH_USD_FEED[chainId],
2366
+ "ethUsd"
2367
+ );
2368
+ }
2369
+ /** Today's EUR/USD from Chainlink on Ethereum, for pricing EURC (ROUT-308). */
2370
+ readEurUsd() {
2371
+ return this.readChainlinkUsd(1, CHAINLINK_EUR_USD_FEED, "eurUsd");
2372
+ }
2373
+ async readChainlinkUsd(chainId, feed, cache) {
2374
+ const cached = this[cache];
2375
+ if (cached && Date.now() - cached.at < ETH_USD_TTL_MS) {
2376
+ return cached.price;
2350
2377
  }
2351
2378
  try {
2352
2379
  const [, answer] = await this.getPublicClient(chainId).readContract({
2353
- address: CHAINLINK_ETH_USD_FEED[chainId],
2380
+ address: feed,
2354
2381
  abi: CHAINLINK_ABI,
2355
2382
  functionName: "latestRoundData"
2356
2383
  });
2357
2384
  const price = Number(answer) / 1e8;
2358
2385
  if (!Number.isFinite(price) || price <= 0) return void 0;
2359
- this.ethUsd = { price, at: Date.now() };
2386
+ this[cache] = { price, at: Date.now() };
2360
2387
  return price;
2361
2388
  } catch (err) {
2362
- debugLog("zyfai:apy", "ETH/USD read failed; token-amount weighting", {
2363
- err
2364
- });
2389
+ debugLog(
2390
+ "zyfai:apy",
2391
+ `${cache === "ethUsd" ? "ETH/USD" : "EUR/USD"} read failed; token-amount weighting`,
2392
+ { err }
2393
+ );
2365
2394
  return void 0;
2366
2395
  }
2367
2396
  }
@@ -2392,6 +2421,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
2392
2421
  return "eth";
2393
2422
  case "EURC":
2394
2423
  return "eurc";
2424
+ // Zyfai has no "usdt" history filter, so USDT is filtered client-side.
2395
2425
  default:
2396
2426
  return void 0;
2397
2427
  }
@@ -2400,6 +2430,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
2400
2430
  const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
2401
2431
  const limit = options?.limit ?? 10;
2402
2432
  const assetType = _ZyfaiAgent.toZyfaiAssetType(options?.tokenSymbol);
2433
+ const clientSideAsset = !assetType && options?.tokenSymbol && SUPPORTED_TOKENS.includes(
2434
+ options.tokenSymbol.toUpperCase()
2435
+ ) ? options.tokenSymbol : void 0;
2403
2436
  const cursor = options?.cursor ? decodeHistoryCursor(options.cursor) : null;
2404
2437
  const toDate = cursor?.toDate ?? options?.toDate ?? (/* @__PURE__ */ new Date()).toISOString();
2405
2438
  let offset = cursor?.rawOffset ?? 0;
@@ -2421,6 +2454,12 @@ var ZyfaiAgent = class _ZyfaiAgent {
2421
2454
  assetType
2422
2455
  });
2423
2456
  raw.data.forEach((entry, idx) => {
2457
+ if (clientSideAsset && !matchesAsset(
2458
+ entry.positions?.[0]?.token_symbol ?? "",
2459
+ clientSideAsset
2460
+ )) {
2461
+ return;
2462
+ }
2424
2463
  if (entry.chainId === validChainId) {
2425
2464
  matched.push({ entry, rawIdx: offset + idx });
2426
2465
  }
@@ -2463,6 +2502,20 @@ var ZyfaiAgent = class _ZyfaiAgent {
2463
2502
  }
2464
2503
  async ensureAutoSelectProtocols(state, chainId, asset) {
2465
2504
  await this.connectAuth(state, chainId);
2505
+ return this.syncAutoSelect(chainId, asset);
2506
+ }
2507
+ /**
2508
+ * Zyfai's first-deposit setup keys off the USDC profile alone: once USDC is
2509
+ * configured it reports `{ applied: false }` for every asset, so an existing
2510
+ * user's first EURC/USDT keeps a chainless profile and the deposit sits as
2511
+ * an idle stale balance (ROUT-308). Configured USDC is what marks such a
2512
+ * user; a brand-new one is still left to first-deposit setup.
2513
+ */
2514
+ async isExistingZyfaiUser() {
2515
+ const usdc = await this.sdk.getUserDetails("USDC");
2516
+ return (usdc.chains?.length ?? 0) > 0 && (usdc.protocols?.length ?? 0) > 0;
2517
+ }
2518
+ async syncAutoSelect(chainId, asset) {
2466
2519
  const current = await this.sdk.getUserDetails(asset);
2467
2520
  debugLog("zyfai:auto-select", `${asset}: profile before check`, {
2468
2521
  autoSelectProtocols: current.autoSelectProtocols,
@@ -2470,7 +2523,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
2470
2523
  protocols: current.protocols,
2471
2524
  strategy: current.strategy
2472
2525
  });
2473
- if ((current.chains?.length ?? 0) === 0) {
2526
+ if ((current.chains?.length ?? 0) === 0 && (asset === "USDC" || !await this.isExistingZyfaiUser())) {
2474
2527
  debugLog(
2475
2528
  "zyfai:auto-select",
2476
2529
  `${asset}: skipping untouched profile until first deposit`
@@ -3365,6 +3418,20 @@ async function readErc20Balance(publicClient, token, owner) {
3365
3418
  });
3366
3419
  }
3367
3420
 
3421
+ // src/lib/erc20-approve.ts
3422
+ var ZERO_RESET_TOKENS = /* @__PURE__ */ new Set([
3423
+ "0xdac17f958d2ee523a2206206994597c13d831ec7"
3424
+ ]);
3425
+ function needsAllowanceReset(token) {
3426
+ return ZERO_RESET_TOKENS.has(token.toLowerCase());
3427
+ }
3428
+ async function approveWithResetIfNeeded(input) {
3429
+ if (input.currentAllowance > 0n && needsAllowanceReset(input.token)) {
3430
+ await input.approve(input.spender, 0n);
3431
+ }
3432
+ return input.approve(input.spender, input.amount);
3433
+ }
3434
+
3368
3435
  // src/lib/swap/swap.secrets.ts
3369
3436
  import { keccak256, toHex } from "viem";
3370
3437
  var SECRET_BYTES = 32;
@@ -3723,6 +3790,15 @@ async function executeSwap(deps, options) {
3723
3790
  }
3724
3791
  return { received: arrived.toString(), ...result ?? {} };
3725
3792
  }
3793
+ function approveMax(deps, token, current, spender) {
3794
+ return approveWithResetIfNeeded({
3795
+ token,
3796
+ currentAllowance: current,
3797
+ spender,
3798
+ amount: MAX_UINT256,
3799
+ approve: deps.approve
3800
+ });
3801
+ }
3726
3802
  async function runClassic(deps, options) {
3727
3803
  const {
3728
3804
  quote,
@@ -3759,7 +3835,7 @@ async function runClassic(deps, options) {
3759
3835
  if (current < needed) {
3760
3836
  onStage?.("approving");
3761
3837
  await deps.ensureChain(quote.src.chainId);
3762
- await deps.approve(tx.to, MAX_UINT256);
3838
+ await approveMax(deps, quote.src.address, current, tx.to);
3763
3839
  debugLog(
3764
3840
  "owney-sdk",
3765
3841
  "swap: re-fetching classic calldata after approval"
@@ -3848,7 +3924,7 @@ async function authoriseSpend(deps, options, amount, isNativeSource) {
3848
3924
  });
3849
3925
  return permit;
3850
3926
  }
3851
- await deps.approve(quote.spender, MAX_UINT256);
3927
+ await approveMax(deps, quote.src.address, current, quote.spender);
3852
3928
  debugLog("owney-sdk", "swap: approved limit order protocol");
3853
3929
  return void 0;
3854
3930
  }
@@ -3944,6 +4020,66 @@ async function runFusion(deps, options, walletAddress) {
3944
4020
  return { orderHash: built.orderHash };
3945
4021
  }
3946
4022
 
4023
+ // src/lib/swap/swap.approve.ts
4024
+ var APPROVE_WATCH_INTERVAL_MS = 4e3;
4025
+ var APPROVE_PROMPT_TIMEOUT_MS = 5 * 60 * 1e3;
4026
+ async function approveWatched(deps, options) {
4027
+ const { amount, symbol, chainId } = options;
4028
+ const landed = (allowance) => amount === 0n ? allowance === 0n : allowance >= amount;
4029
+ const sleep2 = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
4030
+ return new Promise((resolve, reject) => {
4031
+ let done = false;
4032
+ const finish = (settle) => {
4033
+ if (done) return;
4034
+ done = true;
4035
+ clearTimeout(timer);
4036
+ settle();
4037
+ };
4038
+ const timer = setTimeout(
4039
+ () => finish(
4040
+ () => reject(
4041
+ new OwneyError(
4042
+ "SWAP_WALLET_PROMPT_TIMEOUT",
4043
+ // Hedged: a wallet that never answered may still have sent it.
4044
+ `Your wallet didn't answer the request to approve your ${symbol}. Check your wallet before trying again.`,
4045
+ {
4046
+ chainId,
4047
+ prompt: "approve",
4048
+ timeoutMs: APPROVE_PROMPT_TIMEOUT_MS
4049
+ }
4050
+ )
4051
+ )
4052
+ ),
4053
+ APPROVE_PROMPT_TIMEOUT_MS
4054
+ );
4055
+ deps.send().then(async (hash) => {
4056
+ clearTimeout(timer);
4057
+ await deps.waitForReceipt(hash);
4058
+ return hash;
4059
+ }).then(
4060
+ (hash) => finish(() => resolve(hash)),
4061
+ (error) => finish(() => reject(error))
4062
+ );
4063
+ void (async () => {
4064
+ while (!done) {
4065
+ await sleep2(APPROVE_WATCH_INTERVAL_MS);
4066
+ if (done) return;
4067
+ try {
4068
+ if (landed(await deps.readAllowance())) {
4069
+ debugLog(
4070
+ "owney-sdk",
4071
+ "approve: landed on chain before the wallet answered"
4072
+ );
4073
+ finish(() => resolve(void 0));
4074
+ return;
4075
+ }
4076
+ } catch {
4077
+ }
4078
+ }
4079
+ })();
4080
+ });
4081
+ }
4082
+
3947
4083
  // src/lib/swap/swap.permit.ts
3948
4084
  import {
3949
4085
  domainSeparator,
@@ -4673,6 +4809,7 @@ function makeSponsoredDepositCallback(deps) {
4673
4809
  // src/lib/walletconnect-switch.ts
4674
4810
  var WALLET_SWITCH_TIMEOUT_MS = 12e4;
4675
4811
  var HOLD_CHAIN_MS = 15e3;
4812
+ var MAX_RESENDS = 2;
4676
4813
  var holds = /* @__PURE__ */ new Map();
4677
4814
  function parseChainId(raw) {
4678
4815
  if (typeof raw === "number") return raw;
@@ -4681,76 +4818,28 @@ function parseChainId(raw) {
4681
4818
  const id = ref.startsWith("0x") ? Number.parseInt(ref, 16) : Number(ref);
4682
4819
  return Number.isFinite(id) ? id : void 0;
4683
4820
  }
4684
- function walletConnectSession(provider) {
4821
+ function walletConnectCore(provider) {
4685
4822
  const p = provider;
4686
4823
  const core = p?.signer ?? p;
4687
- if (typeof core?.request !== "function" || typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
4824
+ if (typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
4688
4825
  return null;
4689
4826
  }
4690
4827
  const peer = core.session.peer?.metadata?.name ?? "";
4691
- if (/metamask/i.test(peer)) {
4692
- return { core, strategy: "remote-wallet" };
4693
- }
4694
- if (/fireblocks/i.test(peer)) {
4695
- return { core, strategy: "session-default" };
4696
- }
4697
- return null;
4698
- }
4699
- function approvedChains(core) {
4700
- const approved = /* @__PURE__ */ new Set();
4701
- for (const namespace of Object.values(core.session.namespaces ?? {})) {
4702
- for (const chain of namespace.chains ?? []) approved.add(chain);
4703
- for (const account of namespace.accounts ?? []) {
4704
- const [namespaceName, reference] = account.split(":");
4705
- if (namespaceName && reference) {
4706
- approved.add(`${namespaceName}:${reference}`);
4707
- }
4708
- }
4709
- }
4710
- return approved;
4711
- }
4712
- async function selectSessionDefaultChain(core, chainId) {
4713
- const target = `eip155:${chainId}`;
4714
- if (!approvedChains(core).has(target)) {
4715
- throw new Error(
4716
- `The WalletConnect session has not approved ${target}. Reconnect the wallet and try again.`
4717
- );
4718
- }
4719
- core.setDefaultChain(target);
4720
- const selected = parseChainId(
4721
- await core.request({ method: "eth_chainId" })
4722
- );
4723
- debugLog("wc-switch", "selected WalletConnect session default", {
4724
- peer: core.session.peer?.metadata?.name,
4725
- target: chainId,
4726
- selected
4727
- });
4728
- if (selected !== chainId) {
4729
- throw new Error(
4730
- `WalletConnect stayed on chain ${selected ?? "unknown"}; expected ${chainId}.`
4731
- );
4732
- }
4828
+ if (!/metamask/i.test(peer)) return null;
4829
+ return core;
4733
4830
  }
4734
4831
  async function switchWalletConnectChain(provider, chainId, timeoutMs = WALLET_SWITCH_TIMEOUT_MS) {
4735
- const session = walletConnectSession(provider);
4736
- if (!session) return false;
4737
- const { core, strategy } = session;
4832
+ const core = walletConnectCore(provider);
4833
+ if (!core) return false;
4738
4834
  holds.get(core.session.topic)?.();
4739
- if (strategy === "session-default") {
4740
- await selectSessionDefaultChain(core, chainId);
4741
- return true;
4742
- }
4743
4835
  await requestSwitch(core, provider, chainId, timeoutMs);
4744
- holdChain(core, chainId);
4836
+ holdChain(core, provider, chainId);
4745
4837
  return true;
4746
4838
  }
4747
4839
  async function requestSwitch(core, provider, chainId, timeoutMs) {
4748
- const current = parseChainId(
4840
+ const current = Number(
4749
4841
  await provider.request({ method: "eth_chainId" })
4750
4842
  );
4751
- if (current === void 0) {
4752
- throw new Error("WalletConnect could not report its current chain.");
4753
- }
4754
4843
  const hexChainId = `0x${chainId.toString(16)}`;
4755
4844
  let timer;
4756
4845
  try {
@@ -4780,27 +4869,26 @@ async function requestSwitch(core, provider, chainId, timeoutMs) {
4780
4869
  } catch {
4781
4870
  }
4782
4871
  }
4783
- function holdChain(core, chainId) {
4872
+ function holdChain(core, provider, chainId) {
4784
4873
  if (typeof core.on !== "function" || typeof core.removeListener !== "function") {
4785
4874
  return;
4786
4875
  }
4787
- let repins = 0;
4876
+ let resends = 0;
4788
4877
  const listener = (raw) => {
4789
4878
  const reported = parseChainId(raw);
4790
4879
  debugLog("wc-switch", "wallet reported chain", {
4791
4880
  reported,
4792
4881
  holding: chainId,
4793
- repins
4882
+ resends
4794
4883
  });
4795
4884
  if (reported === void 0 || reported === chainId) return;
4796
- repins += 1;
4797
- try {
4798
- core.setDefaultChain(`eip155:${chainId}`);
4799
- } catch (error) {
4800
- debugLog("wc-switch", "session re-pin failed", {
4885
+ if (resends >= MAX_RESENDS) return;
4886
+ resends += 1;
4887
+ void requestSwitch(core, provider, chainId, WALLET_SWITCH_TIMEOUT_MS).catch(
4888
+ (error) => debugLog("wc-switch", "re-switch failed", {
4801
4889
  error: error instanceof Error ? error.message : String(error)
4802
- });
4803
- }
4890
+ })
4891
+ );
4804
4892
  };
4805
4893
  const release = () => {
4806
4894
  clearTimeout(timer);
@@ -4814,7 +4902,7 @@ function holdChain(core, chainId) {
4814
4902
  holds.set(core.session.topic, release);
4815
4903
  }
4816
4904
  function withWalletConnectSwitch(provider) {
4817
- if (!walletConnectSession(provider)) return provider;
4905
+ if (!walletConnectCore(provider)) return provider;
4818
4906
  const target = provider;
4819
4907
  const request2 = async (args) => {
4820
4908
  if (args?.method !== "wallet_switchEthereumChain") {
@@ -4846,7 +4934,7 @@ function makeSponsoredWethCallback(deps) {
4846
4934
  if (!token) {
4847
4935
  throw new OwneyError(
4848
4936
  "CHAIN_UNSUPPORTED",
4849
- `No sponsored WETH configured for chain ${chainId}`
4937
+ `No sponsored ${deps.assetSymbol} configured for chain ${chainId}`
4850
4938
  );
4851
4939
  }
4852
4940
  const amountWei = BigInt(amount);
@@ -4859,14 +4947,14 @@ function makeSponsoredWethCallback(deps) {
4859
4947
  if (balance < amountWei) {
4860
4948
  throw new OwneyError(
4861
4949
  "DEPOSIT_INSUFFICIENT_BALANCE",
4862
- "Insufficient WETH balance for this deposit.",
4950
+ `Insufficient ${deps.assetSymbol} balance for this deposit.`,
4863
4951
  { token, chainId: cid, balance: balance.toString(), amount }
4864
4952
  );
4865
4953
  }
4866
4954
  } catch (err) {
4867
4955
  if (err instanceof OwneyError) throw err;
4868
4956
  console.warn(
4869
- "[owney-sdk] WETH balance pre-check failed (non-fatal):",
4957
+ `[owney-sdk] ${deps.assetSymbol} balance pre-check failed (non-fatal):`,
4870
4958
  err instanceof Error ? err.message : String(err)
4871
4959
  );
4872
4960
  }
@@ -4878,7 +4966,7 @@ function makeSponsoredWethCallback(deps) {
4878
4966
  if (allowance < amountWei) {
4879
4967
  throw new OwneyError(
4880
4968
  "PERMIT2_APPROVAL_REQUIRED",
4881
- "WETH gasless deposits need a one-time Permit2 approval; call approvePermit2() first",
4969
+ `${deps.assetSymbol} gasless deposits need a one-time Permit2 approval; call approvePermit2() first`,
4882
4970
  { token, chainId: cid, allowance: allowance.toString(), amount }
4883
4971
  );
4884
4972
  }
@@ -5065,8 +5153,22 @@ var SPONSORED_WETH_BY_CHAIN = {
5065
5153
  42161: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
5066
5154
  1: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
5067
5155
  };
5156
+ function sponsoredTokenMap(asset) {
5157
+ if (asset === "USDC") return SPONSORED_USDC_BY_CHAIN;
5158
+ if (asset === "WETH") return SPONSORED_WETH_BY_CHAIN;
5159
+ return Object.fromEntries(
5160
+ SUPPORTED_CHAIN_IDS.flatMap((id) => {
5161
+ const a = tokenAddress(asset, id);
5162
+ return a ? [[id, a]] : [];
5163
+ })
5164
+ );
5165
+ }
5166
+ var PERMIT2_ASSETS = /* @__PURE__ */ new Set(["WETH", "USDT"]);
5167
+ function isPermit2Asset(asset) {
5168
+ return PERMIT2_ASSETS.has(asset);
5169
+ }
5068
5170
  function shouldFallbackToUserPaid(error, asset, appCallback) {
5069
- return (asset === "WETH" || asset === "USDC") && appCallback === void 0 && error instanceof OwneyError && error.code === "SPONSOR_REQUEST_FAILED" && error.details?.safeToFallback === true;
5171
+ return SUPPORTED_TOKENS.includes(asset) && appCallback === void 0 && error instanceof OwneyError && error.code === "SPONSOR_REQUEST_FAILED" && error.details?.safeToFallback === true;
5070
5172
  }
5071
5173
  var OwneySDK = class {
5072
5174
  agents = /* @__PURE__ */ new Map();
@@ -5089,9 +5191,8 @@ var OwneySDK = class {
5089
5191
  userPoolCustomization = false;
5090
5192
  routingApiBaseUrl;
5091
5193
  referralSource;
5092
- sessionStore;
5093
- cachedSponsoredCallback = null;
5094
- cachedWethSponsoredCallback = null;
5194
+ cachedSponsoredCallbacks = /* @__PURE__ */ new Map();
5195
+ cachedPermit2SponsoredCallbacks = /* @__PURE__ */ new Map();
5095
5196
  paymasterServiceUrl;
5096
5197
  cachedSponsoredCallsCallbacks = /* @__PURE__ */ new Map();
5097
5198
  agentReads = new AgentReads();
@@ -5113,7 +5214,6 @@ var OwneySDK = class {
5113
5214
  this.routingApiBaseUrl = config.routingApiBaseUrl;
5114
5215
  this.paymasterServiceUrl = config.paymasterServiceUrl;
5115
5216
  this.referralSource = config.referralSource;
5116
- this.sessionStore = config.sessionStore;
5117
5217
  this.userPoolCustomization = config.userPoolCustomization ?? false;
5118
5218
  }
5119
5219
  /**
@@ -5140,8 +5240,8 @@ var OwneySDK = class {
5140
5240
  walletAddress,
5141
5241
  chainId: null
5142
5242
  };
5143
- this.cachedSponsoredCallback = null;
5144
- this.cachedWethSponsoredCallback = null;
5243
+ this.cachedSponsoredCallbacks.clear();
5244
+ this.cachedPermit2SponsoredCallbacks.clear();
5145
5245
  this.cachedSponsoredCallsCallbacks.clear();
5146
5246
  }
5147
5247
  /**
@@ -5157,8 +5257,8 @@ var OwneySDK = class {
5157
5257
  this.agentReads.clearInFlight();
5158
5258
  this.activationChecks.clear();
5159
5259
  this.state = null;
5160
- this.cachedSponsoredCallback = null;
5161
- this.cachedWethSponsoredCallback = null;
5260
+ this.cachedSponsoredCallbacks.clear();
5261
+ this.cachedPermit2SponsoredCallbacks.clear();
5162
5262
  this.cachedSponsoredCallsCallbacks.clear();
5163
5263
  }
5164
5264
  isAgentDisabled(agentId) {
@@ -5208,9 +5308,9 @@ var OwneySDK = class {
5208
5308
  * provider with viem `custom(provider)` to read token meta and sign the
5209
5309
  * `TransferWithAuthorization`, then POSTs to the sponsor API.
5210
5310
  */
5211
- getDefaultSponsoredCallback(onApproved) {
5212
- if (!onApproved && this.cachedSponsoredCallback)
5213
- return this.cachedSponsoredCallback;
5311
+ getDefaultSponsoredCallback(asset, onApproved) {
5312
+ const cached = this.cachedSponsoredCallbacks.get(asset);
5313
+ if (!onApproved && cached) return cached;
5214
5314
  const provider = this.requireConnectedProvider();
5215
5315
  const owner = this.state.walletAddress;
5216
5316
  const callback = makeSponsoredDepositCallback({
@@ -5218,7 +5318,7 @@ var OwneySDK = class {
5218
5318
  baseUrl: this.routingApiBaseUrl,
5219
5319
  ownerAddress: owner,
5220
5320
  onApproved,
5221
- tokenAddressByChain: SPONSORED_USDC_BY_CHAIN,
5321
+ tokenAddressByChain: sponsoredTokenMap(asset),
5222
5322
  // Casts work around viem's chain-narrowed Client vs the generic
5223
5323
  // PublicClient/WalletClient param types — structurally identical at
5224
5324
  // runtime, but the two share a name TS treats as unrelated.
@@ -5235,14 +5335,13 @@ var OwneySDK = class {
5235
5335
  transport: custom(provider)
5236
5336
  })
5237
5337
  });
5238
- if (!onApproved) this.cachedSponsoredCallback = callback;
5338
+ if (!onApproved) this.cachedSponsoredCallbacks.set(asset, callback);
5239
5339
  return callback;
5240
5340
  }
5241
5341
  /**
5242
- * Lazily builds (and caches) the default Permit2 sponsored WETH deposit
5243
- * callback used when the caller omits `depositCallback` for a WETH
5244
- * deposit. Mirrors `getDefaultSponsoredCallback()` but signs a Permit2
5245
- * `PermitTransferFrom` instead of an EIP-3009 authorization.
5342
+ * Lazily builds (and caches, per asset) the default paymaster-sponsored
5343
+ * deposit callback used when the caller omits `depositCallback` and a
5344
+ * `paymasterServiceUrl` is configured. One rail serves every asset.
5246
5345
  */
5247
5346
  getDefaultSponsoredCallsCallback(asset, onApproved) {
5248
5347
  const cached = this.cachedSponsoredCallsCallbacks.get(asset);
@@ -5253,20 +5352,20 @@ var OwneySDK = class {
5253
5352
  ownerAddress: this.state.walletAddress,
5254
5353
  paymasterServiceUrl: this.paymasterServiceUrl,
5255
5354
  onApproved,
5256
- tokenAddressByChain: asset === "WETH" ? SPONSORED_WETH_BY_CHAIN : SPONSORED_USDC_BY_CHAIN
5355
+ tokenAddressByChain: sponsoredTokenMap(asset)
5257
5356
  });
5258
5357
  if (!onApproved) this.cachedSponsoredCallsCallbacks.set(asset, callback);
5259
5358
  return callback;
5260
5359
  }
5261
5360
  /**
5262
- * Lazily builds (and caches) the default Permit2 sponsored WETH deposit
5263
- * callback used when the caller omits `depositCallback` for a WETH deposit.
5264
- * Mirrors `getDefaultSponsoredCallback()` but signs a Permit2
5265
- * `PermitTransferFrom` instead of an EIP-3009 authorization.
5361
+ * Lazily builds (and caches, per asset) the default Permit2 sponsored
5362
+ * deposit callback used when the caller omits `depositCallback` for a
5363
+ * Permit2 asset (WETH, USDT). Mirrors `getDefaultSponsoredCallback()` but
5364
+ * signs a Permit2 `PermitTransferFrom` instead of an EIP-3009 authorization.
5266
5365
  */
5267
- getDefaultWethSponsoredCallback(onApproved) {
5268
- if (!onApproved && this.cachedWethSponsoredCallback)
5269
- return this.cachedWethSponsoredCallback;
5366
+ getDefaultPermit2SponsoredCallback(asset, onApproved) {
5367
+ const cached = this.cachedPermit2SponsoredCallbacks.get(asset);
5368
+ if (!onApproved && cached) return cached;
5270
5369
  const provider = this.requireConnectedProvider();
5271
5370
  const owner = this.state.walletAddress;
5272
5371
  const callback = makeSponsoredWethCallback({
@@ -5274,7 +5373,8 @@ var OwneySDK = class {
5274
5373
  baseUrl: this.routingApiBaseUrl,
5275
5374
  ownerAddress: owner,
5276
5375
  onApproved,
5277
- tokenAddressByChain: SPONSORED_WETH_BY_CHAIN,
5376
+ tokenAddressByChain: sponsoredTokenMap(asset),
5377
+ assetSymbol: asset,
5278
5378
  // Casts work around viem's chain-narrowed Client vs the generic
5279
5379
  // PublicClient/WalletClient param types — structurally identical at
5280
5380
  // runtime, but the two share a name TS treats as unrelated.
@@ -5291,7 +5391,7 @@ var OwneySDK = class {
5291
5391
  transport: custom(provider)
5292
5392
  })
5293
5393
  });
5294
- if (!onApproved) this.cachedWethSponsoredCallback = callback;
5394
+ if (!onApproved) this.cachedPermit2SponsoredCallbacks.set(asset, callback);
5295
5395
  return callback;
5296
5396
  }
5297
5397
  getAgent(agentId) {
@@ -5387,12 +5487,7 @@ var OwneySDK = class {
5387
5487
  }
5388
5488
  createAgent(agentId, key2) {
5389
5489
  if (agentId === "zyfai") {
5390
- return new ZyfaiAgent(
5391
- key2,
5392
- this.zyfaiRpcUrls,
5393
- this.referralSource,
5394
- this.sessionStore
5395
- );
5490
+ return new ZyfaiAgent(key2, this.zyfaiRpcUrls, this.referralSource);
5396
5491
  }
5397
5492
  return null;
5398
5493
  }
@@ -5554,7 +5649,8 @@ var OwneySDK = class {
5554
5649
  }
5555
5650
  const state = this.requireState();
5556
5651
  const chainId = options.chainId ?? this.requireChainId();
5557
- const effectiveCallback = depositCallback ?? (this.paymasterServiceUrl ? this.getDefaultSponsoredCallsCallback(asset, onApproved) : asset === "WETH" ? this.getDefaultWethSponsoredCallback(onApproved) : this.getDefaultSponsoredCallback(onApproved));
5652
+ const sponsoredAsset = asset;
5653
+ const effectiveCallback = depositCallback ?? (this.paymasterServiceUrl ? this.getDefaultSponsoredCallsCallback(sponsoredAsset, onApproved) : isPermit2Asset(sponsoredAsset) ? this.getDefaultPermit2SponsoredCallback(sponsoredAsset, onApproved) : this.getDefaultSponsoredCallback(sponsoredAsset, onApproved));
5558
5654
  if (agentId) {
5559
5655
  if (this.isAgentDisabled(agentId)) {
5560
5656
  throw new OwneyError(
@@ -5668,15 +5764,16 @@ var OwneySDK = class {
5668
5764
  *
5669
5765
  * 1. Missing Permit2 allowance: when the app did not supply its own
5670
5766
  * callback and the attempt fails with `PERMIT2_APPROVAL_REQUIRED` on a
5671
- * WETH deposit, this is the wallet's first gasless WETH deposit. We send
5672
- * the one-time (user-paid) Permit2 approval via `approvePermit2()` and
5673
- * retry the SAME sponsored attempt once. Bounded to one approval attempt
5674
- * per call so a wallet/agent that keeps reporting the allowance as
5675
- * missing can't loop forever. If `approvePermit2()` itself throws (e.g.
5767
+ * Permit2 asset (WETH, USDT), this is the wallet's first gasless deposit
5768
+ * of that asset on this chain. We send the one-time (user-paid) Permit2
5769
+ * approval via `approvePermit2(asset)` and retry the SAME sponsored
5770
+ * attempt once. Bounded to one approval attempt per call so a
5771
+ * wallet/agent that keeps reporting the allowance as missing can't loop
5772
+ * forever. If `approvePermit2()` itself throws (e.g.
5676
5773
  * the user rejects the wallet prompt), that error propagates as-is —
5677
5774
  * the user said no to a transaction, so we must not turn around and ask
5678
5775
  * them to pay for a different one via the fallback below.
5679
- * 2. `shouldFallbackToUserPaid`: the SDK's own WETH sponsor path failed at
5776
+ * 2. `shouldFallbackToUserPaid`: the SDK's own sponsor path failed at
5680
5777
  * the infrastructure layer in a provably safe-to-retry way, so we warn
5681
5778
  * and retry once with `undefined`, falling through to a user-paid
5682
5779
  * native deposit. This still applies after a successful Permit2
@@ -5705,12 +5802,12 @@ var OwneySDK = class {
5705
5802
  try {
5706
5803
  return await attempt(effectiveCallback);
5707
5804
  } catch (error) {
5708
- if (!approvalAttempted && appCallback === void 0 && asset === "WETH" && error instanceof OwneyError && error.code === "PERMIT2_APPROVAL_REQUIRED") {
5805
+ if (!approvalAttempted && appCallback === void 0 && isPermit2Asset(asset) && error instanceof OwneyError && error.code === "PERMIT2_APPROVAL_REQUIRED") {
5709
5806
  approvalAttempted = true;
5710
5807
  console.warn(
5711
- "[owney-sdk] First WETH deposit: sending one-time Permit2 approval..."
5808
+ `[owney-sdk] First ${asset} deposit: sending one-time Permit2 approval...`
5712
5809
  );
5713
- await this.approvePermit2();
5810
+ await this.approvePermit2(asset);
5714
5811
  continue;
5715
5812
  }
5716
5813
  if (!shouldFallbackToUserPaid(error, asset, appCallback)) throw error;
@@ -6147,22 +6244,45 @@ var OwneySDK = class {
6147
6244
  functionName: "allowance",
6148
6245
  args: [state.walletAddress, spender]
6149
6246
  }),
6150
- approve: async (spender, amount) => {
6151
- const hash = await wallet.writeContract({
6152
- address: quote.src.address,
6153
- abi: ERC20_ALLOWANCE_ABI,
6154
- functionName: "approve",
6155
- args: [spender, amount],
6156
- account: state.walletAddress,
6157
- chain: srcChain
6158
- });
6159
- await srcPublic.waitForTransactionReceipt({
6160
- hash,
6161
- confirmations: 1,
6162
- timeout: receiptTimeoutMs(quote.src.chainId)
6163
- });
6164
- return hash;
6165
- },
6247
+ // Watched on chain as well as through the wallet: Trust's extension can
6248
+ // land the approval and never return its hash (ROUT-759).
6249
+ approve: (spender, amount) => approveWatched(
6250
+ {
6251
+ send: () => wallet.writeContract({
6252
+ address: quote.src.address,
6253
+ abi: ERC20_ALLOWANCE_ABI,
6254
+ functionName: "approve",
6255
+ args: [spender, amount],
6256
+ account: state.walletAddress,
6257
+ chain: srcChain
6258
+ }),
6259
+ waitForReceipt: async (hash) => {
6260
+ const receipt = await srcPublic.waitForTransactionReceipt({
6261
+ hash,
6262
+ confirmations: 1,
6263
+ timeout: receiptTimeoutMs(quote.src.chainId)
6264
+ });
6265
+ if (receipt.status !== "success") {
6266
+ throw new OwneyError(
6267
+ "SWAP_REQUEST_FAILED",
6268
+ `Approval transaction reverted (tx ${hash})`,
6269
+ { hash }
6270
+ );
6271
+ }
6272
+ },
6273
+ readAllowance: () => srcPublic.readContract({
6274
+ address: quote.src.address,
6275
+ abi: ERC20_ALLOWANCE_ABI,
6276
+ functionName: "allowance",
6277
+ args: [state.walletAddress, spender]
6278
+ })
6279
+ },
6280
+ {
6281
+ amount,
6282
+ symbol: quote.src.symbol,
6283
+ chainId: quote.src.chainId
6284
+ }
6285
+ ),
6166
6286
  ensureChain: (chainId) => this.ensureSwapChain(chainId),
6167
6287
  /**
6168
6288
  * Sign the approval instead of paying for it. Null means the token
@@ -6250,30 +6370,33 @@ var OwneySDK = class {
6250
6370
  * figure directly. It is the entire arrival, so there is no slack: anything
6251
6371
  * that spends the target asset between the two fails the deposit outright.
6252
6372
  *
6253
- * Something does. A first WETH deposit needs a one-time Permit2 approval,
6254
- * and that approval is a transaction. A wallet holding no native gas token -
6255
- * the normal state of someone who just swapped everything INTO WETH - pays
6256
- * for it out of the WETH. The deposit then asked for ~2e12 wei more than was
6257
- * left and refused with DEPOSIT_INSUFFICIENT_BALANCE, under a wrapper saying
6258
- * the funds were safe but unadded (ROUT-242).
6373
+ * Something does. A first deposit of a Permit2 asset (WETH, USDT) needs a
6374
+ * one-time Permit2 approval, and that approval is a transaction. For WETH,
6375
+ * a wallet holding no native gas token - the normal state of someone who
6376
+ * just swapped everything INTO WETH - pays for it out of the WETH. The
6377
+ * deposit then asked for ~2e12 wei more than was left and refused with
6378
+ * DEPOSIT_INSUFFICIENT_BALANCE, under a wrapper saying the funds were safe
6379
+ * but unadded (ROUT-242). For USDT the gas cannot come out of the token, so
6380
+ * this step only adds the one-time approval and the read changes nothing.
6259
6381
  *
6260
6382
  * So the approval happens here, before the amount is settled, and the amount
6261
6383
  * comes from a read taken after it. Two things this deliberately is not:
6262
6384
  *
6263
6385
  * - It is not a balance sweep. `received` is a DELTA over the pre-swap
6264
- * balance, so a wallet already holding WETH reads far above it; depositing
6265
- * the balance would move funds the user never offered. The arrival is the
6266
- * ceiling and the balance is only ever allowed to lower it.
6267
- * - It does not touch USDC, which moves on signed typed data and so spends
6268
- * nothing of the user's in between, nor a paymaster-configured client,
6269
- * where the sponsor covers the transfer and Permit2 never applies.
6386
+ * balance, so a wallet already holding the asset reads far above it;
6387
+ * depositing the balance would move funds the user never offered. The
6388
+ * arrival is the ceiling and the balance is only ever allowed to lower it.
6389
+ * - It does not touch USDC or EURC, which move on signed typed data
6390
+ * (EIP-3009) and so spend nothing of the user's in between, nor a
6391
+ * paymaster-configured client, where the sponsor covers the transfer and
6392
+ * Permit2 never applies.
6270
6393
  */
6271
6394
  async settleSwapDepositAmount(chainId, token, symbol, received) {
6272
- if (symbol !== "WETH" || this.paymasterServiceUrl) {
6395
+ if (!isPermit2Asset(symbol) || this.paymasterServiceUrl) {
6273
6396
  return received.toString();
6274
6397
  }
6275
6398
  const allowance = await this.readTokenPermit2Allowance(chainId, token);
6276
- if (allowance < received) await this.approvePermit2();
6399
+ if (allowance < received) await this.approvePermit2(symbol);
6277
6400
  const balance = await this.readTokenBalance(chainId, token);
6278
6401
  return (balance < received ? balance : received).toString();
6279
6402
  }
@@ -6438,7 +6561,10 @@ var OwneySDK = class {
6438
6561
  );
6439
6562
  }
6440
6563
  await this.ensureSwapChain(entry.chainId);
6441
- const token = entry.symbol === "WETH" ? SPONSORED_WETH_BY_CHAIN[entry.chainId] : void 0;
6564
+ const supported = SUPPORTED_TOKENS.includes(
6565
+ entry.symbol
6566
+ );
6567
+ const token = supported ? sponsoredTokenMap(entry.symbol)[entry.chainId] : void 0;
6442
6568
  const amount = token ? await this.settleSwapDepositAmount(
6443
6569
  entry.chainId,
6444
6570
  token,
@@ -7591,7 +7717,7 @@ var OwneySDK = class {
7591
7717
  /**
7592
7718
  * Ensure the given asset uses backend protocol auto-selection for the active
7593
7719
  * chain's account. No-op (returns false) for agents that don't support it.
7594
- * @param asset - "USDC" or "WETH".
7720
+ * @param asset - Asset symbol (e.g. "USDC").
7595
7721
  * @param agentId - Agent to target. Defaults to "zyfai".
7596
7722
  * @returns whether a profile write occurred.
7597
7723
  */
@@ -7616,23 +7742,28 @@ var OwneySDK = class {
7616
7742
  return pending;
7617
7743
  }
7618
7744
  /**
7619
- * One-time, user-paid approval of Permit2 on the sponsored WETH token for
7620
- * the active chain. Required once per wallet per chain before gasless WETH
7621
- * deposits; afterwards deposit() is signature-only. Resolves only after the
7622
- * approval transaction is mined (1 confirmation), so a subsequent deposit()
7623
- * will see the new allowance; throws if the transaction reverted.
7745
+ * One-time, user-paid approval of Permit2 on the sponsored WETH (default) or
7746
+ * USDT token for the active chain. Required once per wallet per chain before
7747
+ * gasless deposits of that asset; afterwards deposit() is signature-only.
7748
+ * Resolves only after the approval transaction is mined (1 confirmation), so
7749
+ * a subsequent deposit() will see the new allowance; throws if the
7750
+ * transaction reverted.
7751
+ *
7752
+ * On mainnet USDT only (`needsAllowanceReset`), a non-zero existing allowance
7753
+ * is first zeroed in its own transaction. If the user rejects the second
7754
+ * prompt, the previous Permit2 allowance stays zeroed; calling this again
7755
+ * approves from zero in a single transaction.
7624
7756
  * @returns the approval transaction hash.
7625
7757
  */
7626
7758
  async approvePermit2(asset = "WETH") {
7627
- void asset;
7628
7759
  const state = this.requireState();
7629
7760
  const chainId = this.requireChainId();
7630
- this.validateAssetSupport(this.getAgent("zyfai"), chainId, "WETH");
7631
- const token = SPONSORED_WETH_BY_CHAIN[chainId];
7761
+ this.validateAssetSupport(this.getAgent("zyfai"), chainId, asset);
7762
+ const token = sponsoredTokenMap(asset)[chainId];
7632
7763
  if (!token) {
7633
7764
  throw new OwneyError(
7634
7765
  "CHAIN_UNSUPPORTED",
7635
- `No sponsored WETH on chain ${chainId}`
7766
+ `No sponsored ${asset} on chain ${chainId}`
7636
7767
  );
7637
7768
  }
7638
7769
  const provider = this.requireConnectedProvider();
@@ -7650,22 +7781,52 @@ var OwneySDK = class {
7650
7781
  wallet,
7651
7782
  chainId
7652
7783
  );
7653
- const hash = await wallet.writeContract({
7654
- address: token,
7655
- abi: ERC20_ALLOWANCE_ABI,
7656
- functionName: "approve",
7657
- args: [PERMIT2_ADDRESS, MAX_UINT256],
7658
- account: state.walletAddress,
7659
- chain: VIEM_CHAIN2[chainId]
7784
+ const currentAllowance = await this.readTokenPermit2Allowance(
7785
+ chainId,
7786
+ token
7787
+ ).catch(
7788
+ () => readPermit2Allowance(
7789
+ publicClient,
7790
+ token,
7791
+ state.walletAddress
7792
+ )
7793
+ ).catch((err) => {
7794
+ if (!needsAllowanceReset(token)) return 0n;
7795
+ throw new OwneyError(
7796
+ "PERMIT2_APPROVAL_REQUIRED",
7797
+ `Could not read the current ${asset} allowance for Permit2; please try again.`,
7798
+ {
7799
+ token,
7800
+ chainId,
7801
+ reason: "ALLOWANCE_UNREADABLE",
7802
+ cause: err instanceof Error ? err.message : String(err)
7803
+ }
7804
+ );
7660
7805
  });
7661
- const receipt = await publicClient.waitForTransactionReceipt({
7662
- hash,
7663
- confirmations: 1
7806
+ return approveWithResetIfNeeded({
7807
+ token,
7808
+ currentAllowance,
7809
+ spender: PERMIT2_ADDRESS,
7810
+ amount: MAX_UINT256,
7811
+ approve: async (spender, amount) => {
7812
+ const hash = await wallet.writeContract({
7813
+ address: token,
7814
+ abi: ERC20_ALLOWANCE_ABI,
7815
+ functionName: "approve",
7816
+ args: [spender, amount],
7817
+ account: state.walletAddress,
7818
+ chain: VIEM_CHAIN2[chainId]
7819
+ });
7820
+ const receipt = await publicClient.waitForTransactionReceipt({
7821
+ hash,
7822
+ confirmations: 1
7823
+ });
7824
+ if (receipt.status !== "success") {
7825
+ throw new Error(`Permit2 approval reverted (tx ${hash})`);
7826
+ }
7827
+ return hash;
7828
+ }
7664
7829
  });
7665
- if (receipt.status !== "success") {
7666
- throw new Error(`Permit2 approval reverted (tx ${hash})`);
7667
- }
7668
- return hash;
7669
7830
  }
7670
7831
  // --- Discovery (no wallet required) ---
7671
7832
  /**