@zyfai/sdk 0.1.8 → 0.1.10

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/README.md CHANGED
@@ -85,6 +85,7 @@ await sdk.deploySafe(userAddress, 42161);
85
85
  ```
86
86
 
87
87
  **Note:**
88
+
88
89
  - When using a wallet provider, the SDK automatically detects the chain from the provider. You can optionally specify `chainId` to override.
89
90
  - The SDK automatically performs SIWE authentication when connecting, so you don't need to call any additional authentication methods.
90
91
 
@@ -99,6 +100,7 @@ console.log("Account disconnected and authentication cleared");
99
100
  ```
100
101
 
101
102
  This method:
103
+
102
104
  - Clears the wallet connection
103
105
  - Resets authentication state
104
106
  - Clears the JWT token
@@ -124,7 +126,7 @@ const result = await sdk.deploySafe(userAddress, 42161);
124
126
  if (result.success) {
125
127
  console.log("Safe Address:", result.safeAddress);
126
128
  console.log("Status:", result.status); // 'deployed' | 'failed'
127
-
129
+
128
130
  if (result.alreadyDeployed) {
129
131
  console.log("Safe was already deployed - no action needed");
130
132
  } else {
@@ -195,6 +197,7 @@ Connect account for signing transactions and authenticate via SIWE. Accepts eith
195
197
  **Returns:** Connected wallet address
196
198
 
197
199
  **Automatic Actions:**
200
+
198
201
  - Connects the wallet
199
202
  - Authenticates via SIWE (Sign-In with Ethereum)
200
203
  - Stores JWT token for authenticated endpoints
@@ -217,6 +220,7 @@ Disconnect account and clear all authentication state.
217
220
  **Returns:** Promise that resolves when disconnection is complete
218
221
 
219
222
  **Actions:**
223
+
220
224
  - Clears wallet connection
221
225
  - Resets authentication state
222
226
  - Clears JWT token
@@ -267,6 +271,25 @@ Deploy a Safe smart wallet for a user.
267
271
  }
268
272
  ```
269
273
 
274
+ ##### `addWalletToSdk(walletAddress: string): Promise<AddWalletToSdkResponse>`
275
+
276
+ Add a wallet address to the SDK API key's allowedWallets list. This endpoint requires SDK API key authentication (API key starting with "zyfai\_").
277
+
278
+ **Parameters:**
279
+
280
+ - `walletAddress`: Wallet address to add to the allowed list
281
+
282
+ **Returns:**
283
+
284
+ ```typescript
285
+ {
286
+ success: boolean;
287
+ message: string; // Status message
288
+ }
289
+ ```
290
+
291
+ **Note**: This method is only available when using an SDK API key (starts with "zyfai\_"). Regular API keys cannot use this endpoint.
292
+
270
293
  ### 3. Session Keys
271
294
 
272
295
  Session keys enable delegated transaction execution without exposing the main private key.
@@ -354,6 +377,7 @@ if (result.success) {
354
377
  ```
355
378
 
356
379
  **Important Notes:**
380
+
357
381
  - Amount must be in least decimal units. For USDC (6 decimals): 1 USDC = 1000000
358
382
  - The SDK authenticates via SIWE before calling the withdrawal endpoints
359
383
  - Withdrawals are processed asynchronously - the `txHash` may not be immediately available
@@ -519,7 +543,20 @@ console.log("Tier:", frequency.tier);
519
543
  console.log("Max rebalances/day:", frequency.frequency);
520
544
  ```
521
545
 
522
- ### 12. Portfolio (Premium)
546
+ ### 12. SDK API Key Management
547
+
548
+ #### Add Wallet to SDK API Key
549
+
550
+ Add a wallet address to the SDK API key's allowedWallets list. This endpoint requires SDK API key authentication (API key starting with "zyfai\_").
551
+
552
+ ```typescript
553
+ const result = await sdk.addWalletToSdk("0x1234...");
554
+ console.log(result.message); // "Wallet successfully added to allowed list"
555
+ ```
556
+
557
+ **Note**: This method is only available when using an SDK API key (starts with "zyfai\_"). Regular API keys cannot use this endpoint.
558
+
559
+ ### 13. Portfolio (Premium)
523
560
 
524
561
  #### Get Debank Portfolio (Multi-chain)
525
562
 
@@ -781,10 +818,12 @@ Check that the chain ID is in the supported chains list: Arbitrum (42161), Base
781
818
  ### SIWE Authentication Issues in Browser
782
819
 
783
820
  The SDK automatically performs SIWE authentication when you call `connectAccount()`. The SDK automatically detects browser vs Node.js environments:
821
+
784
822
  - **Browser**: Uses `window.location.origin` for the SIWE message domain/uri to match the browser's automatic `Origin` header
785
823
  - **Node.js**: Uses the API endpoint URL
786
824
 
787
825
  If you encounter SIWE authentication failures in a browser, ensure:
826
+
788
827
  1. Your frontend origin is allowed by the API's CORS configuration
789
828
  2. You're using the correct `environment` setting (`staging` or `production`)
790
829
  3. The user approves the SIWE signature request in their wallet
@@ -796,6 +835,7 @@ If `createSessionKey` returns `{ alreadyActive: true }`, the user already has an
796
835
  ### Withdrawal Transaction Hash Not Available
797
836
 
798
837
  If `withdrawFunds` returns without a `txHash`, the withdrawal is being processed asynchronously by the backend. You can:
838
+
799
839
  1. Check the `message` field for status information
800
840
  2. Use `getHistory()` to track when the withdrawal transaction is processed
801
841
  3. The transaction will appear in the history once it's been executed
package/dist/index.d.mts CHANGED
@@ -352,6 +352,10 @@ interface WithdrawResponse {
352
352
  receiver: string;
353
353
  status: "pending" | "confirmed" | "failed";
354
354
  }
355
+ interface AddWalletToSdkResponse {
356
+ success: boolean;
357
+ message: string;
358
+ }
355
359
  interface PolicyData {
356
360
  policy: Address;
357
361
  initData: Hex;
@@ -852,6 +856,21 @@ declare class ZyfaiSDK {
852
856
  * ```
853
857
  */
854
858
  getRebalanceFrequency(walletAddress: string): Promise<RebalanceFrequencyResponse>;
859
+ /**
860
+ * Add wallet to SDK API key allowedWallets list
861
+ * Adds a wallet address to the SDK API key's allowedWallets list.
862
+ * This endpoint requires SDK API key authentication (API key starting with "zyfai_").
863
+ *
864
+ * @param walletAddress - Wallet address to add to the allowed list
865
+ * @returns Response indicating success and status message
866
+ *
867
+ * @example
868
+ * ```typescript
869
+ * const result = await sdk.addWalletToSdk("0x1234...");
870
+ * console.log(result.message); // "Wallet successfully added to allowed list"
871
+ * ```
872
+ */
873
+ addWalletToSdk(walletAddress: string): Promise<AddWalletToSdkResponse>;
855
874
  }
856
875
 
857
- export { type ActionData, type ActiveWallet, type ActiveWalletsResponse, type Address, type ChainConfig, type ChainPortfolio, type DailyApyEntry, type DailyApyHistoryResponse, type DailyEarning, type DailyEarningsResponse, type DebankPortfolioResponse, type DeploySafeResponse, type DepositResponse, type ERC7739Context, type ERC7739Data, type Environment, type FirstTopupResponse, type Hex, type HistoryEntry, type HistoryPosition, type HistoryResponse, type OnchainEarnings, type OnchainEarningsResponse, type OpportunitiesResponse, type Opportunity, type PolicyData, type Pool, type PortfolioToken, type Position, type PositionSlot, type PositionsResponse, type Protocol, type ProtocolsResponse, type RebalanceFrequencyResponse, type RebalanceInfo, type RebalanceInfoResponse, type SDKConfig, type Session, type SessionKeyResponse, type SmartWalletByEOAResponse, type SmartWalletResponse, type SupportedChainId, type TVLResponse, type UserDetails, type UserDetailsResponse, type VolumeResponse, type WithdrawResponse, ZyfaiSDK, getChainConfig, getSupportedChainIds, isSupportedChain };
876
+ export { type ActionData, type ActiveWallet, type ActiveWalletsResponse, type AddWalletToSdkResponse, type Address, type ChainConfig, type ChainPortfolio, type DailyApyEntry, type DailyApyHistoryResponse, type DailyEarning, type DailyEarningsResponse, type DebankPortfolioResponse, type DeploySafeResponse, type DepositResponse, type ERC7739Context, type ERC7739Data, type Environment, type FirstTopupResponse, type Hex, type HistoryEntry, type HistoryPosition, type HistoryResponse, type OnchainEarnings, type OnchainEarningsResponse, type OpportunitiesResponse, type Opportunity, type PolicyData, type Pool, type PortfolioToken, type Position, type PositionSlot, type PositionsResponse, type Protocol, type ProtocolsResponse, type RebalanceFrequencyResponse, type RebalanceInfo, type RebalanceInfoResponse, type SDKConfig, type Session, type SessionKeyResponse, type SmartWalletByEOAResponse, type SmartWalletResponse, type SupportedChainId, type TVLResponse, type UserDetails, type UserDetailsResponse, type VolumeResponse, type WithdrawResponse, ZyfaiSDK, getChainConfig, getSupportedChainIds, isSupportedChain };
package/dist/index.d.ts CHANGED
@@ -352,6 +352,10 @@ interface WithdrawResponse {
352
352
  receiver: string;
353
353
  status: "pending" | "confirmed" | "failed";
354
354
  }
355
+ interface AddWalletToSdkResponse {
356
+ success: boolean;
357
+ message: string;
358
+ }
355
359
  interface PolicyData {
356
360
  policy: Address;
357
361
  initData: Hex;
@@ -852,6 +856,21 @@ declare class ZyfaiSDK {
852
856
  * ```
853
857
  */
854
858
  getRebalanceFrequency(walletAddress: string): Promise<RebalanceFrequencyResponse>;
859
+ /**
860
+ * Add wallet to SDK API key allowedWallets list
861
+ * Adds a wallet address to the SDK API key's allowedWallets list.
862
+ * This endpoint requires SDK API key authentication (API key starting with "zyfai_").
863
+ *
864
+ * @param walletAddress - Wallet address to add to the allowed list
865
+ * @returns Response indicating success and status message
866
+ *
867
+ * @example
868
+ * ```typescript
869
+ * const result = await sdk.addWalletToSdk("0x1234...");
870
+ * console.log(result.message); // "Wallet successfully added to allowed list"
871
+ * ```
872
+ */
873
+ addWalletToSdk(walletAddress: string): Promise<AddWalletToSdkResponse>;
855
874
  }
856
875
 
857
- export { type ActionData, type ActiveWallet, type ActiveWalletsResponse, type Address, type ChainConfig, type ChainPortfolio, type DailyApyEntry, type DailyApyHistoryResponse, type DailyEarning, type DailyEarningsResponse, type DebankPortfolioResponse, type DeploySafeResponse, type DepositResponse, type ERC7739Context, type ERC7739Data, type Environment, type FirstTopupResponse, type Hex, type HistoryEntry, type HistoryPosition, type HistoryResponse, type OnchainEarnings, type OnchainEarningsResponse, type OpportunitiesResponse, type Opportunity, type PolicyData, type Pool, type PortfolioToken, type Position, type PositionSlot, type PositionsResponse, type Protocol, type ProtocolsResponse, type RebalanceFrequencyResponse, type RebalanceInfo, type RebalanceInfoResponse, type SDKConfig, type Session, type SessionKeyResponse, type SmartWalletByEOAResponse, type SmartWalletResponse, type SupportedChainId, type TVLResponse, type UserDetails, type UserDetailsResponse, type VolumeResponse, type WithdrawResponse, ZyfaiSDK, getChainConfig, getSupportedChainIds, isSupportedChain };
876
+ export { type ActionData, type ActiveWallet, type ActiveWalletsResponse, type AddWalletToSdkResponse, type Address, type ChainConfig, type ChainPortfolio, type DailyApyEntry, type DailyApyHistoryResponse, type DailyEarning, type DailyEarningsResponse, type DebankPortfolioResponse, type DeploySafeResponse, type DepositResponse, type ERC7739Context, type ERC7739Data, type Environment, type FirstTopupResponse, type Hex, type HistoryEntry, type HistoryPosition, type HistoryResponse, type OnchainEarnings, type OnchainEarningsResponse, type OpportunitiesResponse, type Opportunity, type PolicyData, type Pool, type PortfolioToken, type Position, type PositionSlot, type PositionsResponse, type Protocol, type ProtocolsResponse, type RebalanceFrequencyResponse, type RebalanceInfo, type RebalanceInfoResponse, type SDKConfig, type Session, type SessionKeyResponse, type SmartWalletByEOAResponse, type SmartWalletResponse, type SupportedChainId, type TVLResponse, type UserDetails, type UserDetailsResponse, type VolumeResponse, type WithdrawResponse, ZyfaiSDK, getChainConfig, getSupportedChainIds, isSupportedChain };
package/dist/index.js CHANGED
@@ -57,9 +57,9 @@ var ENDPOINTS = {
57
57
  AUTH_CHALLENGE: "/auth/challenge",
58
58
  // User
59
59
  USER_ME: "/users/me",
60
- USER_INITIALIZE: "/users/initialize",
61
60
  USER_WITHDRAW: "/users/withdraw",
62
61
  PARTIAL_WITHDRAW: "/users/partial-withdraw",
62
+ USER_ADD_WALLET_TO_SDK: "/users/add-wallet-to-sdk",
63
63
  // Session Keys
64
64
  SESSION_KEYS_CONFIG: "/session-keys/config",
65
65
  SESSION_KEYS_ADD: "/session-keys/add",
@@ -76,6 +76,8 @@ var ENDPOINTS = {
76
76
  DATA_REBALANCE_FREQUENCY: (walletAddress) => `/data/rebalance-frequency?walletAddress=${walletAddress}`
77
77
  };
78
78
  var DATA_ENDPOINTS = {
79
+ // User Initialization
80
+ USER_INITIALIZE: "/earnings/initialize",
79
81
  // Earnings
80
82
  ONCHAIN_EARNINGS: (walletAddress) => `/usercheck/onchain-earnings?walletAddress=${walletAddress}`,
81
83
  CALCULATE_ONCHAIN_EARNINGS: "/usercheck/calculate-onchain-earnings",
@@ -429,13 +431,23 @@ var getSafeAccount = async (config) => {
429
431
  throw new Error("Wallet not connected. Please connect your wallet first.");
430
432
  }
431
433
  const signerAddress = owner.account.address;
432
- if (safeOwnerAddress && safeOwnerAddress.toLowerCase() !== signerAddress.toLowerCase()) {
434
+ if (!signerAddress) {
435
+ throw new Error("Owner account address is required");
436
+ }
437
+ const effectiveOwnerAddress = safeOwnerAddress || signerAddress;
438
+ if (!effectiveOwnerAddress) {
439
+ throw new Error("Address is required");
440
+ }
441
+ const formattedEffectiveAddress = (0, import_viem3.getAddress)(effectiveOwnerAddress);
442
+ const isReadOnly = safeOwnerAddress && safeOwnerAddress.toLowerCase() !== signerAddress.toLowerCase();
443
+ if (!isReadOnly && safeOwnerAddress && safeOwnerAddress.toLowerCase() !== signerAddress.toLowerCase()) {
433
444
  throw new Error(
434
445
  `Connected wallet address (${signerAddress}) must match the Safe owner address (${safeOwnerAddress}). Please connect with the correct wallet.`
435
446
  );
436
447
  }
437
448
  const ownableValidator = (0, import_module_sdk.getOwnableValidator)({
438
- owners: [signerAddress],
449
+ owners: [formattedEffectiveAddress],
450
+ // Use formatted effective owner address for validator
439
451
  threshold: 1
440
452
  });
441
453
  const saltHex = (0, import_viem3.fromHex)((0, import_viem3.toHex)(effectiveSalt), "bigint");
@@ -751,24 +763,21 @@ var ZyfaiSDK = class {
751
763
  async initializeUser(smartWallet, chainId) {
752
764
  try {
753
765
  await this.authenticateUser();
754
- const response = await this.httpClient.post(
755
- ENDPOINTS.USER_INITIALIZE,
766
+ const response = await this.httpClient.dataPost(
767
+ DATA_ENDPOINTS.USER_INITIALIZE,
756
768
  {
757
- smartWallet,
758
- chainId
769
+ walletAddress: smartWallet
759
770
  }
760
771
  );
761
772
  return {
762
- success: true,
773
+ success: response.status === "success" || true,
763
774
  userId: response.userId || response.id,
764
- smartWallet: response.smartWallet,
765
- chainId: response.chainId,
766
- message: response.message
775
+ smartWallet: response.smartWallet || smartWallet,
776
+ chainId: response.chainId || chainId,
777
+ message: response.message || response.status || "User initialized successfully"
767
778
  };
768
779
  } catch (error) {
769
- throw new Error(
770
- `Failed to initialize user: ${error.message}`
771
- );
780
+ throw new Error(`Failed to initialize user: ${error.message}`);
772
781
  }
773
782
  }
774
783
  /**
@@ -950,8 +959,22 @@ var ZyfaiSDK = class {
950
959
  if (!isSupportedChain(chainId)) {
951
960
  throw new Error(`Unsupported chain ID: ${chainId}`);
952
961
  }
953
- const walletClient = this.getWalletClient();
954
962
  const chainConfig = getChainConfig(chainId);
963
+ try {
964
+ const smartWalletInfo = await this.getSmartWalletByEOA(userAddress);
965
+ if (smartWalletInfo.smartWallet) {
966
+ const isDeployed2 = await isSafeDeployed(
967
+ smartWalletInfo.smartWallet,
968
+ chainConfig.publicClient
969
+ );
970
+ return {
971
+ address: smartWalletInfo.smartWallet,
972
+ isDeployed: isDeployed2
973
+ };
974
+ }
975
+ } catch {
976
+ }
977
+ const walletClient = this.getWalletClient(chainId);
955
978
  const safeAddress = await getDeterministicSafeAddress({
956
979
  owner: walletClient,
957
980
  safeOwnerAddress: userAddress,
@@ -1351,15 +1374,32 @@ var ZyfaiSDK = class {
1351
1374
  if (!isSupportedChain(chainId)) {
1352
1375
  throw new Error(`Unsupported chain ID: ${chainId}`);
1353
1376
  }
1354
- const walletClient = this.getWalletClient();
1355
1377
  const chainConfig = getChainConfig(chainId);
1356
- const safeAddress = await getDeterministicSafeAddress({
1357
- owner: walletClient,
1358
- safeOwnerAddress: userAddress,
1359
- chain: chainConfig.chain,
1360
- publicClient: chainConfig.publicClient,
1361
- environment: this.environment
1362
- });
1378
+ let safeAddress;
1379
+ try {
1380
+ const smartWalletInfo = await this.getSmartWalletByEOA(userAddress);
1381
+ if (smartWalletInfo.smartWallet) {
1382
+ safeAddress = smartWalletInfo.smartWallet;
1383
+ } else {
1384
+ const walletClient = this.getWalletClient();
1385
+ safeAddress = await getDeterministicSafeAddress({
1386
+ owner: walletClient,
1387
+ safeOwnerAddress: userAddress,
1388
+ chain: chainConfig.chain,
1389
+ publicClient: chainConfig.publicClient,
1390
+ environment: this.environment
1391
+ });
1392
+ }
1393
+ } catch {
1394
+ const walletClient = this.getWalletClient();
1395
+ safeAddress = await getDeterministicSafeAddress({
1396
+ owner: walletClient,
1397
+ safeOwnerAddress: userAddress,
1398
+ chain: chainConfig.chain,
1399
+ publicClient: chainConfig.publicClient,
1400
+ environment: this.environment
1401
+ });
1402
+ }
1363
1403
  const isDeployed = await isSafeDeployed(
1364
1404
  safeAddress,
1365
1405
  chainConfig.publicClient
@@ -1455,17 +1495,16 @@ var ZyfaiSDK = class {
1455
1495
  if (chainId && !isSupportedChain(chainId)) {
1456
1496
  throw new Error(`Unsupported chain ID: ${chainId}`);
1457
1497
  }
1458
- const walletClient = this.getWalletClient(chainId);
1459
- const chainConfig = getChainConfig(chainId ?? 8453);
1460
- const safeAddress = await getDeterministicSafeAddress({
1461
- owner: walletClient,
1462
- safeOwnerAddress: userAddress,
1463
- chain: chainConfig.chain,
1464
- publicClient: chainConfig.publicClient,
1465
- environment: this.environment
1466
- });
1498
+ const smartWalletInfo = await this.getSmartWalletByEOA(userAddress);
1499
+ if (!smartWalletInfo.smartWallet) {
1500
+ return {
1501
+ success: true,
1502
+ userAddress,
1503
+ positions: []
1504
+ };
1505
+ }
1467
1506
  const response = await this.httpClient.get(
1468
- ENDPOINTS.DATA_POSITION(safeAddress)
1507
+ ENDPOINTS.DATA_POSITION(smartWalletInfo.smartWallet)
1469
1508
  );
1470
1509
  return {
1471
1510
  success: true,
@@ -2093,6 +2132,49 @@ var ZyfaiSDK = class {
2093
2132
  );
2094
2133
  }
2095
2134
  }
2135
+ // ============================================================================
2136
+ // SDK API Key Management
2137
+ // ============================================================================
2138
+ /**
2139
+ * Add wallet to SDK API key allowedWallets list
2140
+ * Adds a wallet address to the SDK API key's allowedWallets list.
2141
+ * This endpoint requires SDK API key authentication (API key starting with "zyfai_").
2142
+ *
2143
+ * @param walletAddress - Wallet address to add to the allowed list
2144
+ * @returns Response indicating success and status message
2145
+ *
2146
+ * @example
2147
+ * ```typescript
2148
+ * const result = await sdk.addWalletToSdk("0x1234...");
2149
+ * console.log(result.message); // "Wallet successfully added to allowed list"
2150
+ * ```
2151
+ */
2152
+ async addWalletToSdk(walletAddress) {
2153
+ try {
2154
+ if (!walletAddress) {
2155
+ throw new Error("Wallet address is required");
2156
+ }
2157
+ try {
2158
+ (0, import_viem4.getAddress)(walletAddress);
2159
+ } catch {
2160
+ throw new Error("Invalid wallet address format");
2161
+ }
2162
+ const response = await this.httpClient.post(
2163
+ ENDPOINTS.USER_ADD_WALLET_TO_SDK,
2164
+ {
2165
+ walletAddress
2166
+ }
2167
+ );
2168
+ return {
2169
+ success: response.success ?? true,
2170
+ message: response.message || "Wallet added successfully"
2171
+ };
2172
+ } catch (error) {
2173
+ throw new Error(
2174
+ `Failed to add wallet to SDK: ${error.message}`
2175
+ );
2176
+ }
2177
+ }
2096
2178
  };
2097
2179
  // Annotate the CommonJS export names for ESM import in node:
2098
2180
  0 && (module.exports = {
package/dist/index.mjs CHANGED
@@ -18,9 +18,9 @@ var ENDPOINTS = {
18
18
  AUTH_CHALLENGE: "/auth/challenge",
19
19
  // User
20
20
  USER_ME: "/users/me",
21
- USER_INITIALIZE: "/users/initialize",
22
21
  USER_WITHDRAW: "/users/withdraw",
23
22
  PARTIAL_WITHDRAW: "/users/partial-withdraw",
23
+ USER_ADD_WALLET_TO_SDK: "/users/add-wallet-to-sdk",
24
24
  // Session Keys
25
25
  SESSION_KEYS_CONFIG: "/session-keys/config",
26
26
  SESSION_KEYS_ADD: "/session-keys/add",
@@ -37,6 +37,8 @@ var ENDPOINTS = {
37
37
  DATA_REBALANCE_FREQUENCY: (walletAddress) => `/data/rebalance-frequency?walletAddress=${walletAddress}`
38
38
  };
39
39
  var DATA_ENDPOINTS = {
40
+ // User Initialization
41
+ USER_INITIALIZE: "/earnings/initialize",
40
42
  // Earnings
41
43
  ONCHAIN_EARNINGS: (walletAddress) => `/usercheck/onchain-earnings?walletAddress=${walletAddress}`,
42
44
  CALCULATE_ONCHAIN_EARNINGS: "/usercheck/calculate-onchain-earnings",
@@ -296,7 +298,7 @@ import {
296
298
  createWalletClient,
297
299
  custom,
298
300
  http as http3,
299
- getAddress
301
+ getAddress as getAddress2
300
302
  } from "viem";
301
303
 
302
304
  // src/config/chains.ts
@@ -384,6 +386,7 @@ import { createPimlicoClient } from "permissionless/clients/pimlico";
384
386
  import { toSafeSmartAccount } from "permissionless/accounts";
385
387
  import {
386
388
  http as http2,
389
+ getAddress,
387
390
  fromHex,
388
391
  toHex
389
392
  } from "viem";
@@ -408,13 +411,23 @@ var getSafeAccount = async (config) => {
408
411
  throw new Error("Wallet not connected. Please connect your wallet first.");
409
412
  }
410
413
  const signerAddress = owner.account.address;
411
- if (safeOwnerAddress && safeOwnerAddress.toLowerCase() !== signerAddress.toLowerCase()) {
414
+ if (!signerAddress) {
415
+ throw new Error("Owner account address is required");
416
+ }
417
+ const effectiveOwnerAddress = safeOwnerAddress || signerAddress;
418
+ if (!effectiveOwnerAddress) {
419
+ throw new Error("Address is required");
420
+ }
421
+ const formattedEffectiveAddress = getAddress(effectiveOwnerAddress);
422
+ const isReadOnly = safeOwnerAddress && safeOwnerAddress.toLowerCase() !== signerAddress.toLowerCase();
423
+ if (!isReadOnly && safeOwnerAddress && safeOwnerAddress.toLowerCase() !== signerAddress.toLowerCase()) {
412
424
  throw new Error(
413
425
  `Connected wallet address (${signerAddress}) must match the Safe owner address (${safeOwnerAddress}). Please connect with the correct wallet.`
414
426
  );
415
427
  }
416
428
  const ownableValidator = getOwnableValidator({
417
- owners: [signerAddress],
429
+ owners: [formattedEffectiveAddress],
430
+ // Use formatted effective owner address for validator
418
431
  threshold: 1
419
432
  });
420
433
  const saltHex = fromHex(toHex(effectiveSalt), "bigint");
@@ -631,7 +644,7 @@ var ZyfaiSDK = class {
631
644
  return;
632
645
  }
633
646
  const walletClient = this.getWalletClient();
634
- const userAddress = getAddress(walletClient.account.address);
647
+ const userAddress = getAddress2(walletClient.account.address);
635
648
  const chainId = walletClient.chain?.id || 8453;
636
649
  const challengeResponse = await this.httpClient.post(ENDPOINTS.AUTH_CHALLENGE, {});
637
650
  let uri;
@@ -730,24 +743,21 @@ var ZyfaiSDK = class {
730
743
  async initializeUser(smartWallet, chainId) {
731
744
  try {
732
745
  await this.authenticateUser();
733
- const response = await this.httpClient.post(
734
- ENDPOINTS.USER_INITIALIZE,
746
+ const response = await this.httpClient.dataPost(
747
+ DATA_ENDPOINTS.USER_INITIALIZE,
735
748
  {
736
- smartWallet,
737
- chainId
749
+ walletAddress: smartWallet
738
750
  }
739
751
  );
740
752
  return {
741
- success: true,
753
+ success: response.status === "success" || true,
742
754
  userId: response.userId || response.id,
743
- smartWallet: response.smartWallet,
744
- chainId: response.chainId,
745
- message: response.message
755
+ smartWallet: response.smartWallet || smartWallet,
756
+ chainId: response.chainId || chainId,
757
+ message: response.message || response.status || "User initialized successfully"
746
758
  };
747
759
  } catch (error) {
748
- throw new Error(
749
- `Failed to initialize user: ${error.message}`
750
- );
760
+ throw new Error(`Failed to initialize user: ${error.message}`);
751
761
  }
752
762
  }
753
763
  /**
@@ -929,8 +939,22 @@ var ZyfaiSDK = class {
929
939
  if (!isSupportedChain(chainId)) {
930
940
  throw new Error(`Unsupported chain ID: ${chainId}`);
931
941
  }
932
- const walletClient = this.getWalletClient();
933
942
  const chainConfig = getChainConfig(chainId);
943
+ try {
944
+ const smartWalletInfo = await this.getSmartWalletByEOA(userAddress);
945
+ if (smartWalletInfo.smartWallet) {
946
+ const isDeployed2 = await isSafeDeployed(
947
+ smartWalletInfo.smartWallet,
948
+ chainConfig.publicClient
949
+ );
950
+ return {
951
+ address: smartWalletInfo.smartWallet,
952
+ isDeployed: isDeployed2
953
+ };
954
+ }
955
+ } catch {
956
+ }
957
+ const walletClient = this.getWalletClient(chainId);
934
958
  const safeAddress = await getDeterministicSafeAddress({
935
959
  owner: walletClient,
936
960
  safeOwnerAddress: userAddress,
@@ -1330,15 +1354,32 @@ var ZyfaiSDK = class {
1330
1354
  if (!isSupportedChain(chainId)) {
1331
1355
  throw new Error(`Unsupported chain ID: ${chainId}`);
1332
1356
  }
1333
- const walletClient = this.getWalletClient();
1334
1357
  const chainConfig = getChainConfig(chainId);
1335
- const safeAddress = await getDeterministicSafeAddress({
1336
- owner: walletClient,
1337
- safeOwnerAddress: userAddress,
1338
- chain: chainConfig.chain,
1339
- publicClient: chainConfig.publicClient,
1340
- environment: this.environment
1341
- });
1358
+ let safeAddress;
1359
+ try {
1360
+ const smartWalletInfo = await this.getSmartWalletByEOA(userAddress);
1361
+ if (smartWalletInfo.smartWallet) {
1362
+ safeAddress = smartWalletInfo.smartWallet;
1363
+ } else {
1364
+ const walletClient = this.getWalletClient();
1365
+ safeAddress = await getDeterministicSafeAddress({
1366
+ owner: walletClient,
1367
+ safeOwnerAddress: userAddress,
1368
+ chain: chainConfig.chain,
1369
+ publicClient: chainConfig.publicClient,
1370
+ environment: this.environment
1371
+ });
1372
+ }
1373
+ } catch {
1374
+ const walletClient = this.getWalletClient();
1375
+ safeAddress = await getDeterministicSafeAddress({
1376
+ owner: walletClient,
1377
+ safeOwnerAddress: userAddress,
1378
+ chain: chainConfig.chain,
1379
+ publicClient: chainConfig.publicClient,
1380
+ environment: this.environment
1381
+ });
1382
+ }
1342
1383
  const isDeployed = await isSafeDeployed(
1343
1384
  safeAddress,
1344
1385
  chainConfig.publicClient
@@ -1434,17 +1475,16 @@ var ZyfaiSDK = class {
1434
1475
  if (chainId && !isSupportedChain(chainId)) {
1435
1476
  throw new Error(`Unsupported chain ID: ${chainId}`);
1436
1477
  }
1437
- const walletClient = this.getWalletClient(chainId);
1438
- const chainConfig = getChainConfig(chainId ?? 8453);
1439
- const safeAddress = await getDeterministicSafeAddress({
1440
- owner: walletClient,
1441
- safeOwnerAddress: userAddress,
1442
- chain: chainConfig.chain,
1443
- publicClient: chainConfig.publicClient,
1444
- environment: this.environment
1445
- });
1478
+ const smartWalletInfo = await this.getSmartWalletByEOA(userAddress);
1479
+ if (!smartWalletInfo.smartWallet) {
1480
+ return {
1481
+ success: true,
1482
+ userAddress,
1483
+ positions: []
1484
+ };
1485
+ }
1446
1486
  const response = await this.httpClient.get(
1447
- ENDPOINTS.DATA_POSITION(safeAddress)
1487
+ ENDPOINTS.DATA_POSITION(smartWalletInfo.smartWallet)
1448
1488
  );
1449
1489
  return {
1450
1490
  success: true,
@@ -2072,6 +2112,49 @@ var ZyfaiSDK = class {
2072
2112
  );
2073
2113
  }
2074
2114
  }
2115
+ // ============================================================================
2116
+ // SDK API Key Management
2117
+ // ============================================================================
2118
+ /**
2119
+ * Add wallet to SDK API key allowedWallets list
2120
+ * Adds a wallet address to the SDK API key's allowedWallets list.
2121
+ * This endpoint requires SDK API key authentication (API key starting with "zyfai_").
2122
+ *
2123
+ * @param walletAddress - Wallet address to add to the allowed list
2124
+ * @returns Response indicating success and status message
2125
+ *
2126
+ * @example
2127
+ * ```typescript
2128
+ * const result = await sdk.addWalletToSdk("0x1234...");
2129
+ * console.log(result.message); // "Wallet successfully added to allowed list"
2130
+ * ```
2131
+ */
2132
+ async addWalletToSdk(walletAddress) {
2133
+ try {
2134
+ if (!walletAddress) {
2135
+ throw new Error("Wallet address is required");
2136
+ }
2137
+ try {
2138
+ getAddress2(walletAddress);
2139
+ } catch {
2140
+ throw new Error("Invalid wallet address format");
2141
+ }
2142
+ const response = await this.httpClient.post(
2143
+ ENDPOINTS.USER_ADD_WALLET_TO_SDK,
2144
+ {
2145
+ walletAddress
2146
+ }
2147
+ );
2148
+ return {
2149
+ success: response.success ?? true,
2150
+ message: response.message || "Wallet added successfully"
2151
+ };
2152
+ } catch (error) {
2153
+ throw new Error(
2154
+ `Failed to add wallet to SDK: ${error.message}`
2155
+ );
2156
+ }
2157
+ }
2075
2158
  };
2076
2159
  export {
2077
2160
  ZyfaiSDK,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zyfai/sdk",
3
- "version": "0.1.8",
3
+ "version": "0.1.10",
4
4
  "description": "TypeScript SDK for ZyFAI Yield Optimization Engine - Deploy Safe smart wallets, manage session keys, and interact with DeFi protocols",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",