@owney/sdk 0.7.28 → 0.7.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -509,9 +509,18 @@ function netApy(net, gross, field) {
509
509
  debugLog("zyfai:apy", `gross fallback for ${field}`, { gross });
510
510
  return gross;
511
511
  }
512
- function rawPoolApyForChain(entry, chainId, tokenSymbol) {
512
+ function usdPerUnit(tokenSymbol, prices) {
513
+ const symbol = tokenSymbol?.toUpperCase();
514
+ if (symbol === "USDC") return 1;
515
+ const price = symbol ? prices?.[symbol] : void 0;
516
+ return typeof price === "number" && Number.isFinite(price) && price > 0 ? price : void 0;
517
+ }
518
+ function rawPoolApyForChain(entry, chainId, tokenSymbol, usdPrices) {
513
519
  let weightedSum = 0;
514
520
  let totalBalance = 0;
521
+ let usdWeightedSum = 0;
522
+ let usdTotal = 0;
523
+ let unpriced = false;
515
524
  for (const p of entry.positions ?? []) {
516
525
  if (chainId !== void 0 && p.chainId !== chainId) continue;
517
526
  if (tokenSymbol && p.tokenSymbol?.toUpperCase() !== tokenSymbol.toUpperCase()) continue;
@@ -520,7 +529,16 @@ function rawPoolApyForChain(entry, chainId, tokenSymbol) {
520
529
  if (balance <= 0 || typeof apy !== "number") continue;
521
530
  weightedSum += apy * balance;
522
531
  totalBalance += balance;
532
+ if (tokenSymbol) continue;
533
+ const price = usdPerUnit(p.tokenSymbol, usdPrices);
534
+ if (price === void 0) {
535
+ unpriced = true;
536
+ continue;
537
+ }
538
+ usdWeightedSum += apy * balance * price;
539
+ usdTotal += balance * price;
523
540
  }
541
+ if (!tokenSymbol && !unpriced && usdTotal > 0) return usdWeightedSum / usdTotal;
524
542
  return totalBalance > 0 ? weightedSum / totalBalance : null;
525
543
  }
526
544
  function historyCoverage(raw) {
@@ -555,10 +573,10 @@ function historyCoverage(raw) {
555
573
  pairs: [...pairs.values()]
556
574
  };
557
575
  }
558
- function mapApyHistory(raw, chainId, tokenSymbol) {
576
+ function mapApyHistory(raw, chainId, tokenSymbol, usdPrices) {
559
577
  const history = Object.entries(raw.history ?? {}).map(([date, entry]) => ({
560
578
  date,
561
- apy: rawPoolApyForChain(entry, chainId, tokenSymbol),
579
+ apy: rawPoolApyForChain(entry, chainId, tokenSymbol, usdPrices),
562
580
  // Provider position balances are treated as decimal amounts of the
563
581
  // selected token. Carry its unit dynamically for every asset; never
564
582
  // attach a token unit to an unscoped mix of assets.
@@ -1187,6 +1205,15 @@ function assemblePoolCatalog(protocols, poolsByProtocol, asset, chains) {
1187
1205
  var ERC7579_IS_MODULE_INSTALLED_ABI = (0, import_viem.parseAbi)([
1188
1206
  "function isModuleInstalled(uint256 moduleTypeId, address module, bytes additionalContext) view returns (bool)"
1189
1207
  ]);
1208
+ var CHAINLINK_ETH_USD_FEED = {
1209
+ 8453: "0x71041dddad3595F9CEd3DcCFBe3D1F4b0a16Bb70",
1210
+ 42161: "0x639Fe6ab55C921f74e7fac1ee960C0B6293ba612",
1211
+ 1: "0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419"
1212
+ };
1213
+ var CHAINLINK_ABI = (0, import_viem.parseAbi)([
1214
+ "function latestRoundData() view returns (uint80, int256, uint256, uint256, uint80)"
1215
+ ]);
1216
+ var ETH_USD_TTL_MS = 6e4;
1190
1217
  var DEFAULT_ZYFAI_RPC_URLS = {
1191
1218
  8453: "https://base-mainnet.g.alchemy.com/v2/ZWyVU-9XfS3z8Rn-xkq7V",
1192
1219
  42161: "https://arb-mainnet.g.alchemy.com/v2/ZWyVU-9XfS3z8Rn-xkq7V",
@@ -1252,6 +1279,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
1252
1279
  // successful decode is cached forever; failures are NOT cached so a transient
1253
1280
  // RPC error retries on the next fetch.
1254
1281
  withdrawAmountCache = /* @__PURE__ */ new Map();
1282
+ ethUsd = null;
1255
1283
  earningsReads = /* @__PURE__ */ new Map();
1256
1284
  earningsRefreshes = /* @__PURE__ */ new Map();
1257
1285
  earningsSnapshot = null;
@@ -1529,12 +1557,16 @@ var ZyfaiAgent = class _ZyfaiAgent {
1529
1557
  }
1530
1558
  // --- IAgent: Account lifecycle ---
1531
1559
  async activateAgent(state, chainId) {
1560
+ const startedAt = Date.now();
1532
1561
  try {
1533
1562
  debugLog("zyfai:activation", "starting", {
1534
1563
  walletAddress: state.walletAddress,
1535
1564
  chainId
1536
1565
  });
1537
1566
  await this.connectAuth(state, chainId);
1567
+ debugLog("zyfai:activation", "signed in", {
1568
+ ms: Date.now() - startedAt
1569
+ });
1538
1570
  const validChainId = isValidChainId(chainId);
1539
1571
  await Promise.all([
1540
1572
  this.ensureProtocolsSynced(validChainId, "USDC"),
@@ -1545,7 +1577,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
1545
1577
  // validator, so pool-wallet users see no prompt. Non-fatal.
1546
1578
  this.ensureSessionKeyIfDeployed(validChainId)
1547
1579
  ]);
1548
- debugLog("zyfai:activation", "completed", { chainId: validChainId });
1580
+ debugLog("zyfai:activation", "completed", {
1581
+ chainId: validChainId,
1582
+ ms: Date.now() - startedAt
1583
+ });
1549
1584
  } catch (error) {
1550
1585
  throw error;
1551
1586
  }
@@ -2231,8 +2266,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
2231
2266
  }
2232
2267
  // --- IAgent: Portfolio reads ---
2233
2268
  async getBalances(state, chainId) {
2269
+ const startedAt = Date.now();
2234
2270
  const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
2235
2271
  const raw = await this.sdk.getPortfolio(this.getAddress());
2272
+ debugLog("zyfai:balances", "read", { ms: Date.now() - startedAt });
2236
2273
  return mapBalances(raw, validChainId, smartWallet);
2237
2274
  }
2238
2275
  earningsKey(state, chainId, smartWallet) {
@@ -2290,10 +2327,41 @@ var ZyfaiAgent = class _ZyfaiAgent {
2290
2327
  return pending;
2291
2328
  }
2292
2329
  async getAccountApy(state, chainId, days, tokenSymbol, scopeChainId) {
2293
- const { smartWallet } = await this.resolveSmartWallet(state, chainId);
2294
- const raw = await this.sdk.getDailyApyHistory(smartWallet, days);
2330
+ const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
2331
+ const [raw, ethUsd] = await Promise.all([
2332
+ this.sdk.getDailyApyHistory(smartWallet, days),
2333
+ tokenSymbol ? void 0 : this.readEthUsd(validChainId)
2334
+ ]);
2295
2335
  const scope = scopeChainId === null ? void 0 : scopeChainId ?? chainId;
2296
- return mapApyHistory(raw, scope, tokenSymbol);
2336
+ const usdPrices = ethUsd ? { WETH: ethUsd, ETH: ethUsd } : void 0;
2337
+ return mapApyHistory(raw, scope, tokenSymbol, usdPrices);
2338
+ }
2339
+ /**
2340
+ * Today's ETH/USD from Chainlink, cached for a minute. Every day of the
2341
+ * series is weighted at this one price: each day's mix is right, but ETH's
2342
+ * move over the window is not reflected (ROUT-682). Undefined on failure,
2343
+ * which leaves the series on token-amount weighting rather than failing it.
2344
+ */
2345
+ async readEthUsd(chainId) {
2346
+ if (this.ethUsd && Date.now() - this.ethUsd.at < ETH_USD_TTL_MS) {
2347
+ return this.ethUsd.price;
2348
+ }
2349
+ try {
2350
+ const [, answer] = await this.getPublicClient(chainId).readContract({
2351
+ address: CHAINLINK_ETH_USD_FEED[chainId],
2352
+ abi: CHAINLINK_ABI,
2353
+ functionName: "latestRoundData"
2354
+ });
2355
+ const price = Number(answer) / 1e8;
2356
+ if (!Number.isFinite(price) || price <= 0) return void 0;
2357
+ this.ethUsd = { price, at: Date.now() };
2358
+ return price;
2359
+ } catch (err) {
2360
+ debugLog("zyfai:apy", "ETH/USD read failed; token-amount weighting", {
2361
+ err
2362
+ });
2363
+ return void 0;
2364
+ }
2297
2365
  }
2298
2366
  async getDailyEarnings(state, chainId, days, tokenSymbol) {
2299
2367
  const { smartWallet } = await this.resolveSmartWallet(state, chainId);
@@ -5034,8 +5102,9 @@ var OwneySDK = class {
5034
5102
  * that support the given chainId (incompatible agents are silently skipped).
5035
5103
  * If provided, ALL specified agents must support the chainId or the call
5036
5104
  * throws before activating any agent.
5105
+ * @param options - Optional. `onAgentsSelected` fires once reads can start.
5037
5106
  */
5038
- async activateAgent(chainId, agentId) {
5107
+ async activateAgent(chainId, agentId, options = {}) {
5039
5108
  const state = this.requireState();
5040
5109
  await this.ensureAgentsInitialized();
5041
5110
  if (agentId !== void 0) {
@@ -5071,6 +5140,7 @@ var OwneySDK = class {
5071
5140
  this.activeAgents.add(id);
5072
5141
  }
5073
5142
  state.chainId = chainId;
5143
+ options.onAgentsSelected?.();
5074
5144
  await this.activateAgentsInTurn(agents, state, chainId);
5075
5145
  return;
5076
5146
  }
@@ -5089,6 +5159,7 @@ var OwneySDK = class {
5089
5159
  this.activeAgents.add(agent.id);
5090
5160
  }
5091
5161
  state.chainId = chainId;
5162
+ options.onAgentsSelected?.();
5092
5163
  const enabledCompatible = compatible.filter(
5093
5164
  (agent) => !this.isAgentDisabled(agent.id)
5094
5165
  );
package/dist/index.d.cts CHANGED
@@ -326,6 +326,15 @@ type AvailableAgent = {
326
326
  supportedChainIds: readonly number[];
327
327
  supportedAssets: readonly AgentSupportedAssets[];
328
328
  };
329
+ type ActivateAgentOptions = {
330
+ /**
331
+ * Called once the chain and agents are registered, before any agent signs in
332
+ * or runs its setup. From then on reads such as `getBalances` are safe to
333
+ * start: each agent's reads wait on that agent's own sign-in, so they share
334
+ * the activation's one wallet prompt instead of waiting for all of setup.
335
+ */
336
+ onAgentsSelected?: () => void;
337
+ };
329
338
  type AvailableAgentsOptions = {
330
339
  chainId?: number;
331
340
  asset?: Asset;
@@ -1260,8 +1269,9 @@ declare class OwneySDK {
1260
1269
  * that support the given chainId (incompatible agents are silently skipped).
1261
1270
  * If provided, ALL specified agents must support the chainId or the call
1262
1271
  * throws before activating any agent.
1272
+ * @param options - Optional. `onAgentsSelected` fires once reads can start.
1263
1273
  */
1264
- activateAgent(chainId: number, agentId?: AgentId[]): Promise<void>;
1274
+ activateAgent(chainId: number, agentId?: AgentId[], options?: ActivateAgentOptions): Promise<void>;
1265
1275
  /**
1266
1276
  * Activate agents ONE AT A TIME, each followed by its org policy.
1267
1277
  *
@@ -1979,4 +1989,4 @@ type StoredOrder = {
1979
1989
  */
1980
1990
  declare function listOrders(now?: number): StoredOrder[];
1981
1991
 
1982
- export { type AccountAgentApy, type AccountApyOptions, type AccountDailyEarnings, type AgentApy, type AgentApyDetails, type AgentBalance, AgentChainIncompatibleError, type AgentEarnings, type AgentHistoryEntry, type AgentHistoryPosition, type AgentId, AgentNotFoundError, type AgentSupportedAsset, type AgentSupportedAssets, type AgentUserProfile, type AgentWithdrawResult, type AgentsApyOptions, type AllocationAgentApy, type AllocationApyOptions, type ApyByChainAndAsset, type ApyCoverage, type ApyHistoryPoint, type Asset, type AssetDailyEarnings, type AvailableAgent, type AvailableAgentsOptions, type AvailablePool, type ConnectionState, type DailyApyDays, type DailyEarningsOptions, type DailyEarningsPoint, type DepositCallback, type DepositOptions, type HistoryAction, type HistoryFilters, type HistoryOptions, type HistoryTransaction, type IAgent, InvalidHistoryCursorError, type LookbackDays, NotConnectedError, type OrgPoolPolicy, type OrgPoolSelection, type OwneyAccountApy, type OwneyAgentApy, type OwneyAgentHistory, type OwneyAllocationApy, type OwneyBalances, type OwneyDepositResult, type OwneyEarnings, OwneyError, type OwneyErrorCode, type OwneyMultiDepositResult, type OwneyPosition, OwneySDK, type OwneySDKConfig, type OwneySIWXConfig, type OwneySupportedChainId, type OwneySupportedChains, type OwneySupportedTokens, type OwneyToken, type OwneyUserProfile, type OwneyWithdrawAllLeg, type OwneyWithdrawAllResult, type OwneyWithdrawResult, type PendingDeposit, type PoolCatalogProtocol, type PoolSelectionStrategy, type RebalanceLog, type SavedPoolSelection, type SwapChainTokens, type SwapDirection, type SwapOrderStatus, type SwapQuote, type SwapQuoteParams, type SwapRail, type SwapStage, type SwapTokenInfo, type SwapTokenSearchResult, type UserPoolSelection, type UserPoolSelectionRequest, type WithdrawOptions, type WithdrawSwapRecord, type WithdrawSwapStatus, clearWithdrawSwap, createOwneySIWX, listPendingDeposits, listOrders as listPendingSwaps, listWithdrawSwaps, saveWithdrawSwap, setOwneyDebug, subscribeWithdrawSwaps, updateWithdrawSwap };
1992
+ export { type AccountAgentApy, type AccountApyOptions, type AccountDailyEarnings, type ActivateAgentOptions, type AgentApy, type AgentApyDetails, type AgentBalance, AgentChainIncompatibleError, type AgentEarnings, type AgentHistoryEntry, type AgentHistoryPosition, type AgentId, AgentNotFoundError, type AgentSupportedAsset, type AgentSupportedAssets, type AgentUserProfile, type AgentWithdrawResult, type AgentsApyOptions, type AllocationAgentApy, type AllocationApyOptions, type ApyByChainAndAsset, type ApyCoverage, type ApyHistoryPoint, type Asset, type AssetDailyEarnings, type AvailableAgent, type AvailableAgentsOptions, type AvailablePool, type ConnectionState, type DailyApyDays, type DailyEarningsOptions, type DailyEarningsPoint, type DepositCallback, type DepositOptions, type HistoryAction, type HistoryFilters, type HistoryOptions, type HistoryTransaction, type IAgent, InvalidHistoryCursorError, type LookbackDays, NotConnectedError, type OrgPoolPolicy, type OrgPoolSelection, type OwneyAccountApy, type OwneyAgentApy, type OwneyAgentHistory, type OwneyAllocationApy, type OwneyBalances, type OwneyDepositResult, type OwneyEarnings, OwneyError, type OwneyErrorCode, type OwneyMultiDepositResult, type OwneyPosition, OwneySDK, type OwneySDKConfig, type OwneySIWXConfig, type OwneySupportedChainId, type OwneySupportedChains, type OwneySupportedTokens, type OwneyToken, type OwneyUserProfile, type OwneyWithdrawAllLeg, type OwneyWithdrawAllResult, type OwneyWithdrawResult, type PendingDeposit, type PoolCatalogProtocol, type PoolSelectionStrategy, type RebalanceLog, type SavedPoolSelection, type SwapChainTokens, type SwapDirection, type SwapOrderStatus, type SwapQuote, type SwapQuoteParams, type SwapRail, type SwapStage, type SwapTokenInfo, type SwapTokenSearchResult, type UserPoolSelection, type UserPoolSelectionRequest, type WithdrawOptions, type WithdrawSwapRecord, type WithdrawSwapStatus, clearWithdrawSwap, createOwneySIWX, listPendingDeposits, listOrders as listPendingSwaps, listWithdrawSwaps, saveWithdrawSwap, setOwneyDebug, subscribeWithdrawSwaps, updateWithdrawSwap };
package/dist/index.d.ts CHANGED
@@ -326,6 +326,15 @@ type AvailableAgent = {
326
326
  supportedChainIds: readonly number[];
327
327
  supportedAssets: readonly AgentSupportedAssets[];
328
328
  };
329
+ type ActivateAgentOptions = {
330
+ /**
331
+ * Called once the chain and agents are registered, before any agent signs in
332
+ * or runs its setup. From then on reads such as `getBalances` are safe to
333
+ * start: each agent's reads wait on that agent's own sign-in, so they share
334
+ * the activation's one wallet prompt instead of waiting for all of setup.
335
+ */
336
+ onAgentsSelected?: () => void;
337
+ };
329
338
  type AvailableAgentsOptions = {
330
339
  chainId?: number;
331
340
  asset?: Asset;
@@ -1260,8 +1269,9 @@ declare class OwneySDK {
1260
1269
  * that support the given chainId (incompatible agents are silently skipped).
1261
1270
  * If provided, ALL specified agents must support the chainId or the call
1262
1271
  * throws before activating any agent.
1272
+ * @param options - Optional. `onAgentsSelected` fires once reads can start.
1263
1273
  */
1264
- activateAgent(chainId: number, agentId?: AgentId[]): Promise<void>;
1274
+ activateAgent(chainId: number, agentId?: AgentId[], options?: ActivateAgentOptions): Promise<void>;
1265
1275
  /**
1266
1276
  * Activate agents ONE AT A TIME, each followed by its org policy.
1267
1277
  *
@@ -1979,4 +1989,4 @@ type StoredOrder = {
1979
1989
  */
1980
1990
  declare function listOrders(now?: number): StoredOrder[];
1981
1991
 
1982
- export { type AccountAgentApy, type AccountApyOptions, type AccountDailyEarnings, type AgentApy, type AgentApyDetails, type AgentBalance, AgentChainIncompatibleError, type AgentEarnings, type AgentHistoryEntry, type AgentHistoryPosition, type AgentId, AgentNotFoundError, type AgentSupportedAsset, type AgentSupportedAssets, type AgentUserProfile, type AgentWithdrawResult, type AgentsApyOptions, type AllocationAgentApy, type AllocationApyOptions, type ApyByChainAndAsset, type ApyCoverage, type ApyHistoryPoint, type Asset, type AssetDailyEarnings, type AvailableAgent, type AvailableAgentsOptions, type AvailablePool, type ConnectionState, type DailyApyDays, type DailyEarningsOptions, type DailyEarningsPoint, type DepositCallback, type DepositOptions, type HistoryAction, type HistoryFilters, type HistoryOptions, type HistoryTransaction, type IAgent, InvalidHistoryCursorError, type LookbackDays, NotConnectedError, type OrgPoolPolicy, type OrgPoolSelection, type OwneyAccountApy, type OwneyAgentApy, type OwneyAgentHistory, type OwneyAllocationApy, type OwneyBalances, type OwneyDepositResult, type OwneyEarnings, OwneyError, type OwneyErrorCode, type OwneyMultiDepositResult, type OwneyPosition, OwneySDK, type OwneySDKConfig, type OwneySIWXConfig, type OwneySupportedChainId, type OwneySupportedChains, type OwneySupportedTokens, type OwneyToken, type OwneyUserProfile, type OwneyWithdrawAllLeg, type OwneyWithdrawAllResult, type OwneyWithdrawResult, type PendingDeposit, type PoolCatalogProtocol, type PoolSelectionStrategy, type RebalanceLog, type SavedPoolSelection, type SwapChainTokens, type SwapDirection, type SwapOrderStatus, type SwapQuote, type SwapQuoteParams, type SwapRail, type SwapStage, type SwapTokenInfo, type SwapTokenSearchResult, type UserPoolSelection, type UserPoolSelectionRequest, type WithdrawOptions, type WithdrawSwapRecord, type WithdrawSwapStatus, clearWithdrawSwap, createOwneySIWX, listPendingDeposits, listOrders as listPendingSwaps, listWithdrawSwaps, saveWithdrawSwap, setOwneyDebug, subscribeWithdrawSwaps, updateWithdrawSwap };
1992
+ export { type AccountAgentApy, type AccountApyOptions, type AccountDailyEarnings, type ActivateAgentOptions, type AgentApy, type AgentApyDetails, type AgentBalance, AgentChainIncompatibleError, type AgentEarnings, type AgentHistoryEntry, type AgentHistoryPosition, type AgentId, AgentNotFoundError, type AgentSupportedAsset, type AgentSupportedAssets, type AgentUserProfile, type AgentWithdrawResult, type AgentsApyOptions, type AllocationAgentApy, type AllocationApyOptions, type ApyByChainAndAsset, type ApyCoverage, type ApyHistoryPoint, type Asset, type AssetDailyEarnings, type AvailableAgent, type AvailableAgentsOptions, type AvailablePool, type ConnectionState, type DailyApyDays, type DailyEarningsOptions, type DailyEarningsPoint, type DepositCallback, type DepositOptions, type HistoryAction, type HistoryFilters, type HistoryOptions, type HistoryTransaction, type IAgent, InvalidHistoryCursorError, type LookbackDays, NotConnectedError, type OrgPoolPolicy, type OrgPoolSelection, type OwneyAccountApy, type OwneyAgentApy, type OwneyAgentHistory, type OwneyAllocationApy, type OwneyBalances, type OwneyDepositResult, type OwneyEarnings, OwneyError, type OwneyErrorCode, type OwneyMultiDepositResult, type OwneyPosition, OwneySDK, type OwneySDKConfig, type OwneySIWXConfig, type OwneySupportedChainId, type OwneySupportedChains, type OwneySupportedTokens, type OwneyToken, type OwneyUserProfile, type OwneyWithdrawAllLeg, type OwneyWithdrawAllResult, type OwneyWithdrawResult, type PendingDeposit, type PoolCatalogProtocol, type PoolSelectionStrategy, type RebalanceLog, type SavedPoolSelection, type SwapChainTokens, type SwapDirection, type SwapOrderStatus, type SwapQuote, type SwapQuoteParams, type SwapRail, type SwapStage, type SwapTokenInfo, type SwapTokenSearchResult, type UserPoolSelection, type UserPoolSelectionRequest, type WithdrawOptions, type WithdrawSwapRecord, type WithdrawSwapStatus, clearWithdrawSwap, createOwneySIWX, listPendingDeposits, listOrders as listPendingSwaps, listWithdrawSwaps, saveWithdrawSwap, setOwneyDebug, subscribeWithdrawSwaps, updateWithdrawSwap };
package/dist/index.js CHANGED
@@ -469,9 +469,18 @@ function netApy(net, gross, field) {
469
469
  debugLog("zyfai:apy", `gross fallback for ${field}`, { gross });
470
470
  return gross;
471
471
  }
472
- function rawPoolApyForChain(entry, chainId, tokenSymbol) {
472
+ function usdPerUnit(tokenSymbol, prices) {
473
+ const symbol = tokenSymbol?.toUpperCase();
474
+ if (symbol === "USDC") return 1;
475
+ const price = symbol ? prices?.[symbol] : void 0;
476
+ return typeof price === "number" && Number.isFinite(price) && price > 0 ? price : void 0;
477
+ }
478
+ function rawPoolApyForChain(entry, chainId, tokenSymbol, usdPrices) {
473
479
  let weightedSum = 0;
474
480
  let totalBalance = 0;
481
+ let usdWeightedSum = 0;
482
+ let usdTotal = 0;
483
+ let unpriced = false;
475
484
  for (const p of entry.positions ?? []) {
476
485
  if (chainId !== void 0 && p.chainId !== chainId) continue;
477
486
  if (tokenSymbol && p.tokenSymbol?.toUpperCase() !== tokenSymbol.toUpperCase()) continue;
@@ -480,7 +489,16 @@ function rawPoolApyForChain(entry, chainId, tokenSymbol) {
480
489
  if (balance <= 0 || typeof apy !== "number") continue;
481
490
  weightedSum += apy * balance;
482
491
  totalBalance += balance;
492
+ if (tokenSymbol) continue;
493
+ const price = usdPerUnit(p.tokenSymbol, usdPrices);
494
+ if (price === void 0) {
495
+ unpriced = true;
496
+ continue;
497
+ }
498
+ usdWeightedSum += apy * balance * price;
499
+ usdTotal += balance * price;
483
500
  }
501
+ if (!tokenSymbol && !unpriced && usdTotal > 0) return usdWeightedSum / usdTotal;
484
502
  return totalBalance > 0 ? weightedSum / totalBalance : null;
485
503
  }
486
504
  function historyCoverage(raw) {
@@ -515,10 +533,10 @@ function historyCoverage(raw) {
515
533
  pairs: [...pairs.values()]
516
534
  };
517
535
  }
518
- function mapApyHistory(raw, chainId, tokenSymbol) {
536
+ function mapApyHistory(raw, chainId, tokenSymbol, usdPrices) {
519
537
  const history = Object.entries(raw.history ?? {}).map(([date, entry]) => ({
520
538
  date,
521
- apy: rawPoolApyForChain(entry, chainId, tokenSymbol),
539
+ apy: rawPoolApyForChain(entry, chainId, tokenSymbol, usdPrices),
522
540
  // Provider position balances are treated as decimal amounts of the
523
541
  // selected token. Carry its unit dynamically for every asset; never
524
542
  // attach a token unit to an unscoped mix of assets.
@@ -1147,6 +1165,15 @@ function assemblePoolCatalog(protocols, poolsByProtocol, asset, chains) {
1147
1165
  var ERC7579_IS_MODULE_INSTALLED_ABI = parseAbi([
1148
1166
  "function isModuleInstalled(uint256 moduleTypeId, address module, bytes additionalContext) view returns (bool)"
1149
1167
  ]);
1168
+ var CHAINLINK_ETH_USD_FEED = {
1169
+ 8453: "0x71041dddad3595F9CEd3DcCFBe3D1F4b0a16Bb70",
1170
+ 42161: "0x639Fe6ab55C921f74e7fac1ee960C0B6293ba612",
1171
+ 1: "0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419"
1172
+ };
1173
+ var CHAINLINK_ABI = parseAbi([
1174
+ "function latestRoundData() view returns (uint80, int256, uint256, uint256, uint80)"
1175
+ ]);
1176
+ var ETH_USD_TTL_MS = 6e4;
1150
1177
  var DEFAULT_ZYFAI_RPC_URLS = {
1151
1178
  8453: "https://base-mainnet.g.alchemy.com/v2/ZWyVU-9XfS3z8Rn-xkq7V",
1152
1179
  42161: "https://arb-mainnet.g.alchemy.com/v2/ZWyVU-9XfS3z8Rn-xkq7V",
@@ -1212,6 +1239,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
1212
1239
  // successful decode is cached forever; failures are NOT cached so a transient
1213
1240
  // RPC error retries on the next fetch.
1214
1241
  withdrawAmountCache = /* @__PURE__ */ new Map();
1242
+ ethUsd = null;
1215
1243
  earningsReads = /* @__PURE__ */ new Map();
1216
1244
  earningsRefreshes = /* @__PURE__ */ new Map();
1217
1245
  earningsSnapshot = null;
@@ -1489,12 +1517,16 @@ var ZyfaiAgent = class _ZyfaiAgent {
1489
1517
  }
1490
1518
  // --- IAgent: Account lifecycle ---
1491
1519
  async activateAgent(state, chainId) {
1520
+ const startedAt = Date.now();
1492
1521
  try {
1493
1522
  debugLog("zyfai:activation", "starting", {
1494
1523
  walletAddress: state.walletAddress,
1495
1524
  chainId
1496
1525
  });
1497
1526
  await this.connectAuth(state, chainId);
1527
+ debugLog("zyfai:activation", "signed in", {
1528
+ ms: Date.now() - startedAt
1529
+ });
1498
1530
  const validChainId = isValidChainId(chainId);
1499
1531
  await Promise.all([
1500
1532
  this.ensureProtocolsSynced(validChainId, "USDC"),
@@ -1505,7 +1537,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
1505
1537
  // validator, so pool-wallet users see no prompt. Non-fatal.
1506
1538
  this.ensureSessionKeyIfDeployed(validChainId)
1507
1539
  ]);
1508
- debugLog("zyfai:activation", "completed", { chainId: validChainId });
1540
+ debugLog("zyfai:activation", "completed", {
1541
+ chainId: validChainId,
1542
+ ms: Date.now() - startedAt
1543
+ });
1509
1544
  } catch (error) {
1510
1545
  throw error;
1511
1546
  }
@@ -2191,8 +2226,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
2191
2226
  }
2192
2227
  // --- IAgent: Portfolio reads ---
2193
2228
  async getBalances(state, chainId) {
2229
+ const startedAt = Date.now();
2194
2230
  const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
2195
2231
  const raw = await this.sdk.getPortfolio(this.getAddress());
2232
+ debugLog("zyfai:balances", "read", { ms: Date.now() - startedAt });
2196
2233
  return mapBalances(raw, validChainId, smartWallet);
2197
2234
  }
2198
2235
  earningsKey(state, chainId, smartWallet) {
@@ -2250,10 +2287,41 @@ var ZyfaiAgent = class _ZyfaiAgent {
2250
2287
  return pending;
2251
2288
  }
2252
2289
  async getAccountApy(state, chainId, days, tokenSymbol, scopeChainId) {
2253
- const { smartWallet } = await this.resolveSmartWallet(state, chainId);
2254
- const raw = await this.sdk.getDailyApyHistory(smartWallet, days);
2290
+ const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
2291
+ const [raw, ethUsd] = await Promise.all([
2292
+ this.sdk.getDailyApyHistory(smartWallet, days),
2293
+ tokenSymbol ? void 0 : this.readEthUsd(validChainId)
2294
+ ]);
2255
2295
  const scope = scopeChainId === null ? void 0 : scopeChainId ?? chainId;
2256
- return mapApyHistory(raw, scope, tokenSymbol);
2296
+ const usdPrices = ethUsd ? { WETH: ethUsd, ETH: ethUsd } : void 0;
2297
+ return mapApyHistory(raw, scope, tokenSymbol, usdPrices);
2298
+ }
2299
+ /**
2300
+ * Today's ETH/USD from Chainlink, cached for a minute. Every day of the
2301
+ * series is weighted at this one price: each day's mix is right, but ETH's
2302
+ * move over the window is not reflected (ROUT-682). Undefined on failure,
2303
+ * which leaves the series on token-amount weighting rather than failing it.
2304
+ */
2305
+ async readEthUsd(chainId) {
2306
+ if (this.ethUsd && Date.now() - this.ethUsd.at < ETH_USD_TTL_MS) {
2307
+ return this.ethUsd.price;
2308
+ }
2309
+ try {
2310
+ const [, answer] = await this.getPublicClient(chainId).readContract({
2311
+ address: CHAINLINK_ETH_USD_FEED[chainId],
2312
+ abi: CHAINLINK_ABI,
2313
+ functionName: "latestRoundData"
2314
+ });
2315
+ const price = Number(answer) / 1e8;
2316
+ if (!Number.isFinite(price) || price <= 0) return void 0;
2317
+ this.ethUsd = { price, at: Date.now() };
2318
+ return price;
2319
+ } catch (err) {
2320
+ debugLog("zyfai:apy", "ETH/USD read failed; token-amount weighting", {
2321
+ err
2322
+ });
2323
+ return void 0;
2324
+ }
2257
2325
  }
2258
2326
  async getDailyEarnings(state, chainId, days, tokenSymbol) {
2259
2327
  const { smartWallet } = await this.resolveSmartWallet(state, chainId);
@@ -5015,8 +5083,9 @@ var OwneySDK = class {
5015
5083
  * that support the given chainId (incompatible agents are silently skipped).
5016
5084
  * If provided, ALL specified agents must support the chainId or the call
5017
5085
  * throws before activating any agent.
5086
+ * @param options - Optional. `onAgentsSelected` fires once reads can start.
5018
5087
  */
5019
- async activateAgent(chainId, agentId) {
5088
+ async activateAgent(chainId, agentId, options = {}) {
5020
5089
  const state = this.requireState();
5021
5090
  await this.ensureAgentsInitialized();
5022
5091
  if (agentId !== void 0) {
@@ -5052,6 +5121,7 @@ var OwneySDK = class {
5052
5121
  this.activeAgents.add(id);
5053
5122
  }
5054
5123
  state.chainId = chainId;
5124
+ options.onAgentsSelected?.();
5055
5125
  await this.activateAgentsInTurn(agents, state, chainId);
5056
5126
  return;
5057
5127
  }
@@ -5070,6 +5140,7 @@ var OwneySDK = class {
5070
5140
  this.activeAgents.add(agent.id);
5071
5141
  }
5072
5142
  state.chainId = chainId;
5143
+ options.onAgentsSelected?.();
5073
5144
  const enabledCompatible = compatible.filter(
5074
5145
  (agent) => !this.isAgentDisabled(agent.id)
5075
5146
  );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@owney/sdk",
3
- "version": "0.7.28",
3
+ "version": "0.7.29",
4
4
  "type": "module",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.js",