@owney/sdk 0.8.0-beta.1 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -211,7 +211,7 @@ var P_SUPPORTED_CHAINS = {
211
211
  chainIds: [8453, 42161, 1],
212
212
  chains: ["BASE", "ARBITRUM", "ETHEREUM"]
213
213
  };
214
- var SUPPORTED_TOKENS = ["USDC", "WETH", "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,11 +1882,18 @@ 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
  ];
1896
- await this.sdk.updateUserProfile({ asset, strategy, protocols });
1891
+ await this.sdk.updateUserProfile({
1892
+ asset,
1893
+ strategy,
1894
+ protocols,
1895
+ autoSelectProtocols: false
1896
+ });
1897
1897
  })
1898
1898
  );
1899
1899
  } catch (error) {
@@ -2248,10 +2248,11 @@ var ZyfaiAgent = class _ZyfaiAgent {
2248
2248
  requestedStrategy: "aggressive",
2249
2249
  setupResult
2250
2250
  });
2251
- await this.syncAutoSelect(validChainId, asset);
2252
2251
  if (isOwneyDebug()) {
2253
2252
  try {
2254
- const profileAfterSetup = await this.sdk.getUserDetails(asset);
2253
+ const profileAfterSetup = await this.sdk.getUserDetails(
2254
+ asset === "WETH" ? "WETH" : "USDC"
2255
+ );
2255
2256
  debugLog("zyfai:first-deposit", "profile immediately after setup", {
2256
2257
  asset,
2257
2258
  strategy: profileAfterSetup.strategy,
@@ -2269,9 +2270,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
2269
2270
  validChainId
2270
2271
  );
2271
2272
  const txHash = await depositCallback(smartWallet, validChainId, amount);
2272
- const tokenAddress2 = asset === "USDC" ? void 0 : tokenAddress(asset, validChainId);
2273
+ const tokenAddress = asset === "WETH" ? WETH_ADDRESS_BY_CHAIN[validChainId] : void 0;
2273
2274
  try {
2274
- await (tokenAddress2 ? this.sdk.logDeposit(validChainId, txHash, amount, tokenAddress2) : this.sdk.logDeposit(validChainId, txHash, amount));
2275
+ await (tokenAddress ? this.sdk.logDeposit(validChainId, txHash, amount, tokenAddress) : this.sdk.logDeposit(validChainId, txHash, amount));
2275
2276
  } catch (logError) {
2276
2277
  console.warn(
2277
2278
  "[owney-sdk] Deposit landed on-chain but logDeposit failed (non-fatal):",
@@ -2377,22 +2378,13 @@ var ZyfaiAgent = class _ZyfaiAgent {
2377
2378
  }
2378
2379
  async getAccountApy(state, chainId, days, tokenSymbol, scopeChainId) {
2379
2380
  const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
2380
- const [raw, ethUsd, eurUsd] = await Promise.all([
2381
+ const [raw, ethUsd] = await Promise.all([
2381
2382
  this.sdk.getDailyApyHistory(smartWallet, days),
2382
- tokenSymbol ? void 0 : this.readEthUsd(validChainId),
2383
- tokenSymbol ? void 0 : this.readEurUsd()
2383
+ tokenSymbol ? void 0 : this.readEthUsd(validChainId)
2384
2384
  ]);
2385
2385
  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
- );
2386
+ const usdPrices = ethUsd ? { WETH: ethUsd, ETH: ethUsd } : void 0;
2387
+ return mapApyHistory(raw, scope, tokenSymbol, usdPrices);
2396
2388
  }
2397
2389
  /**
2398
2390
  * Today's ETH/USD from Chainlink, cached for a minute. Every day of the
@@ -2400,38 +2392,24 @@ var ZyfaiAgent = class _ZyfaiAgent {
2400
2392
  * move over the window is not reflected (ROUT-682). Undefined on failure,
2401
2393
  * which leaves the series on token-amount weighting rather than failing it.
2402
2394
  */
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;
2395
+ async readEthUsd(chainId) {
2396
+ if (this.ethUsd && Date.now() - this.ethUsd.at < ETH_USD_TTL_MS) {
2397
+ return this.ethUsd.price;
2418
2398
  }
2419
2399
  try {
2420
2400
  const [, answer] = await this.getPublicClient(chainId).readContract({
2421
- address: feed,
2401
+ address: CHAINLINK_ETH_USD_FEED[chainId],
2422
2402
  abi: CHAINLINK_ABI,
2423
2403
  functionName: "latestRoundData"
2424
2404
  });
2425
2405
  const price = Number(answer) / 1e8;
2426
2406
  if (!Number.isFinite(price) || price <= 0) return void 0;
2427
- this[cache] = { price, at: Date.now() };
2407
+ this.ethUsd = { price, at: Date.now() };
2428
2408
  return price;
2429
2409
  } catch (err) {
2430
- debugLog(
2431
- "zyfai:apy",
2432
- `${cache === "ethUsd" ? "ETH/USD" : "EUR/USD"} read failed; token-amount weighting`,
2433
- { err }
2434
- );
2410
+ debugLog("zyfai:apy", "ETH/USD read failed; token-amount weighting", {
2411
+ err
2412
+ });
2435
2413
  return void 0;
2436
2414
  }
2437
2415
  }
@@ -2462,7 +2440,6 @@ var ZyfaiAgent = class _ZyfaiAgent {
2462
2440
  return "eth";
2463
2441
  case "EURC":
2464
2442
  return "eurc";
2465
- // Zyfai has no "usdt" history filter, so USDT is filtered client-side.
2466
2443
  default:
2467
2444
  return void 0;
2468
2445
  }
@@ -2471,9 +2448,6 @@ var ZyfaiAgent = class _ZyfaiAgent {
2471
2448
  const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
2472
2449
  const limit = options?.limit ?? 10;
2473
2450
  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
2451
  const cursor = options?.cursor ? decodeHistoryCursor(options.cursor) : null;
2478
2452
  const toDate = cursor?.toDate ?? options?.toDate ?? (/* @__PURE__ */ new Date()).toISOString();
2479
2453
  let offset = cursor?.rawOffset ?? 0;
@@ -2495,12 +2469,6 @@ var ZyfaiAgent = class _ZyfaiAgent {
2495
2469
  assetType
2496
2470
  });
2497
2471
  raw.data.forEach((entry, idx) => {
2498
- if (clientSideAsset && !matchesAsset(
2499
- entry.positions?.[0]?.token_symbol ?? "",
2500
- clientSideAsset
2501
- )) {
2502
- return;
2503
- }
2504
2472
  if (entry.chainId === validChainId) {
2505
2473
  matched.push({ entry, rawIdx: offset + idx });
2506
2474
  }
@@ -2543,20 +2511,6 @@ var ZyfaiAgent = class _ZyfaiAgent {
2543
2511
  }
2544
2512
  async ensureAutoSelectProtocols(state, chainId, asset) {
2545
2513
  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
2514
  const current = await this.sdk.getUserDetails(asset);
2561
2515
  debugLog("zyfai:auto-select", `${asset}: profile before check`, {
2562
2516
  autoSelectProtocols: current.autoSelectProtocols,
@@ -2564,7 +2518,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
2564
2518
  protocols: current.protocols,
2565
2519
  strategy: current.strategy
2566
2520
  });
2567
- if ((current.chains?.length ?? 0) === 0 && (asset === "USDC" || !await this.isExistingZyfaiUser())) {
2521
+ if ((current.chains?.length ?? 0) === 0) {
2568
2522
  debugLog(
2569
2523
  "zyfai:auto-select",
2570
2524
  `${asset}: skipping untouched profile until first deposit`
@@ -3449,20 +3403,6 @@ async function readErc20Balance(publicClient, token, owner) {
3449
3403
  });
3450
3404
  }
3451
3405
 
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
3406
  // src/lib/swap/swap.secrets.ts
3467
3407
  var import_viem4 = require("viem");
3468
3408
  var SECRET_BYTES = 32;
@@ -3821,15 +3761,6 @@ async function executeSwap(deps, options) {
3821
3761
  }
3822
3762
  return { received: arrived.toString(), ...result ?? {} };
3823
3763
  }
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
3764
  async function runClassic(deps, options) {
3834
3765
  const {
3835
3766
  quote,
@@ -3866,7 +3797,7 @@ async function runClassic(deps, options) {
3866
3797
  if (current < needed) {
3867
3798
  onStage?.("approving");
3868
3799
  await deps.ensureChain(quote.src.chainId);
3869
- await approveMax(deps, quote.src.address, current, tx.to);
3800
+ await deps.approve(tx.to, MAX_UINT256);
3870
3801
  debugLog(
3871
3802
  "owney-sdk",
3872
3803
  "swap: re-fetching classic calldata after approval"
@@ -3955,7 +3886,7 @@ async function authoriseSpend(deps, options, amount, isNativeSource) {
3955
3886
  });
3956
3887
  return permit;
3957
3888
  }
3958
- await approveMax(deps, quote.src.address, current, quote.spender);
3889
+ await deps.approve(quote.spender, MAX_UINT256);
3959
3890
  debugLog("owney-sdk", "swap: approved limit order protocol");
3960
3891
  return void 0;
3961
3892
  }
@@ -4051,66 +3982,6 @@ async function runFusion(deps, options, walletAddress) {
4051
3982
  return { orderHash: built.orderHash };
4052
3983
  }
4053
3984
 
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
3985
  // src/lib/swap/swap.permit.ts
4115
3986
  var import_viem5 = require("viem");
4116
3987
  var PERMIT_ABI = (0, import_viem5.parseAbi)([
@@ -4829,7 +4700,6 @@ function makeSponsoredDepositCallback(deps) {
4829
4700
  // src/lib/walletconnect-switch.ts
4830
4701
  var WALLET_SWITCH_TIMEOUT_MS = 12e4;
4831
4702
  var HOLD_CHAIN_MS = 15e3;
4832
- var MAX_RESENDS = 2;
4833
4703
  var holds = /* @__PURE__ */ new Map();
4834
4704
  function parseChainId(raw) {
4835
4705
  if (typeof raw === "number") return raw;
@@ -4838,28 +4708,76 @@ function parseChainId(raw) {
4838
4708
  const id = ref.startsWith("0x") ? Number.parseInt(ref, 16) : Number(ref);
4839
4709
  return Number.isFinite(id) ? id : void 0;
4840
4710
  }
4841
- function walletConnectCore(provider) {
4711
+ function walletConnectSession(provider) {
4842
4712
  const p = provider;
4843
4713
  const core = p?.signer ?? p;
4844
- if (typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
4714
+ if (typeof core?.request !== "function" || typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
4845
4715
  return null;
4846
4716
  }
4847
4717
  const peer = core.session.peer?.metadata?.name ?? "";
4848
- if (!/metamask/i.test(peer)) return null;
4849
- return core;
4718
+ if (/metamask/i.test(peer)) {
4719
+ return { core, strategy: "remote-wallet" };
4720
+ }
4721
+ if (/fireblocks/i.test(peer)) {
4722
+ return { core, strategy: "session-default" };
4723
+ }
4724
+ return null;
4725
+ }
4726
+ function approvedChains(core) {
4727
+ const approved = /* @__PURE__ */ new Set();
4728
+ for (const namespace of Object.values(core.session.namespaces ?? {})) {
4729
+ for (const chain of namespace.chains ?? []) approved.add(chain);
4730
+ for (const account of namespace.accounts ?? []) {
4731
+ const [namespaceName, reference] = account.split(":");
4732
+ if (namespaceName && reference) {
4733
+ approved.add(`${namespaceName}:${reference}`);
4734
+ }
4735
+ }
4736
+ }
4737
+ return approved;
4738
+ }
4739
+ async function selectSessionDefaultChain(core, chainId) {
4740
+ const target = `eip155:${chainId}`;
4741
+ if (!approvedChains(core).has(target)) {
4742
+ throw new Error(
4743
+ `The WalletConnect session has not approved ${target}. Reconnect the wallet and try again.`
4744
+ );
4745
+ }
4746
+ core.setDefaultChain(target);
4747
+ const selected = parseChainId(
4748
+ await core.request({ method: "eth_chainId" })
4749
+ );
4750
+ debugLog("wc-switch", "selected WalletConnect session default", {
4751
+ peer: core.session.peer?.metadata?.name,
4752
+ target: chainId,
4753
+ selected
4754
+ });
4755
+ if (selected !== chainId) {
4756
+ throw new Error(
4757
+ `WalletConnect stayed on chain ${selected ?? "unknown"}; expected ${chainId}.`
4758
+ );
4759
+ }
4850
4760
  }
4851
4761
  async function switchWalletConnectChain(provider, chainId, timeoutMs = WALLET_SWITCH_TIMEOUT_MS) {
4852
- const core = walletConnectCore(provider);
4853
- if (!core) return false;
4762
+ const session = walletConnectSession(provider);
4763
+ if (!session) return false;
4764
+ const { core, strategy } = session;
4854
4765
  holds.get(core.session.topic)?.();
4766
+ if (strategy === "session-default") {
4767
+ await selectSessionDefaultChain(core, chainId);
4768
+ return true;
4769
+ }
4855
4770
  await requestSwitch(core, provider, chainId, timeoutMs);
4856
- holdChain(core, provider, chainId);
4771
+ holdChain(core, chainId);
4857
4772
  return true;
4858
4773
  }
4859
4774
  async function requestSwitch(core, provider, chainId, timeoutMs) {
4860
- const current = Number(
4775
+ const current = parseChainId(
4861
4776
  await provider.request({ method: "eth_chainId" })
4862
4777
  );
4778
+ if (current === void 0) {
4779
+ throw new Error("WalletConnect could not report its current chain.");
4780
+ }
4863
4781
  const hexChainId = `0x${chainId.toString(16)}`;
4864
4782
  let timer;
4865
4783
  try {
@@ -4889,26 +4807,27 @@ async function requestSwitch(core, provider, chainId, timeoutMs) {
4889
4807
  } catch {
4890
4808
  }
4891
4809
  }
4892
- function holdChain(core, provider, chainId) {
4810
+ function holdChain(core, chainId) {
4893
4811
  if (typeof core.on !== "function" || typeof core.removeListener !== "function") {
4894
4812
  return;
4895
4813
  }
4896
- let resends = 0;
4814
+ let repins = 0;
4897
4815
  const listener = (raw) => {
4898
4816
  const reported = parseChainId(raw);
4899
4817
  debugLog("wc-switch", "wallet reported chain", {
4900
4818
  reported,
4901
4819
  holding: chainId,
4902
- resends
4820
+ repins
4903
4821
  });
4904
4822
  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", {
4823
+ repins += 1;
4824
+ try {
4825
+ core.setDefaultChain(`eip155:${chainId}`);
4826
+ } catch (error) {
4827
+ debugLog("wc-switch", "session re-pin failed", {
4909
4828
  error: error instanceof Error ? error.message : String(error)
4910
- })
4911
- );
4829
+ });
4830
+ }
4912
4831
  };
4913
4832
  const release = () => {
4914
4833
  clearTimeout(timer);
@@ -4922,7 +4841,7 @@ function holdChain(core, provider, chainId) {
4922
4841
  holds.set(core.session.topic, release);
4923
4842
  }
4924
4843
  function withWalletConnectSwitch(provider) {
4925
- if (!walletConnectCore(provider)) return provider;
4844
+ if (!walletConnectSession(provider)) return provider;
4926
4845
  const target = provider;
4927
4846
  const request2 = async (args) => {
4928
4847
  if (args?.method !== "wallet_switchEthereumChain") {
@@ -4954,7 +4873,7 @@ function makeSponsoredWethCallback(deps) {
4954
4873
  if (!token) {
4955
4874
  throw new OwneyError(
4956
4875
  "CHAIN_UNSUPPORTED",
4957
- `No sponsored ${deps.assetSymbol} configured for chain ${chainId}`
4876
+ `No sponsored WETH configured for chain ${chainId}`
4958
4877
  );
4959
4878
  }
4960
4879
  const amountWei = BigInt(amount);
@@ -4967,14 +4886,14 @@ function makeSponsoredWethCallback(deps) {
4967
4886
  if (balance < amountWei) {
4968
4887
  throw new OwneyError(
4969
4888
  "DEPOSIT_INSUFFICIENT_BALANCE",
4970
- `Insufficient ${deps.assetSymbol} balance for this deposit.`,
4889
+ "Insufficient WETH balance for this deposit.",
4971
4890
  { token, chainId: cid, balance: balance.toString(), amount }
4972
4891
  );
4973
4892
  }
4974
4893
  } catch (err) {
4975
4894
  if (err instanceof OwneyError) throw err;
4976
4895
  console.warn(
4977
- `[owney-sdk] ${deps.assetSymbol} balance pre-check failed (non-fatal):`,
4896
+ "[owney-sdk] WETH balance pre-check failed (non-fatal):",
4978
4897
  err instanceof Error ? err.message : String(err)
4979
4898
  );
4980
4899
  }
@@ -4986,7 +4905,7 @@ function makeSponsoredWethCallback(deps) {
4986
4905
  if (allowance < amountWei) {
4987
4906
  throw new OwneyError(
4988
4907
  "PERMIT2_APPROVAL_REQUIRED",
4989
- `${deps.assetSymbol} gasless deposits need a one-time Permit2 approval; call approvePermit2() first`,
4908
+ "WETH gasless deposits need a one-time Permit2 approval; call approvePermit2() first",
4990
4909
  { token, chainId: cid, allowance: allowance.toString(), amount }
4991
4910
  );
4992
4911
  }
@@ -5173,22 +5092,8 @@ var SPONSORED_WETH_BY_CHAIN = {
5173
5092
  42161: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
5174
5093
  1: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
5175
5094
  };
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
5095
  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;
5096
+ return (asset === "WETH" || asset === "USDC") && appCallback === void 0 && error instanceof OwneyError && error.code === "SPONSOR_REQUEST_FAILED" && error.details?.safeToFallback === true;
5192
5097
  }
5193
5098
  var OwneySDK = class {
5194
5099
  agents = /* @__PURE__ */ new Map();
@@ -5211,8 +5116,9 @@ var OwneySDK = class {
5211
5116
  userPoolCustomization = false;
5212
5117
  routingApiBaseUrl;
5213
5118
  referralSource;
5214
- cachedSponsoredCallbacks = /* @__PURE__ */ new Map();
5215
- cachedPermit2SponsoredCallbacks = /* @__PURE__ */ new Map();
5119
+ sessionStore;
5120
+ cachedSponsoredCallback = null;
5121
+ cachedWethSponsoredCallback = null;
5216
5122
  paymasterServiceUrl;
5217
5123
  cachedSponsoredCallsCallbacks = /* @__PURE__ */ new Map();
5218
5124
  agentReads = new AgentReads();
@@ -5234,6 +5140,7 @@ var OwneySDK = class {
5234
5140
  this.routingApiBaseUrl = config.routingApiBaseUrl;
5235
5141
  this.paymasterServiceUrl = config.paymasterServiceUrl;
5236
5142
  this.referralSource = config.referralSource;
5143
+ this.sessionStore = config.sessionStore;
5237
5144
  this.userPoolCustomization = config.userPoolCustomization ?? false;
5238
5145
  }
5239
5146
  /**
@@ -5260,8 +5167,8 @@ var OwneySDK = class {
5260
5167
  walletAddress,
5261
5168
  chainId: null
5262
5169
  };
5263
- this.cachedSponsoredCallbacks.clear();
5264
- this.cachedPermit2SponsoredCallbacks.clear();
5170
+ this.cachedSponsoredCallback = null;
5171
+ this.cachedWethSponsoredCallback = null;
5265
5172
  this.cachedSponsoredCallsCallbacks.clear();
5266
5173
  }
5267
5174
  /**
@@ -5277,8 +5184,8 @@ var OwneySDK = class {
5277
5184
  this.agentReads.clearInFlight();
5278
5185
  this.activationChecks.clear();
5279
5186
  this.state = null;
5280
- this.cachedSponsoredCallbacks.clear();
5281
- this.cachedPermit2SponsoredCallbacks.clear();
5187
+ this.cachedSponsoredCallback = null;
5188
+ this.cachedWethSponsoredCallback = null;
5282
5189
  this.cachedSponsoredCallsCallbacks.clear();
5283
5190
  }
5284
5191
  isAgentDisabled(agentId) {
@@ -5328,9 +5235,9 @@ var OwneySDK = class {
5328
5235
  * provider with viem `custom(provider)` to read token meta and sign the
5329
5236
  * `TransferWithAuthorization`, then POSTs to the sponsor API.
5330
5237
  */
5331
- getDefaultSponsoredCallback(asset, onApproved) {
5332
- const cached = this.cachedSponsoredCallbacks.get(asset);
5333
- if (!onApproved && cached) return cached;
5238
+ getDefaultSponsoredCallback(onApproved) {
5239
+ if (!onApproved && this.cachedSponsoredCallback)
5240
+ return this.cachedSponsoredCallback;
5334
5241
  const provider = this.requireConnectedProvider();
5335
5242
  const owner = this.state.walletAddress;
5336
5243
  const callback = makeSponsoredDepositCallback({
@@ -5338,7 +5245,7 @@ var OwneySDK = class {
5338
5245
  baseUrl: this.routingApiBaseUrl,
5339
5246
  ownerAddress: owner,
5340
5247
  onApproved,
5341
- tokenAddressByChain: sponsoredTokenMap(asset),
5248
+ tokenAddressByChain: SPONSORED_USDC_BY_CHAIN,
5342
5249
  // Casts work around viem's chain-narrowed Client vs the generic
5343
5250
  // PublicClient/WalletClient param types — structurally identical at
5344
5251
  // runtime, but the two share a name TS treats as unrelated.
@@ -5355,13 +5262,14 @@ var OwneySDK = class {
5355
5262
  transport: (0, import_viem9.custom)(provider)
5356
5263
  })
5357
5264
  });
5358
- if (!onApproved) this.cachedSponsoredCallbacks.set(asset, callback);
5265
+ if (!onApproved) this.cachedSponsoredCallback = callback;
5359
5266
  return callback;
5360
5267
  }
5361
5268
  /**
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.
5269
+ * Lazily builds (and caches) the default Permit2 sponsored WETH deposit
5270
+ * callback used when the caller omits `depositCallback` for a WETH
5271
+ * deposit. Mirrors `getDefaultSponsoredCallback()` but signs a Permit2
5272
+ * `PermitTransferFrom` instead of an EIP-3009 authorization.
5365
5273
  */
5366
5274
  getDefaultSponsoredCallsCallback(asset, onApproved) {
5367
5275
  const cached = this.cachedSponsoredCallsCallbacks.get(asset);
@@ -5372,20 +5280,20 @@ var OwneySDK = class {
5372
5280
  ownerAddress: this.state.walletAddress,
5373
5281
  paymasterServiceUrl: this.paymasterServiceUrl,
5374
5282
  onApproved,
5375
- tokenAddressByChain: sponsoredTokenMap(asset)
5283
+ tokenAddressByChain: asset === "WETH" ? SPONSORED_WETH_BY_CHAIN : SPONSORED_USDC_BY_CHAIN
5376
5284
  });
5377
5285
  if (!onApproved) this.cachedSponsoredCallsCallbacks.set(asset, callback);
5378
5286
  return callback;
5379
5287
  }
5380
5288
  /**
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.
5289
+ * Lazily builds (and caches) the default Permit2 sponsored WETH deposit
5290
+ * callback used when the caller omits `depositCallback` for a WETH deposit.
5291
+ * Mirrors `getDefaultSponsoredCallback()` but signs a Permit2
5292
+ * `PermitTransferFrom` instead of an EIP-3009 authorization.
5385
5293
  */
5386
- getDefaultPermit2SponsoredCallback(asset, onApproved) {
5387
- const cached = this.cachedPermit2SponsoredCallbacks.get(asset);
5388
- if (!onApproved && cached) return cached;
5294
+ getDefaultWethSponsoredCallback(onApproved) {
5295
+ if (!onApproved && this.cachedWethSponsoredCallback)
5296
+ return this.cachedWethSponsoredCallback;
5389
5297
  const provider = this.requireConnectedProvider();
5390
5298
  const owner = this.state.walletAddress;
5391
5299
  const callback = makeSponsoredWethCallback({
@@ -5393,8 +5301,7 @@ var OwneySDK = class {
5393
5301
  baseUrl: this.routingApiBaseUrl,
5394
5302
  ownerAddress: owner,
5395
5303
  onApproved,
5396
- tokenAddressByChain: sponsoredTokenMap(asset),
5397
- assetSymbol: asset,
5304
+ tokenAddressByChain: SPONSORED_WETH_BY_CHAIN,
5398
5305
  // Casts work around viem's chain-narrowed Client vs the generic
5399
5306
  // PublicClient/WalletClient param types — structurally identical at
5400
5307
  // runtime, but the two share a name TS treats as unrelated.
@@ -5411,7 +5318,7 @@ var OwneySDK = class {
5411
5318
  transport: (0, import_viem9.custom)(provider)
5412
5319
  })
5413
5320
  });
5414
- if (!onApproved) this.cachedPermit2SponsoredCallbacks.set(asset, callback);
5321
+ if (!onApproved) this.cachedWethSponsoredCallback = callback;
5415
5322
  return callback;
5416
5323
  }
5417
5324
  getAgent(agentId) {
@@ -5507,7 +5414,12 @@ var OwneySDK = class {
5507
5414
  }
5508
5415
  createAgent(agentId, key2) {
5509
5416
  if (agentId === "zyfai") {
5510
- return new ZyfaiAgent(key2, this.zyfaiRpcUrls, this.referralSource);
5417
+ return new ZyfaiAgent(
5418
+ key2,
5419
+ this.zyfaiRpcUrls,
5420
+ this.referralSource,
5421
+ this.sessionStore
5422
+ );
5511
5423
  }
5512
5424
  return null;
5513
5425
  }
@@ -5669,8 +5581,7 @@ var OwneySDK = class {
5669
5581
  }
5670
5582
  const state = this.requireState();
5671
5583
  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));
5584
+ const effectiveCallback = depositCallback ?? (this.paymasterServiceUrl ? this.getDefaultSponsoredCallsCallback(asset, onApproved) : asset === "WETH" ? this.getDefaultWethSponsoredCallback(onApproved) : this.getDefaultSponsoredCallback(onApproved));
5674
5585
  if (agentId) {
5675
5586
  if (this.isAgentDisabled(agentId)) {
5676
5587
  throw new OwneyError(
@@ -5784,16 +5695,15 @@ var OwneySDK = class {
5784
5695
  *
5785
5696
  * 1. Missing Permit2 allowance: when the app did not supply its own
5786
5697
  * 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.
5698
+ * WETH deposit, this is the wallet's first gasless WETH deposit. We send
5699
+ * the one-time (user-paid) Permit2 approval via `approvePermit2()` and
5700
+ * retry the SAME sponsored attempt once. Bounded to one approval attempt
5701
+ * per call so a wallet/agent that keeps reporting the allowance as
5702
+ * missing can't loop forever. If `approvePermit2()` itself throws (e.g.
5793
5703
  * the user rejects the wallet prompt), that error propagates as-is —
5794
5704
  * the user said no to a transaction, so we must not turn around and ask
5795
5705
  * them to pay for a different one via the fallback below.
5796
- * 2. `shouldFallbackToUserPaid`: the SDK's own sponsor path failed at
5706
+ * 2. `shouldFallbackToUserPaid`: the SDK's own WETH sponsor path failed at
5797
5707
  * the infrastructure layer in a provably safe-to-retry way, so we warn
5798
5708
  * and retry once with `undefined`, falling through to a user-paid
5799
5709
  * native deposit. This still applies after a successful Permit2
@@ -5822,12 +5732,12 @@ var OwneySDK = class {
5822
5732
  try {
5823
5733
  return await attempt(effectiveCallback);
5824
5734
  } catch (error) {
5825
- if (!approvalAttempted && appCallback === void 0 && isPermit2Asset(asset) && error instanceof OwneyError && error.code === "PERMIT2_APPROVAL_REQUIRED") {
5735
+ if (!approvalAttempted && appCallback === void 0 && asset === "WETH" && error instanceof OwneyError && error.code === "PERMIT2_APPROVAL_REQUIRED") {
5826
5736
  approvalAttempted = true;
5827
5737
  console.warn(
5828
- `[owney-sdk] First ${asset} deposit: sending one-time Permit2 approval...`
5738
+ "[owney-sdk] First WETH deposit: sending one-time Permit2 approval..."
5829
5739
  );
5830
- await this.approvePermit2(asset);
5740
+ await this.approvePermit2();
5831
5741
  continue;
5832
5742
  }
5833
5743
  if (!shouldFallbackToUserPaid(error, asset, appCallback)) throw error;
@@ -6264,45 +6174,22 @@ var OwneySDK = class {
6264
6174
  functionName: "allowance",
6265
6175
  args: [state.walletAddress, spender]
6266
6176
  }),
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
- ),
6177
+ approve: async (spender, amount) => {
6178
+ const hash = await wallet.writeContract({
6179
+ address: quote.src.address,
6180
+ abi: ERC20_ALLOWANCE_ABI,
6181
+ functionName: "approve",
6182
+ args: [spender, amount],
6183
+ account: state.walletAddress,
6184
+ chain: srcChain
6185
+ });
6186
+ await srcPublic.waitForTransactionReceipt({
6187
+ hash,
6188
+ confirmations: 1,
6189
+ timeout: receiptTimeoutMs(quote.src.chainId)
6190
+ });
6191
+ return hash;
6192
+ },
6306
6193
  ensureChain: (chainId) => this.ensureSwapChain(chainId),
6307
6194
  /**
6308
6195
  * Sign the approval instead of paying for it. Null means the token
@@ -6390,33 +6277,30 @@ var OwneySDK = class {
6390
6277
  * figure directly. It is the entire arrival, so there is no slack: anything
6391
6278
  * that spends the target asset between the two fails the deposit outright.
6392
6279
  *
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.
6280
+ * Something does. A first WETH deposit needs a one-time Permit2 approval,
6281
+ * and that approval is a transaction. A wallet holding no native gas token -
6282
+ * the normal state of someone who just swapped everything INTO WETH - pays
6283
+ * for it out of the WETH. The deposit then asked for ~2e12 wei more than was
6284
+ * left and refused with DEPOSIT_INSUFFICIENT_BALANCE, under a wrapper saying
6285
+ * the funds were safe but unadded (ROUT-242).
6401
6286
  *
6402
6287
  * So the approval happens here, before the amount is settled, and the amount
6403
6288
  * comes from a read taken after it. Two things this deliberately is not:
6404
6289
  *
6405
6290
  * - 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.
6291
+ * balance, so a wallet already holding WETH reads far above it; depositing
6292
+ * the balance would move funds the user never offered. The arrival is the
6293
+ * ceiling and the balance is only ever allowed to lower it.
6294
+ * - It does not touch USDC, which moves on signed typed data and so spends
6295
+ * nothing of the user's in between, nor a paymaster-configured client,
6296
+ * where the sponsor covers the transfer and Permit2 never applies.
6413
6297
  */
6414
6298
  async settleSwapDepositAmount(chainId, token, symbol, received) {
6415
- if (!isPermit2Asset(symbol) || this.paymasterServiceUrl) {
6299
+ if (symbol !== "WETH" || this.paymasterServiceUrl) {
6416
6300
  return received.toString();
6417
6301
  }
6418
6302
  const allowance = await this.readTokenPermit2Allowance(chainId, token);
6419
- if (allowance < received) await this.approvePermit2(symbol);
6303
+ if (allowance < received) await this.approvePermit2();
6420
6304
  const balance = await this.readTokenBalance(chainId, token);
6421
6305
  return (balance < received ? balance : received).toString();
6422
6306
  }
@@ -6581,10 +6465,7 @@ var OwneySDK = class {
6581
6465
  );
6582
6466
  }
6583
6467
  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;
6468
+ const token = entry.symbol === "WETH" ? SPONSORED_WETH_BY_CHAIN[entry.chainId] : void 0;
6588
6469
  const amount = token ? await this.settleSwapDepositAmount(
6589
6470
  entry.chainId,
6590
6471
  token,
@@ -7737,7 +7618,7 @@ var OwneySDK = class {
7737
7618
  /**
7738
7619
  * Ensure the given asset uses backend protocol auto-selection for the active
7739
7620
  * chain's account. No-op (returns false) for agents that don't support it.
7740
- * @param asset - Asset symbol (e.g. "USDC").
7621
+ * @param asset - "USDC" or "WETH".
7741
7622
  * @param agentId - Agent to target. Defaults to "zyfai".
7742
7623
  * @returns whether a profile write occurred.
7743
7624
  */
@@ -7762,28 +7643,23 @@ var OwneySDK = class {
7762
7643
  return pending;
7763
7644
  }
7764
7645
  /**
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.
7646
+ * One-time, user-paid approval of Permit2 on the sponsored WETH token for
7647
+ * the active chain. Required once per wallet per chain before gasless WETH
7648
+ * deposits; afterwards deposit() is signature-only. Resolves only after the
7649
+ * approval transaction is mined (1 confirmation), so a subsequent deposit()
7650
+ * will see the new allowance; throws if the transaction reverted.
7776
7651
  * @returns the approval transaction hash.
7777
7652
  */
7778
7653
  async approvePermit2(asset = "WETH") {
7654
+ void asset;
7779
7655
  const state = this.requireState();
7780
7656
  const chainId = this.requireChainId();
7781
- this.validateAssetSupport(this.getAgent("zyfai"), chainId, asset);
7782
- const token = sponsoredTokenMap(asset)[chainId];
7657
+ this.validateAssetSupport(this.getAgent("zyfai"), chainId, "WETH");
7658
+ const token = SPONSORED_WETH_BY_CHAIN[chainId];
7783
7659
  if (!token) {
7784
7660
  throw new OwneyError(
7785
7661
  "CHAIN_UNSUPPORTED",
7786
- `No sponsored ${asset} on chain ${chainId}`
7662
+ `No sponsored WETH on chain ${chainId}`
7787
7663
  );
7788
7664
  }
7789
7665
  const provider = this.requireConnectedProvider();
@@ -7801,52 +7677,22 @@ var OwneySDK = class {
7801
7677
  wallet,
7802
7678
  chainId
7803
7679
  );
7804
- const currentAllowance = await this.readTokenPermit2Allowance(
7805
- chainId,
7806
- token
7807
- ).catch(
7808
- () => readPermit2Allowance(
7809
- publicClient,
7810
- token,
7811
- state.walletAddress
7812
- )
7813
- ).catch((err) => {
7814
- if (!needsAllowanceReset(token)) return 0n;
7815
- throw new OwneyError(
7816
- "PERMIT2_APPROVAL_REQUIRED",
7817
- `Could not read the current ${asset} allowance for Permit2; please try again.`,
7818
- {
7819
- token,
7820
- chainId,
7821
- reason: "ALLOWANCE_UNREADABLE",
7822
- cause: err instanceof Error ? err.message : String(err)
7823
- }
7824
- );
7680
+ const hash = await wallet.writeContract({
7681
+ address: token,
7682
+ abi: ERC20_ALLOWANCE_ABI,
7683
+ functionName: "approve",
7684
+ args: [PERMIT2_ADDRESS, MAX_UINT256],
7685
+ account: state.walletAddress,
7686
+ chain: VIEM_CHAIN2[chainId]
7825
7687
  });
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
- }
7688
+ const receipt = await publicClient.waitForTransactionReceipt({
7689
+ hash,
7690
+ confirmations: 1
7849
7691
  });
7692
+ if (receipt.status !== "success") {
7693
+ throw new Error(`Permit2 approval reverted (tx ${hash})`);
7694
+ }
7695
+ return hash;
7850
7696
  }
7851
7697
  // --- Discovery (no wallet required) ---
7852
7698
  /**