@owney/sdk 0.7.35 → 0.7.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -917,7 +917,7 @@ var isJwtExpired = (token) => {
917
917
  }
918
918
  };
919
919
  var memorySessions = /* @__PURE__ */ new Map();
920
- var isFreshSession = (session) => !!session && typeof session.isPredeployed === "boolean" && !!session.token && !isJwtExpired(session.token);
920
+ var isFreshSession = (session) => typeof session === "object" && session !== null && typeof session.isPredeployed === "boolean" && !!session.token && !isJwtExpired(session.token);
921
921
  var readLegacySession = (store, address) => {
922
922
  if (!store) return null;
923
923
  const prefix = legacyKeyPrefix(address);
@@ -999,6 +999,17 @@ var clearSession = (address, _chainId) => {
999
999
  }
1000
1000
  readLegacySession(store, address);
1001
1001
  };
1002
+ var BrowserSessionStore = class {
1003
+ read(_agentId, address) {
1004
+ return readSession(address, 0);
1005
+ }
1006
+ write(_agentId, address, session) {
1007
+ writeSession(address, 0, session);
1008
+ }
1009
+ clear(_agentId, address) {
1010
+ clearSession(address, 0);
1011
+ }
1012
+ };
1002
1013
 
1003
1014
  // src/agents/zyfai/autoSelect.ts
1004
1015
  function buildAutoSelectUpdate(current, asset, chainId) {
@@ -1285,7 +1296,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
1285
1296
  earningsRefreshes = /* @__PURE__ */ new Map();
1286
1297
  earningsSnapshot = null;
1287
1298
  earningsGeneration = 0;
1288
- constructor(apiKey, rpcUrls, referralSource) {
1299
+ sessionStore;
1300
+ constructor(apiKey, rpcUrls, referralSource, sessionStore = new BrowserSessionStore()) {
1301
+ this.sessionStore = sessionStore;
1289
1302
  this.rpcUrls = rpcUrls ?? DEFAULT_ZYFAI_RPC_URLS;
1290
1303
  this.sdk = new import_sdk.ZyfaiSDK({
1291
1304
  apiKey,
@@ -1376,21 +1389,36 @@ var ZyfaiAgent = class _ZyfaiAgent {
1376
1389
  * (Zyfai dist line 1374). At that point `walletClient` + `currentChainId`
1377
1390
  * are populated, so the cache lookup has both keys it needs.
1378
1391
  *
1379
- * No-op on the server (no `window`) — the SDK is constructed during SSR
1380
- * for some apps and the patch only matters in the browser anyway.
1392
+ * The session lives in `sessionStore`: localStorage in the browser (a no-op
1393
+ * on the server), or whatever the host passed in `OwneySDKConfig`.
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;
@@ -5029,6 +5061,7 @@ var OwneySDK = class {
5029
5061
  userPoolCustomization = false;
5030
5062
  routingApiBaseUrl;
5031
5063
  referralSource;
5064
+ sessionStore;
5032
5065
  cachedSponsoredCallback = null;
5033
5066
  cachedWethSponsoredCallback = null;
5034
5067
  paymasterServiceUrl;
@@ -5052,6 +5085,7 @@ var OwneySDK = class {
5052
5085
  this.routingApiBaseUrl = config.routingApiBaseUrl;
5053
5086
  this.paymasterServiceUrl = config.paymasterServiceUrl;
5054
5087
  this.referralSource = config.referralSource;
5088
+ this.sessionStore = config.sessionStore;
5055
5089
  this.userPoolCustomization = config.userPoolCustomization ?? false;
5056
5090
  }
5057
5091
  /**
@@ -5325,7 +5359,12 @@ var OwneySDK = class {
5325
5359
  }
5326
5360
  createAgent(agentId, key2) {
5327
5361
  if (agentId === "zyfai") {
5328
- return new ZyfaiAgent(key2, this.zyfaiRpcUrls, this.referralSource);
5362
+ return new ZyfaiAgent(
5363
+ key2,
5364
+ this.zyfaiRpcUrls,
5365
+ this.referralSource,
5366
+ this.sessionStore
5367
+ );
5329
5368
  }
5330
5369
  return null;
5331
5370
  }
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?;
@@ -2021,4 +2046,4 @@ type StoredOrder = {
2021
2046
  */
2022
2047
  declare function listOrders(now?: number): StoredOrder[];
2023
2048
 
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 };
2049
+ export { type AccountAgentApy, type AccountApyOptions, type AccountDailyEarnings, type ActivateAgentOptions, type AgentApy, type AgentApyDetails, type AgentBalance, AgentChainIncompatibleError, type AgentEarnings, type AgentHistoryEntry, type AgentHistoryPosition, type AgentId, AgentNotFoundError, type AgentSessionStore, type AgentSupportedAsset, type AgentSupportedAssets, type AgentUserProfile, type AgentWithdrawResult, type AgentsApyOptions, type AllocationAgentApy, type AllocationApyOptions, type ApyByChainAndAsset, type ApyCoverage, type ApyHistoryPoint, type ApyIncentive, type Asset, type AssetDailyEarnings, type AvailableAgent, type AvailableAgentsOptions, type AvailablePool, type ConnectionState, type DailyApyDays, type DailyEarningsOptions, type DailyEarningsPoint, type DepositCallback, type DepositOptions, type HistoryAction, type HistoryFilters, type HistoryOptions, type HistoryTransaction, type IAgent, InvalidHistoryCursorError, type LookbackDays, NotConnectedError, type OrgPoolPolicy, type OrgPoolSelection, type OwneyAccountApy, type OwneyAgentApy, type OwneyAgentHistory, type OwneyAllocationApy, type OwneyBalances, type OwneyDepositResult, type OwneyEarnings, OwneyError, type OwneyErrorCode, type OwneyMultiDepositResult, type OwneyPosition, OwneySDK, type OwneySDKConfig, type OwneySIWXConfig, type OwneySupportedChainId, type OwneySupportedChains, type OwneySupportedTokens, type OwneyToken, type OwneyUserProfile, type OwneyWithdrawAllLeg, type OwneyWithdrawAllResult, type OwneyWithdrawResult, type PendingDeposit, type PoolCatalogProtocol, type PoolSelectionStrategy, type RebalanceLog, type SavedPoolSelection, type SwapChainTokens, type SwapDirection, type SwapOrderStatus, type SwapQuote, type SwapQuoteParams, type SwapRail, type SwapStage, type SwapTokenInfo, type SwapTokenSearchResult, type UserPoolSelection, type UserPoolSelectionRequest, type WithdrawOptions, type WithdrawSwapRecord, type WithdrawSwapStatus, clearWithdrawSwap, createOwneySIWX, listPendingDeposits, listOrders as listPendingSwaps, listWithdrawSwaps, saveWithdrawSwap, setOwneyDebug, subscribeWithdrawSwaps, switchWalletConnectChain, updateWithdrawSwap };
package/dist/index.d.ts CHANGED
@@ -247,8 +247,32 @@ type SwapQuoteParams = {
247
247
  };
248
248
 
249
249
  type ZyfaiRpcUrlsConfig = Partial<Record<(typeof SUPPORTED_CHAIN_IDS)[number], string>>;
250
+ /**
251
+ * Where an agent keeps its login session (for Zyfai: the JWT plus the flags
252
+ * it caches). The value is opaque JSON owned by the agent; the agent validates
253
+ * it on read. Default is the browser's localStorage; a server passes its own
254
+ * store (database, cache) so one login survives across requests and replicas.
255
+ */
256
+ interface AgentSessionStore {
257
+ read(agentId: string, address: string): Promise<unknown | null> | unknown | null;
258
+ write(agentId: string, address: string, session: unknown): Promise<void> | void;
259
+ clear(agentId: string, address: string): Promise<void> | void;
260
+ }
250
261
  interface OwneySDKConfig {
251
262
  apiKey: string;
263
+ /**
264
+ * Optional persistence for agent authentication sessions.
265
+ *
266
+ * When omitted, browser integrations use the default localStorage store.
267
+ * On the server the default store is a no-op, so every `connect` signs in
268
+ * again unless a store is provided.
269
+ *
270
+ * Stored values may contain bearer tokens and must be treated as secrets.
271
+ * Server implementations should bind each store instance to a trusted
272
+ * application user/session, encrypt values, apply a TTL, and never use a
273
+ * caller-provided wallet address as the sole authorization boundary.
274
+ */
275
+ sessionStore?: AgentSessionStore;
252
276
  /**
253
277
  * Optional per-chain RPC overrides for Zyfai SDK network calls.
254
278
  * Example: { 8453: "https://...", 42161: "https://..." }
@@ -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?;
@@ -2021,4 +2046,4 @@ type StoredOrder = {
2021
2046
  */
2022
2047
  declare function listOrders(now?: number): StoredOrder[];
2023
2048
 
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 };
2049
+ export { type AccountAgentApy, type AccountApyOptions, type AccountDailyEarnings, type ActivateAgentOptions, type AgentApy, type AgentApyDetails, type AgentBalance, AgentChainIncompatibleError, type AgentEarnings, type AgentHistoryEntry, type AgentHistoryPosition, type AgentId, AgentNotFoundError, type AgentSessionStore, type AgentSupportedAsset, type AgentSupportedAssets, type AgentUserProfile, type AgentWithdrawResult, type AgentsApyOptions, type AllocationAgentApy, type AllocationApyOptions, type ApyByChainAndAsset, type ApyCoverage, type ApyHistoryPoint, type ApyIncentive, type Asset, type AssetDailyEarnings, type AvailableAgent, type AvailableAgentsOptions, type AvailablePool, type ConnectionState, type DailyApyDays, type DailyEarningsOptions, type DailyEarningsPoint, type DepositCallback, type DepositOptions, type HistoryAction, type HistoryFilters, type HistoryOptions, type HistoryTransaction, type IAgent, InvalidHistoryCursorError, type LookbackDays, NotConnectedError, type OrgPoolPolicy, type OrgPoolSelection, type OwneyAccountApy, type OwneyAgentApy, type OwneyAgentHistory, type OwneyAllocationApy, type OwneyBalances, type OwneyDepositResult, type OwneyEarnings, OwneyError, type OwneyErrorCode, type OwneyMultiDepositResult, type OwneyPosition, OwneySDK, type OwneySDKConfig, type OwneySIWXConfig, type OwneySupportedChainId, type OwneySupportedChains, type OwneySupportedTokens, type OwneyToken, type OwneyUserProfile, type OwneyWithdrawAllLeg, type OwneyWithdrawAllResult, type OwneyWithdrawResult, type PendingDeposit, type PoolCatalogProtocol, type PoolSelectionStrategy, type RebalanceLog, type SavedPoolSelection, type SwapChainTokens, type SwapDirection, type SwapOrderStatus, type SwapQuote, type SwapQuoteParams, type SwapRail, type SwapStage, type SwapTokenInfo, type SwapTokenSearchResult, type UserPoolSelection, type UserPoolSelectionRequest, type WithdrawOptions, type WithdrawSwapRecord, type WithdrawSwapStatus, clearWithdrawSwap, createOwneySIWX, listPendingDeposits, listOrders as listPendingSwaps, listWithdrawSwaps, saveWithdrawSwap, setOwneyDebug, subscribeWithdrawSwaps, switchWalletConnectChain, updateWithdrawSwap };
package/dist/index.js CHANGED
@@ -876,7 +876,7 @@ var isJwtExpired = (token) => {
876
876
  }
877
877
  };
878
878
  var memorySessions = /* @__PURE__ */ new Map();
879
- var isFreshSession = (session) => !!session && typeof session.isPredeployed === "boolean" && !!session.token && !isJwtExpired(session.token);
879
+ var isFreshSession = (session) => typeof session === "object" && session !== null && typeof session.isPredeployed === "boolean" && !!session.token && !isJwtExpired(session.token);
880
880
  var readLegacySession = (store, address) => {
881
881
  if (!store) return null;
882
882
  const prefix = legacyKeyPrefix(address);
@@ -958,6 +958,17 @@ var clearSession = (address, _chainId) => {
958
958
  }
959
959
  readLegacySession(store, address);
960
960
  };
961
+ var BrowserSessionStore = class {
962
+ read(_agentId, address) {
963
+ return readSession(address, 0);
964
+ }
965
+ write(_agentId, address, session) {
966
+ writeSession(address, 0, session);
967
+ }
968
+ clear(_agentId, address) {
969
+ clearSession(address, 0);
970
+ }
971
+ };
961
972
 
962
973
  // src/agents/zyfai/autoSelect.ts
963
974
  function buildAutoSelectUpdate(current, asset, chainId) {
@@ -1244,7 +1255,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
1244
1255
  earningsRefreshes = /* @__PURE__ */ new Map();
1245
1256
  earningsSnapshot = null;
1246
1257
  earningsGeneration = 0;
1247
- constructor(apiKey, rpcUrls, referralSource) {
1258
+ sessionStore;
1259
+ constructor(apiKey, rpcUrls, referralSource, sessionStore = new BrowserSessionStore()) {
1260
+ this.sessionStore = sessionStore;
1248
1261
  this.rpcUrls = rpcUrls ?? DEFAULT_ZYFAI_RPC_URLS;
1249
1262
  this.sdk = new ZyfaiSDK({
1250
1263
  apiKey,
@@ -1335,21 +1348,36 @@ var ZyfaiAgent = class _ZyfaiAgent {
1335
1348
  * (Zyfai dist line 1374). At that point `walletClient` + `currentChainId`
1336
1349
  * are populated, so the cache lookup has both keys it needs.
1337
1350
  *
1338
- * No-op on the server (no `window`) — the SDK is constructed during SSR
1339
- * for some apps and the patch only matters in the browser anyway.
1351
+ * The session lives in `sessionStore`: localStorage in the browser (a no-op
1352
+ * on the server), or whatever the host passed in `OwneySDKConfig`.
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;
@@ -5009,6 +5041,7 @@ var OwneySDK = class {
5009
5041
  userPoolCustomization = false;
5010
5042
  routingApiBaseUrl;
5011
5043
  referralSource;
5044
+ sessionStore;
5012
5045
  cachedSponsoredCallback = null;
5013
5046
  cachedWethSponsoredCallback = null;
5014
5047
  paymasterServiceUrl;
@@ -5032,6 +5065,7 @@ var OwneySDK = class {
5032
5065
  this.routingApiBaseUrl = config.routingApiBaseUrl;
5033
5066
  this.paymasterServiceUrl = config.paymasterServiceUrl;
5034
5067
  this.referralSource = config.referralSource;
5068
+ this.sessionStore = config.sessionStore;
5035
5069
  this.userPoolCustomization = config.userPoolCustomization ?? false;
5036
5070
  }
5037
5071
  /**
@@ -5305,7 +5339,12 @@ var OwneySDK = class {
5305
5339
  }
5306
5340
  createAgent(agentId, key2) {
5307
5341
  if (agentId === "zyfai") {
5308
- return new ZyfaiAgent(key2, this.zyfaiRpcUrls, this.referralSource);
5342
+ return new ZyfaiAgent(
5343
+ key2,
5344
+ this.zyfaiRpcUrls,
5345
+ this.referralSource,
5346
+ this.sessionStore
5347
+ );
5309
5348
  }
5310
5349
  return null;
5311
5350
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@owney/sdk",
3
- "version": "0.7.35",
3
+ "version": "0.7.36",
4
4
  "type": "module",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.js",