@owney/sdk 0.5.0-beta.0 → 0.6.0-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
 
@@ -933,130 +934,6 @@ function aggregateApyByChainAndAsset(agentApys, agentBalances) {
933
934
  return out;
934
935
  }
935
936
 
936
- // src/client.ts
937
- var import_viem3 = require("viem");
938
- var import_chains = require("viem/chains");
939
-
940
- // src/lib/transfer-auth.ts
941
- var import_viem2 = require("viem");
942
- var ERC20_META_ABI = [
943
- { type: "function", name: "name", stateMutability: "view", inputs: [], outputs: [{ name: "", type: "string" }] },
944
- { type: "function", name: "version", stateMutability: "view", inputs: [], outputs: [{ name: "", type: "string" }] }
945
- ];
946
- function buildTransferWithAuthorizationTypedData(input) {
947
- return {
948
- domain: { name: input.tokenName, version: input.tokenVersion, chainId: input.chainId, verifyingContract: input.token },
949
- types: {
950
- TransferWithAuthorization: [
951
- { name: "from", type: "address" },
952
- { name: "to", type: "address" },
953
- { name: "value", type: "uint256" },
954
- { name: "validAfter", type: "uint256" },
955
- { name: "validBefore", type: "uint256" },
956
- { name: "nonce", type: "bytes32" }
957
- ]
958
- },
959
- primaryType: "TransferWithAuthorization",
960
- message: input.message
961
- };
962
- }
963
- async function readTokenMeta(publicClient, token) {
964
- const [tokenName, tokenVersion] = await Promise.all([
965
- publicClient.readContract({ address: token, abi: ERC20_META_ABI, functionName: "name" }),
966
- publicClient.readContract({ address: token, abi: ERC20_META_ABI, functionName: "version" }).catch(() => "2")
967
- ]);
968
- return { tokenName, tokenVersion };
969
- }
970
- function randomAuthNonce() {
971
- const bytes = new Uint8Array(32);
972
- globalThis.crypto.getRandomValues(bytes);
973
- return (0, import_viem2.bytesToHex)(bytes);
974
- }
975
-
976
- // src/lib/sponsor-client.ts
977
- var ROUTING_API_BASE_URL3 = "https://owney-routing-api-243946518160.europe-west4.run.app";
978
- async function postSponsorTransferAuth(input) {
979
- const base2 = input.baseUrl ?? ROUTING_API_BASE_URL3;
980
- let res;
981
- try {
982
- res = await fetch(`${base2}/api/v1/sponsor/erc20-transfer-auth`, {
983
- method: "POST",
984
- headers: { "content-type": "application/json", "x-owney-api-key": input.apiKey },
985
- body: JSON.stringify(input.body)
986
- });
987
- } catch (networkError) {
988
- throw new OwneyError(
989
- "SPONSOR_REQUEST_FAILED",
990
- `Sponsor API network error: ${networkError instanceof Error ? networkError.message : String(networkError)}`,
991
- { cause: String(networkError) }
992
- );
993
- }
994
- const text = await res.text();
995
- let parsed = null;
996
- try {
997
- parsed = JSON.parse(text);
998
- } catch {
999
- }
1000
- if (!res.ok || !parsed?.success || !parsed.data) {
1001
- throw new OwneyError(
1002
- "SPONSOR_REQUEST_FAILED",
1003
- `Sponsor API error ${res.status}: ${parsed?.message ?? text.slice(0, 500)}`,
1004
- { statusCode: res.status, responseBody: text.slice(0, 500) }
1005
- );
1006
- }
1007
- return parsed.data;
1008
- }
1009
-
1010
- // src/lib/sponsored-deposit.ts
1011
- var AUTH_WINDOW_SECONDS = 15 * 60;
1012
- function makeSponsoredDepositCallback(deps) {
1013
- const post = deps.httpPost ?? postSponsorTransferAuth;
1014
- return async (smartWallet, chainId, amount) => {
1015
- const cid = chainId;
1016
- const token = deps.tokenAddressByChain[cid];
1017
- if (!token) {
1018
- throw new OwneyError(
1019
- "CHAIN_UNSUPPORTED",
1020
- `No sponsored token configured for chain ${chainId}`
1021
- );
1022
- }
1023
- const pub = deps.getPublicClient(cid);
1024
- const wallet = deps.getWalletClient(cid);
1025
- const { tokenName, tokenVersion } = await readTokenMeta(pub, token);
1026
- const validAfter = 0n;
1027
- const validBefore = BigInt(Math.floor(Date.now() / 1e3) + AUTH_WINDOW_SECONDS);
1028
- const nonce = randomAuthNonce();
1029
- const typedData = buildTransferWithAuthorizationTypedData({
1030
- token,
1031
- chainId: cid,
1032
- tokenName,
1033
- tokenVersion,
1034
- message: { from: deps.ownerAddress, to: smartWallet, value: BigInt(amount), validAfter, validBefore, nonce }
1035
- });
1036
- const authSignature = await wallet.signTypedData(
1037
- { account: deps.ownerAddress, ...typedData }
1038
- );
1039
- const result = await post({
1040
- baseUrl: deps.baseUrl,
1041
- apiKey: deps.apiKey,
1042
- body: {
1043
- chainId: cid,
1044
- token,
1045
- from: deps.ownerAddress,
1046
- to: smartWallet,
1047
- value: amount,
1048
- validAfter: validAfter.toString(),
1049
- validBefore: validBefore.toString(),
1050
- nonce,
1051
- authSignature,
1052
- tokenName,
1053
- tokenVersion
1054
- }
1055
- });
1056
- return result.txHash;
1057
- };
1058
- }
1059
-
1060
937
  // src/client.ts
1061
938
  function encodeMultiAgentCursor(map) {
1062
939
  return Buffer.from(JSON.stringify(map), "utf8").toString("base64");
@@ -1078,11 +955,6 @@ function decodeMultiAgentCursor(token) {
1078
955
  }
1079
956
  return parsed;
1080
957
  }
1081
- var SPONSORED_USDC_BY_CHAIN = {
1082
- 8453: "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
1083
- 42161: "0xaf88d065e77c8cc2239327c5edb3a432268e5831"
1084
- };
1085
- var VIEM_CHAIN = { 8453: import_chains.base, 42161: import_chains.arbitrum };
1086
958
  var OwneySDK = class {
1087
959
  agents = /* @__PURE__ */ new Map();
1088
960
  activeAgents = /* @__PURE__ */ new Set();
@@ -1095,7 +967,6 @@ var OwneySDK = class {
1095
967
  state = null;
1096
968
  apiKey;
1097
969
  zyfaiRpcUrls;
1098
- cachedSponsoredCallback = null;
1099
970
  initializingAgentsPromise = null;
1100
971
  constructor(config) {
1101
972
  this.apiKey = config.apiKey;
@@ -1119,7 +990,6 @@ var OwneySDK = class {
1119
990
  );
1120
991
  }
1121
992
  this.state = { provider, walletAddress, chainId: null };
1122
- this.cachedSponsoredCallback = null;
1123
993
  }
1124
994
  /**
1125
995
  * Disconnect from all agents and clear connection state.
@@ -1132,7 +1002,6 @@ var OwneySDK = class {
1132
1002
  this.activeAgents.clear();
1133
1003
  this.disabledAgents.clear();
1134
1004
  this.state = null;
1135
- this.cachedSponsoredCallback = null;
1136
1005
  }
1137
1006
  isAgentDisabled(agentId) {
1138
1007
  return this.disabledAgents.has(agentId);
@@ -1166,46 +1035,6 @@ var OwneySDK = class {
1166
1035
  }
1167
1036
  return chainId;
1168
1037
  }
1169
- requireConnectedProvider() {
1170
- if (!this.state?.provider) {
1171
- throw new OwneyError(
1172
- "NOT_CONNECTED",
1173
- "connect(provider) must be called before deposit",
1174
- {}
1175
- );
1176
- }
1177
- return this.state.provider;
1178
- }
1179
- /**
1180
- * Lazily builds (and caches) the default EIP-3009 sponsored deposit callback
1181
- * used when the caller omits `depositCallback`. Wraps the connected EIP-1193
1182
- * provider with viem `custom(provider)` to read token meta and sign the
1183
- * `TransferWithAuthorization`, then POSTs to the sponsor API.
1184
- */
1185
- getDefaultSponsoredCallback() {
1186
- if (this.cachedSponsoredCallback)
1187
- return this.cachedSponsoredCallback;
1188
- const provider = this.requireConnectedProvider();
1189
- const owner = this.state.walletAddress;
1190
- this.cachedSponsoredCallback = makeSponsoredDepositCallback({
1191
- apiKey: this.apiKey,
1192
- ownerAddress: owner,
1193
- tokenAddressByChain: SPONSORED_USDC_BY_CHAIN,
1194
- // Casts work around viem's chain-narrowed Client vs the generic
1195
- // PublicClient/WalletClient param types — structurally identical at
1196
- // runtime, but the two share a name TS treats as unrelated.
1197
- getPublicClient: (cid) => (0, import_viem3.createPublicClient)({
1198
- chain: VIEM_CHAIN[cid],
1199
- transport: (0, import_viem3.custom)(provider)
1200
- }),
1201
- getWalletClient: (cid) => (0, import_viem3.createWalletClient)({
1202
- account: owner,
1203
- chain: VIEM_CHAIN[cid],
1204
- transport: (0, import_viem3.custom)(provider)
1205
- })
1206
- });
1207
- return this.cachedSponsoredCallback;
1208
- }
1209
1038
  getAgent(agentId) {
1210
1039
  const agent = this.agents.get(agentId);
1211
1040
  if (!agent) {
@@ -1359,7 +1188,6 @@ var OwneySDK = class {
1359
1188
  }
1360
1189
  const state = this.requireState();
1361
1190
  const chainId = this.requireChainId();
1362
- const effectiveCallback = depositCallback ?? this.getDefaultSponsoredCallback();
1363
1191
  if (agentId) {
1364
1192
  if (this.isAgentDisabled(agentId)) {
1365
1193
  throw new OwneyError(
@@ -1374,7 +1202,7 @@ var OwneySDK = class {
1374
1202
  return withFailureReporting(
1375
1203
  this.apiKey,
1376
1204
  agent.id,
1377
- () => agent.deposit(state, chainId, amount, effectiveCallback)
1205
+ () => agent.deposit(state, chainId, amount, depositCallback)
1378
1206
  );
1379
1207
  }
1380
1208
  const totalAmount = BigInt(amount);
@@ -1408,7 +1236,7 @@ var OwneySDK = class {
1408
1236
  agentResults[agent.id] = await withFailureReporting(
1409
1237
  this.apiKey,
1410
1238
  agent.id,
1411
- () => agent.deposit(state, chainId, agentAmount, effectiveCallback)
1239
+ () => agent.deposit(state, chainId, agentAmount, depositCallback)
1412
1240
  );
1413
1241
  }
1414
1242
  return { agentResults };
@@ -2024,6 +1852,172 @@ var OwneySDK = class {
2024
1852
  };
2025
1853
  }
2026
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
+ }
2027
2021
  // Annotate the CommonJS export names for ESM import in node:
2028
2022
  0 && (module.exports = {
2029
2023
  AgentChainIncompatibleError,
@@ -2031,5 +2025,6 @@ var OwneySDK = class {
2031
2025
  InvalidHistoryCursorError,
2032
2026
  NotConnectedError,
2033
2027
  OwneyError,
2034
- OwneySDK
2028
+ OwneySDK,
2029
+ createOwneySIWX
2035
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;
@@ -99,7 +101,7 @@ type AgentsApyOptions = {
99
101
  type DepositOptions = {
100
102
  amount: string;
101
103
  asset: Asset;
102
- depositCallback?: DepositCallback;
104
+ depositCallback: DepositCallback;
103
105
  agentId?: AgentId;
104
106
  };
105
107
 
@@ -235,7 +237,6 @@ declare class OwneySDK {
235
237
  private state;
236
238
  private apiKey;
237
239
  private zyfaiRpcUrls?;
238
- private cachedSponsoredCallback;
239
240
  private initializingAgentsPromise;
240
241
  constructor(config: OwneySDKConfig);
241
242
  /**
@@ -262,14 +263,6 @@ declare class OwneySDK {
262
263
  getActiveChainId(): number | null;
263
264
  private requireState;
264
265
  private requireChainId;
265
- private requireConnectedProvider;
266
- /**
267
- * Lazily builds (and caches) the default EIP-3009 sponsored deposit callback
268
- * used when the caller omits `depositCallback`. Wraps the connected EIP-1193
269
- * provider with viem `custom(provider)` to read token meta and sign the
270
- * `TransferWithAuthorization`, then POSTs to the sponsor API.
271
- */
272
- private getDefaultSponsoredCallback;
273
266
  private getAgent;
274
267
  private getActiveAgents;
275
268
  private ensureAgentsInitialized;
@@ -397,7 +390,7 @@ declare class OwneySDK {
397
390
  getAgentAllocation(): Promise<OwneyAgentAllocation>;
398
391
  }
399
392
 
400
- type OwneyErrorCode = "NOT_CONNECTED" | "NO_ACTIVE_CHAIN" | "WALLET_NO_ACCOUNTS" | "WALLET_ADDRESS_REQUIRED" | "AGENT_NOT_FOUND" | "AGENT_CHAIN_INCOMPATIBLE" | "AGENT_EMPTY_LIST" | "AGENT_DISABLED" | "CHAIN_UNSUPPORTED" | "CHAIN_NO_COMPATIBLE_AGENTS" | "ASSET_UNSUPPORTED" | "ASSET_NO_COMPATIBLE_AGENTS" | "DEPOSIT_AMOUNT_BELOW_MINIMUM" | "DEPOSIT_CALLBACK_REQUIRED" | "DEPOSIT_CALLBACK_INVALID" | "DEPOSIT_NO_PERMITTED_TOKENS" | "WITHDRAW_NO_PERMITTED_TOKENS" | "WITHDRAW_INSUFFICIENT_BALANCE" | "WITHDRAW_ALL_FAILED" | "WITHDRAW_PARTIAL_FAILURE" | "WITHDRAW_FAILED" | "API_ROUTING_ERROR" | "API_ROUTING_FAILED" | "API_SAIL_ERROR" | "API_SAIL_TIMEOUT" | "API_NO_AGENTS" | "SPONSOR_REQUEST_FAILED" | "BALANCE_ALL_FAILED" | "ALLOCATION_ALL_FAILED" | "VALIDATION_INVALID_DAYS";
393
+ type OwneyErrorCode = "NOT_CONNECTED" | "NO_ACTIVE_CHAIN" | "WALLET_NO_ACCOUNTS" | "WALLET_ADDRESS_REQUIRED" | "AGENT_NOT_FOUND" | "AGENT_CHAIN_INCOMPATIBLE" | "AGENT_EMPTY_LIST" | "AGENT_DISABLED" | "CHAIN_UNSUPPORTED" | "CHAIN_NO_COMPATIBLE_AGENTS" | "ASSET_UNSUPPORTED" | "ASSET_NO_COMPATIBLE_AGENTS" | "DEPOSIT_AMOUNT_BELOW_MINIMUM" | "DEPOSIT_CALLBACK_REQUIRED" | "DEPOSIT_CALLBACK_INVALID" | "DEPOSIT_NO_PERMITTED_TOKENS" | "WITHDRAW_NO_PERMITTED_TOKENS" | "WITHDRAW_INSUFFICIENT_BALANCE" | "WITHDRAW_ALL_FAILED" | "WITHDRAW_PARTIAL_FAILURE" | "WITHDRAW_FAILED" | "API_ROUTING_ERROR" | "API_ROUTING_FAILED" | "API_SAIL_ERROR" | "API_SAIL_TIMEOUT" | "API_NO_AGENTS" | "BALANCE_ALL_FAILED" | "ALLOCATION_ALL_FAILED" | "VALIDATION_INVALID_DAYS";
401
394
  declare class OwneyError extends Error {
402
395
  readonly code: OwneyErrorCode;
403
396
  readonly details?: Record<string, unknown>;
@@ -427,4 +420,17 @@ declare class InvalidHistoryCursorError extends Error {
427
420
  constructor(message: string);
428
421
  }
429
422
 
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 };
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;
@@ -99,7 +101,7 @@ type AgentsApyOptions = {
99
101
  type DepositOptions = {
100
102
  amount: string;
101
103
  asset: Asset;
102
- depositCallback?: DepositCallback;
104
+ depositCallback: DepositCallback;
103
105
  agentId?: AgentId;
104
106
  };
105
107
 
@@ -235,7 +237,6 @@ declare class OwneySDK {
235
237
  private state;
236
238
  private apiKey;
237
239
  private zyfaiRpcUrls?;
238
- private cachedSponsoredCallback;
239
240
  private initializingAgentsPromise;
240
241
  constructor(config: OwneySDKConfig);
241
242
  /**
@@ -262,14 +263,6 @@ declare class OwneySDK {
262
263
  getActiveChainId(): number | null;
263
264
  private requireState;
264
265
  private requireChainId;
265
- private requireConnectedProvider;
266
- /**
267
- * Lazily builds (and caches) the default EIP-3009 sponsored deposit callback
268
- * used when the caller omits `depositCallback`. Wraps the connected EIP-1193
269
- * provider with viem `custom(provider)` to read token meta and sign the
270
- * `TransferWithAuthorization`, then POSTs to the sponsor API.
271
- */
272
- private getDefaultSponsoredCallback;
273
266
  private getAgent;
274
267
  private getActiveAgents;
275
268
  private ensureAgentsInitialized;
@@ -397,7 +390,7 @@ declare class OwneySDK {
397
390
  getAgentAllocation(): Promise<OwneyAgentAllocation>;
398
391
  }
399
392
 
400
- type OwneyErrorCode = "NOT_CONNECTED" | "NO_ACTIVE_CHAIN" | "WALLET_NO_ACCOUNTS" | "WALLET_ADDRESS_REQUIRED" | "AGENT_NOT_FOUND" | "AGENT_CHAIN_INCOMPATIBLE" | "AGENT_EMPTY_LIST" | "AGENT_DISABLED" | "CHAIN_UNSUPPORTED" | "CHAIN_NO_COMPATIBLE_AGENTS" | "ASSET_UNSUPPORTED" | "ASSET_NO_COMPATIBLE_AGENTS" | "DEPOSIT_AMOUNT_BELOW_MINIMUM" | "DEPOSIT_CALLBACK_REQUIRED" | "DEPOSIT_CALLBACK_INVALID" | "DEPOSIT_NO_PERMITTED_TOKENS" | "WITHDRAW_NO_PERMITTED_TOKENS" | "WITHDRAW_INSUFFICIENT_BALANCE" | "WITHDRAW_ALL_FAILED" | "WITHDRAW_PARTIAL_FAILURE" | "WITHDRAW_FAILED" | "API_ROUTING_ERROR" | "API_ROUTING_FAILED" | "API_SAIL_ERROR" | "API_SAIL_TIMEOUT" | "API_NO_AGENTS" | "SPONSOR_REQUEST_FAILED" | "BALANCE_ALL_FAILED" | "ALLOCATION_ALL_FAILED" | "VALIDATION_INVALID_DAYS";
393
+ type OwneyErrorCode = "NOT_CONNECTED" | "NO_ACTIVE_CHAIN" | "WALLET_NO_ACCOUNTS" | "WALLET_ADDRESS_REQUIRED" | "AGENT_NOT_FOUND" | "AGENT_CHAIN_INCOMPATIBLE" | "AGENT_EMPTY_LIST" | "AGENT_DISABLED" | "CHAIN_UNSUPPORTED" | "CHAIN_NO_COMPATIBLE_AGENTS" | "ASSET_UNSUPPORTED" | "ASSET_NO_COMPATIBLE_AGENTS" | "DEPOSIT_AMOUNT_BELOW_MINIMUM" | "DEPOSIT_CALLBACK_REQUIRED" | "DEPOSIT_CALLBACK_INVALID" | "DEPOSIT_NO_PERMITTED_TOKENS" | "WITHDRAW_NO_PERMITTED_TOKENS" | "WITHDRAW_INSUFFICIENT_BALANCE" | "WITHDRAW_ALL_FAILED" | "WITHDRAW_PARTIAL_FAILURE" | "WITHDRAW_FAILED" | "API_ROUTING_ERROR" | "API_ROUTING_FAILED" | "API_SAIL_ERROR" | "API_SAIL_TIMEOUT" | "API_NO_AGENTS" | "BALANCE_ALL_FAILED" | "ALLOCATION_ALL_FAILED" | "VALIDATION_INVALID_DAYS";
401
394
  declare class OwneyError extends Error {
402
395
  readonly code: OwneyErrorCode;
403
396
  readonly details?: Record<string, unknown>;
@@ -427,4 +420,17 @@ declare class InvalidHistoryCursorError extends Error {
427
420
  constructor(message: string);
428
421
  }
429
422
 
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 };
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
@@ -902,134 +902,6 @@ function aggregateApyByChainAndAsset(agentApys, agentBalances) {
902
902
  return out;
903
903
  }
904
904
 
905
- // src/client.ts
906
- import {
907
- createPublicClient,
908
- createWalletClient,
909
- custom
910
- } from "viem";
911
- import { base, arbitrum } from "viem/chains";
912
-
913
- // src/lib/transfer-auth.ts
914
- import { bytesToHex } from "viem";
915
- var ERC20_META_ABI = [
916
- { type: "function", name: "name", stateMutability: "view", inputs: [], outputs: [{ name: "", type: "string" }] },
917
- { type: "function", name: "version", stateMutability: "view", inputs: [], outputs: [{ name: "", type: "string" }] }
918
- ];
919
- function buildTransferWithAuthorizationTypedData(input) {
920
- return {
921
- domain: { name: input.tokenName, version: input.tokenVersion, chainId: input.chainId, verifyingContract: input.token },
922
- types: {
923
- TransferWithAuthorization: [
924
- { name: "from", type: "address" },
925
- { name: "to", type: "address" },
926
- { name: "value", type: "uint256" },
927
- { name: "validAfter", type: "uint256" },
928
- { name: "validBefore", type: "uint256" },
929
- { name: "nonce", type: "bytes32" }
930
- ]
931
- },
932
- primaryType: "TransferWithAuthorization",
933
- message: input.message
934
- };
935
- }
936
- async function readTokenMeta(publicClient, token) {
937
- const [tokenName, tokenVersion] = await Promise.all([
938
- publicClient.readContract({ address: token, abi: ERC20_META_ABI, functionName: "name" }),
939
- publicClient.readContract({ address: token, abi: ERC20_META_ABI, functionName: "version" }).catch(() => "2")
940
- ]);
941
- return { tokenName, tokenVersion };
942
- }
943
- function randomAuthNonce() {
944
- const bytes = new Uint8Array(32);
945
- globalThis.crypto.getRandomValues(bytes);
946
- return bytesToHex(bytes);
947
- }
948
-
949
- // src/lib/sponsor-client.ts
950
- var ROUTING_API_BASE_URL3 = "https://owney-routing-api-243946518160.europe-west4.run.app";
951
- async function postSponsorTransferAuth(input) {
952
- const base2 = input.baseUrl ?? ROUTING_API_BASE_URL3;
953
- let res;
954
- try {
955
- res = await fetch(`${base2}/api/v1/sponsor/erc20-transfer-auth`, {
956
- method: "POST",
957
- headers: { "content-type": "application/json", "x-owney-api-key": input.apiKey },
958
- body: JSON.stringify(input.body)
959
- });
960
- } catch (networkError) {
961
- throw new OwneyError(
962
- "SPONSOR_REQUEST_FAILED",
963
- `Sponsor API network error: ${networkError instanceof Error ? networkError.message : String(networkError)}`,
964
- { cause: String(networkError) }
965
- );
966
- }
967
- const text = await res.text();
968
- let parsed = null;
969
- try {
970
- parsed = JSON.parse(text);
971
- } catch {
972
- }
973
- if (!res.ok || !parsed?.success || !parsed.data) {
974
- throw new OwneyError(
975
- "SPONSOR_REQUEST_FAILED",
976
- `Sponsor API error ${res.status}: ${parsed?.message ?? text.slice(0, 500)}`,
977
- { statusCode: res.status, responseBody: text.slice(0, 500) }
978
- );
979
- }
980
- return parsed.data;
981
- }
982
-
983
- // src/lib/sponsored-deposit.ts
984
- var AUTH_WINDOW_SECONDS = 15 * 60;
985
- function makeSponsoredDepositCallback(deps) {
986
- const post = deps.httpPost ?? postSponsorTransferAuth;
987
- return async (smartWallet, chainId, amount) => {
988
- const cid = chainId;
989
- const token = deps.tokenAddressByChain[cid];
990
- if (!token) {
991
- throw new OwneyError(
992
- "CHAIN_UNSUPPORTED",
993
- `No sponsored token configured for chain ${chainId}`
994
- );
995
- }
996
- const pub = deps.getPublicClient(cid);
997
- const wallet = deps.getWalletClient(cid);
998
- const { tokenName, tokenVersion } = await readTokenMeta(pub, token);
999
- const validAfter = 0n;
1000
- const validBefore = BigInt(Math.floor(Date.now() / 1e3) + AUTH_WINDOW_SECONDS);
1001
- const nonce = randomAuthNonce();
1002
- const typedData = buildTransferWithAuthorizationTypedData({
1003
- token,
1004
- chainId: cid,
1005
- tokenName,
1006
- tokenVersion,
1007
- message: { from: deps.ownerAddress, to: smartWallet, value: BigInt(amount), validAfter, validBefore, nonce }
1008
- });
1009
- const authSignature = await wallet.signTypedData(
1010
- { account: deps.ownerAddress, ...typedData }
1011
- );
1012
- const result = await post({
1013
- baseUrl: deps.baseUrl,
1014
- apiKey: deps.apiKey,
1015
- body: {
1016
- chainId: cid,
1017
- token,
1018
- from: deps.ownerAddress,
1019
- to: smartWallet,
1020
- value: amount,
1021
- validAfter: validAfter.toString(),
1022
- validBefore: validBefore.toString(),
1023
- nonce,
1024
- authSignature,
1025
- tokenName,
1026
- tokenVersion
1027
- }
1028
- });
1029
- return result.txHash;
1030
- };
1031
- }
1032
-
1033
905
  // src/client.ts
1034
906
  function encodeMultiAgentCursor(map) {
1035
907
  return Buffer.from(JSON.stringify(map), "utf8").toString("base64");
@@ -1051,11 +923,6 @@ function decodeMultiAgentCursor(token) {
1051
923
  }
1052
924
  return parsed;
1053
925
  }
1054
- var SPONSORED_USDC_BY_CHAIN = {
1055
- 8453: "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
1056
- 42161: "0xaf88d065e77c8cc2239327c5edb3a432268e5831"
1057
- };
1058
- var VIEM_CHAIN = { 8453: base, 42161: arbitrum };
1059
926
  var OwneySDK = class {
1060
927
  agents = /* @__PURE__ */ new Map();
1061
928
  activeAgents = /* @__PURE__ */ new Set();
@@ -1068,7 +935,6 @@ var OwneySDK = class {
1068
935
  state = null;
1069
936
  apiKey;
1070
937
  zyfaiRpcUrls;
1071
- cachedSponsoredCallback = null;
1072
938
  initializingAgentsPromise = null;
1073
939
  constructor(config) {
1074
940
  this.apiKey = config.apiKey;
@@ -1092,7 +958,6 @@ var OwneySDK = class {
1092
958
  );
1093
959
  }
1094
960
  this.state = { provider, walletAddress, chainId: null };
1095
- this.cachedSponsoredCallback = null;
1096
961
  }
1097
962
  /**
1098
963
  * Disconnect from all agents and clear connection state.
@@ -1105,7 +970,6 @@ var OwneySDK = class {
1105
970
  this.activeAgents.clear();
1106
971
  this.disabledAgents.clear();
1107
972
  this.state = null;
1108
- this.cachedSponsoredCallback = null;
1109
973
  }
1110
974
  isAgentDisabled(agentId) {
1111
975
  return this.disabledAgents.has(agentId);
@@ -1139,46 +1003,6 @@ var OwneySDK = class {
1139
1003
  }
1140
1004
  return chainId;
1141
1005
  }
1142
- requireConnectedProvider() {
1143
- if (!this.state?.provider) {
1144
- throw new OwneyError(
1145
- "NOT_CONNECTED",
1146
- "connect(provider) must be called before deposit",
1147
- {}
1148
- );
1149
- }
1150
- return this.state.provider;
1151
- }
1152
- /**
1153
- * Lazily builds (and caches) the default EIP-3009 sponsored deposit callback
1154
- * used when the caller omits `depositCallback`. Wraps the connected EIP-1193
1155
- * provider with viem `custom(provider)` to read token meta and sign the
1156
- * `TransferWithAuthorization`, then POSTs to the sponsor API.
1157
- */
1158
- getDefaultSponsoredCallback() {
1159
- if (this.cachedSponsoredCallback)
1160
- return this.cachedSponsoredCallback;
1161
- const provider = this.requireConnectedProvider();
1162
- const owner = this.state.walletAddress;
1163
- this.cachedSponsoredCallback = makeSponsoredDepositCallback({
1164
- apiKey: this.apiKey,
1165
- ownerAddress: owner,
1166
- tokenAddressByChain: SPONSORED_USDC_BY_CHAIN,
1167
- // Casts work around viem's chain-narrowed Client vs the generic
1168
- // PublicClient/WalletClient param types — structurally identical at
1169
- // runtime, but the two share a name TS treats as unrelated.
1170
- getPublicClient: (cid) => createPublicClient({
1171
- chain: VIEM_CHAIN[cid],
1172
- transport: custom(provider)
1173
- }),
1174
- getWalletClient: (cid) => createWalletClient({
1175
- account: owner,
1176
- chain: VIEM_CHAIN[cid],
1177
- transport: custom(provider)
1178
- })
1179
- });
1180
- return this.cachedSponsoredCallback;
1181
- }
1182
1006
  getAgent(agentId) {
1183
1007
  const agent = this.agents.get(agentId);
1184
1008
  if (!agent) {
@@ -1332,7 +1156,6 @@ var OwneySDK = class {
1332
1156
  }
1333
1157
  const state = this.requireState();
1334
1158
  const chainId = this.requireChainId();
1335
- const effectiveCallback = depositCallback ?? this.getDefaultSponsoredCallback();
1336
1159
  if (agentId) {
1337
1160
  if (this.isAgentDisabled(agentId)) {
1338
1161
  throw new OwneyError(
@@ -1347,7 +1170,7 @@ var OwneySDK = class {
1347
1170
  return withFailureReporting(
1348
1171
  this.apiKey,
1349
1172
  agent.id,
1350
- () => agent.deposit(state, chainId, amount, effectiveCallback)
1173
+ () => agent.deposit(state, chainId, amount, depositCallback)
1351
1174
  );
1352
1175
  }
1353
1176
  const totalAmount = BigInt(amount);
@@ -1381,7 +1204,7 @@ var OwneySDK = class {
1381
1204
  agentResults[agent.id] = await withFailureReporting(
1382
1205
  this.apiKey,
1383
1206
  agent.id,
1384
- () => agent.deposit(state, chainId, agentAmount, effectiveCallback)
1207
+ () => agent.deposit(state, chainId, agentAmount, depositCallback)
1385
1208
  );
1386
1209
  }
1387
1210
  return { agentResults };
@@ -1997,11 +1820,178 @@ var OwneySDK = class {
1997
1820
  };
1998
1821
  }
1999
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
+ }
2000
1989
  export {
2001
1990
  AgentChainIncompatibleError,
2002
1991
  AgentNotFoundError,
2003
1992
  InvalidHistoryCursorError,
2004
1993
  NotConnectedError,
2005
1994
  OwneyError,
2006
- OwneySDK
1995
+ OwneySDK,
1996
+ createOwneySIWX
2007
1997
  };
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.6.0-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",