@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.js CHANGED
@@ -170,7 +170,7 @@ var P_SUPPORTED_CHAINS = {
170
170
  chainIds: [8453, 42161, 1],
171
171
  chains: ["BASE", "ARBITRUM", "ETHEREUM"]
172
172
  };
173
- var SUPPORTED_TOKENS = ["USDC", "WETH", "EURC", "USDT"];
173
+ var SUPPORTED_TOKENS = ["USDC", "WETH"];
174
174
  var SUPPORTED_CHAIN_IDS = P_SUPPORTED_CHAINS.chainIds;
175
175
  var SUPPORTED_CHAINS = P_SUPPORTED_CHAINS.chains;
176
176
  var SupportedAssets = [
@@ -209,31 +209,8 @@ var SupportedAssets = [
209
209
  symbol: "WETH",
210
210
  chainId: 1,
211
211
  decimals: 18
212
- },
213
- {
214
- address: `0x1aBaEA1f7C830bD89Acc67eC4af516284b1bC33c`,
215
- symbol: "EURC",
216
- chainId: 1,
217
- decimals: 6
218
- },
219
- {
220
- address: `0x60a3E35Cc302bFA44Cb288Bc5a4F316Fdb1adb42`,
221
- symbol: "EURC",
222
- chainId: 8453,
223
- decimals: 6
224
- },
225
- {
226
- address: `0xdAC17F958D2ee523a2206206994597C13D831ec7`,
227
- symbol: "USDT",
228
- chainId: 1,
229
- decimals: 6
230
212
  }
231
213
  ];
232
- function tokenAddress(symbol, chainId) {
233
- return SupportedAssets.find(
234
- (a) => a.symbol === symbol && a.chainId === chainId
235
- )?.address;
236
- }
237
214
 
238
215
  // src/lib/debug.ts
239
216
  var configuredDebug = false;
@@ -298,8 +275,6 @@ function matchesAsset(symbol, asset) {
298
275
  // src/agents/zyfai/zyfai.mapper.ts
299
276
  var DECIMALS_BY_SYMBOL = {
300
277
  usdc: 6,
301
- eurc: 6,
302
- usdt: 6,
303
278
  weth: 18,
304
279
  eth: 18,
305
280
  cbeth: 18,
@@ -496,7 +471,7 @@ function netApy(net, gross, field) {
496
471
  }
497
472
  function usdPerUnit(tokenSymbol, prices) {
498
473
  const symbol = tokenSymbol?.toUpperCase();
499
- if (symbol === "USDC" || symbol === "USDT") return 1;
474
+ if (symbol === "USDC") return 1;
500
475
  const price = symbol ? prices?.[symbol] : void 0;
501
476
  return typeof price === "number" && Number.isFinite(price) && price > 0 ? price : void 0;
502
477
  }
@@ -592,14 +567,16 @@ function splitOpportunity(opportunity) {
592
567
  }
593
568
  function mapEntries(rawEntries, chainId) {
594
569
  const actionMap = {
595
- "Top up wallet": "Top up",
570
+ // EOA -> smart wallet. Named "Top up" before ROUT-758; "Deposit" is what
571
+ // users call it.
572
+ "Top up wallet": "Deposit",
596
573
  "Partial withdraw from protocol": "Withdraw",
597
574
  "Withdraw from protocol": "Withdraw",
598
- // The agent's own leg of a top up: the funds the user sent moving into the
575
+ // The agent's own leg of a deposit: the funds the user sent moving into the
599
576
  // pool that earns the APY. Zyfai emits it as a separate entry seconds after
600
- // "Top up wallet" and for slightly less (gas). `Deposit` already exists in
601
- // the public HistoryAction union, so no consumer type change is needed.
602
- "Deposit to protocol": "Deposit",
577
+ // "Top up wallet" and for slightly less (gas). Smart wallet -> pool, so
578
+ // "Allocate" (ROUT-758; it was "Deposit").
579
+ "Deposit to protocol": "Allocate",
603
580
  // Withdrawing from an async vault (Superform) is logged under its own
604
581
  // label and paid out later in a separate batch (ROUT-624).
605
582
  "Request async withdrawal": "Withdraw",
@@ -901,7 +878,7 @@ var isJwtExpired = (token) => {
901
878
  }
902
879
  };
903
880
  var memorySessions = /* @__PURE__ */ new Map();
904
- var isFreshSession = (session) => !!session && typeof session.isPredeployed === "boolean" && !!session.token && !isJwtExpired(session.token);
881
+ var isFreshSession = (session) => typeof session === "object" && session !== null && typeof session.isPredeployed === "boolean" && !!session.token && !isJwtExpired(session.token);
905
882
  var readLegacySession = (store, address) => {
906
883
  if (!store) return null;
907
884
  const prefix = legacyKeyPrefix(address);
@@ -983,6 +960,17 @@ var clearSession = (address, _chainId) => {
983
960
  }
984
961
  readLegacySession(store, address);
985
962
  };
963
+ var BrowserSessionStore = class {
964
+ read(_agentId, address) {
965
+ return readSession(address, 0);
966
+ }
967
+ write(_agentId, address, session) {
968
+ writeSession(address, 0, session);
969
+ }
970
+ clear(_agentId, address) {
971
+ clearSession(address, 0);
972
+ }
973
+ };
986
974
 
987
975
  // src/agents/zyfai/autoSelect.ts
988
976
  function buildAutoSelectUpdate(current, asset, chainId) {
@@ -1195,7 +1183,6 @@ var CHAINLINK_ETH_USD_FEED = {
1195
1183
  42161: "0x639Fe6ab55C921f74e7fac1ee960C0B6293ba612",
1196
1184
  1: "0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419"
1197
1185
  };
1198
- var CHAINLINK_EUR_USD_FEED = "0xb49f677943BC038e9857d61E7d053CaA2C1734C1";
1199
1186
  var CHAINLINK_ABI = parseAbi([
1200
1187
  "function latestRoundData() view returns (uint80, int256, uint256, uint256, uint80)"
1201
1188
  ]);
@@ -1205,8 +1192,13 @@ var DEFAULT_ZYFAI_RPC_URLS = {
1205
1192
  42161: "https://arb-mainnet.g.alchemy.com/v2/ZWyVU-9XfS3z8Rn-xkq7V",
1206
1193
  1: "https://eth-mainnet.g.alchemy.com/v2/ZWyVU-9XfS3z8Rn-xkq7V"
1207
1194
  };
1195
+ var WETH_ADDRESS_BY_CHAIN = {
1196
+ 8453: "0x4200000000000000000000000000000000000006",
1197
+ 42161: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
1198
+ 1: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
1199
+ };
1208
1200
  var VIEM_CHAIN = { 8453: base, 42161: arbitrum, 1: mainnet };
1209
- var SPLITTING_ASSETS = SUPPORTED_TOKENS;
1201
+ var SPLITTING_ASSETS = ["USDC", "WETH"];
1210
1202
  var POOL_POLICY_CHAIN_IDS = [8453, 42161, 1];
1211
1203
  var EARNINGS_REFRESH_COOLDOWN_MS = 60 * 60 * 1e3;
1212
1204
  var ZyfaiAgent = class _ZyfaiAgent {
@@ -1218,8 +1210,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
1218
1210
  chain: "BASE",
1219
1211
  assets: [
1220
1212
  { symbol: "USDC", minDepositAmount: "1500000" },
1221
- { symbol: "WETH", minDepositAmount: "500000000000000" },
1222
- { symbol: "EURC", minDepositAmount: "1500000" }
1213
+ { symbol: "WETH", minDepositAmount: "500000000000000" }
1223
1214
  ]
1224
1215
  },
1225
1216
  {
@@ -1240,12 +1231,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
1240
1231
  // the shipped code enforces 0.005 WETH, so match it or deposits reject on-chain.
1241
1232
  assets: [
1242
1233
  { symbol: "USDC", minDepositAmount: "100000000" },
1243
- { symbol: "WETH", minDepositAmount: "5000000000000000" },
1244
- // ROUT-308: same floor as USDC (6 decimals). Zyfai's own
1245
- // MIN_PORTFOLIO_BALANCE says 10,000 here, but that is only enforced by
1246
- // its sendDeposit, which we don't use. Confirm with Zyfai before release.
1247
- { symbol: "EURC", minDepositAmount: "100000000" },
1248
- { symbol: "USDT", minDepositAmount: "100000000" }
1234
+ { symbol: "WETH", minDepositAmount: "5000000000000000" }
1249
1235
  ]
1250
1236
  }
1251
1237
  ];
@@ -1267,12 +1253,13 @@ var ZyfaiAgent = class _ZyfaiAgent {
1267
1253
  // RPC error retries on the next fetch.
1268
1254
  withdrawAmountCache = /* @__PURE__ */ new Map();
1269
1255
  ethUsd = null;
1270
- eurUsd = null;
1271
1256
  earningsReads = /* @__PURE__ */ new Map();
1272
1257
  earningsRefreshes = /* @__PURE__ */ new Map();
1273
1258
  earningsSnapshot = null;
1274
1259
  earningsGeneration = 0;
1275
- constructor(apiKey, rpcUrls, referralSource) {
1260
+ sessionStore;
1261
+ constructor(apiKey, rpcUrls, referralSource, sessionStore = new BrowserSessionStore()) {
1262
+ this.sessionStore = sessionStore;
1276
1263
  this.rpcUrls = rpcUrls ?? DEFAULT_ZYFAI_RPC_URLS;
1277
1264
  this.sdk = new ZyfaiSDK({
1278
1265
  apiKey,
@@ -1363,21 +1350,36 @@ var ZyfaiAgent = class _ZyfaiAgent {
1363
1350
  * (Zyfai dist line 1374). At that point `walletClient` + `currentChainId`
1364
1351
  * are populated, so the cache lookup has both keys it needs.
1365
1352
  *
1366
- * No-op on the server (no `window`) — the SDK is constructed during SSR
1367
- * for some apps and the patch only matters in the browser anyway.
1353
+ * The session lives in `sessionStore`: localStorage in the browser (a no-op
1354
+ * on the server), or whatever the host passed in `OwneySDKConfig`.
1355
+ */
1356
+ /**
1357
+ * The session store is a cache: an unavailable store must never block
1358
+ * authentication or teardown. Failures read as a cache miss.
1368
1359
  */
1360
+ async storeOp(op) {
1361
+ try {
1362
+ return await op();
1363
+ } catch (error) {
1364
+ console.warn(
1365
+ "owney-sdk: agent session store failed, continuing without it",
1366
+ error
1367
+ );
1368
+ return null;
1369
+ }
1370
+ }
1369
1371
  installAuthCache() {
1370
- if (typeof window === "undefined") return;
1371
1372
  const internals = this.sdk;
1372
1373
  const original = internals.authenticateUser.bind(internals);
1373
1374
  let inFlight = null;
1374
1375
  const authenticate = async () => {
1375
1376
  if (internals.authenticatedUserId !== null) return;
1376
1377
  const address = internals.walletClient?.account?.address;
1377
- const chainId = internals.currentChainId ?? 0;
1378
1378
  if (address) {
1379
- const cached = readSession(address, chainId);
1380
- if (cached) {
1379
+ const cached = await this.storeOp(
1380
+ () => this.sessionStore.read(this.id, address)
1381
+ );
1382
+ if (isFreshSession(cached)) {
1381
1383
  internals.httpClient.setAuthToken(cached.token);
1382
1384
  internals.authenticatedUserId = cached.userId;
1383
1385
  internals.hasActiveSessionKey = cached.hasActiveSessionKey;
@@ -1387,15 +1389,16 @@ var ZyfaiAgent = class _ZyfaiAgent {
1387
1389
  }
1388
1390
  await original();
1389
1391
  const newAddress = internals.walletClient?.account?.address;
1390
- const newChainId = internals.currentChainId ?? 0;
1391
1392
  const newToken = internals.httpClient.authToken;
1392
1393
  if (newAddress && newToken) {
1393
- writeSession(newAddress, newChainId, {
1394
- token: newToken,
1395
- userId: internals.authenticatedUserId,
1396
- hasActiveSessionKey: internals.hasActiveSessionKey,
1397
- isPredeployed: internals.isPredeployed
1398
- });
1394
+ await this.storeOp(
1395
+ () => this.sessionStore.write(this.id, newAddress, {
1396
+ token: newToken,
1397
+ userId: internals.authenticatedUserId,
1398
+ hasActiveSessionKey: internals.hasActiveSessionKey,
1399
+ isPredeployed: internals.isPredeployed
1400
+ })
1401
+ );
1399
1402
  }
1400
1403
  };
1401
1404
  internals.authenticateUser = () => {
@@ -1461,7 +1464,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
1461
1464
  if (!message.toLowerCase().includes("unauthorized")) throw error;
1462
1465
  const internals = this.sdk;
1463
1466
  const address = internals.walletClient?.account?.address;
1464
- if (address) clearSession(address, chainId);
1467
+ if (address) {
1468
+ await this.storeOp(() => this.sessionStore.clear(this.id, address));
1469
+ }
1465
1470
  return await this.sdk.connectAccount(provider, chainId);
1466
1471
  }
1467
1472
  }
@@ -1489,15 +1494,15 @@ var ZyfaiAgent = class _ZyfaiAgent {
1489
1494
  * it diffs available-vs-enabled by protocol id and writes the full union
1490
1495
  * back, or does nothing when none are missing.
1491
1496
  *
1492
- * Non-fatal: a sync failure must never block activation. Assets that do not
1493
- * exist on `chainId` (no token address there) are skipped.
1497
+ * Non-fatal: a sync failure must never block activation. Only "USDC" / "WETH"
1498
+ * are modeled per-asset by the Zyfai profile API, so other assets are skipped.
1494
1499
  */
1495
- async ensureProtocolsSynced(chainId, asset, availableProtocols) {
1496
- if (!tokenAddress(asset, chainId)) return;
1500
+ async ensureProtocolsSynced(chainId, asset) {
1501
+ if (asset !== "USDC" && asset !== "WETH") return;
1497
1502
  try {
1498
1503
  const [current, { protocols: available }] = await Promise.all([
1499
1504
  this.sdk.getUserDetails(asset),
1500
- availableProtocols
1505
+ this.sdk.getAvailableProtocols(chainId)
1501
1506
  ]);
1502
1507
  debugLog("zyfai:protocol-sync", `${asset}: profile before sync`, {
1503
1508
  chains: current.chains,
@@ -1545,8 +1550,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
1545
1550
  this.earningsReads.clear();
1546
1551
  this.earningsRefreshes.clear();
1547
1552
  this.earningsSnapshot = null;
1548
- if (this.connectedAddress && this.connectedChainId !== null) {
1549
- clearSession(this.connectedAddress, this.connectedChainId);
1553
+ if (this.connectedAddress) {
1554
+ const address = this.connectedAddress;
1555
+ await this.storeOp(() => this.sessionStore.clear(this.id, address));
1550
1556
  }
1551
1557
  await this.sdk.disconnectAccount();
1552
1558
  this.connectedAddress = null;
@@ -1566,15 +1572,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
1566
1572
  ms: Date.now() - startedAt
1567
1573
  });
1568
1574
  const validChainId = isValidChainId(chainId);
1569
- const availableProtocols = Promise.resolve().then(
1570
- () => this.sdk.getAvailableProtocols(validChainId)
1571
- );
1572
- availableProtocols.catch(() => {
1573
- });
1574
1575
  await Promise.all([
1575
- ...SUPPORTED_TOKENS.map(
1576
- (asset) => this.ensureProtocolsSynced(validChainId, asset, availableProtocols)
1577
- ),
1576
+ this.ensureProtocolsSynced(validChainId, "USDC"),
1577
+ this.ensureProtocolsSynced(validChainId, "WETH"),
1578
1578
  // Retrofit a session key for old wallets that are already deployed and
1579
1579
  // funded but never got one — otherwise their balance stays idle until
1580
1580
  // they happen to deposit again. Only touches Safes that are missing the
@@ -1688,41 +1688,34 @@ var ZyfaiAgent = class _ZyfaiAgent {
1688
1688
  );
1689
1689
  const desiredAutoSelect = policy.autoApproveProtocols;
1690
1690
  for (const asset of SPLITTING_ASSETS) {
1691
- try {
1692
- const current = await this.sdk.getUserDetails(asset);
1693
- if (strategy === void 0 && (current.strategy === "conservative" || current.strategy === "aggressive")) {
1694
- strategy = current.strategy;
1695
- }
1696
- const needsUpdate = protocolsPolicyNeedsUpdate(
1697
- current,
1698
- desiredProtocols,
1699
- desiredAutoSelect
1700
- );
1701
- debugLog("zyfai:pools", `${asset}: comparing protocols`, {
1702
- current: {
1703
- protocols: current.protocols,
1704
- autoSelectProtocols: current.autoSelectProtocols
1705
- },
1706
- desired: {
1707
- protocols: desiredProtocols,
1708
- autoSelectProtocols: desiredAutoSelect
1709
- },
1710
- decision: needsUpdate ? "will write \u2014 profile differs from the org policy" : "skipping \u2014 profile already matches"
1711
- });
1712
- if (!needsUpdate) continue;
1713
- const update = {
1714
- asset,
1715
- autoSelectProtocols: desiredAutoSelect
1716
- };
1717
- if (desiredProtocols !== null) update.protocols = desiredProtocols;
1718
- await this.sdk.updateUserProfile(update);
1719
- debugLog("zyfai:pools", `${asset}: wrote protocols update`, update);
1720
- } catch (error) {
1721
- console.warn(
1722
- `[zyfai] applyPoolPolicy(${asset}) failed (non-fatal):`,
1723
- error instanceof Error ? error.message : String(error)
1724
- );
1691
+ const current = await this.sdk.getUserDetails(asset);
1692
+ if (strategy === void 0 && (current.strategy === "conservative" || current.strategy === "aggressive")) {
1693
+ strategy = current.strategy;
1725
1694
  }
1695
+ const needsUpdate = protocolsPolicyNeedsUpdate(
1696
+ current,
1697
+ desiredProtocols,
1698
+ desiredAutoSelect
1699
+ );
1700
+ debugLog("zyfai:pools", `${asset}: comparing protocols`, {
1701
+ current: {
1702
+ protocols: current.protocols,
1703
+ autoSelectProtocols: current.autoSelectProtocols
1704
+ },
1705
+ desired: {
1706
+ protocols: desiredProtocols,
1707
+ autoSelectProtocols: desiredAutoSelect
1708
+ },
1709
+ decision: needsUpdate ? "will write \u2014 profile differs from the org policy" : "skipping \u2014 profile already matches"
1710
+ });
1711
+ if (!needsUpdate) continue;
1712
+ const update = {
1713
+ asset,
1714
+ autoSelectProtocols: desiredAutoSelect
1715
+ };
1716
+ if (desiredProtocols !== null) update.protocols = desiredProtocols;
1717
+ await this.sdk.updateUserProfile(update);
1718
+ debugLog("zyfai:pools", `${asset}: wrote protocols update`, update);
1726
1719
  }
1727
1720
  const poolResults = await Promise.all(
1728
1721
  universe.map(async (protocol) => {
@@ -1848,7 +1841,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
1848
1841
  await Promise.all(
1849
1842
  selection.strategies.map(async ({ asset, strategy }) => {
1850
1843
  const current = await this.sdk.getUserDetails(asset);
1851
- const selectedProtocols = selection.selections.filter((entry) => entry.asset === asset && entry.pools.length > 0).map((entry) => entry.protocolId);
1844
+ const selectedProtocols = selection.selections.filter(
1845
+ (entry) => entry.asset === asset && entry.pools.length > 0
1846
+ ).map((entry) => entry.protocolId);
1852
1847
  const protocols = [
1853
1848
  .../* @__PURE__ */ new Set([...current.protocols ?? [], ...selectedProtocols])
1854
1849
  ];
@@ -2207,10 +2202,11 @@ var ZyfaiAgent = class _ZyfaiAgent {
2207
2202
  requestedStrategy: "aggressive",
2208
2203
  setupResult
2209
2204
  });
2210
- await this.syncAutoSelect(validChainId, asset);
2211
2205
  if (isOwneyDebug()) {
2212
2206
  try {
2213
- const profileAfterSetup = await this.sdk.getUserDetails(asset);
2207
+ const profileAfterSetup = await this.sdk.getUserDetails(
2208
+ asset === "WETH" ? "WETH" : "USDC"
2209
+ );
2214
2210
  debugLog("zyfai:first-deposit", "profile immediately after setup", {
2215
2211
  asset,
2216
2212
  strategy: profileAfterSetup.strategy,
@@ -2228,9 +2224,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
2228
2224
  validChainId
2229
2225
  );
2230
2226
  const txHash = await depositCallback(smartWallet, validChainId, amount);
2231
- const tokenAddress2 = asset === "USDC" ? void 0 : tokenAddress(asset, validChainId);
2227
+ const tokenAddress = asset === "WETH" ? WETH_ADDRESS_BY_CHAIN[validChainId] : void 0;
2232
2228
  try {
2233
- await (tokenAddress2 ? this.sdk.logDeposit(validChainId, txHash, amount, tokenAddress2) : this.sdk.logDeposit(validChainId, txHash, amount));
2229
+ await (tokenAddress ? this.sdk.logDeposit(validChainId, txHash, amount, tokenAddress) : this.sdk.logDeposit(validChainId, txHash, amount));
2234
2230
  } catch (logError) {
2235
2231
  console.warn(
2236
2232
  "[owney-sdk] Deposit landed on-chain but logDeposit failed (non-fatal):",
@@ -2336,22 +2332,13 @@ var ZyfaiAgent = class _ZyfaiAgent {
2336
2332
  }
2337
2333
  async getAccountApy(state, chainId, days, tokenSymbol, scopeChainId) {
2338
2334
  const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
2339
- const [raw, ethUsd, eurUsd] = await Promise.all([
2335
+ const [raw, ethUsd] = await Promise.all([
2340
2336
  this.sdk.getDailyApyHistory(smartWallet, days),
2341
- tokenSymbol ? void 0 : this.readEthUsd(validChainId),
2342
- tokenSymbol ? void 0 : this.readEurUsd()
2337
+ tokenSymbol ? void 0 : this.readEthUsd(validChainId)
2343
2338
  ]);
2344
2339
  const scope = scopeChainId === null ? void 0 : scopeChainId ?? chainId;
2345
- const usdPrices = {
2346
- ...ethUsd ? { WETH: ethUsd, ETH: ethUsd } : {},
2347
- ...eurUsd ? { EURC: eurUsd } : {}
2348
- };
2349
- return mapApyHistory(
2350
- raw,
2351
- scope,
2352
- tokenSymbol,
2353
- Object.keys(usdPrices).length ? usdPrices : void 0
2354
- );
2340
+ const usdPrices = ethUsd ? { WETH: ethUsd, ETH: ethUsd } : void 0;
2341
+ return mapApyHistory(raw, scope, tokenSymbol, usdPrices);
2355
2342
  }
2356
2343
  /**
2357
2344
  * Today's ETH/USD from Chainlink, cached for a minute. Every day of the
@@ -2359,38 +2346,24 @@ var ZyfaiAgent = class _ZyfaiAgent {
2359
2346
  * move over the window is not reflected (ROUT-682). Undefined on failure,
2360
2347
  * which leaves the series on token-amount weighting rather than failing it.
2361
2348
  */
2362
- readEthUsd(chainId) {
2363
- return this.readChainlinkUsd(
2364
- chainId,
2365
- CHAINLINK_ETH_USD_FEED[chainId],
2366
- "ethUsd"
2367
- );
2368
- }
2369
- /** Today's EUR/USD from Chainlink on Ethereum, for pricing EURC (ROUT-308). */
2370
- readEurUsd() {
2371
- return this.readChainlinkUsd(1, CHAINLINK_EUR_USD_FEED, "eurUsd");
2372
- }
2373
- async readChainlinkUsd(chainId, feed, cache) {
2374
- const cached = this[cache];
2375
- if (cached && Date.now() - cached.at < ETH_USD_TTL_MS) {
2376
- return cached.price;
2349
+ async readEthUsd(chainId) {
2350
+ if (this.ethUsd && Date.now() - this.ethUsd.at < ETH_USD_TTL_MS) {
2351
+ return this.ethUsd.price;
2377
2352
  }
2378
2353
  try {
2379
2354
  const [, answer] = await this.getPublicClient(chainId).readContract({
2380
- address: feed,
2355
+ address: CHAINLINK_ETH_USD_FEED[chainId],
2381
2356
  abi: CHAINLINK_ABI,
2382
2357
  functionName: "latestRoundData"
2383
2358
  });
2384
2359
  const price = Number(answer) / 1e8;
2385
2360
  if (!Number.isFinite(price) || price <= 0) return void 0;
2386
- this[cache] = { price, at: Date.now() };
2361
+ this.ethUsd = { price, at: Date.now() };
2387
2362
  return price;
2388
2363
  } catch (err) {
2389
- debugLog(
2390
- "zyfai:apy",
2391
- `${cache === "ethUsd" ? "ETH/USD" : "EUR/USD"} read failed; token-amount weighting`,
2392
- { err }
2393
- );
2364
+ debugLog("zyfai:apy", "ETH/USD read failed; token-amount weighting", {
2365
+ err
2366
+ });
2394
2367
  return void 0;
2395
2368
  }
2396
2369
  }
@@ -2421,7 +2394,6 @@ var ZyfaiAgent = class _ZyfaiAgent {
2421
2394
  return "eth";
2422
2395
  case "EURC":
2423
2396
  return "eurc";
2424
- // Zyfai has no "usdt" history filter, so USDT is filtered client-side.
2425
2397
  default:
2426
2398
  return void 0;
2427
2399
  }
@@ -2430,9 +2402,6 @@ var ZyfaiAgent = class _ZyfaiAgent {
2430
2402
  const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
2431
2403
  const limit = options?.limit ?? 10;
2432
2404
  const assetType = _ZyfaiAgent.toZyfaiAssetType(options?.tokenSymbol);
2433
- const clientSideAsset = !assetType && options?.tokenSymbol && SUPPORTED_TOKENS.includes(
2434
- options.tokenSymbol.toUpperCase()
2435
- ) ? options.tokenSymbol : void 0;
2436
2405
  const cursor = options?.cursor ? decodeHistoryCursor(options.cursor) : null;
2437
2406
  const toDate = cursor?.toDate ?? options?.toDate ?? (/* @__PURE__ */ new Date()).toISOString();
2438
2407
  let offset = cursor?.rawOffset ?? 0;
@@ -2454,12 +2423,6 @@ var ZyfaiAgent = class _ZyfaiAgent {
2454
2423
  assetType
2455
2424
  });
2456
2425
  raw.data.forEach((entry, idx) => {
2457
- if (clientSideAsset && !matchesAsset(
2458
- entry.positions?.[0]?.token_symbol ?? "",
2459
- clientSideAsset
2460
- )) {
2461
- return;
2462
- }
2463
2426
  if (entry.chainId === validChainId) {
2464
2427
  matched.push({ entry, rawIdx: offset + idx });
2465
2428
  }
@@ -2502,20 +2465,6 @@ var ZyfaiAgent = class _ZyfaiAgent {
2502
2465
  }
2503
2466
  async ensureAutoSelectProtocols(state, chainId, asset) {
2504
2467
  await this.connectAuth(state, chainId);
2505
- return this.syncAutoSelect(chainId, asset);
2506
- }
2507
- /**
2508
- * Zyfai's first-deposit setup keys off the USDC profile alone: once USDC is
2509
- * configured it reports `{ applied: false }` for every asset, so an existing
2510
- * user's first EURC/USDT keeps a chainless profile and the deposit sits as
2511
- * an idle stale balance (ROUT-308). Configured USDC is what marks such a
2512
- * user; a brand-new one is still left to first-deposit setup.
2513
- */
2514
- async isExistingZyfaiUser() {
2515
- const usdc = await this.sdk.getUserDetails("USDC");
2516
- return (usdc.chains?.length ?? 0) > 0 && (usdc.protocols?.length ?? 0) > 0;
2517
- }
2518
- async syncAutoSelect(chainId, asset) {
2519
2468
  const current = await this.sdk.getUserDetails(asset);
2520
2469
  debugLog("zyfai:auto-select", `${asset}: profile before check`, {
2521
2470
  autoSelectProtocols: current.autoSelectProtocols,
@@ -2523,7 +2472,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
2523
2472
  protocols: current.protocols,
2524
2473
  strategy: current.strategy
2525
2474
  });
2526
- if ((current.chains?.length ?? 0) === 0 && (asset === "USDC" || !await this.isExistingZyfaiUser())) {
2475
+ if ((current.chains?.length ?? 0) === 0) {
2527
2476
  debugLog(
2528
2477
  "zyfai:auto-select",
2529
2478
  `${asset}: skipping untouched profile until first deposit`
@@ -3418,20 +3367,6 @@ async function readErc20Balance(publicClient, token, owner) {
3418
3367
  });
3419
3368
  }
3420
3369
 
3421
- // src/lib/erc20-approve.ts
3422
- var ZERO_RESET_TOKENS = /* @__PURE__ */ new Set([
3423
- "0xdac17f958d2ee523a2206206994597c13d831ec7"
3424
- ]);
3425
- function needsAllowanceReset(token) {
3426
- return ZERO_RESET_TOKENS.has(token.toLowerCase());
3427
- }
3428
- async function approveWithResetIfNeeded(input) {
3429
- if (input.currentAllowance > 0n && needsAllowanceReset(input.token)) {
3430
- await input.approve(input.spender, 0n);
3431
- }
3432
- return input.approve(input.spender, input.amount);
3433
- }
3434
-
3435
3370
  // src/lib/swap/swap.secrets.ts
3436
3371
  import { keccak256, toHex } from "viem";
3437
3372
  var SECRET_BYTES = 32;
@@ -3790,15 +3725,6 @@ async function executeSwap(deps, options) {
3790
3725
  }
3791
3726
  return { received: arrived.toString(), ...result ?? {} };
3792
3727
  }
3793
- function approveMax(deps, token, current, spender) {
3794
- return approveWithResetIfNeeded({
3795
- token,
3796
- currentAllowance: current,
3797
- spender,
3798
- amount: MAX_UINT256,
3799
- approve: deps.approve
3800
- });
3801
- }
3802
3728
  async function runClassic(deps, options) {
3803
3729
  const {
3804
3730
  quote,
@@ -3835,7 +3761,7 @@ async function runClassic(deps, options) {
3835
3761
  if (current < needed) {
3836
3762
  onStage?.("approving");
3837
3763
  await deps.ensureChain(quote.src.chainId);
3838
- await approveMax(deps, quote.src.address, current, tx.to);
3764
+ await deps.approve(tx.to, MAX_UINT256);
3839
3765
  debugLog(
3840
3766
  "owney-sdk",
3841
3767
  "swap: re-fetching classic calldata after approval"
@@ -3924,7 +3850,7 @@ async function authoriseSpend(deps, options, amount, isNativeSource) {
3924
3850
  });
3925
3851
  return permit;
3926
3852
  }
3927
- await approveMax(deps, quote.src.address, current, quote.spender);
3853
+ await deps.approve(quote.spender, MAX_UINT256);
3928
3854
  debugLog("owney-sdk", "swap: approved limit order protocol");
3929
3855
  return void 0;
3930
3856
  }
@@ -4749,7 +4675,6 @@ function makeSponsoredDepositCallback(deps) {
4749
4675
  // src/lib/walletconnect-switch.ts
4750
4676
  var WALLET_SWITCH_TIMEOUT_MS = 12e4;
4751
4677
  var HOLD_CHAIN_MS = 15e3;
4752
- var MAX_RESENDS = 2;
4753
4678
  var holds = /* @__PURE__ */ new Map();
4754
4679
  function parseChainId(raw) {
4755
4680
  if (typeof raw === "number") return raw;
@@ -4758,28 +4683,76 @@ function parseChainId(raw) {
4758
4683
  const id = ref.startsWith("0x") ? Number.parseInt(ref, 16) : Number(ref);
4759
4684
  return Number.isFinite(id) ? id : void 0;
4760
4685
  }
4761
- function walletConnectCore(provider) {
4686
+ function walletConnectSession(provider) {
4762
4687
  const p = provider;
4763
4688
  const core = p?.signer ?? p;
4764
- if (typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
4689
+ if (typeof core?.request !== "function" || typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
4765
4690
  return null;
4766
4691
  }
4767
4692
  const peer = core.session.peer?.metadata?.name ?? "";
4768
- if (!/metamask/i.test(peer)) return null;
4769
- return core;
4693
+ if (/metamask/i.test(peer)) {
4694
+ return { core, strategy: "remote-wallet" };
4695
+ }
4696
+ if (/fireblocks/i.test(peer)) {
4697
+ return { core, strategy: "session-default" };
4698
+ }
4699
+ return null;
4700
+ }
4701
+ function approvedChains(core) {
4702
+ const approved = /* @__PURE__ */ new Set();
4703
+ for (const namespace of Object.values(core.session.namespaces ?? {})) {
4704
+ for (const chain of namespace.chains ?? []) approved.add(chain);
4705
+ for (const account of namespace.accounts ?? []) {
4706
+ const [namespaceName, reference] = account.split(":");
4707
+ if (namespaceName && reference) {
4708
+ approved.add(`${namespaceName}:${reference}`);
4709
+ }
4710
+ }
4711
+ }
4712
+ return approved;
4713
+ }
4714
+ async function selectSessionDefaultChain(core, chainId) {
4715
+ const target = `eip155:${chainId}`;
4716
+ if (!approvedChains(core).has(target)) {
4717
+ throw new Error(
4718
+ `The WalletConnect session has not approved ${target}. Reconnect the wallet and try again.`
4719
+ );
4720
+ }
4721
+ core.setDefaultChain(target);
4722
+ const selected = parseChainId(
4723
+ await core.request({ method: "eth_chainId" })
4724
+ );
4725
+ debugLog("wc-switch", "selected WalletConnect session default", {
4726
+ peer: core.session.peer?.metadata?.name,
4727
+ target: chainId,
4728
+ selected
4729
+ });
4730
+ if (selected !== chainId) {
4731
+ throw new Error(
4732
+ `WalletConnect stayed on chain ${selected ?? "unknown"}; expected ${chainId}.`
4733
+ );
4734
+ }
4770
4735
  }
4771
4736
  async function switchWalletConnectChain(provider, chainId, timeoutMs = WALLET_SWITCH_TIMEOUT_MS) {
4772
- const core = walletConnectCore(provider);
4773
- if (!core) return false;
4737
+ const session = walletConnectSession(provider);
4738
+ if (!session) return false;
4739
+ const { core, strategy } = session;
4774
4740
  holds.get(core.session.topic)?.();
4741
+ if (strategy === "session-default") {
4742
+ await selectSessionDefaultChain(core, chainId);
4743
+ return true;
4744
+ }
4775
4745
  await requestSwitch(core, provider, chainId, timeoutMs);
4776
- holdChain(core, provider, chainId);
4746
+ holdChain(core, chainId);
4777
4747
  return true;
4778
4748
  }
4779
4749
  async function requestSwitch(core, provider, chainId, timeoutMs) {
4780
- const current = Number(
4750
+ const current = parseChainId(
4781
4751
  await provider.request({ method: "eth_chainId" })
4782
4752
  );
4753
+ if (current === void 0) {
4754
+ throw new Error("WalletConnect could not report its current chain.");
4755
+ }
4783
4756
  const hexChainId = `0x${chainId.toString(16)}`;
4784
4757
  let timer;
4785
4758
  try {
@@ -4809,26 +4782,27 @@ async function requestSwitch(core, provider, chainId, timeoutMs) {
4809
4782
  } catch {
4810
4783
  }
4811
4784
  }
4812
- function holdChain(core, provider, chainId) {
4785
+ function holdChain(core, chainId) {
4813
4786
  if (typeof core.on !== "function" || typeof core.removeListener !== "function") {
4814
4787
  return;
4815
4788
  }
4816
- let resends = 0;
4789
+ let repins = 0;
4817
4790
  const listener = (raw) => {
4818
4791
  const reported = parseChainId(raw);
4819
4792
  debugLog("wc-switch", "wallet reported chain", {
4820
4793
  reported,
4821
4794
  holding: chainId,
4822
- resends
4795
+ repins
4823
4796
  });
4824
4797
  if (reported === void 0 || reported === chainId) return;
4825
- if (resends >= MAX_RESENDS) return;
4826
- resends += 1;
4827
- void requestSwitch(core, provider, chainId, WALLET_SWITCH_TIMEOUT_MS).catch(
4828
- (error) => debugLog("wc-switch", "re-switch failed", {
4798
+ repins += 1;
4799
+ try {
4800
+ core.setDefaultChain(`eip155:${chainId}`);
4801
+ } catch (error) {
4802
+ debugLog("wc-switch", "session re-pin failed", {
4829
4803
  error: error instanceof Error ? error.message : String(error)
4830
- })
4831
- );
4804
+ });
4805
+ }
4832
4806
  };
4833
4807
  const release = () => {
4834
4808
  clearTimeout(timer);
@@ -4842,7 +4816,7 @@ function holdChain(core, provider, chainId) {
4842
4816
  holds.set(core.session.topic, release);
4843
4817
  }
4844
4818
  function withWalletConnectSwitch(provider) {
4845
- if (!walletConnectCore(provider)) return provider;
4819
+ if (!walletConnectSession(provider)) return provider;
4846
4820
  const target = provider;
4847
4821
  const request2 = async (args) => {
4848
4822
  if (args?.method !== "wallet_switchEthereumChain") {
@@ -4874,7 +4848,7 @@ function makeSponsoredWethCallback(deps) {
4874
4848
  if (!token) {
4875
4849
  throw new OwneyError(
4876
4850
  "CHAIN_UNSUPPORTED",
4877
- `No sponsored ${deps.assetSymbol} configured for chain ${chainId}`
4851
+ `No sponsored WETH configured for chain ${chainId}`
4878
4852
  );
4879
4853
  }
4880
4854
  const amountWei = BigInt(amount);
@@ -4887,14 +4861,14 @@ function makeSponsoredWethCallback(deps) {
4887
4861
  if (balance < amountWei) {
4888
4862
  throw new OwneyError(
4889
4863
  "DEPOSIT_INSUFFICIENT_BALANCE",
4890
- `Insufficient ${deps.assetSymbol} balance for this deposit.`,
4864
+ "Insufficient WETH balance for this deposit.",
4891
4865
  { token, chainId: cid, balance: balance.toString(), amount }
4892
4866
  );
4893
4867
  }
4894
4868
  } catch (err) {
4895
4869
  if (err instanceof OwneyError) throw err;
4896
4870
  console.warn(
4897
- `[owney-sdk] ${deps.assetSymbol} balance pre-check failed (non-fatal):`,
4871
+ "[owney-sdk] WETH balance pre-check failed (non-fatal):",
4898
4872
  err instanceof Error ? err.message : String(err)
4899
4873
  );
4900
4874
  }
@@ -4906,7 +4880,7 @@ function makeSponsoredWethCallback(deps) {
4906
4880
  if (allowance < amountWei) {
4907
4881
  throw new OwneyError(
4908
4882
  "PERMIT2_APPROVAL_REQUIRED",
4909
- `${deps.assetSymbol} gasless deposits need a one-time Permit2 approval; call approvePermit2() first`,
4883
+ "WETH gasless deposits need a one-time Permit2 approval; call approvePermit2() first",
4910
4884
  { token, chainId: cid, allowance: allowance.toString(), amount }
4911
4885
  );
4912
4886
  }
@@ -5093,22 +5067,8 @@ var SPONSORED_WETH_BY_CHAIN = {
5093
5067
  42161: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
5094
5068
  1: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
5095
5069
  };
5096
- function sponsoredTokenMap(asset) {
5097
- if (asset === "USDC") return SPONSORED_USDC_BY_CHAIN;
5098
- if (asset === "WETH") return SPONSORED_WETH_BY_CHAIN;
5099
- return Object.fromEntries(
5100
- SUPPORTED_CHAIN_IDS.flatMap((id) => {
5101
- const a = tokenAddress(asset, id);
5102
- return a ? [[id, a]] : [];
5103
- })
5104
- );
5105
- }
5106
- var PERMIT2_ASSETS = /* @__PURE__ */ new Set(["WETH", "USDT"]);
5107
- function isPermit2Asset(asset) {
5108
- return PERMIT2_ASSETS.has(asset);
5109
- }
5110
5070
  function shouldFallbackToUserPaid(error, asset, appCallback) {
5111
- return SUPPORTED_TOKENS.includes(asset) && appCallback === void 0 && error instanceof OwneyError && error.code === "SPONSOR_REQUEST_FAILED" && error.details?.safeToFallback === true;
5071
+ return (asset === "WETH" || asset === "USDC") && appCallback === void 0 && error instanceof OwneyError && error.code === "SPONSOR_REQUEST_FAILED" && error.details?.safeToFallback === true;
5112
5072
  }
5113
5073
  var OwneySDK = class {
5114
5074
  agents = /* @__PURE__ */ new Map();
@@ -5131,8 +5091,9 @@ var OwneySDK = class {
5131
5091
  userPoolCustomization = false;
5132
5092
  routingApiBaseUrl;
5133
5093
  referralSource;
5134
- cachedSponsoredCallbacks = /* @__PURE__ */ new Map();
5135
- cachedPermit2SponsoredCallbacks = /* @__PURE__ */ new Map();
5094
+ sessionStore;
5095
+ cachedSponsoredCallback = null;
5096
+ cachedWethSponsoredCallback = null;
5136
5097
  paymasterServiceUrl;
5137
5098
  cachedSponsoredCallsCallbacks = /* @__PURE__ */ new Map();
5138
5099
  agentReads = new AgentReads();
@@ -5154,6 +5115,7 @@ var OwneySDK = class {
5154
5115
  this.routingApiBaseUrl = config.routingApiBaseUrl;
5155
5116
  this.paymasterServiceUrl = config.paymasterServiceUrl;
5156
5117
  this.referralSource = config.referralSource;
5118
+ this.sessionStore = config.sessionStore;
5157
5119
  this.userPoolCustomization = config.userPoolCustomization ?? false;
5158
5120
  }
5159
5121
  /**
@@ -5180,8 +5142,8 @@ var OwneySDK = class {
5180
5142
  walletAddress,
5181
5143
  chainId: null
5182
5144
  };
5183
- this.cachedSponsoredCallbacks.clear();
5184
- this.cachedPermit2SponsoredCallbacks.clear();
5145
+ this.cachedSponsoredCallback = null;
5146
+ this.cachedWethSponsoredCallback = null;
5185
5147
  this.cachedSponsoredCallsCallbacks.clear();
5186
5148
  }
5187
5149
  /**
@@ -5197,8 +5159,8 @@ var OwneySDK = class {
5197
5159
  this.agentReads.clearInFlight();
5198
5160
  this.activationChecks.clear();
5199
5161
  this.state = null;
5200
- this.cachedSponsoredCallbacks.clear();
5201
- this.cachedPermit2SponsoredCallbacks.clear();
5162
+ this.cachedSponsoredCallback = null;
5163
+ this.cachedWethSponsoredCallback = null;
5202
5164
  this.cachedSponsoredCallsCallbacks.clear();
5203
5165
  }
5204
5166
  isAgentDisabled(agentId) {
@@ -5248,9 +5210,9 @@ var OwneySDK = class {
5248
5210
  * provider with viem `custom(provider)` to read token meta and sign the
5249
5211
  * `TransferWithAuthorization`, then POSTs to the sponsor API.
5250
5212
  */
5251
- getDefaultSponsoredCallback(asset, onApproved) {
5252
- const cached = this.cachedSponsoredCallbacks.get(asset);
5253
- if (!onApproved && cached) return cached;
5213
+ getDefaultSponsoredCallback(onApproved) {
5214
+ if (!onApproved && this.cachedSponsoredCallback)
5215
+ return this.cachedSponsoredCallback;
5254
5216
  const provider = this.requireConnectedProvider();
5255
5217
  const owner = this.state.walletAddress;
5256
5218
  const callback = makeSponsoredDepositCallback({
@@ -5258,7 +5220,7 @@ var OwneySDK = class {
5258
5220
  baseUrl: this.routingApiBaseUrl,
5259
5221
  ownerAddress: owner,
5260
5222
  onApproved,
5261
- tokenAddressByChain: sponsoredTokenMap(asset),
5223
+ tokenAddressByChain: SPONSORED_USDC_BY_CHAIN,
5262
5224
  // Casts work around viem's chain-narrowed Client vs the generic
5263
5225
  // PublicClient/WalletClient param types — structurally identical at
5264
5226
  // runtime, but the two share a name TS treats as unrelated.
@@ -5275,13 +5237,14 @@ var OwneySDK = class {
5275
5237
  transport: custom(provider)
5276
5238
  })
5277
5239
  });
5278
- if (!onApproved) this.cachedSponsoredCallbacks.set(asset, callback);
5240
+ if (!onApproved) this.cachedSponsoredCallback = callback;
5279
5241
  return callback;
5280
5242
  }
5281
5243
  /**
5282
- * Lazily builds (and caches, per asset) the default paymaster-sponsored
5283
- * deposit callback used when the caller omits `depositCallback` and a
5284
- * `paymasterServiceUrl` is configured. One rail serves every asset.
5244
+ * Lazily builds (and caches) the default Permit2 sponsored WETH deposit
5245
+ * callback used when the caller omits `depositCallback` for a WETH
5246
+ * deposit. Mirrors `getDefaultSponsoredCallback()` but signs a Permit2
5247
+ * `PermitTransferFrom` instead of an EIP-3009 authorization.
5285
5248
  */
5286
5249
  getDefaultSponsoredCallsCallback(asset, onApproved) {
5287
5250
  const cached = this.cachedSponsoredCallsCallbacks.get(asset);
@@ -5292,20 +5255,20 @@ var OwneySDK = class {
5292
5255
  ownerAddress: this.state.walletAddress,
5293
5256
  paymasterServiceUrl: this.paymasterServiceUrl,
5294
5257
  onApproved,
5295
- tokenAddressByChain: sponsoredTokenMap(asset)
5258
+ tokenAddressByChain: asset === "WETH" ? SPONSORED_WETH_BY_CHAIN : SPONSORED_USDC_BY_CHAIN
5296
5259
  });
5297
5260
  if (!onApproved) this.cachedSponsoredCallsCallbacks.set(asset, callback);
5298
5261
  return callback;
5299
5262
  }
5300
5263
  /**
5301
- * Lazily builds (and caches, per asset) the default Permit2 sponsored
5302
- * deposit callback used when the caller omits `depositCallback` for a
5303
- * Permit2 asset (WETH, USDT). Mirrors `getDefaultSponsoredCallback()` but
5304
- * signs a Permit2 `PermitTransferFrom` instead of an EIP-3009 authorization.
5264
+ * Lazily builds (and caches) the default Permit2 sponsored WETH deposit
5265
+ * callback used when the caller omits `depositCallback` for a WETH deposit.
5266
+ * Mirrors `getDefaultSponsoredCallback()` but signs a Permit2
5267
+ * `PermitTransferFrom` instead of an EIP-3009 authorization.
5305
5268
  */
5306
- getDefaultPermit2SponsoredCallback(asset, onApproved) {
5307
- const cached = this.cachedPermit2SponsoredCallbacks.get(asset);
5308
- if (!onApproved && cached) return cached;
5269
+ getDefaultWethSponsoredCallback(onApproved) {
5270
+ if (!onApproved && this.cachedWethSponsoredCallback)
5271
+ return this.cachedWethSponsoredCallback;
5309
5272
  const provider = this.requireConnectedProvider();
5310
5273
  const owner = this.state.walletAddress;
5311
5274
  const callback = makeSponsoredWethCallback({
@@ -5313,8 +5276,7 @@ var OwneySDK = class {
5313
5276
  baseUrl: this.routingApiBaseUrl,
5314
5277
  ownerAddress: owner,
5315
5278
  onApproved,
5316
- tokenAddressByChain: sponsoredTokenMap(asset),
5317
- assetSymbol: asset,
5279
+ tokenAddressByChain: SPONSORED_WETH_BY_CHAIN,
5318
5280
  // Casts work around viem's chain-narrowed Client vs the generic
5319
5281
  // PublicClient/WalletClient param types — structurally identical at
5320
5282
  // runtime, but the two share a name TS treats as unrelated.
@@ -5331,7 +5293,7 @@ var OwneySDK = class {
5331
5293
  transport: custom(provider)
5332
5294
  })
5333
5295
  });
5334
- if (!onApproved) this.cachedPermit2SponsoredCallbacks.set(asset, callback);
5296
+ if (!onApproved) this.cachedWethSponsoredCallback = callback;
5335
5297
  return callback;
5336
5298
  }
5337
5299
  getAgent(agentId) {
@@ -5427,7 +5389,12 @@ var OwneySDK = class {
5427
5389
  }
5428
5390
  createAgent(agentId, key2) {
5429
5391
  if (agentId === "zyfai") {
5430
- return new ZyfaiAgent(key2, this.zyfaiRpcUrls, this.referralSource);
5392
+ return new ZyfaiAgent(
5393
+ key2,
5394
+ this.zyfaiRpcUrls,
5395
+ this.referralSource,
5396
+ this.sessionStore
5397
+ );
5431
5398
  }
5432
5399
  return null;
5433
5400
  }
@@ -5589,8 +5556,7 @@ var OwneySDK = class {
5589
5556
  }
5590
5557
  const state = this.requireState();
5591
5558
  const chainId = options.chainId ?? this.requireChainId();
5592
- const sponsoredAsset = asset;
5593
- const effectiveCallback = depositCallback ?? (this.paymasterServiceUrl ? this.getDefaultSponsoredCallsCallback(sponsoredAsset, onApproved) : isPermit2Asset(sponsoredAsset) ? this.getDefaultPermit2SponsoredCallback(sponsoredAsset, onApproved) : this.getDefaultSponsoredCallback(sponsoredAsset, onApproved));
5559
+ const effectiveCallback = depositCallback ?? (this.paymasterServiceUrl ? this.getDefaultSponsoredCallsCallback(asset, onApproved) : asset === "WETH" ? this.getDefaultWethSponsoredCallback(onApproved) : this.getDefaultSponsoredCallback(onApproved));
5594
5560
  if (agentId) {
5595
5561
  if (this.isAgentDisabled(agentId)) {
5596
5562
  throw new OwneyError(
@@ -5704,16 +5670,15 @@ var OwneySDK = class {
5704
5670
  *
5705
5671
  * 1. Missing Permit2 allowance: when the app did not supply its own
5706
5672
  * callback and the attempt fails with `PERMIT2_APPROVAL_REQUIRED` on a
5707
- * Permit2 asset (WETH, USDT), this is the wallet's first gasless deposit
5708
- * of that asset on this chain. We send the one-time (user-paid) Permit2
5709
- * approval via `approvePermit2(asset)` and retry the SAME sponsored
5710
- * attempt once. Bounded to one approval attempt per call so a
5711
- * wallet/agent that keeps reporting the allowance as missing can't loop
5712
- * forever. If `approvePermit2()` itself throws (e.g.
5673
+ * WETH deposit, this is the wallet's first gasless WETH deposit. We send
5674
+ * the one-time (user-paid) Permit2 approval via `approvePermit2()` and
5675
+ * retry the SAME sponsored attempt once. Bounded to one approval attempt
5676
+ * per call so a wallet/agent that keeps reporting the allowance as
5677
+ * missing can't loop forever. If `approvePermit2()` itself throws (e.g.
5713
5678
  * the user rejects the wallet prompt), that error propagates as-is —
5714
5679
  * the user said no to a transaction, so we must not turn around and ask
5715
5680
  * them to pay for a different one via the fallback below.
5716
- * 2. `shouldFallbackToUserPaid`: the SDK's own sponsor path failed at
5681
+ * 2. `shouldFallbackToUserPaid`: the SDK's own WETH sponsor path failed at
5717
5682
  * the infrastructure layer in a provably safe-to-retry way, so we warn
5718
5683
  * and retry once with `undefined`, falling through to a user-paid
5719
5684
  * native deposit. This still applies after a successful Permit2
@@ -5742,12 +5707,12 @@ var OwneySDK = class {
5742
5707
  try {
5743
5708
  return await attempt(effectiveCallback);
5744
5709
  } catch (error) {
5745
- if (!approvalAttempted && appCallback === void 0 && isPermit2Asset(asset) && error instanceof OwneyError && error.code === "PERMIT2_APPROVAL_REQUIRED") {
5710
+ if (!approvalAttempted && appCallback === void 0 && asset === "WETH" && error instanceof OwneyError && error.code === "PERMIT2_APPROVAL_REQUIRED") {
5746
5711
  approvalAttempted = true;
5747
5712
  console.warn(
5748
- `[owney-sdk] First ${asset} deposit: sending one-time Permit2 approval...`
5713
+ "[owney-sdk] First WETH deposit: sending one-time Permit2 approval..."
5749
5714
  );
5750
- await this.approvePermit2(asset);
5715
+ await this.approvePermit2();
5751
5716
  continue;
5752
5717
  }
5753
5718
  if (!shouldFallbackToUserPaid(error, asset, appCallback)) throw error;
@@ -6193,18 +6158,11 @@ var OwneySDK = class {
6193
6158
  account: state.walletAddress,
6194
6159
  chain: srcChain
6195
6160
  });
6196
- const receipt = await srcPublic.waitForTransactionReceipt({
6161
+ await srcPublic.waitForTransactionReceipt({
6197
6162
  hash,
6198
6163
  confirmations: 1,
6199
6164
  timeout: receiptTimeoutMs(quote.src.chainId)
6200
6165
  });
6201
- if (receipt.status !== "success") {
6202
- throw new OwneyError(
6203
- "SWAP_REQUEST_FAILED",
6204
- `Approval transaction reverted (tx ${hash})`,
6205
- { hash }
6206
- );
6207
- }
6208
6166
  return hash;
6209
6167
  },
6210
6168
  ensureChain: (chainId) => this.ensureSwapChain(chainId),
@@ -6294,33 +6252,30 @@ var OwneySDK = class {
6294
6252
  * figure directly. It is the entire arrival, so there is no slack: anything
6295
6253
  * that spends the target asset between the two fails the deposit outright.
6296
6254
  *
6297
- * Something does. A first deposit of a Permit2 asset (WETH, USDT) needs a
6298
- * one-time Permit2 approval, and that approval is a transaction. For WETH,
6299
- * a wallet holding no native gas token - the normal state of someone who
6300
- * just swapped everything INTO WETH - pays for it out of the WETH. The
6301
- * deposit then asked for ~2e12 wei more than was left and refused with
6302
- * DEPOSIT_INSUFFICIENT_BALANCE, under a wrapper saying the funds were safe
6303
- * but unadded (ROUT-242). For USDT the gas cannot come out of the token, so
6304
- * this step only adds the one-time approval and the read changes nothing.
6255
+ * Something does. A first WETH deposit needs a one-time Permit2 approval,
6256
+ * and that approval is a transaction. A wallet holding no native gas token -
6257
+ * the normal state of someone who just swapped everything INTO WETH - pays
6258
+ * for it out of the WETH. The deposit then asked for ~2e12 wei more than was
6259
+ * left and refused with DEPOSIT_INSUFFICIENT_BALANCE, under a wrapper saying
6260
+ * the funds were safe but unadded (ROUT-242).
6305
6261
  *
6306
6262
  * So the approval happens here, before the amount is settled, and the amount
6307
6263
  * comes from a read taken after it. Two things this deliberately is not:
6308
6264
  *
6309
6265
  * - It is not a balance sweep. `received` is a DELTA over the pre-swap
6310
- * balance, so a wallet already holding the asset reads far above it;
6311
- * depositing the balance would move funds the user never offered. The
6312
- * arrival is the ceiling and the balance is only ever allowed to lower it.
6313
- * - It does not touch USDC or EURC, which move on signed typed data
6314
- * (EIP-3009) and so spend nothing of the user's in between, nor a
6315
- * paymaster-configured client, where the sponsor covers the transfer and
6316
- * Permit2 never applies.
6266
+ * balance, so a wallet already holding WETH reads far above it; depositing
6267
+ * the balance would move funds the user never offered. The arrival is the
6268
+ * ceiling and the balance is only ever allowed to lower it.
6269
+ * - It does not touch USDC, which moves on signed typed data and so spends
6270
+ * nothing of the user's in between, nor a paymaster-configured client,
6271
+ * where the sponsor covers the transfer and Permit2 never applies.
6317
6272
  */
6318
6273
  async settleSwapDepositAmount(chainId, token, symbol, received) {
6319
- if (!isPermit2Asset(symbol) || this.paymasterServiceUrl) {
6274
+ if (symbol !== "WETH" || this.paymasterServiceUrl) {
6320
6275
  return received.toString();
6321
6276
  }
6322
6277
  const allowance = await this.readTokenPermit2Allowance(chainId, token);
6323
- if (allowance < received) await this.approvePermit2(symbol);
6278
+ if (allowance < received) await this.approvePermit2();
6324
6279
  const balance = await this.readTokenBalance(chainId, token);
6325
6280
  return (balance < received ? balance : received).toString();
6326
6281
  }
@@ -6485,10 +6440,7 @@ var OwneySDK = class {
6485
6440
  );
6486
6441
  }
6487
6442
  await this.ensureSwapChain(entry.chainId);
6488
- const supported = SUPPORTED_TOKENS.includes(
6489
- entry.symbol
6490
- );
6491
- const token = supported ? sponsoredTokenMap(entry.symbol)[entry.chainId] : void 0;
6443
+ const token = entry.symbol === "WETH" ? SPONSORED_WETH_BY_CHAIN[entry.chainId] : void 0;
6492
6444
  const amount = token ? await this.settleSwapDepositAmount(
6493
6445
  entry.chainId,
6494
6446
  token,
@@ -7641,7 +7593,7 @@ var OwneySDK = class {
7641
7593
  /**
7642
7594
  * Ensure the given asset uses backend protocol auto-selection for the active
7643
7595
  * chain's account. No-op (returns false) for agents that don't support it.
7644
- * @param asset - Asset symbol (e.g. "USDC").
7596
+ * @param asset - "USDC" or "WETH".
7645
7597
  * @param agentId - Agent to target. Defaults to "zyfai".
7646
7598
  * @returns whether a profile write occurred.
7647
7599
  */
@@ -7666,28 +7618,23 @@ var OwneySDK = class {
7666
7618
  return pending;
7667
7619
  }
7668
7620
  /**
7669
- * One-time, user-paid approval of Permit2 on the sponsored WETH (default) or
7670
- * USDT token for the active chain. Required once per wallet per chain before
7671
- * gasless deposits of that asset; afterwards deposit() is signature-only.
7672
- * Resolves only after the approval transaction is mined (1 confirmation), so
7673
- * a subsequent deposit() will see the new allowance; throws if the
7674
- * transaction reverted.
7675
- *
7676
- * On mainnet USDT only (`needsAllowanceReset`), a non-zero existing allowance
7677
- * is first zeroed in its own transaction. If the user rejects the second
7678
- * prompt, the previous Permit2 allowance stays zeroed; calling this again
7679
- * approves from zero in a single transaction.
7621
+ * One-time, user-paid approval of Permit2 on the sponsored WETH token for
7622
+ * the active chain. Required once per wallet per chain before gasless WETH
7623
+ * deposits; afterwards deposit() is signature-only. Resolves only after the
7624
+ * approval transaction is mined (1 confirmation), so a subsequent deposit()
7625
+ * will see the new allowance; throws if the transaction reverted.
7680
7626
  * @returns the approval transaction hash.
7681
7627
  */
7682
7628
  async approvePermit2(asset = "WETH") {
7629
+ void asset;
7683
7630
  const state = this.requireState();
7684
7631
  const chainId = this.requireChainId();
7685
- this.validateAssetSupport(this.getAgent("zyfai"), chainId, asset);
7686
- const token = sponsoredTokenMap(asset)[chainId];
7632
+ this.validateAssetSupport(this.getAgent("zyfai"), chainId, "WETH");
7633
+ const token = SPONSORED_WETH_BY_CHAIN[chainId];
7687
7634
  if (!token) {
7688
7635
  throw new OwneyError(
7689
7636
  "CHAIN_UNSUPPORTED",
7690
- `No sponsored ${asset} on chain ${chainId}`
7637
+ `No sponsored WETH on chain ${chainId}`
7691
7638
  );
7692
7639
  }
7693
7640
  const provider = this.requireConnectedProvider();
@@ -7705,52 +7652,22 @@ var OwneySDK = class {
7705
7652
  wallet,
7706
7653
  chainId
7707
7654
  );
7708
- const currentAllowance = await this.readTokenPermit2Allowance(
7709
- chainId,
7710
- token
7711
- ).catch(
7712
- () => readPermit2Allowance(
7713
- publicClient,
7714
- token,
7715
- state.walletAddress
7716
- )
7717
- ).catch((err) => {
7718
- if (!needsAllowanceReset(token)) return 0n;
7719
- throw new OwneyError(
7720
- "PERMIT2_APPROVAL_REQUIRED",
7721
- `Could not read the current ${asset} allowance for Permit2; please try again.`,
7722
- {
7723
- token,
7724
- chainId,
7725
- reason: "ALLOWANCE_UNREADABLE",
7726
- cause: err instanceof Error ? err.message : String(err)
7727
- }
7728
- );
7655
+ const hash = await wallet.writeContract({
7656
+ address: token,
7657
+ abi: ERC20_ALLOWANCE_ABI,
7658
+ functionName: "approve",
7659
+ args: [PERMIT2_ADDRESS, MAX_UINT256],
7660
+ account: state.walletAddress,
7661
+ chain: VIEM_CHAIN2[chainId]
7729
7662
  });
7730
- return approveWithResetIfNeeded({
7731
- token,
7732
- currentAllowance,
7733
- spender: PERMIT2_ADDRESS,
7734
- amount: MAX_UINT256,
7735
- approve: async (spender, amount) => {
7736
- const hash = await wallet.writeContract({
7737
- address: token,
7738
- abi: ERC20_ALLOWANCE_ABI,
7739
- functionName: "approve",
7740
- args: [spender, amount],
7741
- account: state.walletAddress,
7742
- chain: VIEM_CHAIN2[chainId]
7743
- });
7744
- const receipt = await publicClient.waitForTransactionReceipt({
7745
- hash,
7746
- confirmations: 1
7747
- });
7748
- if (receipt.status !== "success") {
7749
- throw new Error(`Permit2 approval reverted (tx ${hash})`);
7750
- }
7751
- return hash;
7752
- }
7663
+ const receipt = await publicClient.waitForTransactionReceipt({
7664
+ hash,
7665
+ confirmations: 1
7753
7666
  });
7667
+ if (receipt.status !== "success") {
7668
+ throw new Error(`Permit2 approval reverted (tx ${hash})`);
7669
+ }
7670
+ return hash;
7754
7671
  }
7755
7672
  // --- Discovery (no wallet required) ---
7756
7673
  /**