@owney/sdk 0.8.0-beta.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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`.
1368
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.
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
  }
@@ -4020,66 +3946,6 @@ async function runFusion(deps, options, walletAddress) {
4020
3946
  return { orderHash: built.orderHash };
4021
3947
  }
4022
3948
 
4023
- // src/lib/swap/swap.approve.ts
4024
- var APPROVE_WATCH_INTERVAL_MS = 4e3;
4025
- var APPROVE_PROMPT_TIMEOUT_MS = 5 * 60 * 1e3;
4026
- async function approveWatched(deps, options) {
4027
- const { amount, symbol, chainId } = options;
4028
- const landed = (allowance) => amount === 0n ? allowance === 0n : allowance >= amount;
4029
- const sleep2 = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
4030
- return new Promise((resolve, reject) => {
4031
- let done = false;
4032
- const finish = (settle) => {
4033
- if (done) return;
4034
- done = true;
4035
- clearTimeout(timer);
4036
- settle();
4037
- };
4038
- const timer = setTimeout(
4039
- () => finish(
4040
- () => reject(
4041
- new OwneyError(
4042
- "SWAP_WALLET_PROMPT_TIMEOUT",
4043
- // Hedged: a wallet that never answered may still have sent it.
4044
- `Your wallet didn't answer the request to approve your ${symbol}. Check your wallet before trying again.`,
4045
- {
4046
- chainId,
4047
- prompt: "approve",
4048
- timeoutMs: APPROVE_PROMPT_TIMEOUT_MS
4049
- }
4050
- )
4051
- )
4052
- ),
4053
- APPROVE_PROMPT_TIMEOUT_MS
4054
- );
4055
- deps.send().then(async (hash) => {
4056
- clearTimeout(timer);
4057
- await deps.waitForReceipt(hash);
4058
- return hash;
4059
- }).then(
4060
- (hash) => finish(() => resolve(hash)),
4061
- (error) => finish(() => reject(error))
4062
- );
4063
- void (async () => {
4064
- while (!done) {
4065
- await sleep2(APPROVE_WATCH_INTERVAL_MS);
4066
- if (done) return;
4067
- try {
4068
- if (landed(await deps.readAllowance())) {
4069
- debugLog(
4070
- "owney-sdk",
4071
- "approve: landed on chain before the wallet answered"
4072
- );
4073
- finish(() => resolve(void 0));
4074
- return;
4075
- }
4076
- } catch {
4077
- }
4078
- }
4079
- })();
4080
- });
4081
- }
4082
-
4083
3949
  // src/lib/swap/swap.permit.ts
4084
3950
  import {
4085
3951
  domainSeparator,
@@ -4809,7 +4675,6 @@ function makeSponsoredDepositCallback(deps) {
4809
4675
  // src/lib/walletconnect-switch.ts
4810
4676
  var WALLET_SWITCH_TIMEOUT_MS = 12e4;
4811
4677
  var HOLD_CHAIN_MS = 15e3;
4812
- var MAX_RESENDS = 2;
4813
4678
  var holds = /* @__PURE__ */ new Map();
4814
4679
  function parseChainId(raw) {
4815
4680
  if (typeof raw === "number") return raw;
@@ -4818,28 +4683,76 @@ function parseChainId(raw) {
4818
4683
  const id = ref.startsWith("0x") ? Number.parseInt(ref, 16) : Number(ref);
4819
4684
  return Number.isFinite(id) ? id : void 0;
4820
4685
  }
4821
- function walletConnectCore(provider) {
4686
+ function walletConnectSession(provider) {
4822
4687
  const p = provider;
4823
4688
  const core = p?.signer ?? p;
4824
- 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") {
4825
4690
  return null;
4826
4691
  }
4827
4692
  const peer = core.session.peer?.metadata?.name ?? "";
4828
- if (!/metamask/i.test(peer)) return null;
4829
- 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
+ }
4830
4735
  }
4831
4736
  async function switchWalletConnectChain(provider, chainId, timeoutMs = WALLET_SWITCH_TIMEOUT_MS) {
4832
- const core = walletConnectCore(provider);
4833
- if (!core) return false;
4737
+ const session = walletConnectSession(provider);
4738
+ if (!session) return false;
4739
+ const { core, strategy } = session;
4834
4740
  holds.get(core.session.topic)?.();
4741
+ if (strategy === "session-default") {
4742
+ await selectSessionDefaultChain(core, chainId);
4743
+ return true;
4744
+ }
4835
4745
  await requestSwitch(core, provider, chainId, timeoutMs);
4836
- holdChain(core, provider, chainId);
4746
+ holdChain(core, chainId);
4837
4747
  return true;
4838
4748
  }
4839
4749
  async function requestSwitch(core, provider, chainId, timeoutMs) {
4840
- const current = Number(
4750
+ const current = parseChainId(
4841
4751
  await provider.request({ method: "eth_chainId" })
4842
4752
  );
4753
+ if (current === void 0) {
4754
+ throw new Error("WalletConnect could not report its current chain.");
4755
+ }
4843
4756
  const hexChainId = `0x${chainId.toString(16)}`;
4844
4757
  let timer;
4845
4758
  try {
@@ -4869,26 +4782,27 @@ async function requestSwitch(core, provider, chainId, timeoutMs) {
4869
4782
  } catch {
4870
4783
  }
4871
4784
  }
4872
- function holdChain(core, provider, chainId) {
4785
+ function holdChain(core, chainId) {
4873
4786
  if (typeof core.on !== "function" || typeof core.removeListener !== "function") {
4874
4787
  return;
4875
4788
  }
4876
- let resends = 0;
4789
+ let repins = 0;
4877
4790
  const listener = (raw) => {
4878
4791
  const reported = parseChainId(raw);
4879
4792
  debugLog("wc-switch", "wallet reported chain", {
4880
4793
  reported,
4881
4794
  holding: chainId,
4882
- resends
4795
+ repins
4883
4796
  });
4884
4797
  if (reported === void 0 || reported === chainId) return;
4885
- if (resends >= MAX_RESENDS) return;
4886
- resends += 1;
4887
- void requestSwitch(core, provider, chainId, WALLET_SWITCH_TIMEOUT_MS).catch(
4888
- (error) => debugLog("wc-switch", "re-switch failed", {
4798
+ repins += 1;
4799
+ try {
4800
+ core.setDefaultChain(`eip155:${chainId}`);
4801
+ } catch (error) {
4802
+ debugLog("wc-switch", "session re-pin failed", {
4889
4803
  error: error instanceof Error ? error.message : String(error)
4890
- })
4891
- );
4804
+ });
4805
+ }
4892
4806
  };
4893
4807
  const release = () => {
4894
4808
  clearTimeout(timer);
@@ -4902,7 +4816,7 @@ function holdChain(core, provider, chainId) {
4902
4816
  holds.set(core.session.topic, release);
4903
4817
  }
4904
4818
  function withWalletConnectSwitch(provider) {
4905
- if (!walletConnectCore(provider)) return provider;
4819
+ if (!walletConnectSession(provider)) return provider;
4906
4820
  const target = provider;
4907
4821
  const request2 = async (args) => {
4908
4822
  if (args?.method !== "wallet_switchEthereumChain") {
@@ -4934,7 +4848,7 @@ function makeSponsoredWethCallback(deps) {
4934
4848
  if (!token) {
4935
4849
  throw new OwneyError(
4936
4850
  "CHAIN_UNSUPPORTED",
4937
- `No sponsored ${deps.assetSymbol} configured for chain ${chainId}`
4851
+ `No sponsored WETH configured for chain ${chainId}`
4938
4852
  );
4939
4853
  }
4940
4854
  const amountWei = BigInt(amount);
@@ -4947,14 +4861,14 @@ function makeSponsoredWethCallback(deps) {
4947
4861
  if (balance < amountWei) {
4948
4862
  throw new OwneyError(
4949
4863
  "DEPOSIT_INSUFFICIENT_BALANCE",
4950
- `Insufficient ${deps.assetSymbol} balance for this deposit.`,
4864
+ "Insufficient WETH balance for this deposit.",
4951
4865
  { token, chainId: cid, balance: balance.toString(), amount }
4952
4866
  );
4953
4867
  }
4954
4868
  } catch (err) {
4955
4869
  if (err instanceof OwneyError) throw err;
4956
4870
  console.warn(
4957
- `[owney-sdk] ${deps.assetSymbol} balance pre-check failed (non-fatal):`,
4871
+ "[owney-sdk] WETH balance pre-check failed (non-fatal):",
4958
4872
  err instanceof Error ? err.message : String(err)
4959
4873
  );
4960
4874
  }
@@ -4966,7 +4880,7 @@ function makeSponsoredWethCallback(deps) {
4966
4880
  if (allowance < amountWei) {
4967
4881
  throw new OwneyError(
4968
4882
  "PERMIT2_APPROVAL_REQUIRED",
4969
- `${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",
4970
4884
  { token, chainId: cid, allowance: allowance.toString(), amount }
4971
4885
  );
4972
4886
  }
@@ -5153,22 +5067,8 @@ var SPONSORED_WETH_BY_CHAIN = {
5153
5067
  42161: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
5154
5068
  1: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
5155
5069
  };
5156
- function sponsoredTokenMap(asset) {
5157
- if (asset === "USDC") return SPONSORED_USDC_BY_CHAIN;
5158
- if (asset === "WETH") return SPONSORED_WETH_BY_CHAIN;
5159
- return Object.fromEntries(
5160
- SUPPORTED_CHAIN_IDS.flatMap((id) => {
5161
- const a = tokenAddress(asset, id);
5162
- return a ? [[id, a]] : [];
5163
- })
5164
- );
5165
- }
5166
- var PERMIT2_ASSETS = /* @__PURE__ */ new Set(["WETH", "USDT"]);
5167
- function isPermit2Asset(asset) {
5168
- return PERMIT2_ASSETS.has(asset);
5169
- }
5170
5070
  function shouldFallbackToUserPaid(error, asset, appCallback) {
5171
- 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;
5172
5072
  }
5173
5073
  var OwneySDK = class {
5174
5074
  agents = /* @__PURE__ */ new Map();
@@ -5191,8 +5091,9 @@ var OwneySDK = class {
5191
5091
  userPoolCustomization = false;
5192
5092
  routingApiBaseUrl;
5193
5093
  referralSource;
5194
- cachedSponsoredCallbacks = /* @__PURE__ */ new Map();
5195
- cachedPermit2SponsoredCallbacks = /* @__PURE__ */ new Map();
5094
+ sessionStore;
5095
+ cachedSponsoredCallback = null;
5096
+ cachedWethSponsoredCallback = null;
5196
5097
  paymasterServiceUrl;
5197
5098
  cachedSponsoredCallsCallbacks = /* @__PURE__ */ new Map();
5198
5099
  agentReads = new AgentReads();
@@ -5214,6 +5115,7 @@ var OwneySDK = class {
5214
5115
  this.routingApiBaseUrl = config.routingApiBaseUrl;
5215
5116
  this.paymasterServiceUrl = config.paymasterServiceUrl;
5216
5117
  this.referralSource = config.referralSource;
5118
+ this.sessionStore = config.sessionStore;
5217
5119
  this.userPoolCustomization = config.userPoolCustomization ?? false;
5218
5120
  }
5219
5121
  /**
@@ -5240,8 +5142,8 @@ var OwneySDK = class {
5240
5142
  walletAddress,
5241
5143
  chainId: null
5242
5144
  };
5243
- this.cachedSponsoredCallbacks.clear();
5244
- this.cachedPermit2SponsoredCallbacks.clear();
5145
+ this.cachedSponsoredCallback = null;
5146
+ this.cachedWethSponsoredCallback = null;
5245
5147
  this.cachedSponsoredCallsCallbacks.clear();
5246
5148
  }
5247
5149
  /**
@@ -5257,8 +5159,8 @@ var OwneySDK = class {
5257
5159
  this.agentReads.clearInFlight();
5258
5160
  this.activationChecks.clear();
5259
5161
  this.state = null;
5260
- this.cachedSponsoredCallbacks.clear();
5261
- this.cachedPermit2SponsoredCallbacks.clear();
5162
+ this.cachedSponsoredCallback = null;
5163
+ this.cachedWethSponsoredCallback = null;
5262
5164
  this.cachedSponsoredCallsCallbacks.clear();
5263
5165
  }
5264
5166
  isAgentDisabled(agentId) {
@@ -5308,9 +5210,9 @@ var OwneySDK = class {
5308
5210
  * provider with viem `custom(provider)` to read token meta and sign the
5309
5211
  * `TransferWithAuthorization`, then POSTs to the sponsor API.
5310
5212
  */
5311
- getDefaultSponsoredCallback(asset, onApproved) {
5312
- const cached = this.cachedSponsoredCallbacks.get(asset);
5313
- if (!onApproved && cached) return cached;
5213
+ getDefaultSponsoredCallback(onApproved) {
5214
+ if (!onApproved && this.cachedSponsoredCallback)
5215
+ return this.cachedSponsoredCallback;
5314
5216
  const provider = this.requireConnectedProvider();
5315
5217
  const owner = this.state.walletAddress;
5316
5218
  const callback = makeSponsoredDepositCallback({
@@ -5318,7 +5220,7 @@ var OwneySDK = class {
5318
5220
  baseUrl: this.routingApiBaseUrl,
5319
5221
  ownerAddress: owner,
5320
5222
  onApproved,
5321
- tokenAddressByChain: sponsoredTokenMap(asset),
5223
+ tokenAddressByChain: SPONSORED_USDC_BY_CHAIN,
5322
5224
  // Casts work around viem's chain-narrowed Client vs the generic
5323
5225
  // PublicClient/WalletClient param types — structurally identical at
5324
5226
  // runtime, but the two share a name TS treats as unrelated.
@@ -5335,13 +5237,14 @@ var OwneySDK = class {
5335
5237
  transport: custom(provider)
5336
5238
  })
5337
5239
  });
5338
- if (!onApproved) this.cachedSponsoredCallbacks.set(asset, callback);
5240
+ if (!onApproved) this.cachedSponsoredCallback = callback;
5339
5241
  return callback;
5340
5242
  }
5341
5243
  /**
5342
- * Lazily builds (and caches, per asset) the default paymaster-sponsored
5343
- * deposit callback used when the caller omits `depositCallback` and a
5344
- * `paymasterServiceUrl` is configured. One rail serves every asset.
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.
5345
5248
  */
5346
5249
  getDefaultSponsoredCallsCallback(asset, onApproved) {
5347
5250
  const cached = this.cachedSponsoredCallsCallbacks.get(asset);
@@ -5352,20 +5255,20 @@ var OwneySDK = class {
5352
5255
  ownerAddress: this.state.walletAddress,
5353
5256
  paymasterServiceUrl: this.paymasterServiceUrl,
5354
5257
  onApproved,
5355
- tokenAddressByChain: sponsoredTokenMap(asset)
5258
+ tokenAddressByChain: asset === "WETH" ? SPONSORED_WETH_BY_CHAIN : SPONSORED_USDC_BY_CHAIN
5356
5259
  });
5357
5260
  if (!onApproved) this.cachedSponsoredCallsCallbacks.set(asset, callback);
5358
5261
  return callback;
5359
5262
  }
5360
5263
  /**
5361
- * Lazily builds (and caches, per asset) the default Permit2 sponsored
5362
- * deposit callback used when the caller omits `depositCallback` for a
5363
- * Permit2 asset (WETH, USDT). Mirrors `getDefaultSponsoredCallback()` but
5364
- * signs a Permit2 `PermitTransferFrom` instead of an EIP-3009 authorization.
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.
5365
5268
  */
5366
- getDefaultPermit2SponsoredCallback(asset, onApproved) {
5367
- const cached = this.cachedPermit2SponsoredCallbacks.get(asset);
5368
- if (!onApproved && cached) return cached;
5269
+ getDefaultWethSponsoredCallback(onApproved) {
5270
+ if (!onApproved && this.cachedWethSponsoredCallback)
5271
+ return this.cachedWethSponsoredCallback;
5369
5272
  const provider = this.requireConnectedProvider();
5370
5273
  const owner = this.state.walletAddress;
5371
5274
  const callback = makeSponsoredWethCallback({
@@ -5373,8 +5276,7 @@ var OwneySDK = class {
5373
5276
  baseUrl: this.routingApiBaseUrl,
5374
5277
  ownerAddress: owner,
5375
5278
  onApproved,
5376
- tokenAddressByChain: sponsoredTokenMap(asset),
5377
- assetSymbol: asset,
5279
+ tokenAddressByChain: SPONSORED_WETH_BY_CHAIN,
5378
5280
  // Casts work around viem's chain-narrowed Client vs the generic
5379
5281
  // PublicClient/WalletClient param types — structurally identical at
5380
5282
  // runtime, but the two share a name TS treats as unrelated.
@@ -5391,7 +5293,7 @@ var OwneySDK = class {
5391
5293
  transport: custom(provider)
5392
5294
  })
5393
5295
  });
5394
- if (!onApproved) this.cachedPermit2SponsoredCallbacks.set(asset, callback);
5296
+ if (!onApproved) this.cachedWethSponsoredCallback = callback;
5395
5297
  return callback;
5396
5298
  }
5397
5299
  getAgent(agentId) {
@@ -5487,7 +5389,12 @@ var OwneySDK = class {
5487
5389
  }
5488
5390
  createAgent(agentId, key2) {
5489
5391
  if (agentId === "zyfai") {
5490
- return new ZyfaiAgent(key2, this.zyfaiRpcUrls, this.referralSource);
5392
+ return new ZyfaiAgent(
5393
+ key2,
5394
+ this.zyfaiRpcUrls,
5395
+ this.referralSource,
5396
+ this.sessionStore
5397
+ );
5491
5398
  }
5492
5399
  return null;
5493
5400
  }
@@ -5649,8 +5556,7 @@ var OwneySDK = class {
5649
5556
  }
5650
5557
  const state = this.requireState();
5651
5558
  const chainId = options.chainId ?? this.requireChainId();
5652
- const sponsoredAsset = asset;
5653
- 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));
5654
5560
  if (agentId) {
5655
5561
  if (this.isAgentDisabled(agentId)) {
5656
5562
  throw new OwneyError(
@@ -5764,16 +5670,15 @@ var OwneySDK = class {
5764
5670
  *
5765
5671
  * 1. Missing Permit2 allowance: when the app did not supply its own
5766
5672
  * callback and the attempt fails with `PERMIT2_APPROVAL_REQUIRED` on a
5767
- * Permit2 asset (WETH, USDT), this is the wallet's first gasless deposit
5768
- * of that asset on this chain. We send the one-time (user-paid) Permit2
5769
- * approval via `approvePermit2(asset)` and retry the SAME sponsored
5770
- * attempt once. Bounded to one approval attempt per call so a
5771
- * wallet/agent that keeps reporting the allowance as missing can't loop
5772
- * forever. If `approvePermit2()` itself throws (e.g.
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.
5773
5678
  * the user rejects the wallet prompt), that error propagates as-is —
5774
5679
  * the user said no to a transaction, so we must not turn around and ask
5775
5680
  * them to pay for a different one via the fallback below.
5776
- * 2. `shouldFallbackToUserPaid`: the SDK's own sponsor path failed at
5681
+ * 2. `shouldFallbackToUserPaid`: the SDK's own WETH sponsor path failed at
5777
5682
  * the infrastructure layer in a provably safe-to-retry way, so we warn
5778
5683
  * and retry once with `undefined`, falling through to a user-paid
5779
5684
  * native deposit. This still applies after a successful Permit2
@@ -5802,12 +5707,12 @@ var OwneySDK = class {
5802
5707
  try {
5803
5708
  return await attempt(effectiveCallback);
5804
5709
  } catch (error) {
5805
- 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") {
5806
5711
  approvalAttempted = true;
5807
5712
  console.warn(
5808
- `[owney-sdk] First ${asset} deposit: sending one-time Permit2 approval...`
5713
+ "[owney-sdk] First WETH deposit: sending one-time Permit2 approval..."
5809
5714
  );
5810
- await this.approvePermit2(asset);
5715
+ await this.approvePermit2();
5811
5716
  continue;
5812
5717
  }
5813
5718
  if (!shouldFallbackToUserPaid(error, asset, appCallback)) throw error;
@@ -6244,45 +6149,22 @@ var OwneySDK = class {
6244
6149
  functionName: "allowance",
6245
6150
  args: [state.walletAddress, spender]
6246
6151
  }),
6247
- // Watched on chain as well as through the wallet: Trust's extension can
6248
- // land the approval and never return its hash (ROUT-759).
6249
- approve: (spender, amount) => approveWatched(
6250
- {
6251
- send: () => wallet.writeContract({
6252
- address: quote.src.address,
6253
- abi: ERC20_ALLOWANCE_ABI,
6254
- functionName: "approve",
6255
- args: [spender, amount],
6256
- account: state.walletAddress,
6257
- chain: srcChain
6258
- }),
6259
- waitForReceipt: async (hash) => {
6260
- const receipt = await srcPublic.waitForTransactionReceipt({
6261
- hash,
6262
- confirmations: 1,
6263
- timeout: receiptTimeoutMs(quote.src.chainId)
6264
- });
6265
- if (receipt.status !== "success") {
6266
- throw new OwneyError(
6267
- "SWAP_REQUEST_FAILED",
6268
- `Approval transaction reverted (tx ${hash})`,
6269
- { hash }
6270
- );
6271
- }
6272
- },
6273
- readAllowance: () => srcPublic.readContract({
6274
- address: quote.src.address,
6275
- abi: ERC20_ALLOWANCE_ABI,
6276
- functionName: "allowance",
6277
- args: [state.walletAddress, spender]
6278
- })
6279
- },
6280
- {
6281
- amount,
6282
- symbol: quote.src.symbol,
6283
- chainId: quote.src.chainId
6284
- }
6285
- ),
6152
+ approve: async (spender, amount) => {
6153
+ const hash = await wallet.writeContract({
6154
+ address: quote.src.address,
6155
+ abi: ERC20_ALLOWANCE_ABI,
6156
+ functionName: "approve",
6157
+ args: [spender, amount],
6158
+ account: state.walletAddress,
6159
+ chain: srcChain
6160
+ });
6161
+ await srcPublic.waitForTransactionReceipt({
6162
+ hash,
6163
+ confirmations: 1,
6164
+ timeout: receiptTimeoutMs(quote.src.chainId)
6165
+ });
6166
+ return hash;
6167
+ },
6286
6168
  ensureChain: (chainId) => this.ensureSwapChain(chainId),
6287
6169
  /**
6288
6170
  * Sign the approval instead of paying for it. Null means the token
@@ -6370,33 +6252,30 @@ var OwneySDK = class {
6370
6252
  * figure directly. It is the entire arrival, so there is no slack: anything
6371
6253
  * that spends the target asset between the two fails the deposit outright.
6372
6254
  *
6373
- * Something does. A first deposit of a Permit2 asset (WETH, USDT) needs a
6374
- * one-time Permit2 approval, and that approval is a transaction. For WETH,
6375
- * a wallet holding no native gas token - the normal state of someone who
6376
- * just swapped everything INTO WETH - pays for it out of the WETH. The
6377
- * deposit then asked for ~2e12 wei more than was left and refused with
6378
- * DEPOSIT_INSUFFICIENT_BALANCE, under a wrapper saying the funds were safe
6379
- * but unadded (ROUT-242). For USDT the gas cannot come out of the token, so
6380
- * this step only adds the one-time approval and the read changes nothing.
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).
6381
6261
  *
6382
6262
  * So the approval happens here, before the amount is settled, and the amount
6383
6263
  * comes from a read taken after it. Two things this deliberately is not:
6384
6264
  *
6385
6265
  * - It is not a balance sweep. `received` is a DELTA over the pre-swap
6386
- * balance, so a wallet already holding the asset reads far above it;
6387
- * depositing the balance would move funds the user never offered. The
6388
- * arrival is the ceiling and the balance is only ever allowed to lower it.
6389
- * - It does not touch USDC or EURC, which move on signed typed data
6390
- * (EIP-3009) and so spend nothing of the user's in between, nor a
6391
- * paymaster-configured client, where the sponsor covers the transfer and
6392
- * Permit2 never applies.
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.
6393
6272
  */
6394
6273
  async settleSwapDepositAmount(chainId, token, symbol, received) {
6395
- if (!isPermit2Asset(symbol) || this.paymasterServiceUrl) {
6274
+ if (symbol !== "WETH" || this.paymasterServiceUrl) {
6396
6275
  return received.toString();
6397
6276
  }
6398
6277
  const allowance = await this.readTokenPermit2Allowance(chainId, token);
6399
- if (allowance < received) await this.approvePermit2(symbol);
6278
+ if (allowance < received) await this.approvePermit2();
6400
6279
  const balance = await this.readTokenBalance(chainId, token);
6401
6280
  return (balance < received ? balance : received).toString();
6402
6281
  }
@@ -6561,10 +6440,7 @@ var OwneySDK = class {
6561
6440
  );
6562
6441
  }
6563
6442
  await this.ensureSwapChain(entry.chainId);
6564
- const supported = SUPPORTED_TOKENS.includes(
6565
- entry.symbol
6566
- );
6567
- const token = supported ? sponsoredTokenMap(entry.symbol)[entry.chainId] : void 0;
6443
+ const token = entry.symbol === "WETH" ? SPONSORED_WETH_BY_CHAIN[entry.chainId] : void 0;
6568
6444
  const amount = token ? await this.settleSwapDepositAmount(
6569
6445
  entry.chainId,
6570
6446
  token,
@@ -7717,7 +7593,7 @@ var OwneySDK = class {
7717
7593
  /**
7718
7594
  * Ensure the given asset uses backend protocol auto-selection for the active
7719
7595
  * chain's account. No-op (returns false) for agents that don't support it.
7720
- * @param asset - Asset symbol (e.g. "USDC").
7596
+ * @param asset - "USDC" or "WETH".
7721
7597
  * @param agentId - Agent to target. Defaults to "zyfai".
7722
7598
  * @returns whether a profile write occurred.
7723
7599
  */
@@ -7742,28 +7618,23 @@ var OwneySDK = class {
7742
7618
  return pending;
7743
7619
  }
7744
7620
  /**
7745
- * One-time, user-paid approval of Permit2 on the sponsored WETH (default) or
7746
- * USDT token for the active chain. Required once per wallet per chain before
7747
- * gasless deposits of that asset; afterwards deposit() is signature-only.
7748
- * Resolves only after the approval transaction is mined (1 confirmation), so
7749
- * a subsequent deposit() will see the new allowance; throws if the
7750
- * transaction reverted.
7751
- *
7752
- * On mainnet USDT only (`needsAllowanceReset`), a non-zero existing allowance
7753
- * is first zeroed in its own transaction. If the user rejects the second
7754
- * prompt, the previous Permit2 allowance stays zeroed; calling this again
7755
- * approves from zero in a single transaction.
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.
7756
7626
  * @returns the approval transaction hash.
7757
7627
  */
7758
7628
  async approvePermit2(asset = "WETH") {
7629
+ void asset;
7759
7630
  const state = this.requireState();
7760
7631
  const chainId = this.requireChainId();
7761
- this.validateAssetSupport(this.getAgent("zyfai"), chainId, asset);
7762
- const token = sponsoredTokenMap(asset)[chainId];
7632
+ this.validateAssetSupport(this.getAgent("zyfai"), chainId, "WETH");
7633
+ const token = SPONSORED_WETH_BY_CHAIN[chainId];
7763
7634
  if (!token) {
7764
7635
  throw new OwneyError(
7765
7636
  "CHAIN_UNSUPPORTED",
7766
- `No sponsored ${asset} on chain ${chainId}`
7637
+ `No sponsored WETH on chain ${chainId}`
7767
7638
  );
7768
7639
  }
7769
7640
  const provider = this.requireConnectedProvider();
@@ -7781,52 +7652,22 @@ var OwneySDK = class {
7781
7652
  wallet,
7782
7653
  chainId
7783
7654
  );
7784
- const currentAllowance = await this.readTokenPermit2Allowance(
7785
- chainId,
7786
- token
7787
- ).catch(
7788
- () => readPermit2Allowance(
7789
- publicClient,
7790
- token,
7791
- state.walletAddress
7792
- )
7793
- ).catch((err) => {
7794
- if (!needsAllowanceReset(token)) return 0n;
7795
- throw new OwneyError(
7796
- "PERMIT2_APPROVAL_REQUIRED",
7797
- `Could not read the current ${asset} allowance for Permit2; please try again.`,
7798
- {
7799
- token,
7800
- chainId,
7801
- reason: "ALLOWANCE_UNREADABLE",
7802
- cause: err instanceof Error ? err.message : String(err)
7803
- }
7804
- );
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]
7805
7662
  });
7806
- return approveWithResetIfNeeded({
7807
- token,
7808
- currentAllowance,
7809
- spender: PERMIT2_ADDRESS,
7810
- amount: MAX_UINT256,
7811
- approve: async (spender, amount) => {
7812
- const hash = await wallet.writeContract({
7813
- address: token,
7814
- abi: ERC20_ALLOWANCE_ABI,
7815
- functionName: "approve",
7816
- args: [spender, amount],
7817
- account: state.walletAddress,
7818
- chain: VIEM_CHAIN2[chainId]
7819
- });
7820
- const receipt = await publicClient.waitForTransactionReceipt({
7821
- hash,
7822
- confirmations: 1
7823
- });
7824
- if (receipt.status !== "success") {
7825
- throw new Error(`Permit2 approval reverted (tx ${hash})`);
7826
- }
7827
- return hash;
7828
- }
7663
+ const receipt = await publicClient.waitForTransactionReceipt({
7664
+ hash,
7665
+ confirmations: 1
7829
7666
  });
7667
+ if (receipt.status !== "success") {
7668
+ throw new Error(`Permit2 approval reverted (tx ${hash})`);
7669
+ }
7670
+ return hash;
7830
7671
  }
7831
7672
  // --- Discovery (no wallet required) ---
7832
7673
  /**