@owney/sdk 0.8.0-beta.0 → 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`.
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.
1409
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
  }
@@ -4769,7 +4695,6 @@ function makeSponsoredDepositCallback(deps) {
4769
4695
  // src/lib/walletconnect-switch.ts
4770
4696
  var WALLET_SWITCH_TIMEOUT_MS = 12e4;
4771
4697
  var HOLD_CHAIN_MS = 15e3;
4772
- var MAX_RESENDS = 2;
4773
4698
  var holds = /* @__PURE__ */ new Map();
4774
4699
  function parseChainId(raw) {
4775
4700
  if (typeof raw === "number") return raw;
@@ -4778,28 +4703,76 @@ function parseChainId(raw) {
4778
4703
  const id = ref.startsWith("0x") ? Number.parseInt(ref, 16) : Number(ref);
4779
4704
  return Number.isFinite(id) ? id : void 0;
4780
4705
  }
4781
- function walletConnectCore(provider) {
4706
+ function walletConnectSession(provider) {
4782
4707
  const p = provider;
4783
4708
  const core = p?.signer ?? p;
4784
- 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") {
4785
4710
  return null;
4786
4711
  }
4787
4712
  const peer = core.session.peer?.metadata?.name ?? "";
4788
- if (!/metamask/i.test(peer)) return null;
4789
- 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
+ }
4790
4755
  }
4791
4756
  async function switchWalletConnectChain(provider, chainId, timeoutMs = WALLET_SWITCH_TIMEOUT_MS) {
4792
- const core = walletConnectCore(provider);
4793
- if (!core) return false;
4757
+ const session = walletConnectSession(provider);
4758
+ if (!session) return false;
4759
+ const { core, strategy } = session;
4794
4760
  holds.get(core.session.topic)?.();
4761
+ if (strategy === "session-default") {
4762
+ await selectSessionDefaultChain(core, chainId);
4763
+ return true;
4764
+ }
4795
4765
  await requestSwitch(core, provider, chainId, timeoutMs);
4796
- holdChain(core, provider, chainId);
4766
+ holdChain(core, chainId);
4797
4767
  return true;
4798
4768
  }
4799
4769
  async function requestSwitch(core, provider, chainId, timeoutMs) {
4800
- const current = Number(
4770
+ const current = parseChainId(
4801
4771
  await provider.request({ method: "eth_chainId" })
4802
4772
  );
4773
+ if (current === void 0) {
4774
+ throw new Error("WalletConnect could not report its current chain.");
4775
+ }
4803
4776
  const hexChainId = `0x${chainId.toString(16)}`;
4804
4777
  let timer;
4805
4778
  try {
@@ -4829,26 +4802,27 @@ async function requestSwitch(core, provider, chainId, timeoutMs) {
4829
4802
  } catch {
4830
4803
  }
4831
4804
  }
4832
- function holdChain(core, provider, chainId) {
4805
+ function holdChain(core, chainId) {
4833
4806
  if (typeof core.on !== "function" || typeof core.removeListener !== "function") {
4834
4807
  return;
4835
4808
  }
4836
- let resends = 0;
4809
+ let repins = 0;
4837
4810
  const listener = (raw) => {
4838
4811
  const reported = parseChainId(raw);
4839
4812
  debugLog("wc-switch", "wallet reported chain", {
4840
4813
  reported,
4841
4814
  holding: chainId,
4842
- resends
4815
+ repins
4843
4816
  });
4844
4817
  if (reported === void 0 || reported === chainId) return;
4845
- if (resends >= MAX_RESENDS) return;
4846
- resends += 1;
4847
- void requestSwitch(core, provider, chainId, WALLET_SWITCH_TIMEOUT_MS).catch(
4848
- (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", {
4849
4823
  error: error instanceof Error ? error.message : String(error)
4850
- })
4851
- );
4824
+ });
4825
+ }
4852
4826
  };
4853
4827
  const release = () => {
4854
4828
  clearTimeout(timer);
@@ -4862,7 +4836,7 @@ function holdChain(core, provider, chainId) {
4862
4836
  holds.set(core.session.topic, release);
4863
4837
  }
4864
4838
  function withWalletConnectSwitch(provider) {
4865
- if (!walletConnectCore(provider)) return provider;
4839
+ if (!walletConnectSession(provider)) return provider;
4866
4840
  const target = provider;
4867
4841
  const request2 = async (args) => {
4868
4842
  if (args?.method !== "wallet_switchEthereumChain") {
@@ -4894,7 +4868,7 @@ function makeSponsoredWethCallback(deps) {
4894
4868
  if (!token) {
4895
4869
  throw new OwneyError(
4896
4870
  "CHAIN_UNSUPPORTED",
4897
- `No sponsored ${deps.assetSymbol} configured for chain ${chainId}`
4871
+ `No sponsored WETH configured for chain ${chainId}`
4898
4872
  );
4899
4873
  }
4900
4874
  const amountWei = BigInt(amount);
@@ -4907,14 +4881,14 @@ function makeSponsoredWethCallback(deps) {
4907
4881
  if (balance < amountWei) {
4908
4882
  throw new OwneyError(
4909
4883
  "DEPOSIT_INSUFFICIENT_BALANCE",
4910
- `Insufficient ${deps.assetSymbol} balance for this deposit.`,
4884
+ "Insufficient WETH balance for this deposit.",
4911
4885
  { token, chainId: cid, balance: balance.toString(), amount }
4912
4886
  );
4913
4887
  }
4914
4888
  } catch (err) {
4915
4889
  if (err instanceof OwneyError) throw err;
4916
4890
  console.warn(
4917
- `[owney-sdk] ${deps.assetSymbol} balance pre-check failed (non-fatal):`,
4891
+ "[owney-sdk] WETH balance pre-check failed (non-fatal):",
4918
4892
  err instanceof Error ? err.message : String(err)
4919
4893
  );
4920
4894
  }
@@ -4926,7 +4900,7 @@ function makeSponsoredWethCallback(deps) {
4926
4900
  if (allowance < amountWei) {
4927
4901
  throw new OwneyError(
4928
4902
  "PERMIT2_APPROVAL_REQUIRED",
4929
- `${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",
4930
4904
  { token, chainId: cid, allowance: allowance.toString(), amount }
4931
4905
  );
4932
4906
  }
@@ -5113,22 +5087,8 @@ var SPONSORED_WETH_BY_CHAIN = {
5113
5087
  42161: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
5114
5088
  1: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
5115
5089
  };
5116
- function sponsoredTokenMap(asset) {
5117
- if (asset === "USDC") return SPONSORED_USDC_BY_CHAIN;
5118
- if (asset === "WETH") return SPONSORED_WETH_BY_CHAIN;
5119
- return Object.fromEntries(
5120
- SUPPORTED_CHAIN_IDS.flatMap((id) => {
5121
- const a = tokenAddress(asset, id);
5122
- return a ? [[id, a]] : [];
5123
- })
5124
- );
5125
- }
5126
- var PERMIT2_ASSETS = /* @__PURE__ */ new Set(["WETH", "USDT"]);
5127
- function isPermit2Asset(asset) {
5128
- return PERMIT2_ASSETS.has(asset);
5129
- }
5130
5090
  function shouldFallbackToUserPaid(error, asset, appCallback) {
5131
- 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;
5132
5092
  }
5133
5093
  var OwneySDK = class {
5134
5094
  agents = /* @__PURE__ */ new Map();
@@ -5151,8 +5111,9 @@ var OwneySDK = class {
5151
5111
  userPoolCustomization = false;
5152
5112
  routingApiBaseUrl;
5153
5113
  referralSource;
5154
- cachedSponsoredCallbacks = /* @__PURE__ */ new Map();
5155
- cachedPermit2SponsoredCallbacks = /* @__PURE__ */ new Map();
5114
+ sessionStore;
5115
+ cachedSponsoredCallback = null;
5116
+ cachedWethSponsoredCallback = null;
5156
5117
  paymasterServiceUrl;
5157
5118
  cachedSponsoredCallsCallbacks = /* @__PURE__ */ new Map();
5158
5119
  agentReads = new AgentReads();
@@ -5174,6 +5135,7 @@ var OwneySDK = class {
5174
5135
  this.routingApiBaseUrl = config.routingApiBaseUrl;
5175
5136
  this.paymasterServiceUrl = config.paymasterServiceUrl;
5176
5137
  this.referralSource = config.referralSource;
5138
+ this.sessionStore = config.sessionStore;
5177
5139
  this.userPoolCustomization = config.userPoolCustomization ?? false;
5178
5140
  }
5179
5141
  /**
@@ -5200,8 +5162,8 @@ var OwneySDK = class {
5200
5162
  walletAddress,
5201
5163
  chainId: null
5202
5164
  };
5203
- this.cachedSponsoredCallbacks.clear();
5204
- this.cachedPermit2SponsoredCallbacks.clear();
5165
+ this.cachedSponsoredCallback = null;
5166
+ this.cachedWethSponsoredCallback = null;
5205
5167
  this.cachedSponsoredCallsCallbacks.clear();
5206
5168
  }
5207
5169
  /**
@@ -5217,8 +5179,8 @@ var OwneySDK = class {
5217
5179
  this.agentReads.clearInFlight();
5218
5180
  this.activationChecks.clear();
5219
5181
  this.state = null;
5220
- this.cachedSponsoredCallbacks.clear();
5221
- this.cachedPermit2SponsoredCallbacks.clear();
5182
+ this.cachedSponsoredCallback = null;
5183
+ this.cachedWethSponsoredCallback = null;
5222
5184
  this.cachedSponsoredCallsCallbacks.clear();
5223
5185
  }
5224
5186
  isAgentDisabled(agentId) {
@@ -5268,9 +5230,9 @@ var OwneySDK = class {
5268
5230
  * provider with viem `custom(provider)` to read token meta and sign the
5269
5231
  * `TransferWithAuthorization`, then POSTs to the sponsor API.
5270
5232
  */
5271
- getDefaultSponsoredCallback(asset, onApproved) {
5272
- const cached = this.cachedSponsoredCallbacks.get(asset);
5273
- if (!onApproved && cached) return cached;
5233
+ getDefaultSponsoredCallback(onApproved) {
5234
+ if (!onApproved && this.cachedSponsoredCallback)
5235
+ return this.cachedSponsoredCallback;
5274
5236
  const provider = this.requireConnectedProvider();
5275
5237
  const owner = this.state.walletAddress;
5276
5238
  const callback = makeSponsoredDepositCallback({
@@ -5278,7 +5240,7 @@ var OwneySDK = class {
5278
5240
  baseUrl: this.routingApiBaseUrl,
5279
5241
  ownerAddress: owner,
5280
5242
  onApproved,
5281
- tokenAddressByChain: sponsoredTokenMap(asset),
5243
+ tokenAddressByChain: SPONSORED_USDC_BY_CHAIN,
5282
5244
  // Casts work around viem's chain-narrowed Client vs the generic
5283
5245
  // PublicClient/WalletClient param types — structurally identical at
5284
5246
  // runtime, but the two share a name TS treats as unrelated.
@@ -5295,13 +5257,14 @@ var OwneySDK = class {
5295
5257
  transport: (0, import_viem9.custom)(provider)
5296
5258
  })
5297
5259
  });
5298
- if (!onApproved) this.cachedSponsoredCallbacks.set(asset, callback);
5260
+ if (!onApproved) this.cachedSponsoredCallback = callback;
5299
5261
  return callback;
5300
5262
  }
5301
5263
  /**
5302
- * Lazily builds (and caches, per asset) the default paymaster-sponsored
5303
- * deposit callback used when the caller omits `depositCallback` and a
5304
- * `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.
5305
5268
  */
5306
5269
  getDefaultSponsoredCallsCallback(asset, onApproved) {
5307
5270
  const cached = this.cachedSponsoredCallsCallbacks.get(asset);
@@ -5312,20 +5275,20 @@ var OwneySDK = class {
5312
5275
  ownerAddress: this.state.walletAddress,
5313
5276
  paymasterServiceUrl: this.paymasterServiceUrl,
5314
5277
  onApproved,
5315
- tokenAddressByChain: sponsoredTokenMap(asset)
5278
+ tokenAddressByChain: asset === "WETH" ? SPONSORED_WETH_BY_CHAIN : SPONSORED_USDC_BY_CHAIN
5316
5279
  });
5317
5280
  if (!onApproved) this.cachedSponsoredCallsCallbacks.set(asset, callback);
5318
5281
  return callback;
5319
5282
  }
5320
5283
  /**
5321
- * Lazily builds (and caches, per asset) the default Permit2 sponsored
5322
- * deposit callback used when the caller omits `depositCallback` for a
5323
- * Permit2 asset (WETH, USDT). Mirrors `getDefaultSponsoredCallback()` but
5324
- * 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.
5325
5288
  */
5326
- getDefaultPermit2SponsoredCallback(asset, onApproved) {
5327
- const cached = this.cachedPermit2SponsoredCallbacks.get(asset);
5328
- if (!onApproved && cached) return cached;
5289
+ getDefaultWethSponsoredCallback(onApproved) {
5290
+ if (!onApproved && this.cachedWethSponsoredCallback)
5291
+ return this.cachedWethSponsoredCallback;
5329
5292
  const provider = this.requireConnectedProvider();
5330
5293
  const owner = this.state.walletAddress;
5331
5294
  const callback = makeSponsoredWethCallback({
@@ -5333,8 +5296,7 @@ var OwneySDK = class {
5333
5296
  baseUrl: this.routingApiBaseUrl,
5334
5297
  ownerAddress: owner,
5335
5298
  onApproved,
5336
- tokenAddressByChain: sponsoredTokenMap(asset),
5337
- assetSymbol: asset,
5299
+ tokenAddressByChain: SPONSORED_WETH_BY_CHAIN,
5338
5300
  // Casts work around viem's chain-narrowed Client vs the generic
5339
5301
  // PublicClient/WalletClient param types — structurally identical at
5340
5302
  // runtime, but the two share a name TS treats as unrelated.
@@ -5351,7 +5313,7 @@ var OwneySDK = class {
5351
5313
  transport: (0, import_viem9.custom)(provider)
5352
5314
  })
5353
5315
  });
5354
- if (!onApproved) this.cachedPermit2SponsoredCallbacks.set(asset, callback);
5316
+ if (!onApproved) this.cachedWethSponsoredCallback = callback;
5355
5317
  return callback;
5356
5318
  }
5357
5319
  getAgent(agentId) {
@@ -5447,7 +5409,12 @@ var OwneySDK = class {
5447
5409
  }
5448
5410
  createAgent(agentId, key2) {
5449
5411
  if (agentId === "zyfai") {
5450
- return new ZyfaiAgent(key2, this.zyfaiRpcUrls, this.referralSource);
5412
+ return new ZyfaiAgent(
5413
+ key2,
5414
+ this.zyfaiRpcUrls,
5415
+ this.referralSource,
5416
+ this.sessionStore
5417
+ );
5451
5418
  }
5452
5419
  return null;
5453
5420
  }
@@ -5609,8 +5576,7 @@ var OwneySDK = class {
5609
5576
  }
5610
5577
  const state = this.requireState();
5611
5578
  const chainId = options.chainId ?? this.requireChainId();
5612
- const sponsoredAsset = asset;
5613
- 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));
5614
5580
  if (agentId) {
5615
5581
  if (this.isAgentDisabled(agentId)) {
5616
5582
  throw new OwneyError(
@@ -5724,16 +5690,15 @@ var OwneySDK = class {
5724
5690
  *
5725
5691
  * 1. Missing Permit2 allowance: when the app did not supply its own
5726
5692
  * callback and the attempt fails with `PERMIT2_APPROVAL_REQUIRED` on a
5727
- * Permit2 asset (WETH, USDT), this is the wallet's first gasless deposit
5728
- * of that asset on this chain. We send the one-time (user-paid) Permit2
5729
- * approval via `approvePermit2(asset)` and retry the SAME sponsored
5730
- * attempt once. Bounded to one approval attempt per call so a
5731
- * wallet/agent that keeps reporting the allowance as missing can't loop
5732
- * 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.
5733
5698
  * the user rejects the wallet prompt), that error propagates as-is —
5734
5699
  * the user said no to a transaction, so we must not turn around and ask
5735
5700
  * them to pay for a different one via the fallback below.
5736
- * 2. `shouldFallbackToUserPaid`: the SDK's own sponsor path failed at
5701
+ * 2. `shouldFallbackToUserPaid`: the SDK's own WETH sponsor path failed at
5737
5702
  * the infrastructure layer in a provably safe-to-retry way, so we warn
5738
5703
  * and retry once with `undefined`, falling through to a user-paid
5739
5704
  * native deposit. This still applies after a successful Permit2
@@ -5762,12 +5727,12 @@ var OwneySDK = class {
5762
5727
  try {
5763
5728
  return await attempt(effectiveCallback);
5764
5729
  } catch (error) {
5765
- 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") {
5766
5731
  approvalAttempted = true;
5767
5732
  console.warn(
5768
- `[owney-sdk] First ${asset} deposit: sending one-time Permit2 approval...`
5733
+ "[owney-sdk] First WETH deposit: sending one-time Permit2 approval..."
5769
5734
  );
5770
- await this.approvePermit2(asset);
5735
+ await this.approvePermit2();
5771
5736
  continue;
5772
5737
  }
5773
5738
  if (!shouldFallbackToUserPaid(error, asset, appCallback)) throw error;
@@ -6213,18 +6178,11 @@ var OwneySDK = class {
6213
6178
  account: state.walletAddress,
6214
6179
  chain: srcChain
6215
6180
  });
6216
- const receipt = await srcPublic.waitForTransactionReceipt({
6181
+ await srcPublic.waitForTransactionReceipt({
6217
6182
  hash,
6218
6183
  confirmations: 1,
6219
6184
  timeout: receiptTimeoutMs(quote.src.chainId)
6220
6185
  });
6221
- if (receipt.status !== "success") {
6222
- throw new OwneyError(
6223
- "SWAP_REQUEST_FAILED",
6224
- `Approval transaction reverted (tx ${hash})`,
6225
- { hash }
6226
- );
6227
- }
6228
6186
  return hash;
6229
6187
  },
6230
6188
  ensureChain: (chainId) => this.ensureSwapChain(chainId),
@@ -6314,33 +6272,30 @@ var OwneySDK = class {
6314
6272
  * figure directly. It is the entire arrival, so there is no slack: anything
6315
6273
  * that spends the target asset between the two fails the deposit outright.
6316
6274
  *
6317
- * Something does. A first deposit of a Permit2 asset (WETH, USDT) needs a
6318
- * one-time Permit2 approval, and that approval is a transaction. For WETH,
6319
- * a wallet holding no native gas token - the normal state of someone who
6320
- * just swapped everything INTO WETH - pays for it out of the WETH. The
6321
- * deposit then asked for ~2e12 wei more than was left and refused with
6322
- * DEPOSIT_INSUFFICIENT_BALANCE, under a wrapper saying the funds were safe
6323
- * but unadded (ROUT-242). For USDT the gas cannot come out of the token, so
6324
- * 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).
6325
6281
  *
6326
6282
  * So the approval happens here, before the amount is settled, and the amount
6327
6283
  * comes from a read taken after it. Two things this deliberately is not:
6328
6284
  *
6329
6285
  * - It is not a balance sweep. `received` is a DELTA over the pre-swap
6330
- * balance, so a wallet already holding the asset reads far above it;
6331
- * depositing the balance would move funds the user never offered. The
6332
- * arrival is the ceiling and the balance is only ever allowed to lower it.
6333
- * - It does not touch USDC or EURC, which move on signed typed data
6334
- * (EIP-3009) and so spend nothing of the user's in between, nor a
6335
- * paymaster-configured client, where the sponsor covers the transfer and
6336
- * 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.
6337
6292
  */
6338
6293
  async settleSwapDepositAmount(chainId, token, symbol, received) {
6339
- if (!isPermit2Asset(symbol) || this.paymasterServiceUrl) {
6294
+ if (symbol !== "WETH" || this.paymasterServiceUrl) {
6340
6295
  return received.toString();
6341
6296
  }
6342
6297
  const allowance = await this.readTokenPermit2Allowance(chainId, token);
6343
- if (allowance < received) await this.approvePermit2(symbol);
6298
+ if (allowance < received) await this.approvePermit2();
6344
6299
  const balance = await this.readTokenBalance(chainId, token);
6345
6300
  return (balance < received ? balance : received).toString();
6346
6301
  }
@@ -6505,10 +6460,7 @@ var OwneySDK = class {
6505
6460
  );
6506
6461
  }
6507
6462
  await this.ensureSwapChain(entry.chainId);
6508
- const supported = SUPPORTED_TOKENS.includes(
6509
- entry.symbol
6510
- );
6511
- const token = supported ? sponsoredTokenMap(entry.symbol)[entry.chainId] : void 0;
6463
+ const token = entry.symbol === "WETH" ? SPONSORED_WETH_BY_CHAIN[entry.chainId] : void 0;
6512
6464
  const amount = token ? await this.settleSwapDepositAmount(
6513
6465
  entry.chainId,
6514
6466
  token,
@@ -7661,7 +7613,7 @@ var OwneySDK = class {
7661
7613
  /**
7662
7614
  * Ensure the given asset uses backend protocol auto-selection for the active
7663
7615
  * chain's account. No-op (returns false) for agents that don't support it.
7664
- * @param asset - Asset symbol (e.g. "USDC").
7616
+ * @param asset - "USDC" or "WETH".
7665
7617
  * @param agentId - Agent to target. Defaults to "zyfai".
7666
7618
  * @returns whether a profile write occurred.
7667
7619
  */
@@ -7686,28 +7638,23 @@ var OwneySDK = class {
7686
7638
  return pending;
7687
7639
  }
7688
7640
  /**
7689
- * One-time, user-paid approval of Permit2 on the sponsored WETH (default) or
7690
- * USDT token for the active chain. Required once per wallet per chain before
7691
- * gasless deposits of that asset; afterwards deposit() is signature-only.
7692
- * Resolves only after the approval transaction is mined (1 confirmation), so
7693
- * a subsequent deposit() will see the new allowance; throws if the
7694
- * transaction reverted.
7695
- *
7696
- * On mainnet USDT only (`needsAllowanceReset`), a non-zero existing allowance
7697
- * is first zeroed in its own transaction. If the user rejects the second
7698
- * prompt, the previous Permit2 allowance stays zeroed; calling this again
7699
- * 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.
7700
7646
  * @returns the approval transaction hash.
7701
7647
  */
7702
7648
  async approvePermit2(asset = "WETH") {
7649
+ void asset;
7703
7650
  const state = this.requireState();
7704
7651
  const chainId = this.requireChainId();
7705
- this.validateAssetSupport(this.getAgent("zyfai"), chainId, asset);
7706
- const token = sponsoredTokenMap(asset)[chainId];
7652
+ this.validateAssetSupport(this.getAgent("zyfai"), chainId, "WETH");
7653
+ const token = SPONSORED_WETH_BY_CHAIN[chainId];
7707
7654
  if (!token) {
7708
7655
  throw new OwneyError(
7709
7656
  "CHAIN_UNSUPPORTED",
7710
- `No sponsored ${asset} on chain ${chainId}`
7657
+ `No sponsored WETH on chain ${chainId}`
7711
7658
  );
7712
7659
  }
7713
7660
  const provider = this.requireConnectedProvider();
@@ -7725,52 +7672,22 @@ var OwneySDK = class {
7725
7672
  wallet,
7726
7673
  chainId
7727
7674
  );
7728
- const currentAllowance = await this.readTokenPermit2Allowance(
7729
- chainId,
7730
- token
7731
- ).catch(
7732
- () => readPermit2Allowance(
7733
- publicClient,
7734
- token,
7735
- state.walletAddress
7736
- )
7737
- ).catch((err) => {
7738
- if (!needsAllowanceReset(token)) return 0n;
7739
- throw new OwneyError(
7740
- "PERMIT2_APPROVAL_REQUIRED",
7741
- `Could not read the current ${asset} allowance for Permit2; please try again.`,
7742
- {
7743
- token,
7744
- chainId,
7745
- reason: "ALLOWANCE_UNREADABLE",
7746
- cause: err instanceof Error ? err.message : String(err)
7747
- }
7748
- );
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]
7749
7682
  });
7750
- return approveWithResetIfNeeded({
7751
- token,
7752
- currentAllowance,
7753
- spender: PERMIT2_ADDRESS,
7754
- amount: MAX_UINT256,
7755
- approve: async (spender, amount) => {
7756
- const hash = await wallet.writeContract({
7757
- address: token,
7758
- abi: ERC20_ALLOWANCE_ABI,
7759
- functionName: "approve",
7760
- args: [spender, amount],
7761
- account: state.walletAddress,
7762
- chain: VIEM_CHAIN2[chainId]
7763
- });
7764
- const receipt = await publicClient.waitForTransactionReceipt({
7765
- hash,
7766
- confirmations: 1
7767
- });
7768
- if (receipt.status !== "success") {
7769
- throw new Error(`Permit2 approval reverted (tx ${hash})`);
7770
- }
7771
- return hash;
7772
- }
7683
+ const receipt = await publicClient.waitForTransactionReceipt({
7684
+ hash,
7685
+ confirmations: 1
7773
7686
  });
7687
+ if (receipt.status !== "success") {
7688
+ throw new Error(`Permit2 approval reverted (tx ${hash})`);
7689
+ }
7690
+ return hash;
7774
7691
  }
7775
7692
  // --- Discovery (no wallet required) ---
7776
7693
  /**