@owney/sdk 0.7.34 → 0.7.36

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
@@ -917,7 +917,7 @@ var isJwtExpired = (token) => {
917
917
  }
918
918
  };
919
919
  var memorySessions = /* @__PURE__ */ new Map();
920
- var isFreshSession = (session) => !!session && typeof session.isPredeployed === "boolean" && !!session.token && !isJwtExpired(session.token);
920
+ var isFreshSession = (session) => typeof session === "object" && session !== null && typeof session.isPredeployed === "boolean" && !!session.token && !isJwtExpired(session.token);
921
921
  var readLegacySession = (store, address) => {
922
922
  if (!store) return null;
923
923
  const prefix = legacyKeyPrefix(address);
@@ -999,6 +999,17 @@ var clearSession = (address, _chainId) => {
999
999
  }
1000
1000
  readLegacySession(store, address);
1001
1001
  };
1002
+ var BrowserSessionStore = class {
1003
+ read(_agentId, address) {
1004
+ return readSession(address, 0);
1005
+ }
1006
+ write(_agentId, address, session) {
1007
+ writeSession(address, 0, session);
1008
+ }
1009
+ clear(_agentId, address) {
1010
+ clearSession(address, 0);
1011
+ }
1012
+ };
1002
1013
 
1003
1014
  // src/agents/zyfai/autoSelect.ts
1004
1015
  function buildAutoSelectUpdate(current, asset, chainId) {
@@ -1285,7 +1296,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
1285
1296
  earningsRefreshes = /* @__PURE__ */ new Map();
1286
1297
  earningsSnapshot = null;
1287
1298
  earningsGeneration = 0;
1288
- constructor(apiKey, rpcUrls, referralSource) {
1299
+ sessionStore;
1300
+ constructor(apiKey, rpcUrls, referralSource, sessionStore = new BrowserSessionStore()) {
1301
+ this.sessionStore = sessionStore;
1289
1302
  this.rpcUrls = rpcUrls ?? DEFAULT_ZYFAI_RPC_URLS;
1290
1303
  this.sdk = new import_sdk.ZyfaiSDK({
1291
1304
  apiKey,
@@ -1376,21 +1389,36 @@ var ZyfaiAgent = class _ZyfaiAgent {
1376
1389
  * (Zyfai dist line 1374). At that point `walletClient` + `currentChainId`
1377
1390
  * are populated, so the cache lookup has both keys it needs.
1378
1391
  *
1379
- * No-op on the server (no `window`) — the SDK is constructed during SSR
1380
- * for some apps and the patch only matters in the browser anyway.
1392
+ * The session lives in `sessionStore`: localStorage in the browser (a no-op
1393
+ * on the server), or whatever the host passed in `OwneySDKConfig`.
1381
1394
  */
1395
+ /**
1396
+ * The session store is a cache: an unavailable store must never block
1397
+ * authentication or teardown. Failures read as a cache miss.
1398
+ */
1399
+ async storeOp(op) {
1400
+ try {
1401
+ return await op();
1402
+ } catch (error) {
1403
+ console.warn(
1404
+ "owney-sdk: agent session store failed, continuing without it",
1405
+ error
1406
+ );
1407
+ return null;
1408
+ }
1409
+ }
1382
1410
  installAuthCache() {
1383
- if (typeof window === "undefined") return;
1384
1411
  const internals = this.sdk;
1385
1412
  const original = internals.authenticateUser.bind(internals);
1386
1413
  let inFlight = null;
1387
1414
  const authenticate = async () => {
1388
1415
  if (internals.authenticatedUserId !== null) return;
1389
1416
  const address = internals.walletClient?.account?.address;
1390
- const chainId = internals.currentChainId ?? 0;
1391
1417
  if (address) {
1392
- const cached = readSession(address, chainId);
1393
- if (cached) {
1418
+ const cached = await this.storeOp(
1419
+ () => this.sessionStore.read(this.id, address)
1420
+ );
1421
+ if (isFreshSession(cached)) {
1394
1422
  internals.httpClient.setAuthToken(cached.token);
1395
1423
  internals.authenticatedUserId = cached.userId;
1396
1424
  internals.hasActiveSessionKey = cached.hasActiveSessionKey;
@@ -1400,15 +1428,16 @@ var ZyfaiAgent = class _ZyfaiAgent {
1400
1428
  }
1401
1429
  await original();
1402
1430
  const newAddress = internals.walletClient?.account?.address;
1403
- const newChainId = internals.currentChainId ?? 0;
1404
1431
  const newToken = internals.httpClient.authToken;
1405
1432
  if (newAddress && newToken) {
1406
- writeSession(newAddress, newChainId, {
1407
- token: newToken,
1408
- userId: internals.authenticatedUserId,
1409
- hasActiveSessionKey: internals.hasActiveSessionKey,
1410
- isPredeployed: internals.isPredeployed
1411
- });
1433
+ await this.storeOp(
1434
+ () => this.sessionStore.write(this.id, newAddress, {
1435
+ token: newToken,
1436
+ userId: internals.authenticatedUserId,
1437
+ hasActiveSessionKey: internals.hasActiveSessionKey,
1438
+ isPredeployed: internals.isPredeployed
1439
+ })
1440
+ );
1412
1441
  }
1413
1442
  };
1414
1443
  internals.authenticateUser = () => {
@@ -1474,7 +1503,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
1474
1503
  if (!message.toLowerCase().includes("unauthorized")) throw error;
1475
1504
  const internals = this.sdk;
1476
1505
  const address = internals.walletClient?.account?.address;
1477
- if (address) clearSession(address, chainId);
1506
+ if (address) {
1507
+ await this.storeOp(() => this.sessionStore.clear(this.id, address));
1508
+ }
1478
1509
  return await this.sdk.connectAccount(provider, chainId);
1479
1510
  }
1480
1511
  }
@@ -1558,8 +1589,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
1558
1589
  this.earningsReads.clear();
1559
1590
  this.earningsRefreshes.clear();
1560
1591
  this.earningsSnapshot = null;
1561
- if (this.connectedAddress && this.connectedChainId !== null) {
1562
- clearSession(this.connectedAddress, this.connectedChainId);
1592
+ if (this.connectedAddress) {
1593
+ const address = this.connectedAddress;
1594
+ await this.storeOp(() => this.sessionStore.clear(this.id, address));
1563
1595
  }
1564
1596
  await this.sdk.disconnectAccount();
1565
1597
  this.connectedAddress = null;
@@ -2628,6 +2660,35 @@ function mergeDailyEarnings(series) {
2628
2660
 
2629
2661
  // src/lib/routing-api.ts
2630
2662
  var ROUTING_API_BASE_URL = "https://owney-routing-api-243946518160.europe-west4.run.app";
2663
+ async function fetchApyIncentives(apiKey, input, baseUrl = ROUTING_API_BASE_URL) {
2664
+ const query = new URLSearchParams({
2665
+ walletAddress: input.walletAddress,
2666
+ agentId: input.agentId,
2667
+ chainId: String(input.chainId),
2668
+ asset: input.asset.toUpperCase(),
2669
+ from: input.from,
2670
+ to: input.to
2671
+ });
2672
+ try {
2673
+ const response = await fetch(`${baseUrl}/api/v1/apy-incentives?${query}`, {
2674
+ headers: {
2675
+ Accept: "application/json",
2676
+ "x-owney-api-key": apiKey
2677
+ }
2678
+ });
2679
+ if (!response.ok) return [];
2680
+ const body = await response.json();
2681
+ if (!body.success || !Array.isArray(body.data)) return [];
2682
+ return body.data.filter(
2683
+ (item) => item && typeof item.date === "string" && item.source === "merkl" && typeof item.opportunityId === "string" && Array.isArray(item.campaignIds) && Number.isFinite(item.apr) && Number.isFinite(item.apyContribution)
2684
+ );
2685
+ } catch (error) {
2686
+ debugLog("owney-sdk", "APY incentives unavailable; using native APY", {
2687
+ error: error instanceof Error ? error.message : String(error)
2688
+ });
2689
+ return [];
2690
+ }
2691
+ }
2631
2692
  async function fetchOrgAgentConfig(apiKey, baseUrl = ROUTING_API_BASE_URL) {
2632
2693
  const url = `${baseUrl}/api/v1/agent/org-config`;
2633
2694
  try {
@@ -4316,9 +4377,40 @@ function aggregateApyHistory(agentApys) {
4316
4377
  const total = points.reduce((sum, p) => sum + p.historicalBalance.amount, 0);
4317
4378
  if (total <= 0 || !Number.isFinite(total)) return [];
4318
4379
  const apy = points.reduce((sum, p) => sum + p.apy * (p.historicalBalance.amount / total), 0);
4319
- return Number.isFinite(apy) ? [{ date, apy }] : [];
4380
+ if (!Number.isFinite(apy)) return [];
4381
+ const incentives = aggregateIncentives(points, total);
4382
+ return [{ date, apy, ...incentives.length > 0 ? { incentives } : {} }];
4320
4383
  });
4321
4384
  }
4385
+ function incentiveKey(incentive) {
4386
+ return JSON.stringify([
4387
+ incentive.source,
4388
+ incentive.agentId,
4389
+ incentive.opportunityId,
4390
+ [...incentive.campaignIds].sort()
4391
+ ]);
4392
+ }
4393
+ function aggregateIncentives(points, totalBalance) {
4394
+ const byProgram = /* @__PURE__ */ new Map();
4395
+ for (const point of points) {
4396
+ const weight = point.historicalBalance.amount / totalBalance;
4397
+ for (const incentive of point.incentives ?? []) {
4398
+ if (!Number.isFinite(incentive.apr) || !Number.isFinite(incentive.apyContribution)) continue;
4399
+ const key2 = incentiveKey(incentive);
4400
+ const existing = byProgram.get(key2);
4401
+ if (existing) {
4402
+ existing.apyContribution += incentive.apyContribution * weight;
4403
+ } else {
4404
+ byProgram.set(key2, {
4405
+ ...incentive,
4406
+ campaignIds: [...incentive.campaignIds],
4407
+ apyContribution: incentive.apyContribution * weight
4408
+ });
4409
+ }
4410
+ }
4411
+ }
4412
+ return [...byProgram.values()];
4413
+ }
4322
4414
  function aggregateApyByChainAndAsset(agentApys, agentBalances) {
4323
4415
  const sums = {};
4324
4416
  const weights = {};
@@ -4969,6 +5061,7 @@ var OwneySDK = class {
4969
5061
  userPoolCustomization = false;
4970
5062
  routingApiBaseUrl;
4971
5063
  referralSource;
5064
+ sessionStore;
4972
5065
  cachedSponsoredCallback = null;
4973
5066
  cachedWethSponsoredCallback = null;
4974
5067
  paymasterServiceUrl;
@@ -4992,6 +5085,7 @@ var OwneySDK = class {
4992
5085
  this.routingApiBaseUrl = config.routingApiBaseUrl;
4993
5086
  this.paymasterServiceUrl = config.paymasterServiceUrl;
4994
5087
  this.referralSource = config.referralSource;
5088
+ this.sessionStore = config.sessionStore;
4995
5089
  this.userPoolCustomization = config.userPoolCustomization ?? false;
4996
5090
  }
4997
5091
  /**
@@ -5265,7 +5359,12 @@ var OwneySDK = class {
5265
5359
  }
5266
5360
  createAgent(agentId, key2) {
5267
5361
  if (agentId === "zyfai") {
5268
- return new ZyfaiAgent(key2, this.zyfaiRpcUrls, this.referralSource);
5362
+ return new ZyfaiAgent(
5363
+ key2,
5364
+ this.zyfaiRpcUrls,
5365
+ this.referralSource,
5366
+ this.sessionStore
5367
+ );
5269
5368
  }
5270
5369
  return null;
5271
5370
  }
@@ -7211,12 +7310,18 @@ var OwneySDK = class {
7211
7310
  const scopeChainId = scope === "all" ? null : scope;
7212
7311
  if (agentId) {
7213
7312
  const agent = this.getAgent(agentId);
7214
- return this.readAgent(
7313
+ const accountApy = await this.readAgent(
7215
7314
  agent,
7216
7315
  "accountApy",
7217
7316
  () => agent.getAccountApy(state, chainId, days, tokenSymbol, scopeChainId),
7218
7317
  { days, tokenSymbol, scopeChainId }
7219
7318
  );
7319
+ return this.enrichApyHistory(
7320
+ accountApy,
7321
+ agentId,
7322
+ scopeChainId === null ? void 0 : scopeChainId ?? chainId,
7323
+ tokenSymbol
7324
+ );
7220
7325
  }
7221
7326
  const activeAgents = this.getActiveAgents();
7222
7327
  const entries = [...activeAgents.entries()];
@@ -7251,7 +7356,12 @@ var OwneySDK = class {
7251
7356
  ]);
7252
7357
  const results = {};
7253
7358
  for (const [id, apy] of apyResults) {
7254
- results[id] = apy;
7359
+ results[id] = await this.enrichApyHistory(
7360
+ apy,
7361
+ id,
7362
+ scopeChainId === null ? void 0 : scopeChainId ?? chainId,
7363
+ tokenSymbol
7364
+ );
7255
7365
  }
7256
7366
  const balances = {};
7257
7367
  for (const [id, bal] of balanceResults) {
@@ -7281,6 +7391,36 @@ var OwneySDK = class {
7281
7391
  history
7282
7392
  };
7283
7393
  }
7394
+ async enrichApyHistory(accountApy, agentId, chainId, tokenSymbol) {
7395
+ const history = accountApy.history;
7396
+ if (agentId !== "zyfai" || chainId === void 0 || !tokenSymbol || !history?.length) return accountApy;
7397
+ const incentives = await fetchApyIncentives(
7398
+ this.apiKey,
7399
+ {
7400
+ walletAddress: accountApy.walletAddress,
7401
+ agentId,
7402
+ chainId,
7403
+ asset: tokenSymbol,
7404
+ from: history[0].date,
7405
+ to: history[history.length - 1].date
7406
+ },
7407
+ this.routingApiBaseUrl
7408
+ );
7409
+ if (incentives.length === 0) return accountApy;
7410
+ const byDate = /* @__PURE__ */ new Map();
7411
+ for (const { date, ...incentive } of incentives) {
7412
+ const entries = byDate.get(date) ?? [];
7413
+ entries.push(incentive);
7414
+ byDate.set(date, entries);
7415
+ }
7416
+ return {
7417
+ ...accountApy,
7418
+ history: history.map((point) => {
7419
+ const pointIncentives = byDate.get(point.date);
7420
+ return pointIncentives?.length ? { ...point, incentives: pointIncentives } : point;
7421
+ })
7422
+ };
7423
+ }
7284
7424
  /**
7285
7425
  * Get transaction history for a specific agent, or all agents.
7286
7426
  *
package/dist/index.d.cts CHANGED
@@ -247,8 +247,32 @@ type SwapQuoteParams = {
247
247
  };
248
248
 
249
249
  type ZyfaiRpcUrlsConfig = Partial<Record<(typeof SUPPORTED_CHAIN_IDS)[number], string>>;
250
+ /**
251
+ * Where an agent keeps its login session (for Zyfai: the JWT plus the flags
252
+ * it caches). The value is opaque JSON owned by the agent; the agent validates
253
+ * it on read. Default is the browser's localStorage; a server passes its own
254
+ * store (database, cache) so one login survives across requests and replicas.
255
+ */
256
+ interface AgentSessionStore {
257
+ read(agentId: string, address: string): Promise<unknown | null> | unknown | null;
258
+ write(agentId: string, address: string, session: unknown): Promise<void> | void;
259
+ clear(agentId: string, address: string): Promise<void> | void;
260
+ }
250
261
  interface OwneySDKConfig {
251
262
  apiKey: string;
263
+ /**
264
+ * Optional persistence for agent authentication sessions.
265
+ *
266
+ * When omitted, browser integrations use the default localStorage store.
267
+ * On the server the default store is a no-op, so every `connect` signs in
268
+ * again unless a store is provided.
269
+ *
270
+ * Stored values may contain bearer tokens and must be treated as secrets.
271
+ * Server implementations should bind each store instance to a trusted
272
+ * application user/session, encrypt values, apply a TTL, and never use a
273
+ * caller-provided wallet address as the sole authorization boundary.
274
+ */
275
+ sessionStore?: AgentSessionStore;
252
276
  /**
253
277
  * Optional per-chain RPC overrides for Zyfai SDK network calls.
254
278
  * Example: { 8453: "https://...", 42161: "https://..." }
@@ -715,17 +739,31 @@ interface OwneyEarnings {
715
739
  agentEarnings: Record<AgentId, AgentEarnings>;
716
740
  }
717
741
  type ApyByChainAndAsset = Partial<Record<OwneySupportedChainId, Partial<Record<OwneySupportedTokens, number>>>>;
742
+ /** One external reward program contributing percentage points to a day. */
743
+ interface ApyIncentive {
744
+ source: "merkl";
745
+ agentId: AgentId;
746
+ opportunityId: string;
747
+ /** All on-chain campaigns represented by the opportunity APR that day. */
748
+ campaignIds: string[];
749
+ /** Source APR before portfolio weighting, expressed as a percentage. */
750
+ apr: number;
751
+ /** Percentage points to add to this point's native/provider `apy`. */
752
+ apyContribution: number;
753
+ }
718
754
  /** A single day's net APY for the connected account, as a percentage number. */
719
755
  interface ApyHistoryPoint {
720
756
  /** ISO date string for the day, e.g. "2026-06-20". */
721
757
  date: string;
722
- /** Net (after-fee) weighted APY for that day, summed across tokens. */
758
+ /** Native/provider net APY. External incentives are deliberately excluded. */
723
759
  apy: number;
724
760
  /** Balance on this date, in the explicitly named unit; never today's balance. */
725
761
  historicalBalance?: {
726
762
  amount: number;
727
763
  unit: string;
728
764
  };
765
+ /** Best-effort external rewards. Absent when none apply or cannot be read. */
766
+ incentives?: ApyIncentive[];
729
767
  }
730
768
  /**
731
769
  * What the APY chart's chain/asset menus are allowed to offer, and how far
@@ -1182,6 +1220,7 @@ declare class OwneySDK {
1182
1220
  private userPoolCustomization;
1183
1221
  private routingApiBaseUrl?;
1184
1222
  private referralSource?;
1223
+ private sessionStore?;
1185
1224
  private cachedSponsoredCallback;
1186
1225
  private cachedWethSponsoredCallback;
1187
1226
  private paymasterServiceUrl?;
@@ -1848,6 +1887,7 @@ declare class OwneySDK {
1848
1887
  agentId?: AgentId;
1849
1888
  }): Promise<SavedPoolSelection>;
1850
1889
  getAccountApy({ agentId, days, tokenSymbol, chainId: scope, }: AccountApyOptions): Promise<OwneyAccountApy | AccountAgentApy>;
1890
+ private enrichApyHistory;
1851
1891
  /**
1852
1892
  * Get transaction history for a specific agent, or all agents.
1853
1893
  *
@@ -2006,4 +2046,4 @@ type StoredOrder = {
2006
2046
  */
2007
2047
  declare function listOrders(now?: number): StoredOrder[];
2008
2048
 
2009
- 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, switchWalletConnectChain, updateWithdrawSwap };
2049
+ 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 AgentSessionStore, type AgentSupportedAsset, type AgentSupportedAssets, type AgentUserProfile, type AgentWithdrawResult, type AgentsApyOptions, type AllocationAgentApy, type AllocationApyOptions, type ApyByChainAndAsset, type ApyCoverage, type ApyHistoryPoint, type ApyIncentive, 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, switchWalletConnectChain, updateWithdrawSwap };
package/dist/index.d.ts CHANGED
@@ -247,8 +247,32 @@ type SwapQuoteParams = {
247
247
  };
248
248
 
249
249
  type ZyfaiRpcUrlsConfig = Partial<Record<(typeof SUPPORTED_CHAIN_IDS)[number], string>>;
250
+ /**
251
+ * Where an agent keeps its login session (for Zyfai: the JWT plus the flags
252
+ * it caches). The value is opaque JSON owned by the agent; the agent validates
253
+ * it on read. Default is the browser's localStorage; a server passes its own
254
+ * store (database, cache) so one login survives across requests and replicas.
255
+ */
256
+ interface AgentSessionStore {
257
+ read(agentId: string, address: string): Promise<unknown | null> | unknown | null;
258
+ write(agentId: string, address: string, session: unknown): Promise<void> | void;
259
+ clear(agentId: string, address: string): Promise<void> | void;
260
+ }
250
261
  interface OwneySDKConfig {
251
262
  apiKey: string;
263
+ /**
264
+ * Optional persistence for agent authentication sessions.
265
+ *
266
+ * When omitted, browser integrations use the default localStorage store.
267
+ * On the server the default store is a no-op, so every `connect` signs in
268
+ * again unless a store is provided.
269
+ *
270
+ * Stored values may contain bearer tokens and must be treated as secrets.
271
+ * Server implementations should bind each store instance to a trusted
272
+ * application user/session, encrypt values, apply a TTL, and never use a
273
+ * caller-provided wallet address as the sole authorization boundary.
274
+ */
275
+ sessionStore?: AgentSessionStore;
252
276
  /**
253
277
  * Optional per-chain RPC overrides for Zyfai SDK network calls.
254
278
  * Example: { 8453: "https://...", 42161: "https://..." }
@@ -715,17 +739,31 @@ interface OwneyEarnings {
715
739
  agentEarnings: Record<AgentId, AgentEarnings>;
716
740
  }
717
741
  type ApyByChainAndAsset = Partial<Record<OwneySupportedChainId, Partial<Record<OwneySupportedTokens, number>>>>;
742
+ /** One external reward program contributing percentage points to a day. */
743
+ interface ApyIncentive {
744
+ source: "merkl";
745
+ agentId: AgentId;
746
+ opportunityId: string;
747
+ /** All on-chain campaigns represented by the opportunity APR that day. */
748
+ campaignIds: string[];
749
+ /** Source APR before portfolio weighting, expressed as a percentage. */
750
+ apr: number;
751
+ /** Percentage points to add to this point's native/provider `apy`. */
752
+ apyContribution: number;
753
+ }
718
754
  /** A single day's net APY for the connected account, as a percentage number. */
719
755
  interface ApyHistoryPoint {
720
756
  /** ISO date string for the day, e.g. "2026-06-20". */
721
757
  date: string;
722
- /** Net (after-fee) weighted APY for that day, summed across tokens. */
758
+ /** Native/provider net APY. External incentives are deliberately excluded. */
723
759
  apy: number;
724
760
  /** Balance on this date, in the explicitly named unit; never today's balance. */
725
761
  historicalBalance?: {
726
762
  amount: number;
727
763
  unit: string;
728
764
  };
765
+ /** Best-effort external rewards. Absent when none apply or cannot be read. */
766
+ incentives?: ApyIncentive[];
729
767
  }
730
768
  /**
731
769
  * What the APY chart's chain/asset menus are allowed to offer, and how far
@@ -1182,6 +1220,7 @@ declare class OwneySDK {
1182
1220
  private userPoolCustomization;
1183
1221
  private routingApiBaseUrl?;
1184
1222
  private referralSource?;
1223
+ private sessionStore?;
1185
1224
  private cachedSponsoredCallback;
1186
1225
  private cachedWethSponsoredCallback;
1187
1226
  private paymasterServiceUrl?;
@@ -1848,6 +1887,7 @@ declare class OwneySDK {
1848
1887
  agentId?: AgentId;
1849
1888
  }): Promise<SavedPoolSelection>;
1850
1889
  getAccountApy({ agentId, days, tokenSymbol, chainId: scope, }: AccountApyOptions): Promise<OwneyAccountApy | AccountAgentApy>;
1890
+ private enrichApyHistory;
1851
1891
  /**
1852
1892
  * Get transaction history for a specific agent, or all agents.
1853
1893
  *
@@ -2006,4 +2046,4 @@ type StoredOrder = {
2006
2046
  */
2007
2047
  declare function listOrders(now?: number): StoredOrder[];
2008
2048
 
2009
- 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, switchWalletConnectChain, updateWithdrawSwap };
2049
+ 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 AgentSessionStore, type AgentSupportedAsset, type AgentSupportedAssets, type AgentUserProfile, type AgentWithdrawResult, type AgentsApyOptions, type AllocationAgentApy, type AllocationApyOptions, type ApyByChainAndAsset, type ApyCoverage, type ApyHistoryPoint, type ApyIncentive, 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, switchWalletConnectChain, updateWithdrawSwap };
package/dist/index.js CHANGED
@@ -876,7 +876,7 @@ var isJwtExpired = (token) => {
876
876
  }
877
877
  };
878
878
  var memorySessions = /* @__PURE__ */ new Map();
879
- var isFreshSession = (session) => !!session && typeof session.isPredeployed === "boolean" && !!session.token && !isJwtExpired(session.token);
879
+ var isFreshSession = (session) => typeof session === "object" && session !== null && typeof session.isPredeployed === "boolean" && !!session.token && !isJwtExpired(session.token);
880
880
  var readLegacySession = (store, address) => {
881
881
  if (!store) return null;
882
882
  const prefix = legacyKeyPrefix(address);
@@ -958,6 +958,17 @@ var clearSession = (address, _chainId) => {
958
958
  }
959
959
  readLegacySession(store, address);
960
960
  };
961
+ var BrowserSessionStore = class {
962
+ read(_agentId, address) {
963
+ return readSession(address, 0);
964
+ }
965
+ write(_agentId, address, session) {
966
+ writeSession(address, 0, session);
967
+ }
968
+ clear(_agentId, address) {
969
+ clearSession(address, 0);
970
+ }
971
+ };
961
972
 
962
973
  // src/agents/zyfai/autoSelect.ts
963
974
  function buildAutoSelectUpdate(current, asset, chainId) {
@@ -1244,7 +1255,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
1244
1255
  earningsRefreshes = /* @__PURE__ */ new Map();
1245
1256
  earningsSnapshot = null;
1246
1257
  earningsGeneration = 0;
1247
- constructor(apiKey, rpcUrls, referralSource) {
1258
+ sessionStore;
1259
+ constructor(apiKey, rpcUrls, referralSource, sessionStore = new BrowserSessionStore()) {
1260
+ this.sessionStore = sessionStore;
1248
1261
  this.rpcUrls = rpcUrls ?? DEFAULT_ZYFAI_RPC_URLS;
1249
1262
  this.sdk = new ZyfaiSDK({
1250
1263
  apiKey,
@@ -1335,21 +1348,36 @@ var ZyfaiAgent = class _ZyfaiAgent {
1335
1348
  * (Zyfai dist line 1374). At that point `walletClient` + `currentChainId`
1336
1349
  * are populated, so the cache lookup has both keys it needs.
1337
1350
  *
1338
- * No-op on the server (no `window`) — the SDK is constructed during SSR
1339
- * for some apps and the patch only matters in the browser anyway.
1351
+ * The session lives in `sessionStore`: localStorage in the browser (a no-op
1352
+ * on the server), or whatever the host passed in `OwneySDKConfig`.
1340
1353
  */
1354
+ /**
1355
+ * The session store is a cache: an unavailable store must never block
1356
+ * authentication or teardown. Failures read as a cache miss.
1357
+ */
1358
+ async storeOp(op) {
1359
+ try {
1360
+ return await op();
1361
+ } catch (error) {
1362
+ console.warn(
1363
+ "owney-sdk: agent session store failed, continuing without it",
1364
+ error
1365
+ );
1366
+ return null;
1367
+ }
1368
+ }
1341
1369
  installAuthCache() {
1342
- if (typeof window === "undefined") return;
1343
1370
  const internals = this.sdk;
1344
1371
  const original = internals.authenticateUser.bind(internals);
1345
1372
  let inFlight = null;
1346
1373
  const authenticate = async () => {
1347
1374
  if (internals.authenticatedUserId !== null) return;
1348
1375
  const address = internals.walletClient?.account?.address;
1349
- const chainId = internals.currentChainId ?? 0;
1350
1376
  if (address) {
1351
- const cached = readSession(address, chainId);
1352
- if (cached) {
1377
+ const cached = await this.storeOp(
1378
+ () => this.sessionStore.read(this.id, address)
1379
+ );
1380
+ if (isFreshSession(cached)) {
1353
1381
  internals.httpClient.setAuthToken(cached.token);
1354
1382
  internals.authenticatedUserId = cached.userId;
1355
1383
  internals.hasActiveSessionKey = cached.hasActiveSessionKey;
@@ -1359,15 +1387,16 @@ var ZyfaiAgent = class _ZyfaiAgent {
1359
1387
  }
1360
1388
  await original();
1361
1389
  const newAddress = internals.walletClient?.account?.address;
1362
- const newChainId = internals.currentChainId ?? 0;
1363
1390
  const newToken = internals.httpClient.authToken;
1364
1391
  if (newAddress && newToken) {
1365
- writeSession(newAddress, newChainId, {
1366
- token: newToken,
1367
- userId: internals.authenticatedUserId,
1368
- hasActiveSessionKey: internals.hasActiveSessionKey,
1369
- isPredeployed: internals.isPredeployed
1370
- });
1392
+ await this.storeOp(
1393
+ () => this.sessionStore.write(this.id, newAddress, {
1394
+ token: newToken,
1395
+ userId: internals.authenticatedUserId,
1396
+ hasActiveSessionKey: internals.hasActiveSessionKey,
1397
+ isPredeployed: internals.isPredeployed
1398
+ })
1399
+ );
1371
1400
  }
1372
1401
  };
1373
1402
  internals.authenticateUser = () => {
@@ -1433,7 +1462,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
1433
1462
  if (!message.toLowerCase().includes("unauthorized")) throw error;
1434
1463
  const internals = this.sdk;
1435
1464
  const address = internals.walletClient?.account?.address;
1436
- if (address) clearSession(address, chainId);
1465
+ if (address) {
1466
+ await this.storeOp(() => this.sessionStore.clear(this.id, address));
1467
+ }
1437
1468
  return await this.sdk.connectAccount(provider, chainId);
1438
1469
  }
1439
1470
  }
@@ -1517,8 +1548,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
1517
1548
  this.earningsReads.clear();
1518
1549
  this.earningsRefreshes.clear();
1519
1550
  this.earningsSnapshot = null;
1520
- if (this.connectedAddress && this.connectedChainId !== null) {
1521
- clearSession(this.connectedAddress, this.connectedChainId);
1551
+ if (this.connectedAddress) {
1552
+ const address = this.connectedAddress;
1553
+ await this.storeOp(() => this.sessionStore.clear(this.id, address));
1522
1554
  }
1523
1555
  await this.sdk.disconnectAccount();
1524
1556
  this.connectedAddress = null;
@@ -2587,6 +2619,35 @@ function mergeDailyEarnings(series) {
2587
2619
 
2588
2620
  // src/lib/routing-api.ts
2589
2621
  var ROUTING_API_BASE_URL = "https://owney-routing-api-243946518160.europe-west4.run.app";
2622
+ async function fetchApyIncentives(apiKey, input, baseUrl = ROUTING_API_BASE_URL) {
2623
+ const query = new URLSearchParams({
2624
+ walletAddress: input.walletAddress,
2625
+ agentId: input.agentId,
2626
+ chainId: String(input.chainId),
2627
+ asset: input.asset.toUpperCase(),
2628
+ from: input.from,
2629
+ to: input.to
2630
+ });
2631
+ try {
2632
+ const response = await fetch(`${baseUrl}/api/v1/apy-incentives?${query}`, {
2633
+ headers: {
2634
+ Accept: "application/json",
2635
+ "x-owney-api-key": apiKey
2636
+ }
2637
+ });
2638
+ if (!response.ok) return [];
2639
+ const body = await response.json();
2640
+ if (!body.success || !Array.isArray(body.data)) return [];
2641
+ return body.data.filter(
2642
+ (item) => item && typeof item.date === "string" && item.source === "merkl" && typeof item.opportunityId === "string" && Array.isArray(item.campaignIds) && Number.isFinite(item.apr) && Number.isFinite(item.apyContribution)
2643
+ );
2644
+ } catch (error) {
2645
+ debugLog("owney-sdk", "APY incentives unavailable; using native APY", {
2646
+ error: error instanceof Error ? error.message : String(error)
2647
+ });
2648
+ return [];
2649
+ }
2650
+ }
2590
2651
  async function fetchOrgAgentConfig(apiKey, baseUrl = ROUTING_API_BASE_URL) {
2591
2652
  const url = `${baseUrl}/api/v1/agent/org-config`;
2592
2653
  try {
@@ -4290,9 +4351,40 @@ function aggregateApyHistory(agentApys) {
4290
4351
  const total = points.reduce((sum, p) => sum + p.historicalBalance.amount, 0);
4291
4352
  if (total <= 0 || !Number.isFinite(total)) return [];
4292
4353
  const apy = points.reduce((sum, p) => sum + p.apy * (p.historicalBalance.amount / total), 0);
4293
- return Number.isFinite(apy) ? [{ date, apy }] : [];
4354
+ if (!Number.isFinite(apy)) return [];
4355
+ const incentives = aggregateIncentives(points, total);
4356
+ return [{ date, apy, ...incentives.length > 0 ? { incentives } : {} }];
4294
4357
  });
4295
4358
  }
4359
+ function incentiveKey(incentive) {
4360
+ return JSON.stringify([
4361
+ incentive.source,
4362
+ incentive.agentId,
4363
+ incentive.opportunityId,
4364
+ [...incentive.campaignIds].sort()
4365
+ ]);
4366
+ }
4367
+ function aggregateIncentives(points, totalBalance) {
4368
+ const byProgram = /* @__PURE__ */ new Map();
4369
+ for (const point of points) {
4370
+ const weight = point.historicalBalance.amount / totalBalance;
4371
+ for (const incentive of point.incentives ?? []) {
4372
+ if (!Number.isFinite(incentive.apr) || !Number.isFinite(incentive.apyContribution)) continue;
4373
+ const key2 = incentiveKey(incentive);
4374
+ const existing = byProgram.get(key2);
4375
+ if (existing) {
4376
+ existing.apyContribution += incentive.apyContribution * weight;
4377
+ } else {
4378
+ byProgram.set(key2, {
4379
+ ...incentive,
4380
+ campaignIds: [...incentive.campaignIds],
4381
+ apyContribution: incentive.apyContribution * weight
4382
+ });
4383
+ }
4384
+ }
4385
+ }
4386
+ return [...byProgram.values()];
4387
+ }
4296
4388
  function aggregateApyByChainAndAsset(agentApys, agentBalances) {
4297
4389
  const sums = {};
4298
4390
  const weights = {};
@@ -4949,6 +5041,7 @@ var OwneySDK = class {
4949
5041
  userPoolCustomization = false;
4950
5042
  routingApiBaseUrl;
4951
5043
  referralSource;
5044
+ sessionStore;
4952
5045
  cachedSponsoredCallback = null;
4953
5046
  cachedWethSponsoredCallback = null;
4954
5047
  paymasterServiceUrl;
@@ -4972,6 +5065,7 @@ var OwneySDK = class {
4972
5065
  this.routingApiBaseUrl = config.routingApiBaseUrl;
4973
5066
  this.paymasterServiceUrl = config.paymasterServiceUrl;
4974
5067
  this.referralSource = config.referralSource;
5068
+ this.sessionStore = config.sessionStore;
4975
5069
  this.userPoolCustomization = config.userPoolCustomization ?? false;
4976
5070
  }
4977
5071
  /**
@@ -5245,7 +5339,12 @@ var OwneySDK = class {
5245
5339
  }
5246
5340
  createAgent(agentId, key2) {
5247
5341
  if (agentId === "zyfai") {
5248
- return new ZyfaiAgent(key2, this.zyfaiRpcUrls, this.referralSource);
5342
+ return new ZyfaiAgent(
5343
+ key2,
5344
+ this.zyfaiRpcUrls,
5345
+ this.referralSource,
5346
+ this.sessionStore
5347
+ );
5249
5348
  }
5250
5349
  return null;
5251
5350
  }
@@ -7191,12 +7290,18 @@ var OwneySDK = class {
7191
7290
  const scopeChainId = scope === "all" ? null : scope;
7192
7291
  if (agentId) {
7193
7292
  const agent = this.getAgent(agentId);
7194
- return this.readAgent(
7293
+ const accountApy = await this.readAgent(
7195
7294
  agent,
7196
7295
  "accountApy",
7197
7296
  () => agent.getAccountApy(state, chainId, days, tokenSymbol, scopeChainId),
7198
7297
  { days, tokenSymbol, scopeChainId }
7199
7298
  );
7299
+ return this.enrichApyHistory(
7300
+ accountApy,
7301
+ agentId,
7302
+ scopeChainId === null ? void 0 : scopeChainId ?? chainId,
7303
+ tokenSymbol
7304
+ );
7200
7305
  }
7201
7306
  const activeAgents = this.getActiveAgents();
7202
7307
  const entries = [...activeAgents.entries()];
@@ -7231,7 +7336,12 @@ var OwneySDK = class {
7231
7336
  ]);
7232
7337
  const results = {};
7233
7338
  for (const [id, apy] of apyResults) {
7234
- results[id] = apy;
7339
+ results[id] = await this.enrichApyHistory(
7340
+ apy,
7341
+ id,
7342
+ scopeChainId === null ? void 0 : scopeChainId ?? chainId,
7343
+ tokenSymbol
7344
+ );
7235
7345
  }
7236
7346
  const balances = {};
7237
7347
  for (const [id, bal] of balanceResults) {
@@ -7261,6 +7371,36 @@ var OwneySDK = class {
7261
7371
  history
7262
7372
  };
7263
7373
  }
7374
+ async enrichApyHistory(accountApy, agentId, chainId, tokenSymbol) {
7375
+ const history = accountApy.history;
7376
+ if (agentId !== "zyfai" || chainId === void 0 || !tokenSymbol || !history?.length) return accountApy;
7377
+ const incentives = await fetchApyIncentives(
7378
+ this.apiKey,
7379
+ {
7380
+ walletAddress: accountApy.walletAddress,
7381
+ agentId,
7382
+ chainId,
7383
+ asset: tokenSymbol,
7384
+ from: history[0].date,
7385
+ to: history[history.length - 1].date
7386
+ },
7387
+ this.routingApiBaseUrl
7388
+ );
7389
+ if (incentives.length === 0) return accountApy;
7390
+ const byDate = /* @__PURE__ */ new Map();
7391
+ for (const { date, ...incentive } of incentives) {
7392
+ const entries = byDate.get(date) ?? [];
7393
+ entries.push(incentive);
7394
+ byDate.set(date, entries);
7395
+ }
7396
+ return {
7397
+ ...accountApy,
7398
+ history: history.map((point) => {
7399
+ const pointIncentives = byDate.get(point.date);
7400
+ return pointIncentives?.length ? { ...point, incentives: pointIncentives } : point;
7401
+ })
7402
+ };
7403
+ }
7264
7404
  /**
7265
7405
  * Get transaction history for a specific agent, or all agents.
7266
7406
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@owney/sdk",
3
- "version": "0.7.34",
3
+ "version": "0.7.36",
4
4
  "type": "module",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.js",