@owney/sdk 0.7.32 → 0.7.34-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -2618,6 +2618,35 @@ function mergeDailyEarnings(series) {
2618
2618
 
2619
2619
  // src/lib/routing-api.ts
2620
2620
  var ROUTING_API_BASE_URL = "https://owney-routing-api-243946518160.europe-west4.run.app";
2621
+ async function fetchApyIncentives(apiKey, input, baseUrl = ROUTING_API_BASE_URL) {
2622
+ const query = new URLSearchParams({
2623
+ walletAddress: input.walletAddress,
2624
+ agentId: input.agentId,
2625
+ chainId: String(input.chainId),
2626
+ asset: input.asset.toUpperCase(),
2627
+ from: input.from,
2628
+ to: input.to
2629
+ });
2630
+ try {
2631
+ const response = await fetch(`${baseUrl}/api/v1/apy-incentives?${query}`, {
2632
+ headers: {
2633
+ Accept: "application/json",
2634
+ "x-owney-api-key": apiKey
2635
+ }
2636
+ });
2637
+ if (!response.ok) return [];
2638
+ const body = await response.json();
2639
+ if (!body.success || !Array.isArray(body.data)) return [];
2640
+ return body.data.filter(
2641
+ (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)
2642
+ );
2643
+ } catch (error) {
2644
+ debugLog("owney-sdk", "APY incentives unavailable; using native APY", {
2645
+ error: error instanceof Error ? error.message : String(error)
2646
+ });
2647
+ return [];
2648
+ }
2649
+ }
2621
2650
  async function fetchOrgAgentConfig(apiKey, baseUrl = ROUTING_API_BASE_URL) {
2622
2651
  const url = `${baseUrl}/api/v1/agent/org-config`;
2623
2652
  try {
@@ -2689,7 +2718,7 @@ var CHAIN_NAMES = {
2689
2718
  function chainName(chainId) {
2690
2719
  return CHAIN_NAMES[chainId] ?? `chain ${chainId}`;
2691
2720
  }
2692
- var SETTLE_TIMEOUT_MS = 15e3;
2721
+ var SETTLE_TIMEOUT_MS = 8e3;
2693
2722
  var POLL_INTERVAL_MS = 200;
2694
2723
  var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2695
2724
  async function readChainId(pub) {
@@ -4306,9 +4335,40 @@ function aggregateApyHistory(agentApys) {
4306
4335
  const total = points.reduce((sum, p) => sum + p.historicalBalance.amount, 0);
4307
4336
  if (total <= 0 || !Number.isFinite(total)) return [];
4308
4337
  const apy = points.reduce((sum, p) => sum + p.apy * (p.historicalBalance.amount / total), 0);
4309
- return Number.isFinite(apy) ? [{ date, apy }] : [];
4338
+ if (!Number.isFinite(apy)) return [];
4339
+ const incentives = aggregateIncentives(points, total);
4340
+ return [{ date, apy, ...incentives.length > 0 ? { incentives } : {} }];
4310
4341
  });
4311
4342
  }
4343
+ function incentiveKey(incentive) {
4344
+ return JSON.stringify([
4345
+ incentive.source,
4346
+ incentive.agentId,
4347
+ incentive.opportunityId,
4348
+ [...incentive.campaignIds].sort()
4349
+ ]);
4350
+ }
4351
+ function aggregateIncentives(points, totalBalance) {
4352
+ const byProgram = /* @__PURE__ */ new Map();
4353
+ for (const point of points) {
4354
+ const weight = point.historicalBalance.amount / totalBalance;
4355
+ for (const incentive of point.incentives ?? []) {
4356
+ if (!Number.isFinite(incentive.apr) || !Number.isFinite(incentive.apyContribution)) continue;
4357
+ const key2 = incentiveKey(incentive);
4358
+ const existing = byProgram.get(key2);
4359
+ if (existing) {
4360
+ existing.apyContribution += incentive.apyContribution * weight;
4361
+ } else {
4362
+ byProgram.set(key2, {
4363
+ ...incentive,
4364
+ campaignIds: [...incentive.campaignIds],
4365
+ apyContribution: incentive.apyContribution * weight
4366
+ });
4367
+ }
4368
+ }
4369
+ }
4370
+ return [...byProgram.values()];
4371
+ }
4312
4372
  function aggregateApyByChainAndAsset(agentApys, agentBalances) {
4313
4373
  const sums = {};
4314
4374
  const weights = {};
@@ -4590,16 +4650,6 @@ function makeSponsoredDepositCallback(deps) {
4590
4650
 
4591
4651
  // src/lib/walletconnect-switch.ts
4592
4652
  var WALLET_SWITCH_TIMEOUT_MS = 12e4;
4593
- var HOLD_CHAIN_MS = 15e3;
4594
- var MAX_RESENDS = 2;
4595
- var holds = /* @__PURE__ */ new WeakMap();
4596
- function parseChainId(raw) {
4597
- if (typeof raw === "number") return raw;
4598
- if (typeof raw !== "string") return void 0;
4599
- const ref = raw.split(":").pop() ?? raw;
4600
- const id = ref.startsWith("0x") ? Number.parseInt(ref, 16) : Number(ref);
4601
- return Number.isFinite(id) ? id : void 0;
4602
- }
4603
4653
  function walletConnectCore(provider) {
4604
4654
  const p = provider;
4605
4655
  const core = p?.signer ?? p;
@@ -4613,12 +4663,6 @@ function walletConnectCore(provider) {
4613
4663
  async function switchWalletConnectChain(provider, chainId, timeoutMs = WALLET_SWITCH_TIMEOUT_MS) {
4614
4664
  const core = walletConnectCore(provider);
4615
4665
  if (!core) return false;
4616
- holds.get(core)?.();
4617
- await requestSwitch(core, provider, chainId, timeoutMs);
4618
- holdChain(core, provider, chainId);
4619
- return true;
4620
- }
4621
- async function requestSwitch(core, provider, chainId, timeoutMs) {
4622
4666
  const current = Number(
4623
4667
  await provider.request({ method: "eth_chainId" })
4624
4668
  );
@@ -4650,36 +4694,7 @@ async function requestSwitch(core, provider, chainId, timeoutMs) {
4650
4694
  core.setDefaultChain(`eip155:${chainId}`);
4651
4695
  } catch {
4652
4696
  }
4653
- }
4654
- function holdChain(core, provider, chainId) {
4655
- if (typeof core.on !== "function" || typeof core.removeListener !== "function") {
4656
- return;
4657
- }
4658
- let resends = 0;
4659
- const listener = (raw) => {
4660
- const reported = parseChainId(raw);
4661
- debugLog("wc-switch", "wallet reported chain", {
4662
- reported,
4663
- holding: chainId,
4664
- resends
4665
- });
4666
- if (reported === void 0 || reported === chainId) return;
4667
- if (resends >= MAX_RESENDS) return;
4668
- resends += 1;
4669
- void requestSwitch(core, provider, chainId, WALLET_SWITCH_TIMEOUT_MS).catch(
4670
- (error) => debugLog("wc-switch", "re-switch failed", {
4671
- error: error instanceof Error ? error.message : String(error)
4672
- })
4673
- );
4674
- };
4675
- const release = () => {
4676
- clearTimeout(timer);
4677
- core.removeListener?.("chainChanged", listener);
4678
- if (holds.get(core) === release) holds.delete(core);
4679
- };
4680
- const timer = setTimeout(release, HOLD_CHAIN_MS);
4681
- core.on("chainChanged", listener);
4682
- holds.set(core, release);
4697
+ return true;
4683
4698
  }
4684
4699
  function withWalletConnectSwitch(provider) {
4685
4700
  if (!walletConnectCore(provider)) return provider;
@@ -7199,12 +7214,18 @@ var OwneySDK = class {
7199
7214
  const scopeChainId = scope === "all" ? null : scope;
7200
7215
  if (agentId) {
7201
7216
  const agent = this.getAgent(agentId);
7202
- return this.readAgent(
7217
+ const accountApy = await this.readAgent(
7203
7218
  agent,
7204
7219
  "accountApy",
7205
7220
  () => agent.getAccountApy(state, chainId, days, tokenSymbol, scopeChainId),
7206
7221
  { days, tokenSymbol, scopeChainId }
7207
7222
  );
7223
+ return this.enrichApyHistory(
7224
+ accountApy,
7225
+ agentId,
7226
+ scopeChainId === null ? void 0 : scopeChainId ?? chainId,
7227
+ tokenSymbol
7228
+ );
7208
7229
  }
7209
7230
  const activeAgents = this.getActiveAgents();
7210
7231
  const entries = [...activeAgents.entries()];
@@ -7239,7 +7260,12 @@ var OwneySDK = class {
7239
7260
  ]);
7240
7261
  const results = {};
7241
7262
  for (const [id, apy] of apyResults) {
7242
- results[id] = apy;
7263
+ results[id] = await this.enrichApyHistory(
7264
+ apy,
7265
+ id,
7266
+ scopeChainId === null ? void 0 : scopeChainId ?? chainId,
7267
+ tokenSymbol
7268
+ );
7243
7269
  }
7244
7270
  const balances = {};
7245
7271
  for (const [id, bal] of balanceResults) {
@@ -7269,6 +7295,36 @@ var OwneySDK = class {
7269
7295
  history
7270
7296
  };
7271
7297
  }
7298
+ async enrichApyHistory(accountApy, agentId, chainId, tokenSymbol) {
7299
+ const history = accountApy.history;
7300
+ if (agentId !== "zyfai" || chainId === void 0 || !tokenSymbol || !history?.length) return accountApy;
7301
+ const incentives = await fetchApyIncentives(
7302
+ this.apiKey,
7303
+ {
7304
+ walletAddress: accountApy.walletAddress,
7305
+ agentId,
7306
+ chainId,
7307
+ asset: tokenSymbol,
7308
+ from: history[0].date,
7309
+ to: history[history.length - 1].date
7310
+ },
7311
+ this.routingApiBaseUrl
7312
+ );
7313
+ if (incentives.length === 0) return accountApy;
7314
+ const byDate = /* @__PURE__ */ new Map();
7315
+ for (const { date, ...incentive } of incentives) {
7316
+ const entries = byDate.get(date) ?? [];
7317
+ entries.push(incentive);
7318
+ byDate.set(date, entries);
7319
+ }
7320
+ return {
7321
+ ...accountApy,
7322
+ history: history.map((point) => {
7323
+ const pointIncentives = byDate.get(point.date);
7324
+ return pointIncentives?.length ? { ...point, incentives: pointIncentives } : point;
7325
+ })
7326
+ };
7327
+ }
7272
7328
  /**
7273
7329
  * Get transaction history for a specific agent, or all agents.
7274
7330
  *
package/dist/index.d.cts CHANGED
@@ -715,17 +715,31 @@ interface OwneyEarnings {
715
715
  agentEarnings: Record<AgentId, AgentEarnings>;
716
716
  }
717
717
  type ApyByChainAndAsset = Partial<Record<OwneySupportedChainId, Partial<Record<OwneySupportedTokens, number>>>>;
718
+ /** One external reward program contributing percentage points to a day. */
719
+ interface ApyIncentive {
720
+ source: "merkl";
721
+ agentId: AgentId;
722
+ opportunityId: string;
723
+ /** All on-chain campaigns represented by the opportunity APR that day. */
724
+ campaignIds: string[];
725
+ /** Source APR before portfolio weighting, expressed as a percentage. */
726
+ apr: number;
727
+ /** Percentage points to add to this point's native/provider `apy`. */
728
+ apyContribution: number;
729
+ }
718
730
  /** A single day's net APY for the connected account, as a percentage number. */
719
731
  interface ApyHistoryPoint {
720
732
  /** ISO date string for the day, e.g. "2026-06-20". */
721
733
  date: string;
722
- /** Net (after-fee) weighted APY for that day, summed across tokens. */
734
+ /** Native/provider net APY. External incentives are deliberately excluded. */
723
735
  apy: number;
724
736
  /** Balance on this date, in the explicitly named unit; never today's balance. */
725
737
  historicalBalance?: {
726
738
  amount: number;
727
739
  unit: string;
728
740
  };
741
+ /** Best-effort external rewards. Absent when none apply or cannot be read. */
742
+ incentives?: ApyIncentive[];
729
743
  }
730
744
  /**
731
745
  * What the APY chart's chain/asset menus are allowed to offer, and how far
@@ -1848,6 +1862,7 @@ declare class OwneySDK {
1848
1862
  agentId?: AgentId;
1849
1863
  }): Promise<SavedPoolSelection>;
1850
1864
  getAccountApy({ agentId, days, tokenSymbol, chainId: scope, }: AccountApyOptions): Promise<OwneyAccountApy | AccountAgentApy>;
1865
+ private enrichApyHistory;
1851
1866
  /**
1852
1867
  * Get transaction history for a specific agent, or all agents.
1853
1868
  *
@@ -2006,4 +2021,4 @@ type StoredOrder = {
2006
2021
  */
2007
2022
  declare function listOrders(now?: number): StoredOrder[];
2008
2023
 
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 };
2024
+ 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 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
@@ -715,17 +715,31 @@ interface OwneyEarnings {
715
715
  agentEarnings: Record<AgentId, AgentEarnings>;
716
716
  }
717
717
  type ApyByChainAndAsset = Partial<Record<OwneySupportedChainId, Partial<Record<OwneySupportedTokens, number>>>>;
718
+ /** One external reward program contributing percentage points to a day. */
719
+ interface ApyIncentive {
720
+ source: "merkl";
721
+ agentId: AgentId;
722
+ opportunityId: string;
723
+ /** All on-chain campaigns represented by the opportunity APR that day. */
724
+ campaignIds: string[];
725
+ /** Source APR before portfolio weighting, expressed as a percentage. */
726
+ apr: number;
727
+ /** Percentage points to add to this point's native/provider `apy`. */
728
+ apyContribution: number;
729
+ }
718
730
  /** A single day's net APY for the connected account, as a percentage number. */
719
731
  interface ApyHistoryPoint {
720
732
  /** ISO date string for the day, e.g. "2026-06-20". */
721
733
  date: string;
722
- /** Net (after-fee) weighted APY for that day, summed across tokens. */
734
+ /** Native/provider net APY. External incentives are deliberately excluded. */
723
735
  apy: number;
724
736
  /** Balance on this date, in the explicitly named unit; never today's balance. */
725
737
  historicalBalance?: {
726
738
  amount: number;
727
739
  unit: string;
728
740
  };
741
+ /** Best-effort external rewards. Absent when none apply or cannot be read. */
742
+ incentives?: ApyIncentive[];
729
743
  }
730
744
  /**
731
745
  * What the APY chart's chain/asset menus are allowed to offer, and how far
@@ -1848,6 +1862,7 @@ declare class OwneySDK {
1848
1862
  agentId?: AgentId;
1849
1863
  }): Promise<SavedPoolSelection>;
1850
1864
  getAccountApy({ agentId, days, tokenSymbol, chainId: scope, }: AccountApyOptions): Promise<OwneyAccountApy | AccountAgentApy>;
1865
+ private enrichApyHistory;
1851
1866
  /**
1852
1867
  * Get transaction history for a specific agent, or all agents.
1853
1868
  *
@@ -2006,4 +2021,4 @@ type StoredOrder = {
2006
2021
  */
2007
2022
  declare function listOrders(now?: number): StoredOrder[];
2008
2023
 
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 };
2024
+ 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 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
@@ -2577,6 +2577,35 @@ function mergeDailyEarnings(series) {
2577
2577
 
2578
2578
  // src/lib/routing-api.ts
2579
2579
  var ROUTING_API_BASE_URL = "https://owney-routing-api-243946518160.europe-west4.run.app";
2580
+ async function fetchApyIncentives(apiKey, input, baseUrl = ROUTING_API_BASE_URL) {
2581
+ const query = new URLSearchParams({
2582
+ walletAddress: input.walletAddress,
2583
+ agentId: input.agentId,
2584
+ chainId: String(input.chainId),
2585
+ asset: input.asset.toUpperCase(),
2586
+ from: input.from,
2587
+ to: input.to
2588
+ });
2589
+ try {
2590
+ const response = await fetch(`${baseUrl}/api/v1/apy-incentives?${query}`, {
2591
+ headers: {
2592
+ Accept: "application/json",
2593
+ "x-owney-api-key": apiKey
2594
+ }
2595
+ });
2596
+ if (!response.ok) return [];
2597
+ const body = await response.json();
2598
+ if (!body.success || !Array.isArray(body.data)) return [];
2599
+ return body.data.filter(
2600
+ (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)
2601
+ );
2602
+ } catch (error) {
2603
+ debugLog("owney-sdk", "APY incentives unavailable; using native APY", {
2604
+ error: error instanceof Error ? error.message : String(error)
2605
+ });
2606
+ return [];
2607
+ }
2608
+ }
2580
2609
  async function fetchOrgAgentConfig(apiKey, baseUrl = ROUTING_API_BASE_URL) {
2581
2610
  const url = `${baseUrl}/api/v1/agent/org-config`;
2582
2611
  try {
@@ -2648,7 +2677,7 @@ var CHAIN_NAMES = {
2648
2677
  function chainName(chainId) {
2649
2678
  return CHAIN_NAMES[chainId] ?? `chain ${chainId}`;
2650
2679
  }
2651
- var SETTLE_TIMEOUT_MS = 15e3;
2680
+ var SETTLE_TIMEOUT_MS = 8e3;
2652
2681
  var POLL_INTERVAL_MS = 200;
2653
2682
  var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2654
2683
  async function readChainId(pub) {
@@ -4280,9 +4309,40 @@ function aggregateApyHistory(agentApys) {
4280
4309
  const total = points.reduce((sum, p) => sum + p.historicalBalance.amount, 0);
4281
4310
  if (total <= 0 || !Number.isFinite(total)) return [];
4282
4311
  const apy = points.reduce((sum, p) => sum + p.apy * (p.historicalBalance.amount / total), 0);
4283
- return Number.isFinite(apy) ? [{ date, apy }] : [];
4312
+ if (!Number.isFinite(apy)) return [];
4313
+ const incentives = aggregateIncentives(points, total);
4314
+ return [{ date, apy, ...incentives.length > 0 ? { incentives } : {} }];
4284
4315
  });
4285
4316
  }
4317
+ function incentiveKey(incentive) {
4318
+ return JSON.stringify([
4319
+ incentive.source,
4320
+ incentive.agentId,
4321
+ incentive.opportunityId,
4322
+ [...incentive.campaignIds].sort()
4323
+ ]);
4324
+ }
4325
+ function aggregateIncentives(points, totalBalance) {
4326
+ const byProgram = /* @__PURE__ */ new Map();
4327
+ for (const point of points) {
4328
+ const weight = point.historicalBalance.amount / totalBalance;
4329
+ for (const incentive of point.incentives ?? []) {
4330
+ if (!Number.isFinite(incentive.apr) || !Number.isFinite(incentive.apyContribution)) continue;
4331
+ const key2 = incentiveKey(incentive);
4332
+ const existing = byProgram.get(key2);
4333
+ if (existing) {
4334
+ existing.apyContribution += incentive.apyContribution * weight;
4335
+ } else {
4336
+ byProgram.set(key2, {
4337
+ ...incentive,
4338
+ campaignIds: [...incentive.campaignIds],
4339
+ apyContribution: incentive.apyContribution * weight
4340
+ });
4341
+ }
4342
+ }
4343
+ }
4344
+ return [...byProgram.values()];
4345
+ }
4286
4346
  function aggregateApyByChainAndAsset(agentApys, agentBalances) {
4287
4347
  const sums = {};
4288
4348
  const weights = {};
@@ -4570,16 +4630,6 @@ function makeSponsoredDepositCallback(deps) {
4570
4630
 
4571
4631
  // src/lib/walletconnect-switch.ts
4572
4632
  var WALLET_SWITCH_TIMEOUT_MS = 12e4;
4573
- var HOLD_CHAIN_MS = 15e3;
4574
- var MAX_RESENDS = 2;
4575
- var holds = /* @__PURE__ */ new WeakMap();
4576
- function parseChainId(raw) {
4577
- if (typeof raw === "number") return raw;
4578
- if (typeof raw !== "string") return void 0;
4579
- const ref = raw.split(":").pop() ?? raw;
4580
- const id = ref.startsWith("0x") ? Number.parseInt(ref, 16) : Number(ref);
4581
- return Number.isFinite(id) ? id : void 0;
4582
- }
4583
4633
  function walletConnectCore(provider) {
4584
4634
  const p = provider;
4585
4635
  const core = p?.signer ?? p;
@@ -4593,12 +4643,6 @@ function walletConnectCore(provider) {
4593
4643
  async function switchWalletConnectChain(provider, chainId, timeoutMs = WALLET_SWITCH_TIMEOUT_MS) {
4594
4644
  const core = walletConnectCore(provider);
4595
4645
  if (!core) return false;
4596
- holds.get(core)?.();
4597
- await requestSwitch(core, provider, chainId, timeoutMs);
4598
- holdChain(core, provider, chainId);
4599
- return true;
4600
- }
4601
- async function requestSwitch(core, provider, chainId, timeoutMs) {
4602
4646
  const current = Number(
4603
4647
  await provider.request({ method: "eth_chainId" })
4604
4648
  );
@@ -4630,36 +4674,7 @@ async function requestSwitch(core, provider, chainId, timeoutMs) {
4630
4674
  core.setDefaultChain(`eip155:${chainId}`);
4631
4675
  } catch {
4632
4676
  }
4633
- }
4634
- function holdChain(core, provider, chainId) {
4635
- if (typeof core.on !== "function" || typeof core.removeListener !== "function") {
4636
- return;
4637
- }
4638
- let resends = 0;
4639
- const listener = (raw) => {
4640
- const reported = parseChainId(raw);
4641
- debugLog("wc-switch", "wallet reported chain", {
4642
- reported,
4643
- holding: chainId,
4644
- resends
4645
- });
4646
- if (reported === void 0 || reported === chainId) return;
4647
- if (resends >= MAX_RESENDS) return;
4648
- resends += 1;
4649
- void requestSwitch(core, provider, chainId, WALLET_SWITCH_TIMEOUT_MS).catch(
4650
- (error) => debugLog("wc-switch", "re-switch failed", {
4651
- error: error instanceof Error ? error.message : String(error)
4652
- })
4653
- );
4654
- };
4655
- const release = () => {
4656
- clearTimeout(timer);
4657
- core.removeListener?.("chainChanged", listener);
4658
- if (holds.get(core) === release) holds.delete(core);
4659
- };
4660
- const timer = setTimeout(release, HOLD_CHAIN_MS);
4661
- core.on("chainChanged", listener);
4662
- holds.set(core, release);
4677
+ return true;
4663
4678
  }
4664
4679
  function withWalletConnectSwitch(provider) {
4665
4680
  if (!walletConnectCore(provider)) return provider;
@@ -7179,12 +7194,18 @@ var OwneySDK = class {
7179
7194
  const scopeChainId = scope === "all" ? null : scope;
7180
7195
  if (agentId) {
7181
7196
  const agent = this.getAgent(agentId);
7182
- return this.readAgent(
7197
+ const accountApy = await this.readAgent(
7183
7198
  agent,
7184
7199
  "accountApy",
7185
7200
  () => agent.getAccountApy(state, chainId, days, tokenSymbol, scopeChainId),
7186
7201
  { days, tokenSymbol, scopeChainId }
7187
7202
  );
7203
+ return this.enrichApyHistory(
7204
+ accountApy,
7205
+ agentId,
7206
+ scopeChainId === null ? void 0 : scopeChainId ?? chainId,
7207
+ tokenSymbol
7208
+ );
7188
7209
  }
7189
7210
  const activeAgents = this.getActiveAgents();
7190
7211
  const entries = [...activeAgents.entries()];
@@ -7219,7 +7240,12 @@ var OwneySDK = class {
7219
7240
  ]);
7220
7241
  const results = {};
7221
7242
  for (const [id, apy] of apyResults) {
7222
- results[id] = apy;
7243
+ results[id] = await this.enrichApyHistory(
7244
+ apy,
7245
+ id,
7246
+ scopeChainId === null ? void 0 : scopeChainId ?? chainId,
7247
+ tokenSymbol
7248
+ );
7223
7249
  }
7224
7250
  const balances = {};
7225
7251
  for (const [id, bal] of balanceResults) {
@@ -7249,6 +7275,36 @@ var OwneySDK = class {
7249
7275
  history
7250
7276
  };
7251
7277
  }
7278
+ async enrichApyHistory(accountApy, agentId, chainId, tokenSymbol) {
7279
+ const history = accountApy.history;
7280
+ if (agentId !== "zyfai" || chainId === void 0 || !tokenSymbol || !history?.length) return accountApy;
7281
+ const incentives = await fetchApyIncentives(
7282
+ this.apiKey,
7283
+ {
7284
+ walletAddress: accountApy.walletAddress,
7285
+ agentId,
7286
+ chainId,
7287
+ asset: tokenSymbol,
7288
+ from: history[0].date,
7289
+ to: history[history.length - 1].date
7290
+ },
7291
+ this.routingApiBaseUrl
7292
+ );
7293
+ if (incentives.length === 0) return accountApy;
7294
+ const byDate = /* @__PURE__ */ new Map();
7295
+ for (const { date, ...incentive } of incentives) {
7296
+ const entries = byDate.get(date) ?? [];
7297
+ entries.push(incentive);
7298
+ byDate.set(date, entries);
7299
+ }
7300
+ return {
7301
+ ...accountApy,
7302
+ history: history.map((point) => {
7303
+ const pointIncentives = byDate.get(point.date);
7304
+ return pointIncentives?.length ? { ...point, incentives: pointIncentives } : point;
7305
+ })
7306
+ };
7307
+ }
7252
7308
  /**
7253
7309
  * Get transaction history for a specific agent, or all agents.
7254
7310
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@owney/sdk",
3
- "version": "0.7.32",
3
+ "version": "0.7.34-beta.0",
4
4
  "type": "module",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.js",