@owney/sdk 0.4.4 → 0.4.6

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
@@ -25,7 +25,8 @@ __export(src_exports, {
25
25
  InvalidHistoryCursorError: () => InvalidHistoryCursorError,
26
26
  NotConnectedError: () => NotConnectedError,
27
27
  OwneyError: () => OwneyError,
28
- OwneySDK: () => OwneySDK
28
+ OwneySDK: () => OwneySDK,
29
+ createOwneySIWX: () => createOwneySIWX
29
30
  });
30
31
  module.exports = __toCommonJS(src_exports);
31
32
 
@@ -240,7 +241,6 @@ function mapApyHistory(raw) {
240
241
  }
241
242
  function mapEntries(rawEntries, chainId) {
242
243
  const actionMap = {
243
- "Deposit to protocol": "Deposit",
244
244
  "Top up wallet": "Top up",
245
245
  "Partial withdraw from protocol": "Withdraw",
246
246
  "Withdraw from protocol": "Withdraw",
@@ -662,7 +662,7 @@ var ZyfaiAgent = class {
662
662
  }
663
663
  async getEarnings(state, chainId) {
664
664
  const { smartWallet } = await this.resolveSmartWallet(state, chainId);
665
- const raw = await this.sdk.calculateOnchainEarnings(smartWallet);
665
+ const raw = await this.sdk.getOnchainEarnings(smartWallet);
666
666
  return mapEarnings(raw, smartWallet);
667
667
  }
668
668
  async getAccountApy(state, chainId, days) {
@@ -688,17 +688,24 @@ var ZyfaiAgent = class {
688
688
  fromDate: options?.fromDate,
689
689
  toDate
690
690
  });
691
- matched.push(...raw.data.filter((e) => e.chainId === validChainId));
691
+ raw.data.forEach((entry, idx) => {
692
+ if (entry.chainId === validChainId && entry.action !== "Deposit to protocol") {
693
+ matched.push({ entry, rawIdx: offset + idx });
694
+ }
695
+ });
692
696
  offset += raw.data.length;
693
697
  if (raw.data.length < backendPageSize) {
694
698
  backendExhausted = true;
695
699
  break;
696
700
  }
697
701
  }
698
- const overshoot = Math.max(0, matched.length - limit);
699
- const pageData = matched.slice(0, limit);
700
- const hasMore = !backendExhausted || overshoot > 0;
701
- const nextCursor = hasMore ? encodeHistoryCursor({ toDate, rawOffset: offset - overshoot }) : void 0;
702
+ const pageData = matched.slice(0, limit).map((m) => m.entry);
703
+ const firstOvershoot = matched[limit];
704
+ const hasMore = !backendExhausted || firstOvershoot !== void 0;
705
+ const nextCursor = hasMore ? encodeHistoryCursor({
706
+ toDate,
707
+ rawOffset: firstOvershoot ? firstOvershoot.rawIdx : offset
708
+ }) : void 0;
702
709
  return {
703
710
  data: mapEntries(pageData, validChainId),
704
711
  hasMore,
@@ -1677,9 +1684,20 @@ var OwneySDK = class {
1677
1684
  hasMore = true;
1678
1685
  }
1679
1686
  }
1680
- merged.sort(
1681
- (a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()
1682
- );
1687
+ merged.sort((a, b) => {
1688
+ const dateDiff = new Date(b.date).getTime() - new Date(a.date).getTime();
1689
+ if (dateDiff !== 0)
1690
+ return dateDiff;
1691
+ if (a.agent !== b.agent)
1692
+ return a.agent < b.agent ? -1 : 1;
1693
+ const aTx = a.transactions?.[0]?.txHashes?.[0] ?? "";
1694
+ const bTx = b.transactions?.[0]?.txHashes?.[0] ?? "";
1695
+ if (aTx !== bTx)
1696
+ return aTx < bTx ? -1 : 1;
1697
+ if (a.action !== b.action)
1698
+ return a.action < b.action ? -1 : 1;
1699
+ return 0;
1700
+ });
1683
1701
  return {
1684
1702
  data: merged,
1685
1703
  hasMore,
@@ -1834,6 +1852,172 @@ var OwneySDK = class {
1834
1852
  };
1835
1853
  }
1836
1854
  };
1855
+
1856
+ // src/agents/zyfai/zyfai.siwx.ts
1857
+ var import_viem2 = require("viem");
1858
+ var import_siwe = require("siwe");
1859
+ var import_sdk2 = require("@zyfai/sdk");
1860
+
1861
+ // src/agents/zyfai/zyfai.siwx-cache.ts
1862
+ var KEY_PREFIX2 = "owney.siwx.session";
1863
+ var storage2 = () => {
1864
+ if (typeof window === "undefined")
1865
+ return null;
1866
+ try {
1867
+ return window.localStorage;
1868
+ } catch {
1869
+ return null;
1870
+ }
1871
+ };
1872
+ var buildKey2 = (address, chainId) => `${KEY_PREFIX2}:${address.toLowerCase()}:${chainId}`;
1873
+ var readSiwxSession = (address, chainId) => {
1874
+ const store = storage2();
1875
+ if (!store)
1876
+ return null;
1877
+ const raw = store.getItem(buildKey2(address, chainId));
1878
+ if (!raw)
1879
+ return null;
1880
+ try {
1881
+ return JSON.parse(raw);
1882
+ } catch {
1883
+ store.removeItem(buildKey2(address, chainId));
1884
+ return null;
1885
+ }
1886
+ };
1887
+ var writeSiwxSession = (address, chainId, session) => {
1888
+ const store = storage2();
1889
+ if (!store)
1890
+ return;
1891
+ try {
1892
+ store.setItem(buildKey2(address, chainId), JSON.stringify(session));
1893
+ } catch {
1894
+ }
1895
+ };
1896
+ var clearSiwxSession = (address, chainId) => {
1897
+ const store = storage2();
1898
+ if (!store)
1899
+ return;
1900
+ try {
1901
+ store.removeItem(buildKey2(address, chainId));
1902
+ } catch {
1903
+ }
1904
+ };
1905
+
1906
+ // src/agents/zyfai/zyfai.siwx.ts
1907
+ var STATEMENT = "Sign in with Ethereum";
1908
+ var VERSION = "1";
1909
+ var numericChainId = (caip) => {
1910
+ const segment = caip.split(":").pop();
1911
+ const id = Number(segment);
1912
+ if (!segment || !Number.isFinite(id) || id <= 0) {
1913
+ throw new Error(`Invalid CAIP chain id: "${caip}"`);
1914
+ }
1915
+ return id;
1916
+ };
1917
+ var browserDomain = () => typeof window !== "undefined" ? window.location.host : "";
1918
+ var browserUri = () => typeof window !== "undefined" ? window.location.origin : "";
1919
+ function buildSIWXConfig(deps) {
1920
+ const { post, referralSource } = deps;
1921
+ const createMessage = async (input) => {
1922
+ const { nonce } = await post("/auth/challenge", {});
1923
+ const domain = browserDomain();
1924
+ const uri = browserUri();
1925
+ const issuedAt = (/* @__PURE__ */ new Date()).toISOString();
1926
+ const chainId = input.chainId;
1927
+ const accountAddress = input.accountAddress;
1928
+ const message = {
1929
+ accountAddress,
1930
+ chainId,
1931
+ domain,
1932
+ uri,
1933
+ version: VERSION,
1934
+ nonce,
1935
+ statement: STATEMENT,
1936
+ issuedAt,
1937
+ toString() {
1938
+ return new import_siwe.SiweMessage({
1939
+ address: (0, import_viem2.getAddress)(accountAddress),
1940
+ chainId: numericChainId(chainId),
1941
+ domain,
1942
+ uri,
1943
+ statement: STATEMENT,
1944
+ nonce,
1945
+ version: VERSION,
1946
+ issuedAt
1947
+ }).prepareMessage();
1948
+ }
1949
+ };
1950
+ return message;
1951
+ };
1952
+ const getSessions = async (chainId, address) => {
1953
+ let id;
1954
+ try {
1955
+ id = numericChainId(chainId);
1956
+ } catch {
1957
+ return [];
1958
+ }
1959
+ const jwt = readSession(address, id);
1960
+ const stored = readSiwxSession(address, id);
1961
+ if (!jwt) {
1962
+ if (stored)
1963
+ clearSiwxSession(address, id);
1964
+ return [];
1965
+ }
1966
+ if (!stored)
1967
+ return [];
1968
+ const session = {
1969
+ // `stored.data.chainId` is a plain string in the cache (kept AppKit-free);
1970
+ // it always holds a valid CaipNetworkId here, so narrow at the boundary.
1971
+ data: stored.data,
1972
+ message: stored.message,
1973
+ signature: stored.signature
1974
+ };
1975
+ return [session];
1976
+ };
1977
+ const persistSession = async (session) => {
1978
+ const address = session.data.accountAddress;
1979
+ const id = numericChainId(session.data.chainId);
1980
+ const message = new import_siwe.SiweMessage(session.message);
1981
+ const login = await post("/auth/login", {
1982
+ message,
1983
+ signature: session.signature,
1984
+ referralSource
1985
+ });
1986
+ writeSession(address, id, {
1987
+ token: login.accessToken,
1988
+ userId: login.userId ?? null,
1989
+ hasActiveSessionKey: Boolean(login.hasActiveSessionKey)
1990
+ });
1991
+ const stored = {
1992
+ data: session.data,
1993
+ message: session.message,
1994
+ signature: session.signature
1995
+ };
1996
+ writeSiwxSession(address, id, stored);
1997
+ };
1998
+ const addSession = async (session) => {
1999
+ await persistSession(session);
2000
+ };
2001
+ const setSessions = async (sessions) => {
2002
+ for (const session of sessions) {
2003
+ await persistSession(session);
2004
+ }
2005
+ };
2006
+ const revokeSession = async (chainId, address) => {
2007
+ const id = numericChainId(chainId);
2008
+ clearSession(address, id);
2009
+ clearSiwxSession(address, id);
2010
+ };
2011
+ return { createMessage, getSessions, addSession, setSessions, revokeSession };
2012
+ }
2013
+ function createOwneySIWX(config) {
2014
+ const zyfai = new import_sdk2.ZyfaiSDK({ apiKey: config.apiKey });
2015
+ const http = zyfai.httpClient;
2016
+ return buildSIWXConfig({
2017
+ post: (url, data) => http.post(url, data),
2018
+ referralSource: config.referralSource
2019
+ });
2020
+ }
1837
2021
  // Annotate the CommonJS export names for ESM import in node:
1838
2022
  0 && (module.exports = {
1839
2023
  AgentChainIncompatibleError,
@@ -1841,5 +2025,6 @@ var OwneySDK = class {
1841
2025
  InvalidHistoryCursorError,
1842
2026
  NotConnectedError,
1843
2027
  OwneyError,
1844
- OwneySDK
2028
+ OwneySDK,
2029
+ createOwneySIWX
1845
2030
  });
package/dist/index.d.cts CHANGED
@@ -1,3 +1,5 @@
1
+ import { SIWXConfig } from '@reown/appkit-controllers';
2
+
1
3
  type ZyfaiRpcUrlsConfig = Partial<Record<(typeof SUPPORTED_CHAIN_IDS)[number], string>>;
2
4
  interface OwneySDKConfig {
3
5
  apiKey: string;
@@ -170,6 +172,12 @@ interface RebalanceLog {
170
172
  amount: string;
171
173
  status: "success" | "failed";
172
174
  }
175
+ interface AgentHistoryPosition {
176
+ protocol: string;
177
+ pool?: string;
178
+ tokenSymbol?: string;
179
+ amount?: string;
180
+ }
173
181
  interface AgentHistoryEntry {
174
182
  agent: AgentId;
175
183
  action: HistoryAction;
@@ -178,6 +186,7 @@ interface AgentHistoryEntry {
178
186
  newApy: string | null;
179
187
  transactions: HistoryTransaction[];
180
188
  rebalanceLog: RebalanceLog[];
189
+ positions?: AgentHistoryPosition[];
181
190
  }
182
191
  interface OwneyAgentHistory {
183
192
  data: AgentHistoryEntry[];
@@ -411,4 +420,17 @@ declare class InvalidHistoryCursorError extends Error {
411
420
  constructor(message: string);
412
421
  }
413
422
 
414
- export { AccountAgentApy, AccountApyOptions, AgentApy, AgentApyDetails, AgentBalance, AgentChainIncompatibleError, AgentEarnings, AgentHistoryEntry, AgentId, AgentNotFoundError, AgentSupportedAsset, AgentSupportedAssets, AgentUserProfile, AgentWithdrawResult, AgentsApyOptions, ApyByChainAndAsset, Asset, ConnectionState, DailyApyDays, DepositCallback, DepositOptions, HistoryAction, HistoryFilters, HistoryOptions, HistoryTransaction, IAgent, InvalidHistoryCursorError, NotConnectedError, OwneyAccountApy, OwneyAgentAllocation, OwneyAgentApy, OwneyAgentHistory, OwneyAgentStatus, OwneyBalances, OwneyDepositResult, OwneyEarnings, OwneyError, OwneyErrorCode, OwneyMultiDepositResult, OwneySDK, OwneySDKConfig, OwneySupportedChainId, OwneySupportedChains, OwneySupportedTokens, OwneyToken, OwneyUserProfile, OwneyWithdrawResult, RebalanceLog, WithdrawOptions };
423
+ type OwneySIWXConfig = {
424
+ /** Owney/Zyfai API key — same value passed to `new OwneySDK({ apiKey })`. */
425
+ apiKey: string;
426
+ /** Optional attribution forwarded to /auth/login. */
427
+ referralSource?: string;
428
+ };
429
+ /**
430
+ * Public factory. Construct ONCE at `createAppKit` time and pass to
431
+ * `createAppKit({ siwx })`. Reuses Zyfai's internal httpClient so the API base
432
+ * URL and `X-API-Key` header stay a single source of truth.
433
+ */
434
+ declare function createOwneySIWX(config: OwneySIWXConfig): SIWXConfig;
435
+
436
+ export { AccountAgentApy, AccountApyOptions, AgentApy, AgentApyDetails, AgentBalance, AgentChainIncompatibleError, AgentEarnings, AgentHistoryEntry, AgentHistoryPosition, AgentId, AgentNotFoundError, AgentSupportedAsset, AgentSupportedAssets, AgentUserProfile, AgentWithdrawResult, AgentsApyOptions, ApyByChainAndAsset, Asset, ConnectionState, DailyApyDays, DepositCallback, DepositOptions, HistoryAction, HistoryFilters, HistoryOptions, HistoryTransaction, IAgent, InvalidHistoryCursorError, NotConnectedError, OwneyAccountApy, OwneyAgentAllocation, OwneyAgentApy, OwneyAgentHistory, OwneyAgentStatus, OwneyBalances, OwneyDepositResult, OwneyEarnings, OwneyError, OwneyErrorCode, OwneyMultiDepositResult, OwneySDK, OwneySDKConfig, OwneySIWXConfig, OwneySupportedChainId, OwneySupportedChains, OwneySupportedTokens, OwneyToken, OwneyUserProfile, OwneyWithdrawResult, RebalanceLog, WithdrawOptions, createOwneySIWX };
package/dist/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { SIWXConfig } from '@reown/appkit-controllers';
2
+
1
3
  type ZyfaiRpcUrlsConfig = Partial<Record<(typeof SUPPORTED_CHAIN_IDS)[number], string>>;
2
4
  interface OwneySDKConfig {
3
5
  apiKey: string;
@@ -170,6 +172,12 @@ interface RebalanceLog {
170
172
  amount: string;
171
173
  status: "success" | "failed";
172
174
  }
175
+ interface AgentHistoryPosition {
176
+ protocol: string;
177
+ pool?: string;
178
+ tokenSymbol?: string;
179
+ amount?: string;
180
+ }
173
181
  interface AgentHistoryEntry {
174
182
  agent: AgentId;
175
183
  action: HistoryAction;
@@ -178,6 +186,7 @@ interface AgentHistoryEntry {
178
186
  newApy: string | null;
179
187
  transactions: HistoryTransaction[];
180
188
  rebalanceLog: RebalanceLog[];
189
+ positions?: AgentHistoryPosition[];
181
190
  }
182
191
  interface OwneyAgentHistory {
183
192
  data: AgentHistoryEntry[];
@@ -411,4 +420,17 @@ declare class InvalidHistoryCursorError extends Error {
411
420
  constructor(message: string);
412
421
  }
413
422
 
414
- export { AccountAgentApy, AccountApyOptions, AgentApy, AgentApyDetails, AgentBalance, AgentChainIncompatibleError, AgentEarnings, AgentHistoryEntry, AgentId, AgentNotFoundError, AgentSupportedAsset, AgentSupportedAssets, AgentUserProfile, AgentWithdrawResult, AgentsApyOptions, ApyByChainAndAsset, Asset, ConnectionState, DailyApyDays, DepositCallback, DepositOptions, HistoryAction, HistoryFilters, HistoryOptions, HistoryTransaction, IAgent, InvalidHistoryCursorError, NotConnectedError, OwneyAccountApy, OwneyAgentAllocation, OwneyAgentApy, OwneyAgentHistory, OwneyAgentStatus, OwneyBalances, OwneyDepositResult, OwneyEarnings, OwneyError, OwneyErrorCode, OwneyMultiDepositResult, OwneySDK, OwneySDKConfig, OwneySupportedChainId, OwneySupportedChains, OwneySupportedTokens, OwneyToken, OwneyUserProfile, OwneyWithdrawResult, RebalanceLog, WithdrawOptions };
423
+ type OwneySIWXConfig = {
424
+ /** Owney/Zyfai API key — same value passed to `new OwneySDK({ apiKey })`. */
425
+ apiKey: string;
426
+ /** Optional attribution forwarded to /auth/login. */
427
+ referralSource?: string;
428
+ };
429
+ /**
430
+ * Public factory. Construct ONCE at `createAppKit` time and pass to
431
+ * `createAppKit({ siwx })`. Reuses Zyfai's internal httpClient so the API base
432
+ * URL and `X-API-Key` header stay a single source of truth.
433
+ */
434
+ declare function createOwneySIWX(config: OwneySIWXConfig): SIWXConfig;
435
+
436
+ export { AccountAgentApy, AccountApyOptions, AgentApy, AgentApyDetails, AgentBalance, AgentChainIncompatibleError, AgentEarnings, AgentHistoryEntry, AgentHistoryPosition, AgentId, AgentNotFoundError, AgentSupportedAsset, AgentSupportedAssets, AgentUserProfile, AgentWithdrawResult, AgentsApyOptions, ApyByChainAndAsset, Asset, ConnectionState, DailyApyDays, DepositCallback, DepositOptions, HistoryAction, HistoryFilters, HistoryOptions, HistoryTransaction, IAgent, InvalidHistoryCursorError, NotConnectedError, OwneyAccountApy, OwneyAgentAllocation, OwneyAgentApy, OwneyAgentHistory, OwneyAgentStatus, OwneyBalances, OwneyDepositResult, OwneyEarnings, OwneyError, OwneyErrorCode, OwneyMultiDepositResult, OwneySDK, OwneySDKConfig, OwneySIWXConfig, OwneySupportedChainId, OwneySupportedChains, OwneySupportedTokens, OwneyToken, OwneyUserProfile, OwneyWithdrawResult, RebalanceLog, WithdrawOptions, createOwneySIWX };
package/dist/index.js CHANGED
@@ -209,7 +209,6 @@ function mapApyHistory(raw) {
209
209
  }
210
210
  function mapEntries(rawEntries, chainId) {
211
211
  const actionMap = {
212
- "Deposit to protocol": "Deposit",
213
212
  "Top up wallet": "Top up",
214
213
  "Partial withdraw from protocol": "Withdraw",
215
214
  "Withdraw from protocol": "Withdraw",
@@ -631,7 +630,7 @@ var ZyfaiAgent = class {
631
630
  }
632
631
  async getEarnings(state, chainId) {
633
632
  const { smartWallet } = await this.resolveSmartWallet(state, chainId);
634
- const raw = await this.sdk.calculateOnchainEarnings(smartWallet);
633
+ const raw = await this.sdk.getOnchainEarnings(smartWallet);
635
634
  return mapEarnings(raw, smartWallet);
636
635
  }
637
636
  async getAccountApy(state, chainId, days) {
@@ -657,17 +656,24 @@ var ZyfaiAgent = class {
657
656
  fromDate: options?.fromDate,
658
657
  toDate
659
658
  });
660
- matched.push(...raw.data.filter((e) => e.chainId === validChainId));
659
+ raw.data.forEach((entry, idx) => {
660
+ if (entry.chainId === validChainId && entry.action !== "Deposit to protocol") {
661
+ matched.push({ entry, rawIdx: offset + idx });
662
+ }
663
+ });
661
664
  offset += raw.data.length;
662
665
  if (raw.data.length < backendPageSize) {
663
666
  backendExhausted = true;
664
667
  break;
665
668
  }
666
669
  }
667
- const overshoot = Math.max(0, matched.length - limit);
668
- const pageData = matched.slice(0, limit);
669
- const hasMore = !backendExhausted || overshoot > 0;
670
- const nextCursor = hasMore ? encodeHistoryCursor({ toDate, rawOffset: offset - overshoot }) : void 0;
670
+ const pageData = matched.slice(0, limit).map((m) => m.entry);
671
+ const firstOvershoot = matched[limit];
672
+ const hasMore = !backendExhausted || firstOvershoot !== void 0;
673
+ const nextCursor = hasMore ? encodeHistoryCursor({
674
+ toDate,
675
+ rawOffset: firstOvershoot ? firstOvershoot.rawIdx : offset
676
+ }) : void 0;
671
677
  return {
672
678
  data: mapEntries(pageData, validChainId),
673
679
  hasMore,
@@ -1646,9 +1652,20 @@ var OwneySDK = class {
1646
1652
  hasMore = true;
1647
1653
  }
1648
1654
  }
1649
- merged.sort(
1650
- (a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()
1651
- );
1655
+ merged.sort((a, b) => {
1656
+ const dateDiff = new Date(b.date).getTime() - new Date(a.date).getTime();
1657
+ if (dateDiff !== 0)
1658
+ return dateDiff;
1659
+ if (a.agent !== b.agent)
1660
+ return a.agent < b.agent ? -1 : 1;
1661
+ const aTx = a.transactions?.[0]?.txHashes?.[0] ?? "";
1662
+ const bTx = b.transactions?.[0]?.txHashes?.[0] ?? "";
1663
+ if (aTx !== bTx)
1664
+ return aTx < bTx ? -1 : 1;
1665
+ if (a.action !== b.action)
1666
+ return a.action < b.action ? -1 : 1;
1667
+ return 0;
1668
+ });
1652
1669
  return {
1653
1670
  data: merged,
1654
1671
  hasMore,
@@ -1803,11 +1820,178 @@ var OwneySDK = class {
1803
1820
  };
1804
1821
  }
1805
1822
  };
1823
+
1824
+ // src/agents/zyfai/zyfai.siwx.ts
1825
+ import { getAddress } from "viem";
1826
+ import { SiweMessage } from "siwe";
1827
+ import { ZyfaiSDK as ZyfaiSDK2 } from "@zyfai/sdk";
1828
+
1829
+ // src/agents/zyfai/zyfai.siwx-cache.ts
1830
+ var KEY_PREFIX2 = "owney.siwx.session";
1831
+ var storage2 = () => {
1832
+ if (typeof window === "undefined")
1833
+ return null;
1834
+ try {
1835
+ return window.localStorage;
1836
+ } catch {
1837
+ return null;
1838
+ }
1839
+ };
1840
+ var buildKey2 = (address, chainId) => `${KEY_PREFIX2}:${address.toLowerCase()}:${chainId}`;
1841
+ var readSiwxSession = (address, chainId) => {
1842
+ const store = storage2();
1843
+ if (!store)
1844
+ return null;
1845
+ const raw = store.getItem(buildKey2(address, chainId));
1846
+ if (!raw)
1847
+ return null;
1848
+ try {
1849
+ return JSON.parse(raw);
1850
+ } catch {
1851
+ store.removeItem(buildKey2(address, chainId));
1852
+ return null;
1853
+ }
1854
+ };
1855
+ var writeSiwxSession = (address, chainId, session) => {
1856
+ const store = storage2();
1857
+ if (!store)
1858
+ return;
1859
+ try {
1860
+ store.setItem(buildKey2(address, chainId), JSON.stringify(session));
1861
+ } catch {
1862
+ }
1863
+ };
1864
+ var clearSiwxSession = (address, chainId) => {
1865
+ const store = storage2();
1866
+ if (!store)
1867
+ return;
1868
+ try {
1869
+ store.removeItem(buildKey2(address, chainId));
1870
+ } catch {
1871
+ }
1872
+ };
1873
+
1874
+ // src/agents/zyfai/zyfai.siwx.ts
1875
+ var STATEMENT = "Sign in with Ethereum";
1876
+ var VERSION = "1";
1877
+ var numericChainId = (caip) => {
1878
+ const segment = caip.split(":").pop();
1879
+ const id = Number(segment);
1880
+ if (!segment || !Number.isFinite(id) || id <= 0) {
1881
+ throw new Error(`Invalid CAIP chain id: "${caip}"`);
1882
+ }
1883
+ return id;
1884
+ };
1885
+ var browserDomain = () => typeof window !== "undefined" ? window.location.host : "";
1886
+ var browserUri = () => typeof window !== "undefined" ? window.location.origin : "";
1887
+ function buildSIWXConfig(deps) {
1888
+ const { post, referralSource } = deps;
1889
+ const createMessage = async (input) => {
1890
+ const { nonce } = await post("/auth/challenge", {});
1891
+ const domain = browserDomain();
1892
+ const uri = browserUri();
1893
+ const issuedAt = (/* @__PURE__ */ new Date()).toISOString();
1894
+ const chainId = input.chainId;
1895
+ const accountAddress = input.accountAddress;
1896
+ const message = {
1897
+ accountAddress,
1898
+ chainId,
1899
+ domain,
1900
+ uri,
1901
+ version: VERSION,
1902
+ nonce,
1903
+ statement: STATEMENT,
1904
+ issuedAt,
1905
+ toString() {
1906
+ return new SiweMessage({
1907
+ address: getAddress(accountAddress),
1908
+ chainId: numericChainId(chainId),
1909
+ domain,
1910
+ uri,
1911
+ statement: STATEMENT,
1912
+ nonce,
1913
+ version: VERSION,
1914
+ issuedAt
1915
+ }).prepareMessage();
1916
+ }
1917
+ };
1918
+ return message;
1919
+ };
1920
+ const getSessions = async (chainId, address) => {
1921
+ let id;
1922
+ try {
1923
+ id = numericChainId(chainId);
1924
+ } catch {
1925
+ return [];
1926
+ }
1927
+ const jwt = readSession(address, id);
1928
+ const stored = readSiwxSession(address, id);
1929
+ if (!jwt) {
1930
+ if (stored)
1931
+ clearSiwxSession(address, id);
1932
+ return [];
1933
+ }
1934
+ if (!stored)
1935
+ return [];
1936
+ const session = {
1937
+ // `stored.data.chainId` is a plain string in the cache (kept AppKit-free);
1938
+ // it always holds a valid CaipNetworkId here, so narrow at the boundary.
1939
+ data: stored.data,
1940
+ message: stored.message,
1941
+ signature: stored.signature
1942
+ };
1943
+ return [session];
1944
+ };
1945
+ const persistSession = async (session) => {
1946
+ const address = session.data.accountAddress;
1947
+ const id = numericChainId(session.data.chainId);
1948
+ const message = new SiweMessage(session.message);
1949
+ const login = await post("/auth/login", {
1950
+ message,
1951
+ signature: session.signature,
1952
+ referralSource
1953
+ });
1954
+ writeSession(address, id, {
1955
+ token: login.accessToken,
1956
+ userId: login.userId ?? null,
1957
+ hasActiveSessionKey: Boolean(login.hasActiveSessionKey)
1958
+ });
1959
+ const stored = {
1960
+ data: session.data,
1961
+ message: session.message,
1962
+ signature: session.signature
1963
+ };
1964
+ writeSiwxSession(address, id, stored);
1965
+ };
1966
+ const addSession = async (session) => {
1967
+ await persistSession(session);
1968
+ };
1969
+ const setSessions = async (sessions) => {
1970
+ for (const session of sessions) {
1971
+ await persistSession(session);
1972
+ }
1973
+ };
1974
+ const revokeSession = async (chainId, address) => {
1975
+ const id = numericChainId(chainId);
1976
+ clearSession(address, id);
1977
+ clearSiwxSession(address, id);
1978
+ };
1979
+ return { createMessage, getSessions, addSession, setSessions, revokeSession };
1980
+ }
1981
+ function createOwneySIWX(config) {
1982
+ const zyfai = new ZyfaiSDK2({ apiKey: config.apiKey });
1983
+ const http = zyfai.httpClient;
1984
+ return buildSIWXConfig({
1985
+ post: (url, data) => http.post(url, data),
1986
+ referralSource: config.referralSource
1987
+ });
1988
+ }
1806
1989
  export {
1807
1990
  AgentChainIncompatibleError,
1808
1991
  AgentNotFoundError,
1809
1992
  InvalidHistoryCursorError,
1810
1993
  NotConnectedError,
1811
1994
  OwneyError,
1812
- OwneySDK
1995
+ OwneySDK,
1996
+ createOwneySIWX
1813
1997
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@owney/sdk",
3
- "version": "0.4.4",
3
+ "version": "0.4.6",
4
4
  "type": "module",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.js",
@@ -24,9 +24,11 @@
24
24
  },
25
25
  "dependencies": {
26
26
  "@zyfai/sdk": "^0.2.36",
27
+ "siwe": "^3.0.0",
27
28
  "viem": "^2.48.1"
28
29
  },
29
30
  "devDependencies": {
31
+ "@reown/appkit-controllers": "^1.8.20",
30
32
  "dotenv": "^17.3.1",
31
33
  "tsup": "^7.0.0",
32
34
  "typescript": "^5.0.0",
@@ -35,4 +37,4 @@
35
37
  "publishConfig": {
36
38
  "access": "public"
37
39
  }
38
- }
40
+ }