@owney/sdk 0.8.0-beta.1 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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,11 +1841,18 @@ 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
  ];
1855
- await this.sdk.updateUserProfile({ asset, strategy, protocols });
1850
+ await this.sdk.updateUserProfile({
1851
+ asset,
1852
+ strategy,
1853
+ protocols,
1854
+ autoSelectProtocols: false
1855
+ });
1856
1856
  })
1857
1857
  );
1858
1858
  } catch (error) {
@@ -2207,10 +2207,11 @@ var ZyfaiAgent = class _ZyfaiAgent {
2207
2207
  requestedStrategy: "aggressive",
2208
2208
  setupResult
2209
2209
  });
2210
- await this.syncAutoSelect(validChainId, asset);
2211
2210
  if (isOwneyDebug()) {
2212
2211
  try {
2213
- const profileAfterSetup = await this.sdk.getUserDetails(asset);
2212
+ const profileAfterSetup = await this.sdk.getUserDetails(
2213
+ asset === "WETH" ? "WETH" : "USDC"
2214
+ );
2214
2215
  debugLog("zyfai:first-deposit", "profile immediately after setup", {
2215
2216
  asset,
2216
2217
  strategy: profileAfterSetup.strategy,
@@ -2228,9 +2229,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
2228
2229
  validChainId
2229
2230
  );
2230
2231
  const txHash = await depositCallback(smartWallet, validChainId, amount);
2231
- const tokenAddress2 = asset === "USDC" ? void 0 : tokenAddress(asset, validChainId);
2232
+ const tokenAddress = asset === "WETH" ? WETH_ADDRESS_BY_CHAIN[validChainId] : void 0;
2232
2233
  try {
2233
- await (tokenAddress2 ? this.sdk.logDeposit(validChainId, txHash, amount, tokenAddress2) : this.sdk.logDeposit(validChainId, txHash, amount));
2234
+ await (tokenAddress ? this.sdk.logDeposit(validChainId, txHash, amount, tokenAddress) : this.sdk.logDeposit(validChainId, txHash, amount));
2234
2235
  } catch (logError) {
2235
2236
  console.warn(
2236
2237
  "[owney-sdk] Deposit landed on-chain but logDeposit failed (non-fatal):",
@@ -2336,22 +2337,13 @@ var ZyfaiAgent = class _ZyfaiAgent {
2336
2337
  }
2337
2338
  async getAccountApy(state, chainId, days, tokenSymbol, scopeChainId) {
2338
2339
  const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
2339
- const [raw, ethUsd, eurUsd] = await Promise.all([
2340
+ const [raw, ethUsd] = await Promise.all([
2340
2341
  this.sdk.getDailyApyHistory(smartWallet, days),
2341
- tokenSymbol ? void 0 : this.readEthUsd(validChainId),
2342
- tokenSymbol ? void 0 : this.readEurUsd()
2342
+ tokenSymbol ? void 0 : this.readEthUsd(validChainId)
2343
2343
  ]);
2344
2344
  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
- );
2345
+ const usdPrices = ethUsd ? { WETH: ethUsd, ETH: ethUsd } : void 0;
2346
+ return mapApyHistory(raw, scope, tokenSymbol, usdPrices);
2355
2347
  }
2356
2348
  /**
2357
2349
  * Today's ETH/USD from Chainlink, cached for a minute. Every day of the
@@ -2359,38 +2351,24 @@ var ZyfaiAgent = class _ZyfaiAgent {
2359
2351
  * move over the window is not reflected (ROUT-682). Undefined on failure,
2360
2352
  * which leaves the series on token-amount weighting rather than failing it.
2361
2353
  */
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;
2354
+ async readEthUsd(chainId) {
2355
+ if (this.ethUsd && Date.now() - this.ethUsd.at < ETH_USD_TTL_MS) {
2356
+ return this.ethUsd.price;
2377
2357
  }
2378
2358
  try {
2379
2359
  const [, answer] = await this.getPublicClient(chainId).readContract({
2380
- address: feed,
2360
+ address: CHAINLINK_ETH_USD_FEED[chainId],
2381
2361
  abi: CHAINLINK_ABI,
2382
2362
  functionName: "latestRoundData"
2383
2363
  });
2384
2364
  const price = Number(answer) / 1e8;
2385
2365
  if (!Number.isFinite(price) || price <= 0) return void 0;
2386
- this[cache] = { price, at: Date.now() };
2366
+ this.ethUsd = { price, at: Date.now() };
2387
2367
  return price;
2388
2368
  } catch (err) {
2389
- debugLog(
2390
- "zyfai:apy",
2391
- `${cache === "ethUsd" ? "ETH/USD" : "EUR/USD"} read failed; token-amount weighting`,
2392
- { err }
2393
- );
2369
+ debugLog("zyfai:apy", "ETH/USD read failed; token-amount weighting", {
2370
+ err
2371
+ });
2394
2372
  return void 0;
2395
2373
  }
2396
2374
  }
@@ -2421,7 +2399,6 @@ var ZyfaiAgent = class _ZyfaiAgent {
2421
2399
  return "eth";
2422
2400
  case "EURC":
2423
2401
  return "eurc";
2424
- // Zyfai has no "usdt" history filter, so USDT is filtered client-side.
2425
2402
  default:
2426
2403
  return void 0;
2427
2404
  }
@@ -2430,9 +2407,6 @@ var ZyfaiAgent = class _ZyfaiAgent {
2430
2407
  const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
2431
2408
  const limit = options?.limit ?? 10;
2432
2409
  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
2410
  const cursor = options?.cursor ? decodeHistoryCursor(options.cursor) : null;
2437
2411
  const toDate = cursor?.toDate ?? options?.toDate ?? (/* @__PURE__ */ new Date()).toISOString();
2438
2412
  let offset = cursor?.rawOffset ?? 0;
@@ -2454,12 +2428,6 @@ var ZyfaiAgent = class _ZyfaiAgent {
2454
2428
  assetType
2455
2429
  });
2456
2430
  raw.data.forEach((entry, idx) => {
2457
- if (clientSideAsset && !matchesAsset(
2458
- entry.positions?.[0]?.token_symbol ?? "",
2459
- clientSideAsset
2460
- )) {
2461
- return;
2462
- }
2463
2431
  if (entry.chainId === validChainId) {
2464
2432
  matched.push({ entry, rawIdx: offset + idx });
2465
2433
  }
@@ -2502,20 +2470,6 @@ var ZyfaiAgent = class _ZyfaiAgent {
2502
2470
  }
2503
2471
  async ensureAutoSelectProtocols(state, chainId, asset) {
2504
2472
  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
2473
  const current = await this.sdk.getUserDetails(asset);
2520
2474
  debugLog("zyfai:auto-select", `${asset}: profile before check`, {
2521
2475
  autoSelectProtocols: current.autoSelectProtocols,
@@ -2523,7 +2477,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
2523
2477
  protocols: current.protocols,
2524
2478
  strategy: current.strategy
2525
2479
  });
2526
- if ((current.chains?.length ?? 0) === 0 && (asset === "USDC" || !await this.isExistingZyfaiUser())) {
2480
+ if ((current.chains?.length ?? 0) === 0) {
2527
2481
  debugLog(
2528
2482
  "zyfai:auto-select",
2529
2483
  `${asset}: skipping untouched profile until first deposit`
@@ -3418,20 +3372,6 @@ async function readErc20Balance(publicClient, token, owner) {
3418
3372
  });
3419
3373
  }
3420
3374
 
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
3375
  // src/lib/swap/swap.secrets.ts
3436
3376
  import { keccak256, toHex } from "viem";
3437
3377
  var SECRET_BYTES = 32;
@@ -3790,15 +3730,6 @@ async function executeSwap(deps, options) {
3790
3730
  }
3791
3731
  return { received: arrived.toString(), ...result ?? {} };
3792
3732
  }
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
3733
  async function runClassic(deps, options) {
3803
3734
  const {
3804
3735
  quote,
@@ -3835,7 +3766,7 @@ async function runClassic(deps, options) {
3835
3766
  if (current < needed) {
3836
3767
  onStage?.("approving");
3837
3768
  await deps.ensureChain(quote.src.chainId);
3838
- await approveMax(deps, quote.src.address, current, tx.to);
3769
+ await deps.approve(tx.to, MAX_UINT256);
3839
3770
  debugLog(
3840
3771
  "owney-sdk",
3841
3772
  "swap: re-fetching classic calldata after approval"
@@ -3924,7 +3855,7 @@ async function authoriseSpend(deps, options, amount, isNativeSource) {
3924
3855
  });
3925
3856
  return permit;
3926
3857
  }
3927
- await approveMax(deps, quote.src.address, current, quote.spender);
3858
+ await deps.approve(quote.spender, MAX_UINT256);
3928
3859
  debugLog("owney-sdk", "swap: approved limit order protocol");
3929
3860
  return void 0;
3930
3861
  }
@@ -4020,66 +3951,6 @@ async function runFusion(deps, options, walletAddress) {
4020
3951
  return { orderHash: built.orderHash };
4021
3952
  }
4022
3953
 
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
3954
  // src/lib/swap/swap.permit.ts
4084
3955
  import {
4085
3956
  domainSeparator,
@@ -4809,7 +4680,6 @@ function makeSponsoredDepositCallback(deps) {
4809
4680
  // src/lib/walletconnect-switch.ts
4810
4681
  var WALLET_SWITCH_TIMEOUT_MS = 12e4;
4811
4682
  var HOLD_CHAIN_MS = 15e3;
4812
- var MAX_RESENDS = 2;
4813
4683
  var holds = /* @__PURE__ */ new Map();
4814
4684
  function parseChainId(raw) {
4815
4685
  if (typeof raw === "number") return raw;
@@ -4818,28 +4688,76 @@ function parseChainId(raw) {
4818
4688
  const id = ref.startsWith("0x") ? Number.parseInt(ref, 16) : Number(ref);
4819
4689
  return Number.isFinite(id) ? id : void 0;
4820
4690
  }
4821
- function walletConnectCore(provider) {
4691
+ function walletConnectSession(provider) {
4822
4692
  const p = provider;
4823
4693
  const core = p?.signer ?? p;
4824
- if (typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
4694
+ if (typeof core?.request !== "function" || typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
4825
4695
  return null;
4826
4696
  }
4827
4697
  const peer = core.session.peer?.metadata?.name ?? "";
4828
- if (!/metamask/i.test(peer)) return null;
4829
- return core;
4698
+ if (/metamask/i.test(peer)) {
4699
+ return { core, strategy: "remote-wallet" };
4700
+ }
4701
+ if (/fireblocks/i.test(peer)) {
4702
+ return { core, strategy: "session-default" };
4703
+ }
4704
+ return null;
4705
+ }
4706
+ function approvedChains(core) {
4707
+ const approved = /* @__PURE__ */ new Set();
4708
+ for (const namespace of Object.values(core.session.namespaces ?? {})) {
4709
+ for (const chain of namespace.chains ?? []) approved.add(chain);
4710
+ for (const account of namespace.accounts ?? []) {
4711
+ const [namespaceName, reference] = account.split(":");
4712
+ if (namespaceName && reference) {
4713
+ approved.add(`${namespaceName}:${reference}`);
4714
+ }
4715
+ }
4716
+ }
4717
+ return approved;
4718
+ }
4719
+ async function selectSessionDefaultChain(core, chainId) {
4720
+ const target = `eip155:${chainId}`;
4721
+ if (!approvedChains(core).has(target)) {
4722
+ throw new Error(
4723
+ `The WalletConnect session has not approved ${target}. Reconnect the wallet and try again.`
4724
+ );
4725
+ }
4726
+ core.setDefaultChain(target);
4727
+ const selected = parseChainId(
4728
+ await core.request({ method: "eth_chainId" })
4729
+ );
4730
+ debugLog("wc-switch", "selected WalletConnect session default", {
4731
+ peer: core.session.peer?.metadata?.name,
4732
+ target: chainId,
4733
+ selected
4734
+ });
4735
+ if (selected !== chainId) {
4736
+ throw new Error(
4737
+ `WalletConnect stayed on chain ${selected ?? "unknown"}; expected ${chainId}.`
4738
+ );
4739
+ }
4830
4740
  }
4831
4741
  async function switchWalletConnectChain(provider, chainId, timeoutMs = WALLET_SWITCH_TIMEOUT_MS) {
4832
- const core = walletConnectCore(provider);
4833
- if (!core) return false;
4742
+ const session = walletConnectSession(provider);
4743
+ if (!session) return false;
4744
+ const { core, strategy } = session;
4834
4745
  holds.get(core.session.topic)?.();
4746
+ if (strategy === "session-default") {
4747
+ await selectSessionDefaultChain(core, chainId);
4748
+ return true;
4749
+ }
4835
4750
  await requestSwitch(core, provider, chainId, timeoutMs);
4836
- holdChain(core, provider, chainId);
4751
+ holdChain(core, chainId);
4837
4752
  return true;
4838
4753
  }
4839
4754
  async function requestSwitch(core, provider, chainId, timeoutMs) {
4840
- const current = Number(
4755
+ const current = parseChainId(
4841
4756
  await provider.request({ method: "eth_chainId" })
4842
4757
  );
4758
+ if (current === void 0) {
4759
+ throw new Error("WalletConnect could not report its current chain.");
4760
+ }
4843
4761
  const hexChainId = `0x${chainId.toString(16)}`;
4844
4762
  let timer;
4845
4763
  try {
@@ -4869,26 +4787,27 @@ async function requestSwitch(core, provider, chainId, timeoutMs) {
4869
4787
  } catch {
4870
4788
  }
4871
4789
  }
4872
- function holdChain(core, provider, chainId) {
4790
+ function holdChain(core, chainId) {
4873
4791
  if (typeof core.on !== "function" || typeof core.removeListener !== "function") {
4874
4792
  return;
4875
4793
  }
4876
- let resends = 0;
4794
+ let repins = 0;
4877
4795
  const listener = (raw) => {
4878
4796
  const reported = parseChainId(raw);
4879
4797
  debugLog("wc-switch", "wallet reported chain", {
4880
4798
  reported,
4881
4799
  holding: chainId,
4882
- resends
4800
+ repins
4883
4801
  });
4884
4802
  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", {
4803
+ repins += 1;
4804
+ try {
4805
+ core.setDefaultChain(`eip155:${chainId}`);
4806
+ } catch (error) {
4807
+ debugLog("wc-switch", "session re-pin failed", {
4889
4808
  error: error instanceof Error ? error.message : String(error)
4890
- })
4891
- );
4809
+ });
4810
+ }
4892
4811
  };
4893
4812
  const release = () => {
4894
4813
  clearTimeout(timer);
@@ -4902,7 +4821,7 @@ function holdChain(core, provider, chainId) {
4902
4821
  holds.set(core.session.topic, release);
4903
4822
  }
4904
4823
  function withWalletConnectSwitch(provider) {
4905
- if (!walletConnectCore(provider)) return provider;
4824
+ if (!walletConnectSession(provider)) return provider;
4906
4825
  const target = provider;
4907
4826
  const request2 = async (args) => {
4908
4827
  if (args?.method !== "wallet_switchEthereumChain") {
@@ -4934,7 +4853,7 @@ function makeSponsoredWethCallback(deps) {
4934
4853
  if (!token) {
4935
4854
  throw new OwneyError(
4936
4855
  "CHAIN_UNSUPPORTED",
4937
- `No sponsored ${deps.assetSymbol} configured for chain ${chainId}`
4856
+ `No sponsored WETH configured for chain ${chainId}`
4938
4857
  );
4939
4858
  }
4940
4859
  const amountWei = BigInt(amount);
@@ -4947,14 +4866,14 @@ function makeSponsoredWethCallback(deps) {
4947
4866
  if (balance < amountWei) {
4948
4867
  throw new OwneyError(
4949
4868
  "DEPOSIT_INSUFFICIENT_BALANCE",
4950
- `Insufficient ${deps.assetSymbol} balance for this deposit.`,
4869
+ "Insufficient WETH balance for this deposit.",
4951
4870
  { token, chainId: cid, balance: balance.toString(), amount }
4952
4871
  );
4953
4872
  }
4954
4873
  } catch (err) {
4955
4874
  if (err instanceof OwneyError) throw err;
4956
4875
  console.warn(
4957
- `[owney-sdk] ${deps.assetSymbol} balance pre-check failed (non-fatal):`,
4876
+ "[owney-sdk] WETH balance pre-check failed (non-fatal):",
4958
4877
  err instanceof Error ? err.message : String(err)
4959
4878
  );
4960
4879
  }
@@ -4966,7 +4885,7 @@ function makeSponsoredWethCallback(deps) {
4966
4885
  if (allowance < amountWei) {
4967
4886
  throw new OwneyError(
4968
4887
  "PERMIT2_APPROVAL_REQUIRED",
4969
- `${deps.assetSymbol} gasless deposits need a one-time Permit2 approval; call approvePermit2() first`,
4888
+ "WETH gasless deposits need a one-time Permit2 approval; call approvePermit2() first",
4970
4889
  { token, chainId: cid, allowance: allowance.toString(), amount }
4971
4890
  );
4972
4891
  }
@@ -5153,22 +5072,8 @@ var SPONSORED_WETH_BY_CHAIN = {
5153
5072
  42161: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
5154
5073
  1: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
5155
5074
  };
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
5075
  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;
5076
+ return (asset === "WETH" || asset === "USDC") && appCallback === void 0 && error instanceof OwneyError && error.code === "SPONSOR_REQUEST_FAILED" && error.details?.safeToFallback === true;
5172
5077
  }
5173
5078
  var OwneySDK = class {
5174
5079
  agents = /* @__PURE__ */ new Map();
@@ -5191,8 +5096,9 @@ var OwneySDK = class {
5191
5096
  userPoolCustomization = false;
5192
5097
  routingApiBaseUrl;
5193
5098
  referralSource;
5194
- cachedSponsoredCallbacks = /* @__PURE__ */ new Map();
5195
- cachedPermit2SponsoredCallbacks = /* @__PURE__ */ new Map();
5099
+ sessionStore;
5100
+ cachedSponsoredCallback = null;
5101
+ cachedWethSponsoredCallback = null;
5196
5102
  paymasterServiceUrl;
5197
5103
  cachedSponsoredCallsCallbacks = /* @__PURE__ */ new Map();
5198
5104
  agentReads = new AgentReads();
@@ -5214,6 +5120,7 @@ var OwneySDK = class {
5214
5120
  this.routingApiBaseUrl = config.routingApiBaseUrl;
5215
5121
  this.paymasterServiceUrl = config.paymasterServiceUrl;
5216
5122
  this.referralSource = config.referralSource;
5123
+ this.sessionStore = config.sessionStore;
5217
5124
  this.userPoolCustomization = config.userPoolCustomization ?? false;
5218
5125
  }
5219
5126
  /**
@@ -5240,8 +5147,8 @@ var OwneySDK = class {
5240
5147
  walletAddress,
5241
5148
  chainId: null
5242
5149
  };
5243
- this.cachedSponsoredCallbacks.clear();
5244
- this.cachedPermit2SponsoredCallbacks.clear();
5150
+ this.cachedSponsoredCallback = null;
5151
+ this.cachedWethSponsoredCallback = null;
5245
5152
  this.cachedSponsoredCallsCallbacks.clear();
5246
5153
  }
5247
5154
  /**
@@ -5257,8 +5164,8 @@ var OwneySDK = class {
5257
5164
  this.agentReads.clearInFlight();
5258
5165
  this.activationChecks.clear();
5259
5166
  this.state = null;
5260
- this.cachedSponsoredCallbacks.clear();
5261
- this.cachedPermit2SponsoredCallbacks.clear();
5167
+ this.cachedSponsoredCallback = null;
5168
+ this.cachedWethSponsoredCallback = null;
5262
5169
  this.cachedSponsoredCallsCallbacks.clear();
5263
5170
  }
5264
5171
  isAgentDisabled(agentId) {
@@ -5308,9 +5215,9 @@ var OwneySDK = class {
5308
5215
  * provider with viem `custom(provider)` to read token meta and sign the
5309
5216
  * `TransferWithAuthorization`, then POSTs to the sponsor API.
5310
5217
  */
5311
- getDefaultSponsoredCallback(asset, onApproved) {
5312
- const cached = this.cachedSponsoredCallbacks.get(asset);
5313
- if (!onApproved && cached) return cached;
5218
+ getDefaultSponsoredCallback(onApproved) {
5219
+ if (!onApproved && this.cachedSponsoredCallback)
5220
+ return this.cachedSponsoredCallback;
5314
5221
  const provider = this.requireConnectedProvider();
5315
5222
  const owner = this.state.walletAddress;
5316
5223
  const callback = makeSponsoredDepositCallback({
@@ -5318,7 +5225,7 @@ var OwneySDK = class {
5318
5225
  baseUrl: this.routingApiBaseUrl,
5319
5226
  ownerAddress: owner,
5320
5227
  onApproved,
5321
- tokenAddressByChain: sponsoredTokenMap(asset),
5228
+ tokenAddressByChain: SPONSORED_USDC_BY_CHAIN,
5322
5229
  // Casts work around viem's chain-narrowed Client vs the generic
5323
5230
  // PublicClient/WalletClient param types — structurally identical at
5324
5231
  // runtime, but the two share a name TS treats as unrelated.
@@ -5335,13 +5242,14 @@ var OwneySDK = class {
5335
5242
  transport: custom(provider)
5336
5243
  })
5337
5244
  });
5338
- if (!onApproved) this.cachedSponsoredCallbacks.set(asset, callback);
5245
+ if (!onApproved) this.cachedSponsoredCallback = callback;
5339
5246
  return callback;
5340
5247
  }
5341
5248
  /**
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.
5249
+ * Lazily builds (and caches) the default Permit2 sponsored WETH deposit
5250
+ * callback used when the caller omits `depositCallback` for a WETH
5251
+ * deposit. Mirrors `getDefaultSponsoredCallback()` but signs a Permit2
5252
+ * `PermitTransferFrom` instead of an EIP-3009 authorization.
5345
5253
  */
5346
5254
  getDefaultSponsoredCallsCallback(asset, onApproved) {
5347
5255
  const cached = this.cachedSponsoredCallsCallbacks.get(asset);
@@ -5352,20 +5260,20 @@ var OwneySDK = class {
5352
5260
  ownerAddress: this.state.walletAddress,
5353
5261
  paymasterServiceUrl: this.paymasterServiceUrl,
5354
5262
  onApproved,
5355
- tokenAddressByChain: sponsoredTokenMap(asset)
5263
+ tokenAddressByChain: asset === "WETH" ? SPONSORED_WETH_BY_CHAIN : SPONSORED_USDC_BY_CHAIN
5356
5264
  });
5357
5265
  if (!onApproved) this.cachedSponsoredCallsCallbacks.set(asset, callback);
5358
5266
  return callback;
5359
5267
  }
5360
5268
  /**
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.
5269
+ * Lazily builds (and caches) the default Permit2 sponsored WETH deposit
5270
+ * callback used when the caller omits `depositCallback` for a WETH deposit.
5271
+ * Mirrors `getDefaultSponsoredCallback()` but signs a Permit2
5272
+ * `PermitTransferFrom` instead of an EIP-3009 authorization.
5365
5273
  */
5366
- getDefaultPermit2SponsoredCallback(asset, onApproved) {
5367
- const cached = this.cachedPermit2SponsoredCallbacks.get(asset);
5368
- if (!onApproved && cached) return cached;
5274
+ getDefaultWethSponsoredCallback(onApproved) {
5275
+ if (!onApproved && this.cachedWethSponsoredCallback)
5276
+ return this.cachedWethSponsoredCallback;
5369
5277
  const provider = this.requireConnectedProvider();
5370
5278
  const owner = this.state.walletAddress;
5371
5279
  const callback = makeSponsoredWethCallback({
@@ -5373,8 +5281,7 @@ var OwneySDK = class {
5373
5281
  baseUrl: this.routingApiBaseUrl,
5374
5282
  ownerAddress: owner,
5375
5283
  onApproved,
5376
- tokenAddressByChain: sponsoredTokenMap(asset),
5377
- assetSymbol: asset,
5284
+ tokenAddressByChain: SPONSORED_WETH_BY_CHAIN,
5378
5285
  // Casts work around viem's chain-narrowed Client vs the generic
5379
5286
  // PublicClient/WalletClient param types — structurally identical at
5380
5287
  // runtime, but the two share a name TS treats as unrelated.
@@ -5391,7 +5298,7 @@ var OwneySDK = class {
5391
5298
  transport: custom(provider)
5392
5299
  })
5393
5300
  });
5394
- if (!onApproved) this.cachedPermit2SponsoredCallbacks.set(asset, callback);
5301
+ if (!onApproved) this.cachedWethSponsoredCallback = callback;
5395
5302
  return callback;
5396
5303
  }
5397
5304
  getAgent(agentId) {
@@ -5487,7 +5394,12 @@ var OwneySDK = class {
5487
5394
  }
5488
5395
  createAgent(agentId, key2) {
5489
5396
  if (agentId === "zyfai") {
5490
- return new ZyfaiAgent(key2, this.zyfaiRpcUrls, this.referralSource);
5397
+ return new ZyfaiAgent(
5398
+ key2,
5399
+ this.zyfaiRpcUrls,
5400
+ this.referralSource,
5401
+ this.sessionStore
5402
+ );
5491
5403
  }
5492
5404
  return null;
5493
5405
  }
@@ -5649,8 +5561,7 @@ var OwneySDK = class {
5649
5561
  }
5650
5562
  const state = this.requireState();
5651
5563
  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));
5564
+ const effectiveCallback = depositCallback ?? (this.paymasterServiceUrl ? this.getDefaultSponsoredCallsCallback(asset, onApproved) : asset === "WETH" ? this.getDefaultWethSponsoredCallback(onApproved) : this.getDefaultSponsoredCallback(onApproved));
5654
5565
  if (agentId) {
5655
5566
  if (this.isAgentDisabled(agentId)) {
5656
5567
  throw new OwneyError(
@@ -5764,16 +5675,15 @@ var OwneySDK = class {
5764
5675
  *
5765
5676
  * 1. Missing Permit2 allowance: when the app did not supply its own
5766
5677
  * 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.
5678
+ * WETH deposit, this is the wallet's first gasless WETH deposit. We send
5679
+ * the one-time (user-paid) Permit2 approval via `approvePermit2()` and
5680
+ * retry the SAME sponsored attempt once. Bounded to one approval attempt
5681
+ * per call so a wallet/agent that keeps reporting the allowance as
5682
+ * missing can't loop forever. If `approvePermit2()` itself throws (e.g.
5773
5683
  * the user rejects the wallet prompt), that error propagates as-is —
5774
5684
  * the user said no to a transaction, so we must not turn around and ask
5775
5685
  * them to pay for a different one via the fallback below.
5776
- * 2. `shouldFallbackToUserPaid`: the SDK's own sponsor path failed at
5686
+ * 2. `shouldFallbackToUserPaid`: the SDK's own WETH sponsor path failed at
5777
5687
  * the infrastructure layer in a provably safe-to-retry way, so we warn
5778
5688
  * and retry once with `undefined`, falling through to a user-paid
5779
5689
  * native deposit. This still applies after a successful Permit2
@@ -5802,12 +5712,12 @@ var OwneySDK = class {
5802
5712
  try {
5803
5713
  return await attempt(effectiveCallback);
5804
5714
  } catch (error) {
5805
- if (!approvalAttempted && appCallback === void 0 && isPermit2Asset(asset) && error instanceof OwneyError && error.code === "PERMIT2_APPROVAL_REQUIRED") {
5715
+ if (!approvalAttempted && appCallback === void 0 && asset === "WETH" && error instanceof OwneyError && error.code === "PERMIT2_APPROVAL_REQUIRED") {
5806
5716
  approvalAttempted = true;
5807
5717
  console.warn(
5808
- `[owney-sdk] First ${asset} deposit: sending one-time Permit2 approval...`
5718
+ "[owney-sdk] First WETH deposit: sending one-time Permit2 approval..."
5809
5719
  );
5810
- await this.approvePermit2(asset);
5720
+ await this.approvePermit2();
5811
5721
  continue;
5812
5722
  }
5813
5723
  if (!shouldFallbackToUserPaid(error, asset, appCallback)) throw error;
@@ -6244,45 +6154,22 @@ var OwneySDK = class {
6244
6154
  functionName: "allowance",
6245
6155
  args: [state.walletAddress, spender]
6246
6156
  }),
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
- ),
6157
+ approve: async (spender, amount) => {
6158
+ const hash = await wallet.writeContract({
6159
+ address: quote.src.address,
6160
+ abi: ERC20_ALLOWANCE_ABI,
6161
+ functionName: "approve",
6162
+ args: [spender, amount],
6163
+ account: state.walletAddress,
6164
+ chain: srcChain
6165
+ });
6166
+ await srcPublic.waitForTransactionReceipt({
6167
+ hash,
6168
+ confirmations: 1,
6169
+ timeout: receiptTimeoutMs(quote.src.chainId)
6170
+ });
6171
+ return hash;
6172
+ },
6286
6173
  ensureChain: (chainId) => this.ensureSwapChain(chainId),
6287
6174
  /**
6288
6175
  * Sign the approval instead of paying for it. Null means the token
@@ -6370,33 +6257,30 @@ var OwneySDK = class {
6370
6257
  * figure directly. It is the entire arrival, so there is no slack: anything
6371
6258
  * that spends the target asset between the two fails the deposit outright.
6372
6259
  *
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.
6260
+ * Something does. A first WETH deposit needs a one-time Permit2 approval,
6261
+ * and that approval is a transaction. A wallet holding no native gas token -
6262
+ * the normal state of someone who just swapped everything INTO WETH - pays
6263
+ * for it out of the WETH. The deposit then asked for ~2e12 wei more than was
6264
+ * left and refused with DEPOSIT_INSUFFICIENT_BALANCE, under a wrapper saying
6265
+ * the funds were safe but unadded (ROUT-242).
6381
6266
  *
6382
6267
  * So the approval happens here, before the amount is settled, and the amount
6383
6268
  * comes from a read taken after it. Two things this deliberately is not:
6384
6269
  *
6385
6270
  * - 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.
6271
+ * balance, so a wallet already holding WETH reads far above it; depositing
6272
+ * the balance would move funds the user never offered. The arrival is the
6273
+ * ceiling and the balance is only ever allowed to lower it.
6274
+ * - It does not touch USDC, which moves on signed typed data and so spends
6275
+ * nothing of the user's in between, nor a paymaster-configured client,
6276
+ * where the sponsor covers the transfer and Permit2 never applies.
6393
6277
  */
6394
6278
  async settleSwapDepositAmount(chainId, token, symbol, received) {
6395
- if (!isPermit2Asset(symbol) || this.paymasterServiceUrl) {
6279
+ if (symbol !== "WETH" || this.paymasterServiceUrl) {
6396
6280
  return received.toString();
6397
6281
  }
6398
6282
  const allowance = await this.readTokenPermit2Allowance(chainId, token);
6399
- if (allowance < received) await this.approvePermit2(symbol);
6283
+ if (allowance < received) await this.approvePermit2();
6400
6284
  const balance = await this.readTokenBalance(chainId, token);
6401
6285
  return (balance < received ? balance : received).toString();
6402
6286
  }
@@ -6561,10 +6445,7 @@ var OwneySDK = class {
6561
6445
  );
6562
6446
  }
6563
6447
  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;
6448
+ const token = entry.symbol === "WETH" ? SPONSORED_WETH_BY_CHAIN[entry.chainId] : void 0;
6568
6449
  const amount = token ? await this.settleSwapDepositAmount(
6569
6450
  entry.chainId,
6570
6451
  token,
@@ -7717,7 +7598,7 @@ var OwneySDK = class {
7717
7598
  /**
7718
7599
  * Ensure the given asset uses backend protocol auto-selection for the active
7719
7600
  * chain's account. No-op (returns false) for agents that don't support it.
7720
- * @param asset - Asset symbol (e.g. "USDC").
7601
+ * @param asset - "USDC" or "WETH".
7721
7602
  * @param agentId - Agent to target. Defaults to "zyfai".
7722
7603
  * @returns whether a profile write occurred.
7723
7604
  */
@@ -7742,28 +7623,23 @@ var OwneySDK = class {
7742
7623
  return pending;
7743
7624
  }
7744
7625
  /**
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.
7626
+ * One-time, user-paid approval of Permit2 on the sponsored WETH token for
7627
+ * the active chain. Required once per wallet per chain before gasless WETH
7628
+ * deposits; afterwards deposit() is signature-only. Resolves only after the
7629
+ * approval transaction is mined (1 confirmation), so a subsequent deposit()
7630
+ * will see the new allowance; throws if the transaction reverted.
7756
7631
  * @returns the approval transaction hash.
7757
7632
  */
7758
7633
  async approvePermit2(asset = "WETH") {
7634
+ void asset;
7759
7635
  const state = this.requireState();
7760
7636
  const chainId = this.requireChainId();
7761
- this.validateAssetSupport(this.getAgent("zyfai"), chainId, asset);
7762
- const token = sponsoredTokenMap(asset)[chainId];
7637
+ this.validateAssetSupport(this.getAgent("zyfai"), chainId, "WETH");
7638
+ const token = SPONSORED_WETH_BY_CHAIN[chainId];
7763
7639
  if (!token) {
7764
7640
  throw new OwneyError(
7765
7641
  "CHAIN_UNSUPPORTED",
7766
- `No sponsored ${asset} on chain ${chainId}`
7642
+ `No sponsored WETH on chain ${chainId}`
7767
7643
  );
7768
7644
  }
7769
7645
  const provider = this.requireConnectedProvider();
@@ -7781,52 +7657,22 @@ var OwneySDK = class {
7781
7657
  wallet,
7782
7658
  chainId
7783
7659
  );
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
- );
7660
+ const hash = await wallet.writeContract({
7661
+ address: token,
7662
+ abi: ERC20_ALLOWANCE_ABI,
7663
+ functionName: "approve",
7664
+ args: [PERMIT2_ADDRESS, MAX_UINT256],
7665
+ account: state.walletAddress,
7666
+ chain: VIEM_CHAIN2[chainId]
7805
7667
  });
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
- }
7668
+ const receipt = await publicClient.waitForTransactionReceipt({
7669
+ hash,
7670
+ confirmations: 1
7829
7671
  });
7672
+ if (receipt.status !== "success") {
7673
+ throw new Error(`Permit2 approval reverted (tx ${hash})`);
7674
+ }
7675
+ return hash;
7830
7676
  }
7831
7677
  // --- Discovery (no wallet required) ---
7832
7678
  /**