@owney/sdk 0.8.0-beta.1 → 0.8.0

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", "EURC", "USDT"];
214
+ var SUPPORTED_TOKENS = ["USDC", "WETH"];
215
215
  var SUPPORTED_CHAIN_IDS = P_SUPPORTED_CHAINS.chainIds;
216
216
  var SUPPORTED_CHAINS = P_SUPPORTED_CHAINS.chains;
217
217
  var SupportedAssets = [
@@ -250,31 +250,8 @@ 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
271
253
  }
272
254
  ];
273
- function tokenAddress(symbol, chainId) {
274
- return SupportedAssets.find(
275
- (a) => a.symbol === symbol && a.chainId === chainId
276
- )?.address;
277
- }
278
255
 
279
256
  // src/lib/debug.ts
280
257
  var configuredDebug = false;
@@ -339,8 +316,6 @@ function matchesAsset(symbol, asset) {
339
316
  // src/agents/zyfai/zyfai.mapper.ts
340
317
  var DECIMALS_BY_SYMBOL = {
341
318
  usdc: 6,
342
- eurc: 6,
343
- usdt: 6,
344
319
  weth: 18,
345
320
  eth: 18,
346
321
  cbeth: 18,
@@ -537,7 +512,7 @@ function netApy(net, gross, field) {
537
512
  }
538
513
  function usdPerUnit(tokenSymbol, prices) {
539
514
  const symbol = tokenSymbol?.toUpperCase();
540
- if (symbol === "USDC" || symbol === "USDT") return 1;
515
+ if (symbol === "USDC") return 1;
541
516
  const price = symbol ? prices?.[symbol] : void 0;
542
517
  return typeof price === "number" && Number.isFinite(price) && price > 0 ? price : void 0;
543
518
  }
@@ -633,14 +608,16 @@ function splitOpportunity(opportunity) {
633
608
  }
634
609
  function mapEntries(rawEntries, chainId) {
635
610
  const actionMap = {
636
- "Top up wallet": "Top up",
611
+ // EOA -> smart wallet. Named "Top up" before ROUT-758; "Deposit" is what
612
+ // users call it.
613
+ "Top up wallet": "Deposit",
637
614
  "Partial withdraw from protocol": "Withdraw",
638
615
  "Withdraw from protocol": "Withdraw",
639
- // The agent's own leg of a top up: the funds the user sent moving into the
616
+ // The agent's own leg of a deposit: the funds the user sent moving into the
640
617
  // pool that earns the APY. Zyfai emits it as a separate entry seconds after
641
- // "Top up wallet" and for slightly less (gas). `Deposit` already exists in
642
- // the public HistoryAction union, so no consumer type change is needed.
643
- "Deposit to protocol": "Deposit",
618
+ // "Top up wallet" and for slightly less (gas). Smart wallet -> pool, so
619
+ // "Allocate" (ROUT-758; it was "Deposit").
620
+ "Deposit to protocol": "Allocate",
644
621
  // Withdrawing from an async vault (Superform) is logged under its own
645
622
  // label and paid out later in a separate batch (ROUT-624).
646
623
  "Request async withdrawal": "Withdraw",
@@ -942,7 +919,7 @@ var isJwtExpired = (token) => {
942
919
  }
943
920
  };
944
921
  var memorySessions = /* @__PURE__ */ new Map();
945
- var isFreshSession = (session) => !!session && typeof session.isPredeployed === "boolean" && !!session.token && !isJwtExpired(session.token);
922
+ var isFreshSession = (session) => typeof session === "object" && session !== null && typeof session.isPredeployed === "boolean" && !!session.token && !isJwtExpired(session.token);
946
923
  var readLegacySession = (store, address) => {
947
924
  if (!store) return null;
948
925
  const prefix = legacyKeyPrefix(address);
@@ -1024,6 +1001,17 @@ var clearSession = (address, _chainId) => {
1024
1001
  }
1025
1002
  readLegacySession(store, address);
1026
1003
  };
1004
+ var BrowserSessionStore = class {
1005
+ read(_agentId, address) {
1006
+ return readSession(address, 0);
1007
+ }
1008
+ write(_agentId, address, session) {
1009
+ writeSession(address, 0, session);
1010
+ }
1011
+ clear(_agentId, address) {
1012
+ clearSession(address, 0);
1013
+ }
1014
+ };
1027
1015
 
1028
1016
  // src/agents/zyfai/autoSelect.ts
1029
1017
  function buildAutoSelectUpdate(current, asset, chainId) {
@@ -1236,7 +1224,6 @@ var CHAINLINK_ETH_USD_FEED = {
1236
1224
  42161: "0x639Fe6ab55C921f74e7fac1ee960C0B6293ba612",
1237
1225
  1: "0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419"
1238
1226
  };
1239
- var CHAINLINK_EUR_USD_FEED = "0xb49f677943BC038e9857d61E7d053CaA2C1734C1";
1240
1227
  var CHAINLINK_ABI = (0, import_viem.parseAbi)([
1241
1228
  "function latestRoundData() view returns (uint80, int256, uint256, uint256, uint80)"
1242
1229
  ]);
@@ -1246,8 +1233,13 @@ var DEFAULT_ZYFAI_RPC_URLS = {
1246
1233
  42161: "https://arb-mainnet.g.alchemy.com/v2/ZWyVU-9XfS3z8Rn-xkq7V",
1247
1234
  1: "https://eth-mainnet.g.alchemy.com/v2/ZWyVU-9XfS3z8Rn-xkq7V"
1248
1235
  };
1236
+ var WETH_ADDRESS_BY_CHAIN = {
1237
+ 8453: "0x4200000000000000000000000000000000000006",
1238
+ 42161: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
1239
+ 1: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
1240
+ };
1249
1241
  var VIEM_CHAIN = { 8453: import_chains.base, 42161: import_chains.arbitrum, 1: import_chains.mainnet };
1250
- var SPLITTING_ASSETS = SUPPORTED_TOKENS;
1242
+ var SPLITTING_ASSETS = ["USDC", "WETH"];
1251
1243
  var POOL_POLICY_CHAIN_IDS = [8453, 42161, 1];
1252
1244
  var EARNINGS_REFRESH_COOLDOWN_MS = 60 * 60 * 1e3;
1253
1245
  var ZyfaiAgent = class _ZyfaiAgent {
@@ -1259,8 +1251,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
1259
1251
  chain: "BASE",
1260
1252
  assets: [
1261
1253
  { symbol: "USDC", minDepositAmount: "1500000" },
1262
- { symbol: "WETH", minDepositAmount: "500000000000000" },
1263
- { symbol: "EURC", minDepositAmount: "1500000" }
1254
+ { symbol: "WETH", minDepositAmount: "500000000000000" }
1264
1255
  ]
1265
1256
  },
1266
1257
  {
@@ -1281,12 +1272,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
1281
1272
  // the shipped code enforces 0.005 WETH, so match it or deposits reject on-chain.
1282
1273
  assets: [
1283
1274
  { symbol: "USDC", minDepositAmount: "100000000" },
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" }
1275
+ { symbol: "WETH", minDepositAmount: "5000000000000000" }
1290
1276
  ]
1291
1277
  }
1292
1278
  ];
@@ -1308,12 +1294,13 @@ var ZyfaiAgent = class _ZyfaiAgent {
1308
1294
  // RPC error retries on the next fetch.
1309
1295
  withdrawAmountCache = /* @__PURE__ */ new Map();
1310
1296
  ethUsd = null;
1311
- eurUsd = null;
1312
1297
  earningsReads = /* @__PURE__ */ new Map();
1313
1298
  earningsRefreshes = /* @__PURE__ */ new Map();
1314
1299
  earningsSnapshot = null;
1315
1300
  earningsGeneration = 0;
1316
- constructor(apiKey, rpcUrls, referralSource) {
1301
+ sessionStore;
1302
+ constructor(apiKey, rpcUrls, referralSource, sessionStore = new BrowserSessionStore()) {
1303
+ this.sessionStore = sessionStore;
1317
1304
  this.rpcUrls = rpcUrls ?? DEFAULT_ZYFAI_RPC_URLS;
1318
1305
  this.sdk = new import_sdk.ZyfaiSDK({
1319
1306
  apiKey,
@@ -1404,21 +1391,36 @@ var ZyfaiAgent = class _ZyfaiAgent {
1404
1391
  * (Zyfai dist line 1374). At that point `walletClient` + `currentChainId`
1405
1392
  * are populated, so the cache lookup has both keys it needs.
1406
1393
  *
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
+ * The session lives in `sessionStore`: localStorage in the browser (a no-op
1395
+ * on the server), or whatever the host passed in `OwneySDKConfig`.
1409
1396
  */
1397
+ /**
1398
+ * The session store is a cache: an unavailable store must never block
1399
+ * authentication or teardown. Failures read as a cache miss.
1400
+ */
1401
+ async storeOp(op) {
1402
+ try {
1403
+ return await op();
1404
+ } catch (error) {
1405
+ console.warn(
1406
+ "owney-sdk: agent session store failed, continuing without it",
1407
+ error
1408
+ );
1409
+ return null;
1410
+ }
1411
+ }
1410
1412
  installAuthCache() {
1411
- if (typeof window === "undefined") return;
1412
1413
  const internals = this.sdk;
1413
1414
  const original = internals.authenticateUser.bind(internals);
1414
1415
  let inFlight = null;
1415
1416
  const authenticate = async () => {
1416
1417
  if (internals.authenticatedUserId !== null) return;
1417
1418
  const address = internals.walletClient?.account?.address;
1418
- const chainId = internals.currentChainId ?? 0;
1419
1419
  if (address) {
1420
- const cached = readSession(address, chainId);
1421
- if (cached) {
1420
+ const cached = await this.storeOp(
1421
+ () => this.sessionStore.read(this.id, address)
1422
+ );
1423
+ if (isFreshSession(cached)) {
1422
1424
  internals.httpClient.setAuthToken(cached.token);
1423
1425
  internals.authenticatedUserId = cached.userId;
1424
1426
  internals.hasActiveSessionKey = cached.hasActiveSessionKey;
@@ -1428,15 +1430,16 @@ var ZyfaiAgent = class _ZyfaiAgent {
1428
1430
  }
1429
1431
  await original();
1430
1432
  const newAddress = internals.walletClient?.account?.address;
1431
- const newChainId = internals.currentChainId ?? 0;
1432
1433
  const newToken = internals.httpClient.authToken;
1433
1434
  if (newAddress && newToken) {
1434
- writeSession(newAddress, newChainId, {
1435
- token: newToken,
1436
- userId: internals.authenticatedUserId,
1437
- hasActiveSessionKey: internals.hasActiveSessionKey,
1438
- isPredeployed: internals.isPredeployed
1439
- });
1435
+ await this.storeOp(
1436
+ () => this.sessionStore.write(this.id, newAddress, {
1437
+ token: newToken,
1438
+ userId: internals.authenticatedUserId,
1439
+ hasActiveSessionKey: internals.hasActiveSessionKey,
1440
+ isPredeployed: internals.isPredeployed
1441
+ })
1442
+ );
1440
1443
  }
1441
1444
  };
1442
1445
  internals.authenticateUser = () => {
@@ -1502,7 +1505,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
1502
1505
  if (!message.toLowerCase().includes("unauthorized")) throw error;
1503
1506
  const internals = this.sdk;
1504
1507
  const address = internals.walletClient?.account?.address;
1505
- if (address) clearSession(address, chainId);
1508
+ if (address) {
1509
+ await this.storeOp(() => this.sessionStore.clear(this.id, address));
1510
+ }
1506
1511
  return await this.sdk.connectAccount(provider, chainId);
1507
1512
  }
1508
1513
  }
@@ -1530,15 +1535,15 @@ var ZyfaiAgent = class _ZyfaiAgent {
1530
1535
  * it diffs available-vs-enabled by protocol id and writes the full union
1531
1536
  * back, or does nothing when none are missing.
1532
1537
  *
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
+ * Non-fatal: a sync failure must never block activation. Only "USDC" / "WETH"
1539
+ * are modeled per-asset by the Zyfai profile API, so other assets are skipped.
1535
1540
  */
1536
- async ensureProtocolsSynced(chainId, asset, availableProtocols) {
1537
- if (!tokenAddress(asset, chainId)) return;
1541
+ async ensureProtocolsSynced(chainId, asset) {
1542
+ if (asset !== "USDC" && asset !== "WETH") return;
1538
1543
  try {
1539
1544
  const [current, { protocols: available }] = await Promise.all([
1540
1545
  this.sdk.getUserDetails(asset),
1541
- availableProtocols
1546
+ this.sdk.getAvailableProtocols(chainId)
1542
1547
  ]);
1543
1548
  debugLog("zyfai:protocol-sync", `${asset}: profile before sync`, {
1544
1549
  chains: current.chains,
@@ -1586,8 +1591,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
1586
1591
  this.earningsReads.clear();
1587
1592
  this.earningsRefreshes.clear();
1588
1593
  this.earningsSnapshot = null;
1589
- if (this.connectedAddress && this.connectedChainId !== null) {
1590
- clearSession(this.connectedAddress, this.connectedChainId);
1594
+ if (this.connectedAddress) {
1595
+ const address = this.connectedAddress;
1596
+ await this.storeOp(() => this.sessionStore.clear(this.id, address));
1591
1597
  }
1592
1598
  await this.sdk.disconnectAccount();
1593
1599
  this.connectedAddress = null;
@@ -1607,15 +1613,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
1607
1613
  ms: Date.now() - startedAt
1608
1614
  });
1609
1615
  const validChainId = isValidChainId(chainId);
1610
- const availableProtocols = Promise.resolve().then(
1611
- () => this.sdk.getAvailableProtocols(validChainId)
1612
- );
1613
- availableProtocols.catch(() => {
1614
- });
1615
1616
  await Promise.all([
1616
- ...SUPPORTED_TOKENS.map(
1617
- (asset) => this.ensureProtocolsSynced(validChainId, asset, availableProtocols)
1618
- ),
1617
+ this.ensureProtocolsSynced(validChainId, "USDC"),
1618
+ this.ensureProtocolsSynced(validChainId, "WETH"),
1619
1619
  // Retrofit a session key for old wallets that are already deployed and
1620
1620
  // funded but never got one — otherwise their balance stays idle until
1621
1621
  // they happen to deposit again. Only touches Safes that are missing the
@@ -1729,41 +1729,34 @@ var ZyfaiAgent = class _ZyfaiAgent {
1729
1729
  );
1730
1730
  const desiredAutoSelect = policy.autoApproveProtocols;
1731
1731
  for (const asset of SPLITTING_ASSETS) {
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,
1756
- autoSelectProtocols: desiredAutoSelect
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
- );
1732
+ const current = await this.sdk.getUserDetails(asset);
1733
+ if (strategy === void 0 && (current.strategy === "conservative" || current.strategy === "aggressive")) {
1734
+ strategy = current.strategy;
1766
1735
  }
1736
+ const needsUpdate = protocolsPolicyNeedsUpdate(
1737
+ current,
1738
+ desiredProtocols,
1739
+ desiredAutoSelect
1740
+ );
1741
+ debugLog("zyfai:pools", `${asset}: comparing protocols`, {
1742
+ current: {
1743
+ protocols: current.protocols,
1744
+ autoSelectProtocols: current.autoSelectProtocols
1745
+ },
1746
+ desired: {
1747
+ protocols: desiredProtocols,
1748
+ autoSelectProtocols: desiredAutoSelect
1749
+ },
1750
+ decision: needsUpdate ? "will write \u2014 profile differs from the org policy" : "skipping \u2014 profile already matches"
1751
+ });
1752
+ if (!needsUpdate) continue;
1753
+ const update = {
1754
+ asset,
1755
+ autoSelectProtocols: desiredAutoSelect
1756
+ };
1757
+ if (desiredProtocols !== null) update.protocols = desiredProtocols;
1758
+ await this.sdk.updateUserProfile(update);
1759
+ debugLog("zyfai:pools", `${asset}: wrote protocols update`, update);
1767
1760
  }
1768
1761
  const poolResults = await Promise.all(
1769
1762
  universe.map(async (protocol) => {
@@ -1889,7 +1882,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
1889
1882
  await Promise.all(
1890
1883
  selection.strategies.map(async ({ asset, strategy }) => {
1891
1884
  const current = await this.sdk.getUserDetails(asset);
1892
- const selectedProtocols = selection.selections.filter((entry) => entry.asset === asset && entry.pools.length > 0).map((entry) => entry.protocolId);
1885
+ const selectedProtocols = selection.selections.filter(
1886
+ (entry) => entry.asset === asset && entry.pools.length > 0
1887
+ ).map((entry) => entry.protocolId);
1893
1888
  const protocols = [
1894
1889
  .../* @__PURE__ */ new Set([...current.protocols ?? [], ...selectedProtocols])
1895
1890
  ];
@@ -2248,10 +2243,11 @@ var ZyfaiAgent = class _ZyfaiAgent {
2248
2243
  requestedStrategy: "aggressive",
2249
2244
  setupResult
2250
2245
  });
2251
- await this.syncAutoSelect(validChainId, asset);
2252
2246
  if (isOwneyDebug()) {
2253
2247
  try {
2254
- const profileAfterSetup = await this.sdk.getUserDetails(asset);
2248
+ const profileAfterSetup = await this.sdk.getUserDetails(
2249
+ asset === "WETH" ? "WETH" : "USDC"
2250
+ );
2255
2251
  debugLog("zyfai:first-deposit", "profile immediately after setup", {
2256
2252
  asset,
2257
2253
  strategy: profileAfterSetup.strategy,
@@ -2269,9 +2265,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
2269
2265
  validChainId
2270
2266
  );
2271
2267
  const txHash = await depositCallback(smartWallet, validChainId, amount);
2272
- const tokenAddress2 = asset === "USDC" ? void 0 : tokenAddress(asset, validChainId);
2268
+ const tokenAddress = asset === "WETH" ? WETH_ADDRESS_BY_CHAIN[validChainId] : void 0;
2273
2269
  try {
2274
- await (tokenAddress2 ? this.sdk.logDeposit(validChainId, txHash, amount, tokenAddress2) : this.sdk.logDeposit(validChainId, txHash, amount));
2270
+ await (tokenAddress ? this.sdk.logDeposit(validChainId, txHash, amount, tokenAddress) : this.sdk.logDeposit(validChainId, txHash, amount));
2275
2271
  } catch (logError) {
2276
2272
  console.warn(
2277
2273
  "[owney-sdk] Deposit landed on-chain but logDeposit failed (non-fatal):",
@@ -2377,22 +2373,13 @@ var ZyfaiAgent = class _ZyfaiAgent {
2377
2373
  }
2378
2374
  async getAccountApy(state, chainId, days, tokenSymbol, scopeChainId) {
2379
2375
  const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
2380
- const [raw, ethUsd, eurUsd] = await Promise.all([
2376
+ const [raw, ethUsd] = await Promise.all([
2381
2377
  this.sdk.getDailyApyHistory(smartWallet, days),
2382
- tokenSymbol ? void 0 : this.readEthUsd(validChainId),
2383
- tokenSymbol ? void 0 : this.readEurUsd()
2378
+ tokenSymbol ? void 0 : this.readEthUsd(validChainId)
2384
2379
  ]);
2385
2380
  const scope = scopeChainId === null ? void 0 : scopeChainId ?? chainId;
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
+ const usdPrices = ethUsd ? { WETH: ethUsd, ETH: ethUsd } : void 0;
2382
+ return mapApyHistory(raw, scope, tokenSymbol, usdPrices);
2396
2383
  }
2397
2384
  /**
2398
2385
  * Today's ETH/USD from Chainlink, cached for a minute. Every day of the
@@ -2400,38 +2387,24 @@ var ZyfaiAgent = class _ZyfaiAgent {
2400
2387
  * move over the window is not reflected (ROUT-682). Undefined on failure,
2401
2388
  * which leaves the series on token-amount weighting rather than failing it.
2402
2389
  */
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;
2390
+ async readEthUsd(chainId) {
2391
+ if (this.ethUsd && Date.now() - this.ethUsd.at < ETH_USD_TTL_MS) {
2392
+ return this.ethUsd.price;
2418
2393
  }
2419
2394
  try {
2420
2395
  const [, answer] = await this.getPublicClient(chainId).readContract({
2421
- address: feed,
2396
+ address: CHAINLINK_ETH_USD_FEED[chainId],
2422
2397
  abi: CHAINLINK_ABI,
2423
2398
  functionName: "latestRoundData"
2424
2399
  });
2425
2400
  const price = Number(answer) / 1e8;
2426
2401
  if (!Number.isFinite(price) || price <= 0) return void 0;
2427
- this[cache] = { price, at: Date.now() };
2402
+ this.ethUsd = { price, at: Date.now() };
2428
2403
  return price;
2429
2404
  } catch (err) {
2430
- debugLog(
2431
- "zyfai:apy",
2432
- `${cache === "ethUsd" ? "ETH/USD" : "EUR/USD"} read failed; token-amount weighting`,
2433
- { err }
2434
- );
2405
+ debugLog("zyfai:apy", "ETH/USD read failed; token-amount weighting", {
2406
+ err
2407
+ });
2435
2408
  return void 0;
2436
2409
  }
2437
2410
  }
@@ -2462,7 +2435,6 @@ var ZyfaiAgent = class _ZyfaiAgent {
2462
2435
  return "eth";
2463
2436
  case "EURC":
2464
2437
  return "eurc";
2465
- // Zyfai has no "usdt" history filter, so USDT is filtered client-side.
2466
2438
  default:
2467
2439
  return void 0;
2468
2440
  }
@@ -2471,9 +2443,6 @@ var ZyfaiAgent = class _ZyfaiAgent {
2471
2443
  const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
2472
2444
  const limit = options?.limit ?? 10;
2473
2445
  const assetType = _ZyfaiAgent.toZyfaiAssetType(options?.tokenSymbol);
2474
- const clientSideAsset = !assetType && options?.tokenSymbol && SUPPORTED_TOKENS.includes(
2475
- options.tokenSymbol.toUpperCase()
2476
- ) ? options.tokenSymbol : void 0;
2477
2446
  const cursor = options?.cursor ? decodeHistoryCursor(options.cursor) : null;
2478
2447
  const toDate = cursor?.toDate ?? options?.toDate ?? (/* @__PURE__ */ new Date()).toISOString();
2479
2448
  let offset = cursor?.rawOffset ?? 0;
@@ -2495,12 +2464,6 @@ var ZyfaiAgent = class _ZyfaiAgent {
2495
2464
  assetType
2496
2465
  });
2497
2466
  raw.data.forEach((entry, idx) => {
2498
- if (clientSideAsset && !matchesAsset(
2499
- entry.positions?.[0]?.token_symbol ?? "",
2500
- clientSideAsset
2501
- )) {
2502
- return;
2503
- }
2504
2467
  if (entry.chainId === validChainId) {
2505
2468
  matched.push({ entry, rawIdx: offset + idx });
2506
2469
  }
@@ -2543,20 +2506,6 @@ var ZyfaiAgent = class _ZyfaiAgent {
2543
2506
  }
2544
2507
  async ensureAutoSelectProtocols(state, chainId, asset) {
2545
2508
  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) {
2560
2509
  const current = await this.sdk.getUserDetails(asset);
2561
2510
  debugLog("zyfai:auto-select", `${asset}: profile before check`, {
2562
2511
  autoSelectProtocols: current.autoSelectProtocols,
@@ -2564,7 +2513,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
2564
2513
  protocols: current.protocols,
2565
2514
  strategy: current.strategy
2566
2515
  });
2567
- if ((current.chains?.length ?? 0) === 0 && (asset === "USDC" || !await this.isExistingZyfaiUser())) {
2516
+ if ((current.chains?.length ?? 0) === 0) {
2568
2517
  debugLog(
2569
2518
  "zyfai:auto-select",
2570
2519
  `${asset}: skipping untouched profile until first deposit`
@@ -3449,20 +3398,6 @@ async function readErc20Balance(publicClient, token, owner) {
3449
3398
  });
3450
3399
  }
3451
3400
 
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
-
3466
3401
  // src/lib/swap/swap.secrets.ts
3467
3402
  var import_viem4 = require("viem");
3468
3403
  var SECRET_BYTES = 32;
@@ -3821,15 +3756,6 @@ async function executeSwap(deps, options) {
3821
3756
  }
3822
3757
  return { received: arrived.toString(), ...result ?? {} };
3823
3758
  }
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
- }
3833
3759
  async function runClassic(deps, options) {
3834
3760
  const {
3835
3761
  quote,
@@ -3866,7 +3792,7 @@ async function runClassic(deps, options) {
3866
3792
  if (current < needed) {
3867
3793
  onStage?.("approving");
3868
3794
  await deps.ensureChain(quote.src.chainId);
3869
- await approveMax(deps, quote.src.address, current, tx.to);
3795
+ await deps.approve(tx.to, MAX_UINT256);
3870
3796
  debugLog(
3871
3797
  "owney-sdk",
3872
3798
  "swap: re-fetching classic calldata after approval"
@@ -3955,7 +3881,7 @@ async function authoriseSpend(deps, options, amount, isNativeSource) {
3955
3881
  });
3956
3882
  return permit;
3957
3883
  }
3958
- await approveMax(deps, quote.src.address, current, quote.spender);
3884
+ await deps.approve(quote.spender, MAX_UINT256);
3959
3885
  debugLog("owney-sdk", "swap: approved limit order protocol");
3960
3886
  return void 0;
3961
3887
  }
@@ -4051,66 +3977,6 @@ async function runFusion(deps, options, walletAddress) {
4051
3977
  return { orderHash: built.orderHash };
4052
3978
  }
4053
3979
 
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
-
4114
3980
  // src/lib/swap/swap.permit.ts
4115
3981
  var import_viem5 = require("viem");
4116
3982
  var PERMIT_ABI = (0, import_viem5.parseAbi)([
@@ -4829,7 +4695,6 @@ function makeSponsoredDepositCallback(deps) {
4829
4695
  // src/lib/walletconnect-switch.ts
4830
4696
  var WALLET_SWITCH_TIMEOUT_MS = 12e4;
4831
4697
  var HOLD_CHAIN_MS = 15e3;
4832
- var MAX_RESENDS = 2;
4833
4698
  var holds = /* @__PURE__ */ new Map();
4834
4699
  function parseChainId(raw) {
4835
4700
  if (typeof raw === "number") return raw;
@@ -4838,28 +4703,76 @@ function parseChainId(raw) {
4838
4703
  const id = ref.startsWith("0x") ? Number.parseInt(ref, 16) : Number(ref);
4839
4704
  return Number.isFinite(id) ? id : void 0;
4840
4705
  }
4841
- function walletConnectCore(provider) {
4706
+ function walletConnectSession(provider) {
4842
4707
  const p = provider;
4843
4708
  const core = p?.signer ?? p;
4844
- if (typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
4709
+ if (typeof core?.request !== "function" || typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
4845
4710
  return null;
4846
4711
  }
4847
4712
  const peer = core.session.peer?.metadata?.name ?? "";
4848
- if (!/metamask/i.test(peer)) return null;
4849
- return core;
4713
+ if (/metamask/i.test(peer)) {
4714
+ return { core, strategy: "remote-wallet" };
4715
+ }
4716
+ if (/fireblocks/i.test(peer)) {
4717
+ return { core, strategy: "session-default" };
4718
+ }
4719
+ return null;
4720
+ }
4721
+ function approvedChains(core) {
4722
+ const approved = /* @__PURE__ */ new Set();
4723
+ for (const namespace of Object.values(core.session.namespaces ?? {})) {
4724
+ for (const chain of namespace.chains ?? []) approved.add(chain);
4725
+ for (const account of namespace.accounts ?? []) {
4726
+ const [namespaceName, reference] = account.split(":");
4727
+ if (namespaceName && reference) {
4728
+ approved.add(`${namespaceName}:${reference}`);
4729
+ }
4730
+ }
4731
+ }
4732
+ return approved;
4733
+ }
4734
+ async function selectSessionDefaultChain(core, chainId) {
4735
+ const target = `eip155:${chainId}`;
4736
+ if (!approvedChains(core).has(target)) {
4737
+ throw new Error(
4738
+ `The WalletConnect session has not approved ${target}. Reconnect the wallet and try again.`
4739
+ );
4740
+ }
4741
+ core.setDefaultChain(target);
4742
+ const selected = parseChainId(
4743
+ await core.request({ method: "eth_chainId" })
4744
+ );
4745
+ debugLog("wc-switch", "selected WalletConnect session default", {
4746
+ peer: core.session.peer?.metadata?.name,
4747
+ target: chainId,
4748
+ selected
4749
+ });
4750
+ if (selected !== chainId) {
4751
+ throw new Error(
4752
+ `WalletConnect stayed on chain ${selected ?? "unknown"}; expected ${chainId}.`
4753
+ );
4754
+ }
4850
4755
  }
4851
4756
  async function switchWalletConnectChain(provider, chainId, timeoutMs = WALLET_SWITCH_TIMEOUT_MS) {
4852
- const core = walletConnectCore(provider);
4853
- if (!core) return false;
4757
+ const session = walletConnectSession(provider);
4758
+ if (!session) return false;
4759
+ const { core, strategy } = session;
4854
4760
  holds.get(core.session.topic)?.();
4761
+ if (strategy === "session-default") {
4762
+ await selectSessionDefaultChain(core, chainId);
4763
+ return true;
4764
+ }
4855
4765
  await requestSwitch(core, provider, chainId, timeoutMs);
4856
- holdChain(core, provider, chainId);
4766
+ holdChain(core, chainId);
4857
4767
  return true;
4858
4768
  }
4859
4769
  async function requestSwitch(core, provider, chainId, timeoutMs) {
4860
- const current = Number(
4770
+ const current = parseChainId(
4861
4771
  await provider.request({ method: "eth_chainId" })
4862
4772
  );
4773
+ if (current === void 0) {
4774
+ throw new Error("WalletConnect could not report its current chain.");
4775
+ }
4863
4776
  const hexChainId = `0x${chainId.toString(16)}`;
4864
4777
  let timer;
4865
4778
  try {
@@ -4889,26 +4802,27 @@ async function requestSwitch(core, provider, chainId, timeoutMs) {
4889
4802
  } catch {
4890
4803
  }
4891
4804
  }
4892
- function holdChain(core, provider, chainId) {
4805
+ function holdChain(core, chainId) {
4893
4806
  if (typeof core.on !== "function" || typeof core.removeListener !== "function") {
4894
4807
  return;
4895
4808
  }
4896
- let resends = 0;
4809
+ let repins = 0;
4897
4810
  const listener = (raw) => {
4898
4811
  const reported = parseChainId(raw);
4899
4812
  debugLog("wc-switch", "wallet reported chain", {
4900
4813
  reported,
4901
4814
  holding: chainId,
4902
- resends
4815
+ repins
4903
4816
  });
4904
4817
  if (reported === void 0 || reported === chainId) return;
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", {
4818
+ repins += 1;
4819
+ try {
4820
+ core.setDefaultChain(`eip155:${chainId}`);
4821
+ } catch (error) {
4822
+ debugLog("wc-switch", "session re-pin failed", {
4909
4823
  error: error instanceof Error ? error.message : String(error)
4910
- })
4911
- );
4824
+ });
4825
+ }
4912
4826
  };
4913
4827
  const release = () => {
4914
4828
  clearTimeout(timer);
@@ -4922,7 +4836,7 @@ function holdChain(core, provider, chainId) {
4922
4836
  holds.set(core.session.topic, release);
4923
4837
  }
4924
4838
  function withWalletConnectSwitch(provider) {
4925
- if (!walletConnectCore(provider)) return provider;
4839
+ if (!walletConnectSession(provider)) return provider;
4926
4840
  const target = provider;
4927
4841
  const request2 = async (args) => {
4928
4842
  if (args?.method !== "wallet_switchEthereumChain") {
@@ -4954,7 +4868,7 @@ function makeSponsoredWethCallback(deps) {
4954
4868
  if (!token) {
4955
4869
  throw new OwneyError(
4956
4870
  "CHAIN_UNSUPPORTED",
4957
- `No sponsored ${deps.assetSymbol} configured for chain ${chainId}`
4871
+ `No sponsored WETH configured for chain ${chainId}`
4958
4872
  );
4959
4873
  }
4960
4874
  const amountWei = BigInt(amount);
@@ -4967,14 +4881,14 @@ function makeSponsoredWethCallback(deps) {
4967
4881
  if (balance < amountWei) {
4968
4882
  throw new OwneyError(
4969
4883
  "DEPOSIT_INSUFFICIENT_BALANCE",
4970
- `Insufficient ${deps.assetSymbol} balance for this deposit.`,
4884
+ "Insufficient WETH balance for this deposit.",
4971
4885
  { token, chainId: cid, balance: balance.toString(), amount }
4972
4886
  );
4973
4887
  }
4974
4888
  } catch (err) {
4975
4889
  if (err instanceof OwneyError) throw err;
4976
4890
  console.warn(
4977
- `[owney-sdk] ${deps.assetSymbol} balance pre-check failed (non-fatal):`,
4891
+ "[owney-sdk] WETH balance pre-check failed (non-fatal):",
4978
4892
  err instanceof Error ? err.message : String(err)
4979
4893
  );
4980
4894
  }
@@ -4986,7 +4900,7 @@ function makeSponsoredWethCallback(deps) {
4986
4900
  if (allowance < amountWei) {
4987
4901
  throw new OwneyError(
4988
4902
  "PERMIT2_APPROVAL_REQUIRED",
4989
- `${deps.assetSymbol} gasless deposits need a one-time Permit2 approval; call approvePermit2() first`,
4903
+ "WETH gasless deposits need a one-time Permit2 approval; call approvePermit2() first",
4990
4904
  { token, chainId: cid, allowance: allowance.toString(), amount }
4991
4905
  );
4992
4906
  }
@@ -5173,22 +5087,8 @@ var SPONSORED_WETH_BY_CHAIN = {
5173
5087
  42161: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
5174
5088
  1: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
5175
5089
  };
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
- }
5190
5090
  function shouldFallbackToUserPaid(error, asset, appCallback) {
5191
- return SUPPORTED_TOKENS.includes(asset) && appCallback === void 0 && error instanceof OwneyError && error.code === "SPONSOR_REQUEST_FAILED" && error.details?.safeToFallback === true;
5091
+ return (asset === "WETH" || asset === "USDC") && appCallback === void 0 && error instanceof OwneyError && error.code === "SPONSOR_REQUEST_FAILED" && error.details?.safeToFallback === true;
5192
5092
  }
5193
5093
  var OwneySDK = class {
5194
5094
  agents = /* @__PURE__ */ new Map();
@@ -5211,8 +5111,9 @@ var OwneySDK = class {
5211
5111
  userPoolCustomization = false;
5212
5112
  routingApiBaseUrl;
5213
5113
  referralSource;
5214
- cachedSponsoredCallbacks = /* @__PURE__ */ new Map();
5215
- cachedPermit2SponsoredCallbacks = /* @__PURE__ */ new Map();
5114
+ sessionStore;
5115
+ cachedSponsoredCallback = null;
5116
+ cachedWethSponsoredCallback = null;
5216
5117
  paymasterServiceUrl;
5217
5118
  cachedSponsoredCallsCallbacks = /* @__PURE__ */ new Map();
5218
5119
  agentReads = new AgentReads();
@@ -5234,6 +5135,7 @@ var OwneySDK = class {
5234
5135
  this.routingApiBaseUrl = config.routingApiBaseUrl;
5235
5136
  this.paymasterServiceUrl = config.paymasterServiceUrl;
5236
5137
  this.referralSource = config.referralSource;
5138
+ this.sessionStore = config.sessionStore;
5237
5139
  this.userPoolCustomization = config.userPoolCustomization ?? false;
5238
5140
  }
5239
5141
  /**
@@ -5260,8 +5162,8 @@ var OwneySDK = class {
5260
5162
  walletAddress,
5261
5163
  chainId: null
5262
5164
  };
5263
- this.cachedSponsoredCallbacks.clear();
5264
- this.cachedPermit2SponsoredCallbacks.clear();
5165
+ this.cachedSponsoredCallback = null;
5166
+ this.cachedWethSponsoredCallback = null;
5265
5167
  this.cachedSponsoredCallsCallbacks.clear();
5266
5168
  }
5267
5169
  /**
@@ -5277,8 +5179,8 @@ var OwneySDK = class {
5277
5179
  this.agentReads.clearInFlight();
5278
5180
  this.activationChecks.clear();
5279
5181
  this.state = null;
5280
- this.cachedSponsoredCallbacks.clear();
5281
- this.cachedPermit2SponsoredCallbacks.clear();
5182
+ this.cachedSponsoredCallback = null;
5183
+ this.cachedWethSponsoredCallback = null;
5282
5184
  this.cachedSponsoredCallsCallbacks.clear();
5283
5185
  }
5284
5186
  isAgentDisabled(agentId) {
@@ -5328,9 +5230,9 @@ var OwneySDK = class {
5328
5230
  * provider with viem `custom(provider)` to read token meta and sign the
5329
5231
  * `TransferWithAuthorization`, then POSTs to the sponsor API.
5330
5232
  */
5331
- getDefaultSponsoredCallback(asset, onApproved) {
5332
- const cached = this.cachedSponsoredCallbacks.get(asset);
5333
- if (!onApproved && cached) return cached;
5233
+ getDefaultSponsoredCallback(onApproved) {
5234
+ if (!onApproved && this.cachedSponsoredCallback)
5235
+ return this.cachedSponsoredCallback;
5334
5236
  const provider = this.requireConnectedProvider();
5335
5237
  const owner = this.state.walletAddress;
5336
5238
  const callback = makeSponsoredDepositCallback({
@@ -5338,7 +5240,7 @@ var OwneySDK = class {
5338
5240
  baseUrl: this.routingApiBaseUrl,
5339
5241
  ownerAddress: owner,
5340
5242
  onApproved,
5341
- tokenAddressByChain: sponsoredTokenMap(asset),
5243
+ tokenAddressByChain: SPONSORED_USDC_BY_CHAIN,
5342
5244
  // Casts work around viem's chain-narrowed Client vs the generic
5343
5245
  // PublicClient/WalletClient param types — structurally identical at
5344
5246
  // runtime, but the two share a name TS treats as unrelated.
@@ -5355,13 +5257,14 @@ var OwneySDK = class {
5355
5257
  transport: (0, import_viem9.custom)(provider)
5356
5258
  })
5357
5259
  });
5358
- if (!onApproved) this.cachedSponsoredCallbacks.set(asset, callback);
5260
+ if (!onApproved) this.cachedSponsoredCallback = callback;
5359
5261
  return callback;
5360
5262
  }
5361
5263
  /**
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.
5264
+ * Lazily builds (and caches) the default Permit2 sponsored WETH deposit
5265
+ * callback used when the caller omits `depositCallback` for a WETH
5266
+ * deposit. Mirrors `getDefaultSponsoredCallback()` but signs a Permit2
5267
+ * `PermitTransferFrom` instead of an EIP-3009 authorization.
5365
5268
  */
5366
5269
  getDefaultSponsoredCallsCallback(asset, onApproved) {
5367
5270
  const cached = this.cachedSponsoredCallsCallbacks.get(asset);
@@ -5372,20 +5275,20 @@ var OwneySDK = class {
5372
5275
  ownerAddress: this.state.walletAddress,
5373
5276
  paymasterServiceUrl: this.paymasterServiceUrl,
5374
5277
  onApproved,
5375
- tokenAddressByChain: sponsoredTokenMap(asset)
5278
+ tokenAddressByChain: asset === "WETH" ? SPONSORED_WETH_BY_CHAIN : SPONSORED_USDC_BY_CHAIN
5376
5279
  });
5377
5280
  if (!onApproved) this.cachedSponsoredCallsCallbacks.set(asset, callback);
5378
5281
  return callback;
5379
5282
  }
5380
5283
  /**
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.
5284
+ * Lazily builds (and caches) the default Permit2 sponsored WETH deposit
5285
+ * callback used when the caller omits `depositCallback` for a WETH deposit.
5286
+ * Mirrors `getDefaultSponsoredCallback()` but signs a Permit2
5287
+ * `PermitTransferFrom` instead of an EIP-3009 authorization.
5385
5288
  */
5386
- getDefaultPermit2SponsoredCallback(asset, onApproved) {
5387
- const cached = this.cachedPermit2SponsoredCallbacks.get(asset);
5388
- if (!onApproved && cached) return cached;
5289
+ getDefaultWethSponsoredCallback(onApproved) {
5290
+ if (!onApproved && this.cachedWethSponsoredCallback)
5291
+ return this.cachedWethSponsoredCallback;
5389
5292
  const provider = this.requireConnectedProvider();
5390
5293
  const owner = this.state.walletAddress;
5391
5294
  const callback = makeSponsoredWethCallback({
@@ -5393,8 +5296,7 @@ var OwneySDK = class {
5393
5296
  baseUrl: this.routingApiBaseUrl,
5394
5297
  ownerAddress: owner,
5395
5298
  onApproved,
5396
- tokenAddressByChain: sponsoredTokenMap(asset),
5397
- assetSymbol: asset,
5299
+ tokenAddressByChain: SPONSORED_WETH_BY_CHAIN,
5398
5300
  // Casts work around viem's chain-narrowed Client vs the generic
5399
5301
  // PublicClient/WalletClient param types — structurally identical at
5400
5302
  // runtime, but the two share a name TS treats as unrelated.
@@ -5411,7 +5313,7 @@ var OwneySDK = class {
5411
5313
  transport: (0, import_viem9.custom)(provider)
5412
5314
  })
5413
5315
  });
5414
- if (!onApproved) this.cachedPermit2SponsoredCallbacks.set(asset, callback);
5316
+ if (!onApproved) this.cachedWethSponsoredCallback = callback;
5415
5317
  return callback;
5416
5318
  }
5417
5319
  getAgent(agentId) {
@@ -5507,7 +5409,12 @@ var OwneySDK = class {
5507
5409
  }
5508
5410
  createAgent(agentId, key2) {
5509
5411
  if (agentId === "zyfai") {
5510
- return new ZyfaiAgent(key2, this.zyfaiRpcUrls, this.referralSource);
5412
+ return new ZyfaiAgent(
5413
+ key2,
5414
+ this.zyfaiRpcUrls,
5415
+ this.referralSource,
5416
+ this.sessionStore
5417
+ );
5511
5418
  }
5512
5419
  return null;
5513
5420
  }
@@ -5669,8 +5576,7 @@ var OwneySDK = class {
5669
5576
  }
5670
5577
  const state = this.requireState();
5671
5578
  const chainId = options.chainId ?? this.requireChainId();
5672
- const sponsoredAsset = asset;
5673
- const effectiveCallback = depositCallback ?? (this.paymasterServiceUrl ? this.getDefaultSponsoredCallsCallback(sponsoredAsset, onApproved) : isPermit2Asset(sponsoredAsset) ? this.getDefaultPermit2SponsoredCallback(sponsoredAsset, onApproved) : this.getDefaultSponsoredCallback(sponsoredAsset, onApproved));
5579
+ const effectiveCallback = depositCallback ?? (this.paymasterServiceUrl ? this.getDefaultSponsoredCallsCallback(asset, onApproved) : asset === "WETH" ? this.getDefaultWethSponsoredCallback(onApproved) : this.getDefaultSponsoredCallback(onApproved));
5674
5580
  if (agentId) {
5675
5581
  if (this.isAgentDisabled(agentId)) {
5676
5582
  throw new OwneyError(
@@ -5784,16 +5690,15 @@ var OwneySDK = class {
5784
5690
  *
5785
5691
  * 1. Missing Permit2 allowance: when the app did not supply its own
5786
5692
  * callback and the attempt fails with `PERMIT2_APPROVAL_REQUIRED` on a
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.
5693
+ * WETH deposit, this is the wallet's first gasless WETH deposit. We send
5694
+ * the one-time (user-paid) Permit2 approval via `approvePermit2()` and
5695
+ * retry the SAME sponsored attempt once. Bounded to one approval attempt
5696
+ * per call so a wallet/agent that keeps reporting the allowance as
5697
+ * missing can't loop forever. If `approvePermit2()` itself throws (e.g.
5793
5698
  * the user rejects the wallet prompt), that error propagates as-is —
5794
5699
  * the user said no to a transaction, so we must not turn around and ask
5795
5700
  * them to pay for a different one via the fallback below.
5796
- * 2. `shouldFallbackToUserPaid`: the SDK's own sponsor path failed at
5701
+ * 2. `shouldFallbackToUserPaid`: the SDK's own WETH sponsor path failed at
5797
5702
  * the infrastructure layer in a provably safe-to-retry way, so we warn
5798
5703
  * and retry once with `undefined`, falling through to a user-paid
5799
5704
  * native deposit. This still applies after a successful Permit2
@@ -5822,12 +5727,12 @@ var OwneySDK = class {
5822
5727
  try {
5823
5728
  return await attempt(effectiveCallback);
5824
5729
  } catch (error) {
5825
- if (!approvalAttempted && appCallback === void 0 && isPermit2Asset(asset) && error instanceof OwneyError && error.code === "PERMIT2_APPROVAL_REQUIRED") {
5730
+ if (!approvalAttempted && appCallback === void 0 && asset === "WETH" && error instanceof OwneyError && error.code === "PERMIT2_APPROVAL_REQUIRED") {
5826
5731
  approvalAttempted = true;
5827
5732
  console.warn(
5828
- `[owney-sdk] First ${asset} deposit: sending one-time Permit2 approval...`
5733
+ "[owney-sdk] First WETH deposit: sending one-time Permit2 approval..."
5829
5734
  );
5830
- await this.approvePermit2(asset);
5735
+ await this.approvePermit2();
5831
5736
  continue;
5832
5737
  }
5833
5738
  if (!shouldFallbackToUserPaid(error, asset, appCallback)) throw error;
@@ -6264,45 +6169,22 @@ var OwneySDK = class {
6264
6169
  functionName: "allowance",
6265
6170
  args: [state.walletAddress, spender]
6266
6171
  }),
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
- ),
6172
+ approve: async (spender, amount) => {
6173
+ const hash = await wallet.writeContract({
6174
+ address: quote.src.address,
6175
+ abi: ERC20_ALLOWANCE_ABI,
6176
+ functionName: "approve",
6177
+ args: [spender, amount],
6178
+ account: state.walletAddress,
6179
+ chain: srcChain
6180
+ });
6181
+ await srcPublic.waitForTransactionReceipt({
6182
+ hash,
6183
+ confirmations: 1,
6184
+ timeout: receiptTimeoutMs(quote.src.chainId)
6185
+ });
6186
+ return hash;
6187
+ },
6306
6188
  ensureChain: (chainId) => this.ensureSwapChain(chainId),
6307
6189
  /**
6308
6190
  * Sign the approval instead of paying for it. Null means the token
@@ -6390,33 +6272,30 @@ var OwneySDK = class {
6390
6272
  * figure directly. It is the entire arrival, so there is no slack: anything
6391
6273
  * that spends the target asset between the two fails the deposit outright.
6392
6274
  *
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.
6275
+ * Something does. A first WETH deposit needs a one-time Permit2 approval,
6276
+ * and that approval is a transaction. A wallet holding no native gas token -
6277
+ * the normal state of someone who just swapped everything INTO WETH - pays
6278
+ * for it out of the WETH. The deposit then asked for ~2e12 wei more than was
6279
+ * left and refused with DEPOSIT_INSUFFICIENT_BALANCE, under a wrapper saying
6280
+ * the funds were safe but unadded (ROUT-242).
6401
6281
  *
6402
6282
  * So the approval happens here, before the amount is settled, and the amount
6403
6283
  * comes from a read taken after it. Two things this deliberately is not:
6404
6284
  *
6405
6285
  * - It is not a balance sweep. `received` is a DELTA over the pre-swap
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.
6286
+ * balance, so a wallet already holding WETH reads far above it; depositing
6287
+ * the balance would move funds the user never offered. The arrival is the
6288
+ * ceiling and the balance is only ever allowed to lower it.
6289
+ * - It does not touch USDC, which moves on signed typed data and so spends
6290
+ * nothing of the user's in between, nor a paymaster-configured client,
6291
+ * where the sponsor covers the transfer and Permit2 never applies.
6413
6292
  */
6414
6293
  async settleSwapDepositAmount(chainId, token, symbol, received) {
6415
- if (!isPermit2Asset(symbol) || this.paymasterServiceUrl) {
6294
+ if (symbol !== "WETH" || this.paymasterServiceUrl) {
6416
6295
  return received.toString();
6417
6296
  }
6418
6297
  const allowance = await this.readTokenPermit2Allowance(chainId, token);
6419
- if (allowance < received) await this.approvePermit2(symbol);
6298
+ if (allowance < received) await this.approvePermit2();
6420
6299
  const balance = await this.readTokenBalance(chainId, token);
6421
6300
  return (balance < received ? balance : received).toString();
6422
6301
  }
@@ -6581,10 +6460,7 @@ var OwneySDK = class {
6581
6460
  );
6582
6461
  }
6583
6462
  await this.ensureSwapChain(entry.chainId);
6584
- const supported = SUPPORTED_TOKENS.includes(
6585
- entry.symbol
6586
- );
6587
- const token = supported ? sponsoredTokenMap(entry.symbol)[entry.chainId] : void 0;
6463
+ const token = entry.symbol === "WETH" ? SPONSORED_WETH_BY_CHAIN[entry.chainId] : void 0;
6588
6464
  const amount = token ? await this.settleSwapDepositAmount(
6589
6465
  entry.chainId,
6590
6466
  token,
@@ -7737,7 +7613,7 @@ var OwneySDK = class {
7737
7613
  /**
7738
7614
  * Ensure the given asset uses backend protocol auto-selection for the active
7739
7615
  * chain's account. No-op (returns false) for agents that don't support it.
7740
- * @param asset - Asset symbol (e.g. "USDC").
7616
+ * @param asset - "USDC" or "WETH".
7741
7617
  * @param agentId - Agent to target. Defaults to "zyfai".
7742
7618
  * @returns whether a profile write occurred.
7743
7619
  */
@@ -7762,28 +7638,23 @@ var OwneySDK = class {
7762
7638
  return pending;
7763
7639
  }
7764
7640
  /**
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.
7641
+ * One-time, user-paid approval of Permit2 on the sponsored WETH token for
7642
+ * the active chain. Required once per wallet per chain before gasless WETH
7643
+ * deposits; afterwards deposit() is signature-only. Resolves only after the
7644
+ * approval transaction is mined (1 confirmation), so a subsequent deposit()
7645
+ * will see the new allowance; throws if the transaction reverted.
7776
7646
  * @returns the approval transaction hash.
7777
7647
  */
7778
7648
  async approvePermit2(asset = "WETH") {
7649
+ void asset;
7779
7650
  const state = this.requireState();
7780
7651
  const chainId = this.requireChainId();
7781
- this.validateAssetSupport(this.getAgent("zyfai"), chainId, asset);
7782
- const token = sponsoredTokenMap(asset)[chainId];
7652
+ this.validateAssetSupport(this.getAgent("zyfai"), chainId, "WETH");
7653
+ const token = SPONSORED_WETH_BY_CHAIN[chainId];
7783
7654
  if (!token) {
7784
7655
  throw new OwneyError(
7785
7656
  "CHAIN_UNSUPPORTED",
7786
- `No sponsored ${asset} on chain ${chainId}`
7657
+ `No sponsored WETH on chain ${chainId}`
7787
7658
  );
7788
7659
  }
7789
7660
  const provider = this.requireConnectedProvider();
@@ -7801,52 +7672,22 @@ var OwneySDK = class {
7801
7672
  wallet,
7802
7673
  chainId
7803
7674
  );
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
- );
7675
+ const hash = await wallet.writeContract({
7676
+ address: token,
7677
+ abi: ERC20_ALLOWANCE_ABI,
7678
+ functionName: "approve",
7679
+ args: [PERMIT2_ADDRESS, MAX_UINT256],
7680
+ account: state.walletAddress,
7681
+ chain: VIEM_CHAIN2[chainId]
7825
7682
  });
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
- }
7683
+ const receipt = await publicClient.waitForTransactionReceipt({
7684
+ hash,
7685
+ confirmations: 1
7849
7686
  });
7687
+ if (receipt.status !== "success") {
7688
+ throw new Error(`Permit2 approval reverted (tx ${hash})`);
7689
+ }
7690
+ return hash;
7850
7691
  }
7851
7692
  // --- Discovery (no wallet required) ---
7852
7693
  /**