@owney/sdk 0.5.0-beta.0 → 0.5.1-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
@@ -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
 
@@ -176,10 +177,27 @@ function mapBalances(raw, _chainId, smartWallet) {
176
177
  });
177
178
  }
178
179
  }
180
+ const positions = (portfolio.positions ?? []).map((p) => ({
181
+ chain: p.chain ?? "",
182
+ protocol: p.protocol_name ?? p.protocol_id ?? "",
183
+ protocolId: p.protocol_id,
184
+ pool: p.pool,
185
+ asset: p.token_symbol ?? "",
186
+ // Position amount is hex-encoded base units (like the token balances
187
+ // above). Supported assets (USDC/USDT) are 6-decimal — hexToDecimal's
188
+ // default — so no per-token decimals lookup is needed.
189
+ amount: String(hexToDecimal(p.amount || "0")),
190
+ apy: p.pool_apy,
191
+ tvl: p.pool_tvl,
192
+ // PositionSlot has no `liquidity` field yet; Zyfai will add it. Narrow
193
+ // structural read keeps it undefined today and auto-populates later.
194
+ liquidity: p.liquidity
195
+ }));
179
196
  return {
180
197
  smartWallet,
181
198
  totalBalance: String(totalBalance),
182
- tokens
199
+ tokens,
200
+ positions
183
201
  };
184
202
  }
185
203
  function sumTokenValues(tokens) {
@@ -1971,12 +1989,13 @@ var OwneySDK = class {
1971
1989
  const chainId = this.requireChainId();
1972
1990
  const activeAgents = this.getActiveAgents();
1973
1991
  const balances = {};
1992
+ const positionsByAgent = {};
1974
1993
  let totalBalance = 0;
1975
1994
  const entries = [...activeAgents.entries()];
1976
1995
  const balanceResults = await Promise.allSettled(
1977
1996
  entries.map(async ([id, agent]) => {
1978
1997
  const b = await agent.getBalances(state, chainId);
1979
- return [id, Number(b.totalBalance)];
1998
+ return [id, Number(b.totalBalance), b.positions ?? []];
1980
1999
  })
1981
2000
  );
1982
2001
  let successCount = 0;
@@ -1985,8 +2004,9 @@ var OwneySDK = class {
1985
2004
  const settledResult = balanceResults[i];
1986
2005
  const [agentId] = entries[i];
1987
2006
  if (settledResult.status === "fulfilled") {
1988
- const [id, bal] = settledResult.value;
2007
+ const [id, bal, agentPositions] = settledResult.value;
1989
2008
  balances[id] = bal;
2009
+ positionsByAgent[id] = agentPositions;
1990
2010
  totalBalance += bal;
1991
2011
  successCount += 1;
1992
2012
  } else {
@@ -2020,10 +2040,177 @@ var OwneySDK = class {
2020
2040
  }
2021
2041
  }
2022
2042
  return {
2023
- agentAllocation: allocation
2043
+ agentAllocation: allocation,
2044
+ agentPositions: positionsByAgent
2024
2045
  };
2025
2046
  }
2026
2047
  };
2048
+
2049
+ // src/agents/zyfai/zyfai.siwx.ts
2050
+ var import_viem4 = require("viem");
2051
+ var import_siwe = require("siwe");
2052
+ var import_sdk2 = require("@zyfai/sdk");
2053
+
2054
+ // src/agents/zyfai/zyfai.siwx-cache.ts
2055
+ var KEY_PREFIX2 = "owney.siwx.session";
2056
+ var storage2 = () => {
2057
+ if (typeof window === "undefined")
2058
+ return null;
2059
+ try {
2060
+ return window.localStorage;
2061
+ } catch {
2062
+ return null;
2063
+ }
2064
+ };
2065
+ var buildKey2 = (address, chainId) => `${KEY_PREFIX2}:${address.toLowerCase()}:${chainId}`;
2066
+ var readSiwxSession = (address, chainId) => {
2067
+ const store = storage2();
2068
+ if (!store)
2069
+ return null;
2070
+ const raw = store.getItem(buildKey2(address, chainId));
2071
+ if (!raw)
2072
+ return null;
2073
+ try {
2074
+ return JSON.parse(raw);
2075
+ } catch {
2076
+ store.removeItem(buildKey2(address, chainId));
2077
+ return null;
2078
+ }
2079
+ };
2080
+ var writeSiwxSession = (address, chainId, session) => {
2081
+ const store = storage2();
2082
+ if (!store)
2083
+ return;
2084
+ try {
2085
+ store.setItem(buildKey2(address, chainId), JSON.stringify(session));
2086
+ } catch {
2087
+ }
2088
+ };
2089
+ var clearSiwxSession = (address, chainId) => {
2090
+ const store = storage2();
2091
+ if (!store)
2092
+ return;
2093
+ try {
2094
+ store.removeItem(buildKey2(address, chainId));
2095
+ } catch {
2096
+ }
2097
+ };
2098
+
2099
+ // src/agents/zyfai/zyfai.siwx.ts
2100
+ var STATEMENT = "Sign in with Ethereum";
2101
+ var VERSION = "1";
2102
+ var numericChainId = (caip) => {
2103
+ const segment = caip.split(":").pop();
2104
+ const id = Number(segment);
2105
+ if (!segment || !Number.isFinite(id) || id <= 0) {
2106
+ throw new Error(`Invalid CAIP chain id: "${caip}"`);
2107
+ }
2108
+ return id;
2109
+ };
2110
+ var browserDomain = () => typeof window !== "undefined" ? window.location.host : "";
2111
+ var browserUri = () => typeof window !== "undefined" ? window.location.origin : "";
2112
+ function buildSIWXConfig(deps) {
2113
+ const { post, referralSource } = deps;
2114
+ const createMessage = async (input) => {
2115
+ const { nonce } = await post("/auth/challenge", {});
2116
+ const domain = browserDomain();
2117
+ const uri = browserUri();
2118
+ const issuedAt = (/* @__PURE__ */ new Date()).toISOString();
2119
+ const chainId = input.chainId;
2120
+ const accountAddress = input.accountAddress;
2121
+ const message = {
2122
+ accountAddress,
2123
+ chainId,
2124
+ domain,
2125
+ uri,
2126
+ version: VERSION,
2127
+ nonce,
2128
+ statement: STATEMENT,
2129
+ issuedAt,
2130
+ toString() {
2131
+ return new import_siwe.SiweMessage({
2132
+ address: (0, import_viem4.getAddress)(accountAddress),
2133
+ chainId: numericChainId(chainId),
2134
+ domain,
2135
+ uri,
2136
+ statement: STATEMENT,
2137
+ nonce,
2138
+ version: VERSION,
2139
+ issuedAt
2140
+ }).prepareMessage();
2141
+ }
2142
+ };
2143
+ return message;
2144
+ };
2145
+ const getSessions = async (chainId, address) => {
2146
+ let id;
2147
+ try {
2148
+ id = numericChainId(chainId);
2149
+ } catch {
2150
+ return [];
2151
+ }
2152
+ const jwt = readSession(address, id);
2153
+ const stored = readSiwxSession(address, id);
2154
+ if (!jwt) {
2155
+ if (stored)
2156
+ clearSiwxSession(address, id);
2157
+ return [];
2158
+ }
2159
+ if (!stored)
2160
+ return [];
2161
+ const session = {
2162
+ // `stored.data.chainId` is a plain string in the cache (kept AppKit-free);
2163
+ // it always holds a valid CaipNetworkId here, so narrow at the boundary.
2164
+ data: stored.data,
2165
+ message: stored.message,
2166
+ signature: stored.signature
2167
+ };
2168
+ return [session];
2169
+ };
2170
+ const persistSession = async (session) => {
2171
+ const address = session.data.accountAddress;
2172
+ const id = numericChainId(session.data.chainId);
2173
+ const message = new import_siwe.SiweMessage(session.message);
2174
+ const login = await post("/auth/login", {
2175
+ message,
2176
+ signature: session.signature,
2177
+ referralSource
2178
+ });
2179
+ writeSession(address, id, {
2180
+ token: login.accessToken,
2181
+ userId: login.userId ?? null,
2182
+ hasActiveSessionKey: Boolean(login.hasActiveSessionKey)
2183
+ });
2184
+ const stored = {
2185
+ data: session.data,
2186
+ message: session.message,
2187
+ signature: session.signature
2188
+ };
2189
+ writeSiwxSession(address, id, stored);
2190
+ };
2191
+ const addSession = async (session) => {
2192
+ await persistSession(session);
2193
+ };
2194
+ const setSessions = async (sessions) => {
2195
+ for (const session of sessions) {
2196
+ await persistSession(session);
2197
+ }
2198
+ };
2199
+ const revokeSession = async (chainId, address) => {
2200
+ const id = numericChainId(chainId);
2201
+ clearSession(address, id);
2202
+ clearSiwxSession(address, id);
2203
+ };
2204
+ return { createMessage, getSessions, addSession, setSessions, revokeSession };
2205
+ }
2206
+ function createOwneySIWX(config) {
2207
+ const zyfai = new import_sdk2.ZyfaiSDK({ apiKey: config.apiKey });
2208
+ const http = zyfai.httpClient;
2209
+ return buildSIWXConfig({
2210
+ post: (url, data) => http.post(url, data),
2211
+ referralSource: config.referralSource
2212
+ });
2213
+ }
2027
2214
  // Annotate the CommonJS export names for ESM import in node:
2028
2215
  0 && (module.exports = {
2029
2216
  AgentChainIncompatibleError,
@@ -2031,5 +2218,6 @@ var OwneySDK = class {
2031
2218
  InvalidHistoryCursorError,
2032
2219
  NotConnectedError,
2033
2220
  OwneyError,
2034
- OwneySDK
2221
+ OwneySDK,
2222
+ createOwneySIWX
2035
2223
  });
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;
@@ -126,10 +128,29 @@ interface OwneyToken {
126
128
  asset: OwneySupportedTokens;
127
129
  amount: string;
128
130
  }
131
+ interface OwneyPosition {
132
+ /** Raw chain identifier as returned by the agent (chain id or name); not coerced. */
133
+ chain: string;
134
+ protocol: string;
135
+ protocolId?: string;
136
+ pool?: string;
137
+ asset: string;
138
+ amount: string;
139
+ apy?: number;
140
+ tvl?: number;
141
+ /** Pool liquidity. Prepared slot — Zyfai will add this to its portfolio
142
+ * response later; undefined until then. */
143
+ liquidity?: number;
144
+ }
129
145
  interface AgentBalance {
130
146
  smartWallet?: `0x${string}`;
131
147
  totalBalance: string;
132
148
  tokens: OwneyToken[];
149
+ /**
150
+ * Per-protocol/pool positions when the agent's portfolio payload includes
151
+ * them (zyfai). Omitted for agents that don't expose positions (sail).
152
+ */
153
+ positions?: OwneyPosition[];
133
154
  }
134
155
  interface OwneyBalances {
135
156
  totalBalance: string;
@@ -221,6 +242,8 @@ interface OwneyAgentApy {
221
242
  }
222
243
  interface OwneyAgentAllocation {
223
244
  agentAllocation: Record<AgentId, number>;
245
+ /** Per-agent positions. Empty array for agents that don't expose positions. */
246
+ agentPositions: Record<AgentId, OwneyPosition[]>;
224
247
  }
225
248
 
226
249
  declare class OwneySDK {
@@ -427,4 +450,17 @@ declare class InvalidHistoryCursorError extends Error {
427
450
  constructor(message: string);
428
451
  }
429
452
 
430
- 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, OwneySupportedChainId, OwneySupportedChains, OwneySupportedTokens, OwneyToken, OwneyUserProfile, OwneyWithdrawResult, RebalanceLog, WithdrawOptions };
453
+ type OwneySIWXConfig = {
454
+ /** Owney/Zyfai API key — same value passed to `new OwneySDK({ apiKey })`. */
455
+ apiKey: string;
456
+ /** Optional attribution forwarded to /auth/login. */
457
+ referralSource?: string;
458
+ };
459
+ /**
460
+ * Public factory. Construct ONCE at `createAppKit` time and pass to
461
+ * `createAppKit({ siwx })`. Reuses Zyfai's internal httpClient so the API base
462
+ * URL and `X-API-Key` header stay a single source of truth.
463
+ */
464
+ declare function createOwneySIWX(config: OwneySIWXConfig): SIWXConfig;
465
+
466
+ 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, OwneyPosition, 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;
@@ -126,10 +128,29 @@ interface OwneyToken {
126
128
  asset: OwneySupportedTokens;
127
129
  amount: string;
128
130
  }
131
+ interface OwneyPosition {
132
+ /** Raw chain identifier as returned by the agent (chain id or name); not coerced. */
133
+ chain: string;
134
+ protocol: string;
135
+ protocolId?: string;
136
+ pool?: string;
137
+ asset: string;
138
+ amount: string;
139
+ apy?: number;
140
+ tvl?: number;
141
+ /** Pool liquidity. Prepared slot — Zyfai will add this to its portfolio
142
+ * response later; undefined until then. */
143
+ liquidity?: number;
144
+ }
129
145
  interface AgentBalance {
130
146
  smartWallet?: `0x${string}`;
131
147
  totalBalance: string;
132
148
  tokens: OwneyToken[];
149
+ /**
150
+ * Per-protocol/pool positions when the agent's portfolio payload includes
151
+ * them (zyfai). Omitted for agents that don't expose positions (sail).
152
+ */
153
+ positions?: OwneyPosition[];
133
154
  }
134
155
  interface OwneyBalances {
135
156
  totalBalance: string;
@@ -221,6 +242,8 @@ interface OwneyAgentApy {
221
242
  }
222
243
  interface OwneyAgentAllocation {
223
244
  agentAllocation: Record<AgentId, number>;
245
+ /** Per-agent positions. Empty array for agents that don't expose positions. */
246
+ agentPositions: Record<AgentId, OwneyPosition[]>;
224
247
  }
225
248
 
226
249
  declare class OwneySDK {
@@ -427,4 +450,17 @@ declare class InvalidHistoryCursorError extends Error {
427
450
  constructor(message: string);
428
451
  }
429
452
 
430
- 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, OwneySupportedChainId, OwneySupportedChains, OwneySupportedTokens, OwneyToken, OwneyUserProfile, OwneyWithdrawResult, RebalanceLog, WithdrawOptions };
453
+ type OwneySIWXConfig = {
454
+ /** Owney/Zyfai API key — same value passed to `new OwneySDK({ apiKey })`. */
455
+ apiKey: string;
456
+ /** Optional attribution forwarded to /auth/login. */
457
+ referralSource?: string;
458
+ };
459
+ /**
460
+ * Public factory. Construct ONCE at `createAppKit` time and pass to
461
+ * `createAppKit({ siwx })`. Reuses Zyfai's internal httpClient so the API base
462
+ * URL and `X-API-Key` header stay a single source of truth.
463
+ */
464
+ declare function createOwneySIWX(config: OwneySIWXConfig): SIWXConfig;
465
+
466
+ 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, OwneyPosition, OwneySDK, OwneySDKConfig, OwneySIWXConfig, OwneySupportedChainId, OwneySupportedChains, OwneySupportedTokens, OwneyToken, OwneyUserProfile, OwneyWithdrawResult, RebalanceLog, WithdrawOptions, createOwneySIWX };
package/dist/index.js CHANGED
@@ -145,10 +145,27 @@ function mapBalances(raw, _chainId, smartWallet) {
145
145
  });
146
146
  }
147
147
  }
148
+ const positions = (portfolio.positions ?? []).map((p) => ({
149
+ chain: p.chain ?? "",
150
+ protocol: p.protocol_name ?? p.protocol_id ?? "",
151
+ protocolId: p.protocol_id,
152
+ pool: p.pool,
153
+ asset: p.token_symbol ?? "",
154
+ // Position amount is hex-encoded base units (like the token balances
155
+ // above). Supported assets (USDC/USDT) are 6-decimal — hexToDecimal's
156
+ // default — so no per-token decimals lookup is needed.
157
+ amount: String(hexToDecimal(p.amount || "0")),
158
+ apy: p.pool_apy,
159
+ tvl: p.pool_tvl,
160
+ // PositionSlot has no `liquidity` field yet; Zyfai will add it. Narrow
161
+ // structural read keeps it undefined today and auto-populates later.
162
+ liquidity: p.liquidity
163
+ }));
148
164
  return {
149
165
  smartWallet,
150
166
  totalBalance: String(totalBalance),
151
- tokens
167
+ tokens,
168
+ positions
152
169
  };
153
170
  }
154
171
  function sumTokenValues(tokens) {
@@ -1944,12 +1961,13 @@ var OwneySDK = class {
1944
1961
  const chainId = this.requireChainId();
1945
1962
  const activeAgents = this.getActiveAgents();
1946
1963
  const balances = {};
1964
+ const positionsByAgent = {};
1947
1965
  let totalBalance = 0;
1948
1966
  const entries = [...activeAgents.entries()];
1949
1967
  const balanceResults = await Promise.allSettled(
1950
1968
  entries.map(async ([id, agent]) => {
1951
1969
  const b = await agent.getBalances(state, chainId);
1952
- return [id, Number(b.totalBalance)];
1970
+ return [id, Number(b.totalBalance), b.positions ?? []];
1953
1971
  })
1954
1972
  );
1955
1973
  let successCount = 0;
@@ -1958,8 +1976,9 @@ var OwneySDK = class {
1958
1976
  const settledResult = balanceResults[i];
1959
1977
  const [agentId] = entries[i];
1960
1978
  if (settledResult.status === "fulfilled") {
1961
- const [id, bal] = settledResult.value;
1979
+ const [id, bal, agentPositions] = settledResult.value;
1962
1980
  balances[id] = bal;
1981
+ positionsByAgent[id] = agentPositions;
1963
1982
  totalBalance += bal;
1964
1983
  successCount += 1;
1965
1984
  } else {
@@ -1993,15 +2012,183 @@ var OwneySDK = class {
1993
2012
  }
1994
2013
  }
1995
2014
  return {
1996
- agentAllocation: allocation
2015
+ agentAllocation: allocation,
2016
+ agentPositions: positionsByAgent
1997
2017
  };
1998
2018
  }
1999
2019
  };
2020
+
2021
+ // src/agents/zyfai/zyfai.siwx.ts
2022
+ import { getAddress } from "viem";
2023
+ import { SiweMessage } from "siwe";
2024
+ import { ZyfaiSDK as ZyfaiSDK2 } from "@zyfai/sdk";
2025
+
2026
+ // src/agents/zyfai/zyfai.siwx-cache.ts
2027
+ var KEY_PREFIX2 = "owney.siwx.session";
2028
+ var storage2 = () => {
2029
+ if (typeof window === "undefined")
2030
+ return null;
2031
+ try {
2032
+ return window.localStorage;
2033
+ } catch {
2034
+ return null;
2035
+ }
2036
+ };
2037
+ var buildKey2 = (address, chainId) => `${KEY_PREFIX2}:${address.toLowerCase()}:${chainId}`;
2038
+ var readSiwxSession = (address, chainId) => {
2039
+ const store = storage2();
2040
+ if (!store)
2041
+ return null;
2042
+ const raw = store.getItem(buildKey2(address, chainId));
2043
+ if (!raw)
2044
+ return null;
2045
+ try {
2046
+ return JSON.parse(raw);
2047
+ } catch {
2048
+ store.removeItem(buildKey2(address, chainId));
2049
+ return null;
2050
+ }
2051
+ };
2052
+ var writeSiwxSession = (address, chainId, session) => {
2053
+ const store = storage2();
2054
+ if (!store)
2055
+ return;
2056
+ try {
2057
+ store.setItem(buildKey2(address, chainId), JSON.stringify(session));
2058
+ } catch {
2059
+ }
2060
+ };
2061
+ var clearSiwxSession = (address, chainId) => {
2062
+ const store = storage2();
2063
+ if (!store)
2064
+ return;
2065
+ try {
2066
+ store.removeItem(buildKey2(address, chainId));
2067
+ } catch {
2068
+ }
2069
+ };
2070
+
2071
+ // src/agents/zyfai/zyfai.siwx.ts
2072
+ var STATEMENT = "Sign in with Ethereum";
2073
+ var VERSION = "1";
2074
+ var numericChainId = (caip) => {
2075
+ const segment = caip.split(":").pop();
2076
+ const id = Number(segment);
2077
+ if (!segment || !Number.isFinite(id) || id <= 0) {
2078
+ throw new Error(`Invalid CAIP chain id: "${caip}"`);
2079
+ }
2080
+ return id;
2081
+ };
2082
+ var browserDomain = () => typeof window !== "undefined" ? window.location.host : "";
2083
+ var browserUri = () => typeof window !== "undefined" ? window.location.origin : "";
2084
+ function buildSIWXConfig(deps) {
2085
+ const { post, referralSource } = deps;
2086
+ const createMessage = async (input) => {
2087
+ const { nonce } = await post("/auth/challenge", {});
2088
+ const domain = browserDomain();
2089
+ const uri = browserUri();
2090
+ const issuedAt = (/* @__PURE__ */ new Date()).toISOString();
2091
+ const chainId = input.chainId;
2092
+ const accountAddress = input.accountAddress;
2093
+ const message = {
2094
+ accountAddress,
2095
+ chainId,
2096
+ domain,
2097
+ uri,
2098
+ version: VERSION,
2099
+ nonce,
2100
+ statement: STATEMENT,
2101
+ issuedAt,
2102
+ toString() {
2103
+ return new SiweMessage({
2104
+ address: getAddress(accountAddress),
2105
+ chainId: numericChainId(chainId),
2106
+ domain,
2107
+ uri,
2108
+ statement: STATEMENT,
2109
+ nonce,
2110
+ version: VERSION,
2111
+ issuedAt
2112
+ }).prepareMessage();
2113
+ }
2114
+ };
2115
+ return message;
2116
+ };
2117
+ const getSessions = async (chainId, address) => {
2118
+ let id;
2119
+ try {
2120
+ id = numericChainId(chainId);
2121
+ } catch {
2122
+ return [];
2123
+ }
2124
+ const jwt = readSession(address, id);
2125
+ const stored = readSiwxSession(address, id);
2126
+ if (!jwt) {
2127
+ if (stored)
2128
+ clearSiwxSession(address, id);
2129
+ return [];
2130
+ }
2131
+ if (!stored)
2132
+ return [];
2133
+ const session = {
2134
+ // `stored.data.chainId` is a plain string in the cache (kept AppKit-free);
2135
+ // it always holds a valid CaipNetworkId here, so narrow at the boundary.
2136
+ data: stored.data,
2137
+ message: stored.message,
2138
+ signature: stored.signature
2139
+ };
2140
+ return [session];
2141
+ };
2142
+ const persistSession = async (session) => {
2143
+ const address = session.data.accountAddress;
2144
+ const id = numericChainId(session.data.chainId);
2145
+ const message = new SiweMessage(session.message);
2146
+ const login = await post("/auth/login", {
2147
+ message,
2148
+ signature: session.signature,
2149
+ referralSource
2150
+ });
2151
+ writeSession(address, id, {
2152
+ token: login.accessToken,
2153
+ userId: login.userId ?? null,
2154
+ hasActiveSessionKey: Boolean(login.hasActiveSessionKey)
2155
+ });
2156
+ const stored = {
2157
+ data: session.data,
2158
+ message: session.message,
2159
+ signature: session.signature
2160
+ };
2161
+ writeSiwxSession(address, id, stored);
2162
+ };
2163
+ const addSession = async (session) => {
2164
+ await persistSession(session);
2165
+ };
2166
+ const setSessions = async (sessions) => {
2167
+ for (const session of sessions) {
2168
+ await persistSession(session);
2169
+ }
2170
+ };
2171
+ const revokeSession = async (chainId, address) => {
2172
+ const id = numericChainId(chainId);
2173
+ clearSession(address, id);
2174
+ clearSiwxSession(address, id);
2175
+ };
2176
+ return { createMessage, getSessions, addSession, setSessions, revokeSession };
2177
+ }
2178
+ function createOwneySIWX(config) {
2179
+ const zyfai = new ZyfaiSDK2({ apiKey: config.apiKey });
2180
+ const http = zyfai.httpClient;
2181
+ return buildSIWXConfig({
2182
+ post: (url, data) => http.post(url, data),
2183
+ referralSource: config.referralSource
2184
+ });
2185
+ }
2000
2186
  export {
2001
2187
  AgentChainIncompatibleError,
2002
2188
  AgentNotFoundError,
2003
2189
  InvalidHistoryCursorError,
2004
2190
  NotConnectedError,
2005
2191
  OwneyError,
2006
- OwneySDK
2192
+ OwneySDK,
2193
+ createOwneySIWX
2007
2194
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@owney/sdk",
3
- "version": "0.5.0-beta.0",
3
+ "version": "0.5.1-beta.0",
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",