@owney/sdk 0.7.34-beta.0 → 0.7.34

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
@@ -1383,11 +1383,12 @@ var ZyfaiAgent = class _ZyfaiAgent {
1383
1383
  if (typeof window === "undefined") return;
1384
1384
  const internals = this.sdk;
1385
1385
  const original = internals.authenticateUser.bind(internals);
1386
- internals.authenticateUser = async () => {
1386
+ let inFlight = null;
1387
+ const authenticate = async () => {
1387
1388
  if (internals.authenticatedUserId !== null) return;
1388
1389
  const address = internals.walletClient?.account?.address;
1389
- const chainId = internals.currentChainId;
1390
- if (address && chainId) {
1390
+ const chainId = internals.currentChainId ?? 0;
1391
+ if (address) {
1391
1392
  const cached = readSession(address, chainId);
1392
1393
  if (cached) {
1393
1394
  internals.httpClient.setAuthToken(cached.token);
@@ -1399,9 +1400,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
1399
1400
  }
1400
1401
  await original();
1401
1402
  const newAddress = internals.walletClient?.account?.address;
1402
- const newChainId = internals.currentChainId;
1403
+ const newChainId = internals.currentChainId ?? 0;
1403
1404
  const newToken = internals.httpClient.authToken;
1404
- if (newAddress && newChainId && newToken) {
1405
+ if (newAddress && newToken) {
1405
1406
  writeSession(newAddress, newChainId, {
1406
1407
  token: newToken,
1407
1408
  userId: internals.authenticatedUserId,
@@ -1410,6 +1411,15 @@ var ZyfaiAgent = class _ZyfaiAgent {
1410
1411
  });
1411
1412
  }
1412
1413
  };
1414
+ internals.authenticateUser = () => {
1415
+ const address = internals.walletClient?.account?.address?.toLowerCase();
1416
+ if (inFlight && inFlight.address === address) return inFlight.promise;
1417
+ const promise = authenticate().finally(() => {
1418
+ if (inFlight?.promise === promise) inFlight = null;
1419
+ });
1420
+ inFlight = { address, promise };
1421
+ return promise;
1422
+ };
1413
1423
  }
1414
1424
  // --- Private helpers ---
1415
1425
  getAddress() {
@@ -2618,35 +2628,6 @@ function mergeDailyEarnings(series) {
2618
2628
 
2619
2629
  // src/lib/routing-api.ts
2620
2630
  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
- }
2650
2631
  async function fetchOrgAgentConfig(apiKey, baseUrl = ROUTING_API_BASE_URL) {
2651
2632
  const url = `${baseUrl}/api/v1/agent/org-config`;
2652
2633
  try {
@@ -2718,7 +2699,7 @@ var CHAIN_NAMES = {
2718
2699
  function chainName(chainId) {
2719
2700
  return CHAIN_NAMES[chainId] ?? `chain ${chainId}`;
2720
2701
  }
2721
- var SETTLE_TIMEOUT_MS = 8e3;
2702
+ var SETTLE_TIMEOUT_MS = 15e3;
2722
2703
  var POLL_INTERVAL_MS = 200;
2723
2704
  var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2724
2705
  async function readChainId(pub) {
@@ -4335,40 +4316,9 @@ function aggregateApyHistory(agentApys) {
4335
4316
  const total = points.reduce((sum, p) => sum + p.historicalBalance.amount, 0);
4336
4317
  if (total <= 0 || !Number.isFinite(total)) return [];
4337
4318
  const apy = points.reduce((sum, p) => sum + p.apy * (p.historicalBalance.amount / total), 0);
4338
- if (!Number.isFinite(apy)) return [];
4339
- const incentives = aggregateIncentives(points, total);
4340
- return [{ date, apy, ...incentives.length > 0 ? { incentives } : {} }];
4319
+ return Number.isFinite(apy) ? [{ date, apy }] : [];
4341
4320
  });
4342
4321
  }
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
- }
4372
4322
  function aggregateApyByChainAndAsset(agentApys, agentBalances) {
4373
4323
  const sums = {};
4374
4324
  const weights = {};
@@ -4650,6 +4600,16 @@ function makeSponsoredDepositCallback(deps) {
4650
4600
 
4651
4601
  // src/lib/walletconnect-switch.ts
4652
4602
  var WALLET_SWITCH_TIMEOUT_MS = 12e4;
4603
+ var HOLD_CHAIN_MS = 15e3;
4604
+ var MAX_RESENDS = 2;
4605
+ var holds = /* @__PURE__ */ new Map();
4606
+ function parseChainId(raw) {
4607
+ if (typeof raw === "number") return raw;
4608
+ if (typeof raw !== "string") return void 0;
4609
+ const ref = raw.split(":").pop() ?? raw;
4610
+ const id = ref.startsWith("0x") ? Number.parseInt(ref, 16) : Number(ref);
4611
+ return Number.isFinite(id) ? id : void 0;
4612
+ }
4653
4613
  function walletConnectCore(provider) {
4654
4614
  const p = provider;
4655
4615
  const core = p?.signer ?? p;
@@ -4663,6 +4623,12 @@ function walletConnectCore(provider) {
4663
4623
  async function switchWalletConnectChain(provider, chainId, timeoutMs = WALLET_SWITCH_TIMEOUT_MS) {
4664
4624
  const core = walletConnectCore(provider);
4665
4625
  if (!core) return false;
4626
+ holds.get(core.session.topic)?.();
4627
+ await requestSwitch(core, provider, chainId, timeoutMs);
4628
+ holdChain(core, provider, chainId);
4629
+ return true;
4630
+ }
4631
+ async function requestSwitch(core, provider, chainId, timeoutMs) {
4666
4632
  const current = Number(
4667
4633
  await provider.request({ method: "eth_chainId" })
4668
4634
  );
@@ -4694,7 +4660,38 @@ async function switchWalletConnectChain(provider, chainId, timeoutMs = WALLET_SW
4694
4660
  core.setDefaultChain(`eip155:${chainId}`);
4695
4661
  } catch {
4696
4662
  }
4697
- return true;
4663
+ }
4664
+ function holdChain(core, provider, chainId) {
4665
+ if (typeof core.on !== "function" || typeof core.removeListener !== "function") {
4666
+ return;
4667
+ }
4668
+ let resends = 0;
4669
+ const listener = (raw) => {
4670
+ const reported = parseChainId(raw);
4671
+ debugLog("wc-switch", "wallet reported chain", {
4672
+ reported,
4673
+ holding: chainId,
4674
+ resends
4675
+ });
4676
+ if (reported === void 0 || reported === chainId) return;
4677
+ if (resends >= MAX_RESENDS) return;
4678
+ resends += 1;
4679
+ void requestSwitch(core, provider, chainId, WALLET_SWITCH_TIMEOUT_MS).catch(
4680
+ (error) => debugLog("wc-switch", "re-switch failed", {
4681
+ error: error instanceof Error ? error.message : String(error)
4682
+ })
4683
+ );
4684
+ };
4685
+ const release = () => {
4686
+ clearTimeout(timer);
4687
+ core.removeListener?.("chainChanged", listener);
4688
+ if (holds.get(core.session.topic) === release) {
4689
+ holds.delete(core.session.topic);
4690
+ }
4691
+ };
4692
+ const timer = setTimeout(release, HOLD_CHAIN_MS);
4693
+ core.on("chainChanged", listener);
4694
+ holds.set(core.session.topic, release);
4698
4695
  }
4699
4696
  function withWalletConnectSwitch(provider) {
4700
4697
  if (!walletConnectCore(provider)) return provider;
@@ -7214,18 +7211,12 @@ var OwneySDK = class {
7214
7211
  const scopeChainId = scope === "all" ? null : scope;
7215
7212
  if (agentId) {
7216
7213
  const agent = this.getAgent(agentId);
7217
- const accountApy = await this.readAgent(
7214
+ return this.readAgent(
7218
7215
  agent,
7219
7216
  "accountApy",
7220
7217
  () => agent.getAccountApy(state, chainId, days, tokenSymbol, scopeChainId),
7221
7218
  { days, tokenSymbol, scopeChainId }
7222
7219
  );
7223
- return this.enrichApyHistory(
7224
- accountApy,
7225
- agentId,
7226
- scopeChainId === null ? void 0 : scopeChainId ?? chainId,
7227
- tokenSymbol
7228
- );
7229
7220
  }
7230
7221
  const activeAgents = this.getActiveAgents();
7231
7222
  const entries = [...activeAgents.entries()];
@@ -7260,12 +7251,7 @@ var OwneySDK = class {
7260
7251
  ]);
7261
7252
  const results = {};
7262
7253
  for (const [id, apy] of apyResults) {
7263
- results[id] = await this.enrichApyHistory(
7264
- apy,
7265
- id,
7266
- scopeChainId === null ? void 0 : scopeChainId ?? chainId,
7267
- tokenSymbol
7268
- );
7254
+ results[id] = apy;
7269
7255
  }
7270
7256
  const balances = {};
7271
7257
  for (const [id, bal] of balanceResults) {
@@ -7295,36 +7281,6 @@ var OwneySDK = class {
7295
7281
  history
7296
7282
  };
7297
7283
  }
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
- }
7328
7284
  /**
7329
7285
  * Get transaction history for a specific agent, or all agents.
7330
7286
  *
package/dist/index.d.cts CHANGED
@@ -715,31 +715,17 @@ 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
- }
730
718
  /** A single day's net APY for the connected account, as a percentage number. */
731
719
  interface ApyHistoryPoint {
732
720
  /** ISO date string for the day, e.g. "2026-06-20". */
733
721
  date: string;
734
- /** Native/provider net APY. External incentives are deliberately excluded. */
722
+ /** Net (after-fee) weighted APY for that day, summed across tokens. */
735
723
  apy: number;
736
724
  /** Balance on this date, in the explicitly named unit; never today's balance. */
737
725
  historicalBalance?: {
738
726
  amount: number;
739
727
  unit: string;
740
728
  };
741
- /** Best-effort external rewards. Absent when none apply or cannot be read. */
742
- incentives?: ApyIncentive[];
743
729
  }
744
730
  /**
745
731
  * What the APY chart's chain/asset menus are allowed to offer, and how far
@@ -1862,7 +1848,6 @@ declare class OwneySDK {
1862
1848
  agentId?: AgentId;
1863
1849
  }): Promise<SavedPoolSelection>;
1864
1850
  getAccountApy({ agentId, days, tokenSymbol, chainId: scope, }: AccountApyOptions): Promise<OwneyAccountApy | AccountAgentApy>;
1865
- private enrichApyHistory;
1866
1851
  /**
1867
1852
  * Get transaction history for a specific agent, or all agents.
1868
1853
  *
@@ -2021,4 +2006,4 @@ type StoredOrder = {
2021
2006
  */
2022
2007
  declare function listOrders(now?: number): StoredOrder[];
2023
2008
 
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 };
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 };
package/dist/index.d.ts CHANGED
@@ -715,31 +715,17 @@ 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
- }
730
718
  /** A single day's net APY for the connected account, as a percentage number. */
731
719
  interface ApyHistoryPoint {
732
720
  /** ISO date string for the day, e.g. "2026-06-20". */
733
721
  date: string;
734
- /** Native/provider net APY. External incentives are deliberately excluded. */
722
+ /** Net (after-fee) weighted APY for that day, summed across tokens. */
735
723
  apy: number;
736
724
  /** Balance on this date, in the explicitly named unit; never today's balance. */
737
725
  historicalBalance?: {
738
726
  amount: number;
739
727
  unit: string;
740
728
  };
741
- /** Best-effort external rewards. Absent when none apply or cannot be read. */
742
- incentives?: ApyIncentive[];
743
729
  }
744
730
  /**
745
731
  * What the APY chart's chain/asset menus are allowed to offer, and how far
@@ -1862,7 +1848,6 @@ declare class OwneySDK {
1862
1848
  agentId?: AgentId;
1863
1849
  }): Promise<SavedPoolSelection>;
1864
1850
  getAccountApy({ agentId, days, tokenSymbol, chainId: scope, }: AccountApyOptions): Promise<OwneyAccountApy | AccountAgentApy>;
1865
- private enrichApyHistory;
1866
1851
  /**
1867
1852
  * Get transaction history for a specific agent, or all agents.
1868
1853
  *
@@ -2021,4 +2006,4 @@ type StoredOrder = {
2021
2006
  */
2022
2007
  declare function listOrders(now?: number): StoredOrder[];
2023
2008
 
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 };
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 };
package/dist/index.js CHANGED
@@ -1342,11 +1342,12 @@ var ZyfaiAgent = class _ZyfaiAgent {
1342
1342
  if (typeof window === "undefined") return;
1343
1343
  const internals = this.sdk;
1344
1344
  const original = internals.authenticateUser.bind(internals);
1345
- internals.authenticateUser = async () => {
1345
+ let inFlight = null;
1346
+ const authenticate = async () => {
1346
1347
  if (internals.authenticatedUserId !== null) return;
1347
1348
  const address = internals.walletClient?.account?.address;
1348
- const chainId = internals.currentChainId;
1349
- if (address && chainId) {
1349
+ const chainId = internals.currentChainId ?? 0;
1350
+ if (address) {
1350
1351
  const cached = readSession(address, chainId);
1351
1352
  if (cached) {
1352
1353
  internals.httpClient.setAuthToken(cached.token);
@@ -1358,9 +1359,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
1358
1359
  }
1359
1360
  await original();
1360
1361
  const newAddress = internals.walletClient?.account?.address;
1361
- const newChainId = internals.currentChainId;
1362
+ const newChainId = internals.currentChainId ?? 0;
1362
1363
  const newToken = internals.httpClient.authToken;
1363
- if (newAddress && newChainId && newToken) {
1364
+ if (newAddress && newToken) {
1364
1365
  writeSession(newAddress, newChainId, {
1365
1366
  token: newToken,
1366
1367
  userId: internals.authenticatedUserId,
@@ -1369,6 +1370,15 @@ var ZyfaiAgent = class _ZyfaiAgent {
1369
1370
  });
1370
1371
  }
1371
1372
  };
1373
+ internals.authenticateUser = () => {
1374
+ const address = internals.walletClient?.account?.address?.toLowerCase();
1375
+ if (inFlight && inFlight.address === address) return inFlight.promise;
1376
+ const promise = authenticate().finally(() => {
1377
+ if (inFlight?.promise === promise) inFlight = null;
1378
+ });
1379
+ inFlight = { address, promise };
1380
+ return promise;
1381
+ };
1372
1382
  }
1373
1383
  // --- Private helpers ---
1374
1384
  getAddress() {
@@ -2577,35 +2587,6 @@ function mergeDailyEarnings(series) {
2577
2587
 
2578
2588
  // src/lib/routing-api.ts
2579
2589
  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
- }
2609
2590
  async function fetchOrgAgentConfig(apiKey, baseUrl = ROUTING_API_BASE_URL) {
2610
2591
  const url = `${baseUrl}/api/v1/agent/org-config`;
2611
2592
  try {
@@ -2677,7 +2658,7 @@ var CHAIN_NAMES = {
2677
2658
  function chainName(chainId) {
2678
2659
  return CHAIN_NAMES[chainId] ?? `chain ${chainId}`;
2679
2660
  }
2680
- var SETTLE_TIMEOUT_MS = 8e3;
2661
+ var SETTLE_TIMEOUT_MS = 15e3;
2681
2662
  var POLL_INTERVAL_MS = 200;
2682
2663
  var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2683
2664
  async function readChainId(pub) {
@@ -4309,40 +4290,9 @@ function aggregateApyHistory(agentApys) {
4309
4290
  const total = points.reduce((sum, p) => sum + p.historicalBalance.amount, 0);
4310
4291
  if (total <= 0 || !Number.isFinite(total)) return [];
4311
4292
  const apy = points.reduce((sum, p) => sum + p.apy * (p.historicalBalance.amount / total), 0);
4312
- if (!Number.isFinite(apy)) return [];
4313
- const incentives = aggregateIncentives(points, total);
4314
- return [{ date, apy, ...incentives.length > 0 ? { incentives } : {} }];
4293
+ return Number.isFinite(apy) ? [{ date, apy }] : [];
4315
4294
  });
4316
4295
  }
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
- }
4346
4296
  function aggregateApyByChainAndAsset(agentApys, agentBalances) {
4347
4297
  const sums = {};
4348
4298
  const weights = {};
@@ -4630,6 +4580,16 @@ function makeSponsoredDepositCallback(deps) {
4630
4580
 
4631
4581
  // src/lib/walletconnect-switch.ts
4632
4582
  var WALLET_SWITCH_TIMEOUT_MS = 12e4;
4583
+ var HOLD_CHAIN_MS = 15e3;
4584
+ var MAX_RESENDS = 2;
4585
+ var holds = /* @__PURE__ */ new Map();
4586
+ function parseChainId(raw) {
4587
+ if (typeof raw === "number") return raw;
4588
+ if (typeof raw !== "string") return void 0;
4589
+ const ref = raw.split(":").pop() ?? raw;
4590
+ const id = ref.startsWith("0x") ? Number.parseInt(ref, 16) : Number(ref);
4591
+ return Number.isFinite(id) ? id : void 0;
4592
+ }
4633
4593
  function walletConnectCore(provider) {
4634
4594
  const p = provider;
4635
4595
  const core = p?.signer ?? p;
@@ -4643,6 +4603,12 @@ function walletConnectCore(provider) {
4643
4603
  async function switchWalletConnectChain(provider, chainId, timeoutMs = WALLET_SWITCH_TIMEOUT_MS) {
4644
4604
  const core = walletConnectCore(provider);
4645
4605
  if (!core) return false;
4606
+ holds.get(core.session.topic)?.();
4607
+ await requestSwitch(core, provider, chainId, timeoutMs);
4608
+ holdChain(core, provider, chainId);
4609
+ return true;
4610
+ }
4611
+ async function requestSwitch(core, provider, chainId, timeoutMs) {
4646
4612
  const current = Number(
4647
4613
  await provider.request({ method: "eth_chainId" })
4648
4614
  );
@@ -4674,7 +4640,38 @@ async function switchWalletConnectChain(provider, chainId, timeoutMs = WALLET_SW
4674
4640
  core.setDefaultChain(`eip155:${chainId}`);
4675
4641
  } catch {
4676
4642
  }
4677
- return true;
4643
+ }
4644
+ function holdChain(core, provider, chainId) {
4645
+ if (typeof core.on !== "function" || typeof core.removeListener !== "function") {
4646
+ return;
4647
+ }
4648
+ let resends = 0;
4649
+ const listener = (raw) => {
4650
+ const reported = parseChainId(raw);
4651
+ debugLog("wc-switch", "wallet reported chain", {
4652
+ reported,
4653
+ holding: chainId,
4654
+ resends
4655
+ });
4656
+ if (reported === void 0 || reported === chainId) return;
4657
+ if (resends >= MAX_RESENDS) return;
4658
+ resends += 1;
4659
+ void requestSwitch(core, provider, chainId, WALLET_SWITCH_TIMEOUT_MS).catch(
4660
+ (error) => debugLog("wc-switch", "re-switch failed", {
4661
+ error: error instanceof Error ? error.message : String(error)
4662
+ })
4663
+ );
4664
+ };
4665
+ const release = () => {
4666
+ clearTimeout(timer);
4667
+ core.removeListener?.("chainChanged", listener);
4668
+ if (holds.get(core.session.topic) === release) {
4669
+ holds.delete(core.session.topic);
4670
+ }
4671
+ };
4672
+ const timer = setTimeout(release, HOLD_CHAIN_MS);
4673
+ core.on("chainChanged", listener);
4674
+ holds.set(core.session.topic, release);
4678
4675
  }
4679
4676
  function withWalletConnectSwitch(provider) {
4680
4677
  if (!walletConnectCore(provider)) return provider;
@@ -7194,18 +7191,12 @@ var OwneySDK = class {
7194
7191
  const scopeChainId = scope === "all" ? null : scope;
7195
7192
  if (agentId) {
7196
7193
  const agent = this.getAgent(agentId);
7197
- const accountApy = await this.readAgent(
7194
+ return this.readAgent(
7198
7195
  agent,
7199
7196
  "accountApy",
7200
7197
  () => agent.getAccountApy(state, chainId, days, tokenSymbol, scopeChainId),
7201
7198
  { days, tokenSymbol, scopeChainId }
7202
7199
  );
7203
- return this.enrichApyHistory(
7204
- accountApy,
7205
- agentId,
7206
- scopeChainId === null ? void 0 : scopeChainId ?? chainId,
7207
- tokenSymbol
7208
- );
7209
7200
  }
7210
7201
  const activeAgents = this.getActiveAgents();
7211
7202
  const entries = [...activeAgents.entries()];
@@ -7240,12 +7231,7 @@ var OwneySDK = class {
7240
7231
  ]);
7241
7232
  const results = {};
7242
7233
  for (const [id, apy] of apyResults) {
7243
- results[id] = await this.enrichApyHistory(
7244
- apy,
7245
- id,
7246
- scopeChainId === null ? void 0 : scopeChainId ?? chainId,
7247
- tokenSymbol
7248
- );
7234
+ results[id] = apy;
7249
7235
  }
7250
7236
  const balances = {};
7251
7237
  for (const [id, bal] of balanceResults) {
@@ -7275,36 +7261,6 @@ var OwneySDK = class {
7275
7261
  history
7276
7262
  };
7277
7263
  }
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
- }
7308
7264
  /**
7309
7265
  * Get transaction history for a specific agent, or all agents.
7310
7266
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@owney/sdk",
3
- "version": "0.7.34-beta.0",
3
+ "version": "0.7.34",
4
4
  "type": "module",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.js",