@owney/sdk 0.7.35 → 0.7.37-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
@@ -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`.
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.
1381
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;
@@ -4670,28 +4702,76 @@ function parseChainId(raw) {
4670
4702
  const id = ref.startsWith("0x") ? Number.parseInt(ref, 16) : Number(ref);
4671
4703
  return Number.isFinite(id) ? id : void 0;
4672
4704
  }
4673
- function walletConnectCore(provider) {
4705
+ function walletConnectSession(provider) {
4674
4706
  const p = provider;
4675
4707
  const core = p?.signer ?? p;
4676
- if (typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
4708
+ if (typeof core?.request !== "function" || typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
4677
4709
  return null;
4678
4710
  }
4679
4711
  const peer = core.session.peer?.metadata?.name ?? "";
4680
- if (!/metamask/i.test(peer)) return null;
4681
- return core;
4712
+ if (/metamask/i.test(peer)) {
4713
+ return { core, strategy: "remote-wallet" };
4714
+ }
4715
+ if (/fireblocks/i.test(peer)) {
4716
+ return { core, strategy: "session-default" };
4717
+ }
4718
+ return null;
4719
+ }
4720
+ function approvedChains(core) {
4721
+ const approved = /* @__PURE__ */ new Set();
4722
+ for (const namespace of Object.values(core.session.namespaces ?? {})) {
4723
+ for (const chain of namespace.chains ?? []) approved.add(chain);
4724
+ for (const account of namespace.accounts ?? []) {
4725
+ const [namespaceName, reference] = account.split(":");
4726
+ if (namespaceName && reference) {
4727
+ approved.add(`${namespaceName}:${reference}`);
4728
+ }
4729
+ }
4730
+ }
4731
+ return approved;
4732
+ }
4733
+ async function selectSessionDefaultChain(core, chainId) {
4734
+ const target = `eip155:${chainId}`;
4735
+ if (!approvedChains(core).has(target)) {
4736
+ throw new Error(
4737
+ `The WalletConnect session has not approved ${target}. Reconnect the wallet and try again.`
4738
+ );
4739
+ }
4740
+ core.setDefaultChain(target);
4741
+ const selected = parseChainId(
4742
+ await core.request({ method: "eth_chainId" })
4743
+ );
4744
+ debugLog("wc-switch", "selected WalletConnect session default", {
4745
+ peer: core.session.peer?.metadata?.name,
4746
+ target: chainId,
4747
+ selected
4748
+ });
4749
+ if (selected !== chainId) {
4750
+ throw new Error(
4751
+ `WalletConnect stayed on chain ${selected ?? "unknown"}; expected ${chainId}.`
4752
+ );
4753
+ }
4682
4754
  }
4683
4755
  async function switchWalletConnectChain(provider, chainId, timeoutMs = WALLET_SWITCH_TIMEOUT_MS) {
4684
- const core = walletConnectCore(provider);
4685
- if (!core) return false;
4756
+ const session = walletConnectSession(provider);
4757
+ if (!session) return false;
4758
+ const { core, strategy } = session;
4686
4759
  holds.get(core.session.topic)?.();
4760
+ if (strategy === "session-default") {
4761
+ await selectSessionDefaultChain(core, chainId);
4762
+ return true;
4763
+ }
4687
4764
  await requestSwitch(core, provider, chainId, timeoutMs);
4688
4765
  holdChain(core, provider, chainId);
4689
4766
  return true;
4690
4767
  }
4691
4768
  async function requestSwitch(core, provider, chainId, timeoutMs) {
4692
- const current = Number(
4769
+ const current = parseChainId(
4693
4770
  await provider.request({ method: "eth_chainId" })
4694
4771
  );
4772
+ if (current === void 0) {
4773
+ throw new Error("WalletConnect could not report its current chain.");
4774
+ }
4695
4775
  const hexChainId = `0x${chainId.toString(16)}`;
4696
4776
  let timer;
4697
4777
  try {
@@ -4754,7 +4834,7 @@ function holdChain(core, provider, chainId) {
4754
4834
  holds.set(core.session.topic, release);
4755
4835
  }
4756
4836
  function withWalletConnectSwitch(provider) {
4757
- if (!walletConnectCore(provider)) return provider;
4837
+ if (!walletConnectSession(provider)) return provider;
4758
4838
  const target = provider;
4759
4839
  const request2 = async (args) => {
4760
4840
  if (args?.method !== "wallet_switchEthereumChain") {
@@ -5029,6 +5109,7 @@ var OwneySDK = class {
5029
5109
  userPoolCustomization = false;
5030
5110
  routingApiBaseUrl;
5031
5111
  referralSource;
5112
+ sessionStore;
5032
5113
  cachedSponsoredCallback = null;
5033
5114
  cachedWethSponsoredCallback = null;
5034
5115
  paymasterServiceUrl;
@@ -5052,6 +5133,7 @@ var OwneySDK = class {
5052
5133
  this.routingApiBaseUrl = config.routingApiBaseUrl;
5053
5134
  this.paymasterServiceUrl = config.paymasterServiceUrl;
5054
5135
  this.referralSource = config.referralSource;
5136
+ this.sessionStore = config.sessionStore;
5055
5137
  this.userPoolCustomization = config.userPoolCustomization ?? false;
5056
5138
  }
5057
5139
  /**
@@ -5325,7 +5407,12 @@ var OwneySDK = class {
5325
5407
  }
5326
5408
  createAgent(agentId, key2) {
5327
5409
  if (agentId === "zyfai") {
5328
- return new ZyfaiAgent(key2, this.zyfaiRpcUrls, this.referralSource);
5410
+ return new ZyfaiAgent(
5411
+ key2,
5412
+ this.zyfaiRpcUrls,
5413
+ this.referralSource,
5414
+ this.sessionStore
5415
+ );
5329
5416
  }
5330
5417
  return null;
5331
5418
  }
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://..." }
@@ -1196,6 +1220,7 @@ declare class OwneySDK {
1196
1220
  private userPoolCustomization;
1197
1221
  private routingApiBaseUrl?;
1198
1222
  private referralSource?;
1223
+ private sessionStore?;
1199
1224
  private cachedSponsoredCallback;
1200
1225
  private cachedWethSponsoredCallback;
1201
1226
  private paymasterServiceUrl?;
@@ -1969,16 +1994,17 @@ type OwneySIWXConfig = {
1969
1994
  declare function createOwneySIWX(config: OwneySIWXConfig): SIWXConfig;
1970
1995
 
1971
1996
  /**
1972
- * Ask the wallet ITSELF to switch networks, over WalletConnect.
1997
+ * Align a supported WalletConnect session with `chainId`.
1973
1998
  *
1974
1999
  * WalletConnect's provider answers `wallet_switchEthereumChain` locally when
1975
2000
  * the chain was approved at connect time: it moves its own default chain and
1976
2001
  * reports success without telling the wallet. MetaMask mobile then stays on
1977
2002
  * its network, keeps reporting it, and every guard downstream fails with
1978
2003
  * CHAIN_MISMATCH — after a swap, with the user's funds already moved (ROUT-727).
1979
- * Sending the request through the session client reaches the wallet, which
1980
- * shows a real "switch network" prompt; the client also deep-links the wallet
1981
- * app open on mobile.
2004
+ * Sending the request through the session client reaches MetaMask, which shows
2005
+ * a real "switch network" prompt. Fireblocks instead uses the approved
2006
+ * multi-chain session's local default; its subsequent signature request is
2007
+ * explicitly scoped to that chain and needs no separate network prompt.
1982
2008
  *
1983
2009
  * Returns false when `provider` is not a WalletConnect session, so the caller
1984
2010
  * can fall back to an ordinary switch.
@@ -2021,4 +2047,4 @@ type StoredOrder = {
2021
2047
  */
2022
2048
  declare function listOrders(now?: number): StoredOrder[];
2023
2049
 
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 };
2050
+ 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://..." }
@@ -1196,6 +1220,7 @@ declare class OwneySDK {
1196
1220
  private userPoolCustomization;
1197
1221
  private routingApiBaseUrl?;
1198
1222
  private referralSource?;
1223
+ private sessionStore?;
1199
1224
  private cachedSponsoredCallback;
1200
1225
  private cachedWethSponsoredCallback;
1201
1226
  private paymasterServiceUrl?;
@@ -1969,16 +1994,17 @@ type OwneySIWXConfig = {
1969
1994
  declare function createOwneySIWX(config: OwneySIWXConfig): SIWXConfig;
1970
1995
 
1971
1996
  /**
1972
- * Ask the wallet ITSELF to switch networks, over WalletConnect.
1997
+ * Align a supported WalletConnect session with `chainId`.
1973
1998
  *
1974
1999
  * WalletConnect's provider answers `wallet_switchEthereumChain` locally when
1975
2000
  * the chain was approved at connect time: it moves its own default chain and
1976
2001
  * reports success without telling the wallet. MetaMask mobile then stays on
1977
2002
  * its network, keeps reporting it, and every guard downstream fails with
1978
2003
  * CHAIN_MISMATCH — after a swap, with the user's funds already moved (ROUT-727).
1979
- * Sending the request through the session client reaches the wallet, which
1980
- * shows a real "switch network" prompt; the client also deep-links the wallet
1981
- * app open on mobile.
2004
+ * Sending the request through the session client reaches MetaMask, which shows
2005
+ * a real "switch network" prompt. Fireblocks instead uses the approved
2006
+ * multi-chain session's local default; its subsequent signature request is
2007
+ * explicitly scoped to that chain and needs no separate network prompt.
1982
2008
  *
1983
2009
  * Returns false when `provider` is not a WalletConnect session, so the caller
1984
2010
  * can fall back to an ordinary switch.
@@ -2021,4 +2047,4 @@ type StoredOrder = {
2021
2047
  */
2022
2048
  declare function listOrders(now?: number): StoredOrder[];
2023
2049
 
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 };
2050
+ 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`.
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.
1340
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;
@@ -4650,28 +4682,76 @@ function parseChainId(raw) {
4650
4682
  const id = ref.startsWith("0x") ? Number.parseInt(ref, 16) : Number(ref);
4651
4683
  return Number.isFinite(id) ? id : void 0;
4652
4684
  }
4653
- function walletConnectCore(provider) {
4685
+ function walletConnectSession(provider) {
4654
4686
  const p = provider;
4655
4687
  const core = p?.signer ?? p;
4656
- if (typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
4688
+ if (typeof core?.request !== "function" || typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
4657
4689
  return null;
4658
4690
  }
4659
4691
  const peer = core.session.peer?.metadata?.name ?? "";
4660
- if (!/metamask/i.test(peer)) return null;
4661
- return core;
4692
+ if (/metamask/i.test(peer)) {
4693
+ return { core, strategy: "remote-wallet" };
4694
+ }
4695
+ if (/fireblocks/i.test(peer)) {
4696
+ return { core, strategy: "session-default" };
4697
+ }
4698
+ return null;
4699
+ }
4700
+ function approvedChains(core) {
4701
+ const approved = /* @__PURE__ */ new Set();
4702
+ for (const namespace of Object.values(core.session.namespaces ?? {})) {
4703
+ for (const chain of namespace.chains ?? []) approved.add(chain);
4704
+ for (const account of namespace.accounts ?? []) {
4705
+ const [namespaceName, reference] = account.split(":");
4706
+ if (namespaceName && reference) {
4707
+ approved.add(`${namespaceName}:${reference}`);
4708
+ }
4709
+ }
4710
+ }
4711
+ return approved;
4712
+ }
4713
+ async function selectSessionDefaultChain(core, chainId) {
4714
+ const target = `eip155:${chainId}`;
4715
+ if (!approvedChains(core).has(target)) {
4716
+ throw new Error(
4717
+ `The WalletConnect session has not approved ${target}. Reconnect the wallet and try again.`
4718
+ );
4719
+ }
4720
+ core.setDefaultChain(target);
4721
+ const selected = parseChainId(
4722
+ await core.request({ method: "eth_chainId" })
4723
+ );
4724
+ debugLog("wc-switch", "selected WalletConnect session default", {
4725
+ peer: core.session.peer?.metadata?.name,
4726
+ target: chainId,
4727
+ selected
4728
+ });
4729
+ if (selected !== chainId) {
4730
+ throw new Error(
4731
+ `WalletConnect stayed on chain ${selected ?? "unknown"}; expected ${chainId}.`
4732
+ );
4733
+ }
4662
4734
  }
4663
4735
  async function switchWalletConnectChain(provider, chainId, timeoutMs = WALLET_SWITCH_TIMEOUT_MS) {
4664
- const core = walletConnectCore(provider);
4665
- if (!core) return false;
4736
+ const session = walletConnectSession(provider);
4737
+ if (!session) return false;
4738
+ const { core, strategy } = session;
4666
4739
  holds.get(core.session.topic)?.();
4740
+ if (strategy === "session-default") {
4741
+ await selectSessionDefaultChain(core, chainId);
4742
+ return true;
4743
+ }
4667
4744
  await requestSwitch(core, provider, chainId, timeoutMs);
4668
4745
  holdChain(core, provider, chainId);
4669
4746
  return true;
4670
4747
  }
4671
4748
  async function requestSwitch(core, provider, chainId, timeoutMs) {
4672
- const current = Number(
4749
+ const current = parseChainId(
4673
4750
  await provider.request({ method: "eth_chainId" })
4674
4751
  );
4752
+ if (current === void 0) {
4753
+ throw new Error("WalletConnect could not report its current chain.");
4754
+ }
4675
4755
  const hexChainId = `0x${chainId.toString(16)}`;
4676
4756
  let timer;
4677
4757
  try {
@@ -4734,7 +4814,7 @@ function holdChain(core, provider, chainId) {
4734
4814
  holds.set(core.session.topic, release);
4735
4815
  }
4736
4816
  function withWalletConnectSwitch(provider) {
4737
- if (!walletConnectCore(provider)) return provider;
4817
+ if (!walletConnectSession(provider)) return provider;
4738
4818
  const target = provider;
4739
4819
  const request2 = async (args) => {
4740
4820
  if (args?.method !== "wallet_switchEthereumChain") {
@@ -5009,6 +5089,7 @@ var OwneySDK = class {
5009
5089
  userPoolCustomization = false;
5010
5090
  routingApiBaseUrl;
5011
5091
  referralSource;
5092
+ sessionStore;
5012
5093
  cachedSponsoredCallback = null;
5013
5094
  cachedWethSponsoredCallback = null;
5014
5095
  paymasterServiceUrl;
@@ -5032,6 +5113,7 @@ var OwneySDK = class {
5032
5113
  this.routingApiBaseUrl = config.routingApiBaseUrl;
5033
5114
  this.paymasterServiceUrl = config.paymasterServiceUrl;
5034
5115
  this.referralSource = config.referralSource;
5116
+ this.sessionStore = config.sessionStore;
5035
5117
  this.userPoolCustomization = config.userPoolCustomization ?? false;
5036
5118
  }
5037
5119
  /**
@@ -5305,7 +5387,12 @@ var OwneySDK = class {
5305
5387
  }
5306
5388
  createAgent(agentId, key2) {
5307
5389
  if (agentId === "zyfai") {
5308
- return new ZyfaiAgent(key2, this.zyfaiRpcUrls, this.referralSource);
5390
+ return new ZyfaiAgent(
5391
+ key2,
5392
+ this.zyfaiRpcUrls,
5393
+ this.referralSource,
5394
+ this.sessionStore
5395
+ );
5309
5396
  }
5310
5397
  return null;
5311
5398
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@owney/sdk",
3
- "version": "0.7.35",
3
+ "version": "0.7.37-beta.0",
4
4
  "type": "module",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.js",