@zyfai/sdk 0.2.40 → 0.2.42

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
@@ -301,6 +301,12 @@ Deploy a Safe smart wallet for a user. **Deployment is handled by the backend AP
301
301
 
302
302
  - User must be authenticated (automatically done via `connectAccount()`)
303
303
  - Backend handles all RPC calls, avoiding rate limiting
304
+ - After deployment, the SDK automatically patches the user's protocol selection for the target `chainId` and `strategy` on **both USDC and WETH**:
305
+ - Fetches protocols compatible with the strategy (`aggressive` includes both `safe` and `degen` protocols)
306
+ - Drops any protocol that has no pool available for the asset/chain (via `/customization/pools`)
307
+ - **Merges** the new `chainId` with the user's existing chains (never overwrites — safe to call again on a new chain)
308
+ - Persists via `updateUserProfile` into `assetTypeSettings.[usdc|eth]`
309
+ - No need to call `updateUserProfile` manually after `deploySafe` — the SDK handles it
304
310
 
305
311
  ##### `addWalletToSdk(walletAddress: string): Promise<AddWalletToSdkResponse>`
306
312
 
@@ -356,6 +362,7 @@ console.log("User ID:", result.userId);
356
362
  - User must be authenticated (automatically done via `connectAccount()`)
357
363
  - The SDK proactively checks if the user already has an active session key and returns early without requiring any signature if one exists
358
364
  - The user record must have `smartWallet` and `chainId` set (automatically handled after calling `deploySafe`)
365
+ - Protocol selection is **not** touched by `createSessionKey` — it's set by `deploySafe`
359
366
  - When `alreadyActive` is `true`, `sessionKeyAddress` and `signature` are not available in the response
360
367
 
361
368
  ### 4. Deposit Funds
package/dist/index.d.mts CHANGED
@@ -436,6 +436,7 @@ interface SimulateBestPositionsParams {
436
436
  protocols?: string[];
437
437
  pools?: string[];
438
438
  userPositions?: UserPosition[];
439
+ partOfZyfiTvl?: boolean;
439
440
  }
440
441
  interface SimulateCalldataItem {
441
442
  contract_address: Address;
@@ -444,9 +445,17 @@ interface SimulateCalldataItem {
444
445
  value: string;
445
446
  description: string;
446
447
  }
448
+ interface AllocationDetail {
449
+ pool_capacity_usd: number;
450
+ zyfi_position_usd: number;
451
+ available_capacity_usd: number;
452
+ fair_share_usd: number;
453
+ overflow_usd: number;
454
+ }
447
455
  interface SimulatedPosition {
448
456
  protocol: string;
449
457
  pool: string;
458
+ rank: number;
450
459
  simulated_apy: number;
451
460
  combined_apy: number;
452
461
  amount: number;
@@ -455,11 +464,20 @@ interface SimulatedPosition {
455
464
  tvl: number;
456
465
  liquidity: number;
457
466
  averageCombinedApy30Days: number;
467
+ allocation_detail: AllocationDetail;
458
468
  calldata: SimulateCalldataItem[];
459
469
  }
470
+ interface ExcludedPool {
471
+ protocol: string;
472
+ pool: string;
473
+ reason: string;
474
+ detail: string;
475
+ failed_checks?: string[];
476
+ }
460
477
  interface SimulateBestPositionsResponse {
461
478
  success: boolean;
462
479
  data: Record<string, SimulatedPosition[]>;
480
+ excluded: Record<string, ExcludedPool[]>;
463
481
  messages: Record<string, string>;
464
482
  }
465
483
  interface OpportunityPosition {
@@ -909,13 +927,33 @@ declare class ZyfaiSDK {
909
927
  */
910
928
  private signSessionKey;
911
929
  /**
912
- * Update user protocols with available protocols from the chain
913
- * This method is automatically called before activating session key
930
+ * Patch the user's protocol selection for the given chain + strategy on
931
+ * both USDC and WETH. Mirrors the front-end customization flow:
932
+ * 1. Merge existing chains from `getUserDetails` with the new `chainId`
933
+ * (never overwrite already-configured chains).
934
+ * 2. Filter protocols by strategy, chain and asset support.
935
+ * 3. Drop protocols that don't have any pools available for the
936
+ * asset/chain/strategy combo.
937
+ * 4. Persist via `updateUserProfile` (writes `assetTypeSettings`).
938
+ *
939
+ * Called from `deploySafe` — SDK consumers don't handle protocols manually.
914
940
  *
915
- * @param chainId - Target chain ID
916
941
  * @internal
917
942
  */
918
943
  private updateUserProtocols;
944
+ /**
945
+ * Compute and persist the protocol selection for a single asset.
946
+ * @internal
947
+ */
948
+ private updateUserProtocolsForAsset;
949
+ /**
950
+ * Drop protocols that have no pools on any of the selected chains for the
951
+ * requested asset. Uses the /customization/pools endpoint with
952
+ * `degen_strategy` as the master strategy so the response includes both
953
+ * safe and degen pools — mirrors the front-end behavior.
954
+ * @internal
955
+ */
956
+ private filterProtocolIdsWithPools;
919
957
  /**
920
958
  * Activate session key via Zyfai API
921
959
  */
@@ -1675,4 +1713,4 @@ type BankrProvider = ReturnType<typeof createBankrProvider>;
1675
1713
 
1676
1714
  declare const VAULT_ADDRESS: "0xD580071c47d4a667858B5FafAb85BC9C609beC5D";
1677
1715
 
1678
- export { type APYPerStrategy, type APYPerStrategyResponse, type ActionData, type ActiveWallet, type ActiveWalletsResponse, type AddWalletToSdkResponse, type Address, type ApyPosition, type BankrProvider, type BankrProviderConfig, type BestOpportunityDetails, type BestOpportunityResponse, type ChainConfig, type ChainPortfolio, type ChainTokenEarnings, type CustomizationConfig, type CustomizeBatchRequest, type CustomizeBatchResponse, DEFAULT_TOKEN_ADDRESSES, type DailyApyEntry, type DailyApyHistoryResponse, type DailyEarning, type DailyEarningsResponse, type DebankPortfolioResponse, type DepegEvent, type DeploySafeResponse, type DepositResponse, type ERC7739Context, type ERC7739Data, type FirstTopupResponse, type GetPoolsResponse, type GetSelectedPoolsResponse, type Hex, type HistoryEntry, type HistoryPosition, type HistoryResponse, type LiquidityDropEvent, type LogDepositResponse, type NewCollateralDetectedEvent, type OnchainEarnings, type OnchainEarningsResponse, type OpportunitiesResponse, type Opportunity, type OpportunityPosition, type PolicyData, type Pool, type Portfolio, type PortfolioAssetBalance, type PortfolioByAssetType, type PortfolioByChain, type PortfolioDetailed, type PortfolioDetailedResponse, type PortfolioResponse, type PortfolioToken, type PositionSlot, type Protocol, type ProtocolsResponse, type RebalanceFrequencyResponse, type RegisterAgentResponse, type SDKConfig, type SdkKeyTVLResponse, type Session, type SessionKeyResponse, type SimulateBestPositionsParams, type SimulateBestPositionsResponse, type SimulateCalldataItem, type SimulatedPosition, type SmartWalletByEOAResponse, type SmartWalletResponse, type Strategy, type SupportedChainId, type TVLResponse, type TokenApy, type TokenEarnings, type UpdateUserProfileRequest, type UpdateUserProfileResponse, type UserPosition, VAULT_ADDRESS, type VaultAsset, type VaultClaimResponse, type VaultDepositResponse, type VaultSharesResponse, type VaultWithdrawResponse, type VaultWithdrawStatusResponse, type VolumeResponse, type WalletTVL, type WithdrawResponse, type ZyfaiEventFilters, type ZyfaiEventHandlers, ZyfaiSDK, createBankrProvider, getChainConfig, getDefaultTokenAddress, getSupportedChainIds, isSupportedChain };
1716
+ export { type APYPerStrategy, type APYPerStrategyResponse, type ActionData, type ActiveWallet, type ActiveWalletsResponse, type AddWalletToSdkResponse, type Address, type AllocationDetail, type ApyPosition, type BankrProvider, type BankrProviderConfig, type BestOpportunityDetails, type BestOpportunityResponse, type ChainConfig, type ChainPortfolio, type ChainTokenEarnings, type CustomizationConfig, type CustomizeBatchRequest, type CustomizeBatchResponse, DEFAULT_TOKEN_ADDRESSES, type DailyApyEntry, type DailyApyHistoryResponse, type DailyEarning, type DailyEarningsResponse, type DebankPortfolioResponse, type DepegEvent, type DeploySafeResponse, type DepositResponse, type ERC7739Context, type ERC7739Data, type ExcludedPool, type FirstTopupResponse, type GetPoolsResponse, type GetSelectedPoolsResponse, type Hex, type HistoryEntry, type HistoryPosition, type HistoryResponse, type LiquidityDropEvent, type LogDepositResponse, type NewCollateralDetectedEvent, type OnchainEarnings, type OnchainEarningsResponse, type OpportunitiesResponse, type Opportunity, type OpportunityPosition, type PolicyData, type Pool, type Portfolio, type PortfolioAssetBalance, type PortfolioByAssetType, type PortfolioByChain, type PortfolioDetailed, type PortfolioDetailedResponse, type PortfolioResponse, type PortfolioToken, type PositionSlot, type Protocol, type ProtocolsResponse, type RebalanceFrequencyResponse, type RegisterAgentResponse, type SDKConfig, type SdkKeyTVLResponse, type Session, type SessionKeyResponse, type SimulateBestPositionsParams, type SimulateBestPositionsResponse, type SimulateCalldataItem, type SimulatedPosition, type SmartWalletByEOAResponse, type SmartWalletResponse, type Strategy, type SupportedChainId, type TVLResponse, type TokenApy, type TokenEarnings, type UpdateUserProfileRequest, type UpdateUserProfileResponse, type UserPosition, VAULT_ADDRESS, type VaultAsset, type VaultClaimResponse, type VaultDepositResponse, type VaultSharesResponse, type VaultWithdrawResponse, type VaultWithdrawStatusResponse, type VolumeResponse, type WalletTVL, type WithdrawResponse, type ZyfaiEventFilters, type ZyfaiEventHandlers, ZyfaiSDK, createBankrProvider, getChainConfig, getDefaultTokenAddress, getSupportedChainIds, isSupportedChain };
package/dist/index.d.ts CHANGED
@@ -436,6 +436,7 @@ interface SimulateBestPositionsParams {
436
436
  protocols?: string[];
437
437
  pools?: string[];
438
438
  userPositions?: UserPosition[];
439
+ partOfZyfiTvl?: boolean;
439
440
  }
440
441
  interface SimulateCalldataItem {
441
442
  contract_address: Address;
@@ -444,9 +445,17 @@ interface SimulateCalldataItem {
444
445
  value: string;
445
446
  description: string;
446
447
  }
448
+ interface AllocationDetail {
449
+ pool_capacity_usd: number;
450
+ zyfi_position_usd: number;
451
+ available_capacity_usd: number;
452
+ fair_share_usd: number;
453
+ overflow_usd: number;
454
+ }
447
455
  interface SimulatedPosition {
448
456
  protocol: string;
449
457
  pool: string;
458
+ rank: number;
450
459
  simulated_apy: number;
451
460
  combined_apy: number;
452
461
  amount: number;
@@ -455,11 +464,20 @@ interface SimulatedPosition {
455
464
  tvl: number;
456
465
  liquidity: number;
457
466
  averageCombinedApy30Days: number;
467
+ allocation_detail: AllocationDetail;
458
468
  calldata: SimulateCalldataItem[];
459
469
  }
470
+ interface ExcludedPool {
471
+ protocol: string;
472
+ pool: string;
473
+ reason: string;
474
+ detail: string;
475
+ failed_checks?: string[];
476
+ }
460
477
  interface SimulateBestPositionsResponse {
461
478
  success: boolean;
462
479
  data: Record<string, SimulatedPosition[]>;
480
+ excluded: Record<string, ExcludedPool[]>;
463
481
  messages: Record<string, string>;
464
482
  }
465
483
  interface OpportunityPosition {
@@ -909,13 +927,33 @@ declare class ZyfaiSDK {
909
927
  */
910
928
  private signSessionKey;
911
929
  /**
912
- * Update user protocols with available protocols from the chain
913
- * This method is automatically called before activating session key
930
+ * Patch the user's protocol selection for the given chain + strategy on
931
+ * both USDC and WETH. Mirrors the front-end customization flow:
932
+ * 1. Merge existing chains from `getUserDetails` with the new `chainId`
933
+ * (never overwrite already-configured chains).
934
+ * 2. Filter protocols by strategy, chain and asset support.
935
+ * 3. Drop protocols that don't have any pools available for the
936
+ * asset/chain/strategy combo.
937
+ * 4. Persist via `updateUserProfile` (writes `assetTypeSettings`).
938
+ *
939
+ * Called from `deploySafe` — SDK consumers don't handle protocols manually.
914
940
  *
915
- * @param chainId - Target chain ID
916
941
  * @internal
917
942
  */
918
943
  private updateUserProtocols;
944
+ /**
945
+ * Compute and persist the protocol selection for a single asset.
946
+ * @internal
947
+ */
948
+ private updateUserProtocolsForAsset;
949
+ /**
950
+ * Drop protocols that have no pools on any of the selected chains for the
951
+ * requested asset. Uses the /customization/pools endpoint with
952
+ * `degen_strategy` as the master strategy so the response includes both
953
+ * safe and degen pools — mirrors the front-end behavior.
954
+ * @internal
955
+ */
956
+ private filterProtocolIdsWithPools;
919
957
  /**
920
958
  * Activate session key via Zyfai API
921
959
  */
@@ -1675,4 +1713,4 @@ type BankrProvider = ReturnType<typeof createBankrProvider>;
1675
1713
 
1676
1714
  declare const VAULT_ADDRESS: "0xD580071c47d4a667858B5FafAb85BC9C609beC5D";
1677
1715
 
1678
- export { type APYPerStrategy, type APYPerStrategyResponse, type ActionData, type ActiveWallet, type ActiveWalletsResponse, type AddWalletToSdkResponse, type Address, type ApyPosition, type BankrProvider, type BankrProviderConfig, type BestOpportunityDetails, type BestOpportunityResponse, type ChainConfig, type ChainPortfolio, type ChainTokenEarnings, type CustomizationConfig, type CustomizeBatchRequest, type CustomizeBatchResponse, DEFAULT_TOKEN_ADDRESSES, type DailyApyEntry, type DailyApyHistoryResponse, type DailyEarning, type DailyEarningsResponse, type DebankPortfolioResponse, type DepegEvent, type DeploySafeResponse, type DepositResponse, type ERC7739Context, type ERC7739Data, type FirstTopupResponse, type GetPoolsResponse, type GetSelectedPoolsResponse, type Hex, type HistoryEntry, type HistoryPosition, type HistoryResponse, type LiquidityDropEvent, type LogDepositResponse, type NewCollateralDetectedEvent, type OnchainEarnings, type OnchainEarningsResponse, type OpportunitiesResponse, type Opportunity, type OpportunityPosition, type PolicyData, type Pool, type Portfolio, type PortfolioAssetBalance, type PortfolioByAssetType, type PortfolioByChain, type PortfolioDetailed, type PortfolioDetailedResponse, type PortfolioResponse, type PortfolioToken, type PositionSlot, type Protocol, type ProtocolsResponse, type RebalanceFrequencyResponse, type RegisterAgentResponse, type SDKConfig, type SdkKeyTVLResponse, type Session, type SessionKeyResponse, type SimulateBestPositionsParams, type SimulateBestPositionsResponse, type SimulateCalldataItem, type SimulatedPosition, type SmartWalletByEOAResponse, type SmartWalletResponse, type Strategy, type SupportedChainId, type TVLResponse, type TokenApy, type TokenEarnings, type UpdateUserProfileRequest, type UpdateUserProfileResponse, type UserPosition, VAULT_ADDRESS, type VaultAsset, type VaultClaimResponse, type VaultDepositResponse, type VaultSharesResponse, type VaultWithdrawResponse, type VaultWithdrawStatusResponse, type VolumeResponse, type WalletTVL, type WithdrawResponse, type ZyfaiEventFilters, type ZyfaiEventHandlers, ZyfaiSDK, createBankrProvider, getChainConfig, getDefaultTokenAddress, getSupportedChainIds, isSupportedChain };
1716
+ export { type APYPerStrategy, type APYPerStrategyResponse, type ActionData, type ActiveWallet, type ActiveWalletsResponse, type AddWalletToSdkResponse, type Address, type AllocationDetail, type ApyPosition, type BankrProvider, type BankrProviderConfig, type BestOpportunityDetails, type BestOpportunityResponse, type ChainConfig, type ChainPortfolio, type ChainTokenEarnings, type CustomizationConfig, type CustomizeBatchRequest, type CustomizeBatchResponse, DEFAULT_TOKEN_ADDRESSES, type DailyApyEntry, type DailyApyHistoryResponse, type DailyEarning, type DailyEarningsResponse, type DebankPortfolioResponse, type DepegEvent, type DeploySafeResponse, type DepositResponse, type ERC7739Context, type ERC7739Data, type ExcludedPool, type FirstTopupResponse, type GetPoolsResponse, type GetSelectedPoolsResponse, type Hex, type HistoryEntry, type HistoryPosition, type HistoryResponse, type LiquidityDropEvent, type LogDepositResponse, type NewCollateralDetectedEvent, type OnchainEarnings, type OnchainEarningsResponse, type OpportunitiesResponse, type Opportunity, type OpportunityPosition, type PolicyData, type Pool, type Portfolio, type PortfolioAssetBalance, type PortfolioByAssetType, type PortfolioByChain, type PortfolioDetailed, type PortfolioDetailedResponse, type PortfolioResponse, type PortfolioToken, type PositionSlot, type Protocol, type ProtocolsResponse, type RebalanceFrequencyResponse, type RegisterAgentResponse, type SDKConfig, type SdkKeyTVLResponse, type Session, type SessionKeyResponse, type SimulateBestPositionsParams, type SimulateBestPositionsResponse, type SimulateCalldataItem, type SimulatedPosition, type SmartWalletByEOAResponse, type SmartWalletResponse, type Strategy, type SupportedChainId, type TVLResponse, type TokenApy, type TokenEarnings, type UpdateUserProfileRequest, type UpdateUserProfileResponse, type UserPosition, VAULT_ADDRESS, type VaultAsset, type VaultClaimResponse, type VaultDepositResponse, type VaultSharesResponse, type VaultWithdrawResponse, type VaultWithdrawStatusResponse, type VolumeResponse, type WalletTVL, type WithdrawResponse, type ZyfaiEventFilters, type ZyfaiEventHandlers, ZyfaiSDK, createBankrProvider, getChainConfig, getDefaultTokenAddress, getSupportedChainIds, isSupportedChain };
package/dist/index.js CHANGED
@@ -94,6 +94,7 @@ var ENDPOINTS = {
94
94
  if (params.protocols?.length) query.push(`protocols=${params.protocols.join(",")}`);
95
95
  if (params.pools?.length) query.push(`pools=${params.pools.join(",")}`);
96
96
  if (params.userPositions?.length) query.push(`userPositions=${encodeURIComponent(JSON.stringify(params.userPositions))}`);
97
+ if (params.partOfZyfiTvl !== void 0) query.push(`partOfZyfiTvl=${params.partOfZyfiTvl}`);
97
98
  return `/simulate/best-positions?${query.join("&")}`;
98
99
  },
99
100
  // Customization
@@ -917,6 +918,43 @@ function convertStrategiesToPublicAndNaming(array) {
917
918
  return array.map((item) => convertStrategyToPublicAndNaming(item));
918
919
  }
919
920
 
921
+ // src/utils/protocol-selection.ts
922
+ var getValidSymbols = (asset) => ASSET_CONFIGS[asset]?.tokenSymbols ?? [];
923
+ var hasAssetOnSelectedChains = (protocol, chains, asset) => {
924
+ if (!protocol.assets || protocol.assets.length === 0) return true;
925
+ const validSymbols = getValidSymbols(asset);
926
+ return protocol.assets.some(
927
+ (a) => chains.includes(a.chainId) && validSymbols.includes(a.symbol)
928
+ );
929
+ };
930
+ var getMatchingProtocolIds = (protocols, internalStrategy, chains, asset) => {
931
+ if (chains.length === 0) return [];
932
+ return protocols.filter((protocol) => {
933
+ if (!protocol || !protocol.strategies) return false;
934
+ if (!protocol.chains?.some((c) => chains.includes(c))) return false;
935
+ if (!hasAssetOnSelectedChains(protocol, chains, asset)) return false;
936
+ if (internalStrategy === "degen_strategy") {
937
+ return protocol.strategies.includes("degen_strategy") || protocol.strategies.includes("safe_strategy");
938
+ }
939
+ return protocol.strategies.includes("safe_strategy");
940
+ }).map((protocol) => protocol.id);
941
+ };
942
+ var hasMatchingPool = (data, chains, asset) => {
943
+ if (!data || typeof data !== "object") return false;
944
+ const validSymbols = getValidSymbols(asset);
945
+ for (const [chainIdStr, chainData] of Object.entries(data)) {
946
+ const chainIdNum = Number.parseInt(chainIdStr, 10);
947
+ if (!chains.includes(chainIdNum)) continue;
948
+ if (!chainData || typeof chainData !== "object") continue;
949
+ for (const [tokenSymbol, tokenData] of Object.entries(chainData)) {
950
+ if (!validSymbols.includes(tokenSymbol)) continue;
951
+ const pools = tokenData?.pools;
952
+ if (Array.isArray(pools) && pools.length > 0) return true;
953
+ }
954
+ }
955
+ return false;
956
+ };
957
+
920
958
  // src/core/ZyfaiSDK.ts
921
959
  var import_siwe = require("siwe");
922
960
  var _ZyfaiSDK = class _ZyfaiSDK {
@@ -1542,6 +1580,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1542
1580
  chainConfig.publicClient
1543
1581
  );
1544
1582
  if (alreadyDeployed) {
1583
+ await this.updateUserProtocols(chainId, strategy);
1545
1584
  let sessionKeyCreated2 = false;
1546
1585
  if (createSessionKey) {
1547
1586
  try {
@@ -1581,6 +1620,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1581
1620
  initError.message
1582
1621
  );
1583
1622
  }
1623
+ await this.updateUserProtocols(chainId, strategy);
1584
1624
  let sessionKeyCreated = false;
1585
1625
  if (createSessionKey) {
1586
1626
  try {
@@ -1672,9 +1712,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1672
1712
  if (!signatureResult.signature) {
1673
1713
  throw new Error("Failed to obtain session key signature");
1674
1714
  }
1675
- await this.updateUserProtocols(chainId);
1676
1715
  const signer = sessions[0].sessionValidator;
1677
- console.log("Session validator:", signer);
1678
1716
  const activation = await this.activateSessionKey(
1679
1717
  signer,
1680
1718
  signatureResult.signature,
@@ -1745,35 +1783,95 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1745
1783
  }
1746
1784
  }
1747
1785
  /**
1748
- * Update user protocols with available protocols from the chain
1749
- * This method is automatically called before activating session key
1786
+ * Patch the user's protocol selection for the given chain + strategy on
1787
+ * both USDC and WETH. Mirrors the front-end customization flow:
1788
+ * 1. Merge existing chains from `getUserDetails` with the new `chainId`
1789
+ * (never overwrite already-configured chains).
1790
+ * 2. Filter protocols by strategy, chain and asset support.
1791
+ * 3. Drop protocols that don't have any pools available for the
1792
+ * asset/chain/strategy combo.
1793
+ * 4. Persist via `updateUserProfile` (writes `assetTypeSettings`).
1794
+ *
1795
+ * Called from `deploySafe` — SDK consumers don't handle protocols manually.
1750
1796
  *
1751
- * @param chainId - Target chain ID
1752
1797
  * @internal
1753
1798
  */
1754
- async updateUserProtocols(chainId) {
1799
+ async updateUserProtocols(chainId, strategy) {
1755
1800
  try {
1756
- const protocolsResponse = await this.getAvailableProtocols(chainId);
1757
- const userDetails = await this.getUserDetails();
1758
- const filteredProtocols = userDetails.strategy ? protocolsResponse.protocols.filter((p) => p.strategies?.includes(userDetails.strategy)) : protocolsResponse.protocols;
1759
- if (!filteredProtocols || filteredProtocols.length === 0) {
1760
- console.warn(`No protocols available for chain ${chainId}`);
1761
- return;
1801
+ const allProtocols = await this.httpClient.get(
1802
+ ENDPOINTS.PROTOCOLS()
1803
+ );
1804
+ for (const asset of ["USDC", "WETH"]) {
1805
+ try {
1806
+ await this.updateUserProtocolsForAsset(
1807
+ asset,
1808
+ chainId,
1809
+ strategy,
1810
+ allProtocols
1811
+ );
1812
+ } catch (assetError) {
1813
+ console.warn(
1814
+ `Failed to update ${asset} protocols: ${assetError.message}`
1815
+ );
1816
+ }
1762
1817
  }
1763
- const protocolIds = filteredProtocols.map((p) => p.id);
1764
- await this.updateUserProfile({
1765
- protocols: protocolIds
1766
- });
1767
- await this.updateUserProfile({
1768
- protocols: protocolIds,
1769
- asset: "WETH"
1770
- });
1771
1818
  } catch (error) {
1772
1819
  console.warn(
1773
1820
  `Failed to update user protocols: ${error.message}`
1774
1821
  );
1775
1822
  }
1776
1823
  }
1824
+ /**
1825
+ * Compute and persist the protocol selection for a single asset.
1826
+ * @internal
1827
+ */
1828
+ async updateUserProtocolsForAsset(asset, chainId, strategy, allProtocols) {
1829
+ const userDetails = await this.getUserDetails(asset);
1830
+ const existingChains = userDetails.chains ?? [];
1831
+ const effectiveChains = Array.from(
1832
+ /* @__PURE__ */ new Set([...existingChains, chainId])
1833
+ );
1834
+ const publicStrategy = strategy ?? (isValidPublicStrategy(userDetails.strategy ?? "") ? userDetails.strategy : "conservative");
1835
+ const internalStrategy = toInternalStrategy(publicStrategy);
1836
+ const matching = getMatchingProtocolIds(
1837
+ allProtocols,
1838
+ internalStrategy,
1839
+ effectiveChains,
1840
+ asset
1841
+ );
1842
+ const withPools = await this.filterProtocolIdsWithPools(
1843
+ matching,
1844
+ effectiveChains,
1845
+ asset
1846
+ );
1847
+ console.log("withPools", withPools, "effectiveChains", effectiveChains, "asset", asset);
1848
+ await this.updateUserProfile({
1849
+ asset,
1850
+ protocols: withPools,
1851
+ chains: effectiveChains
1852
+ });
1853
+ }
1854
+ /**
1855
+ * Drop protocols that have no pools on any of the selected chains for the
1856
+ * requested asset. Uses the /customization/pools endpoint with
1857
+ * `degen_strategy` as the master strategy so the response includes both
1858
+ * safe and degen pools — mirrors the front-end behavior.
1859
+ * @internal
1860
+ */
1861
+ async filterProtocolIdsWithPools(protocolIds, chains, asset) {
1862
+ if (protocolIds.length === 0) return [];
1863
+ const results = await Promise.allSettled(
1864
+ protocolIds.map(async (id) => {
1865
+ const poolsData = await this.httpClient.get(
1866
+ ENDPOINTS.CUSTOMIZATION_POOLS(id, "degen_strategy")
1867
+ );
1868
+ return { id, hasPool: hasMatchingPool(poolsData, chains, asset) };
1869
+ })
1870
+ );
1871
+ return results.flatMap(
1872
+ (r) => r.status === "fulfilled" && r.value.hasPool ? [r.value.id] : []
1873
+ );
1874
+ }
1777
1875
  /**
1778
1876
  * Activate session key via Zyfai API
1779
1877
  */
package/dist/index.mjs CHANGED
@@ -51,6 +51,7 @@ var ENDPOINTS = {
51
51
  if (params.protocols?.length) query.push(`protocols=${params.protocols.join(",")}`);
52
52
  if (params.pools?.length) query.push(`pools=${params.pools.join(",")}`);
53
53
  if (params.userPositions?.length) query.push(`userPositions=${encodeURIComponent(JSON.stringify(params.userPositions))}`);
54
+ if (params.partOfZyfiTvl !== void 0) query.push(`partOfZyfiTvl=${params.partOfZyfiTvl}`);
54
55
  return `/simulate/best-positions?${query.join("&")}`;
55
56
  },
56
57
  // Customization
@@ -893,6 +894,43 @@ function convertStrategiesToPublicAndNaming(array) {
893
894
  return array.map((item) => convertStrategyToPublicAndNaming(item));
894
895
  }
895
896
 
897
+ // src/utils/protocol-selection.ts
898
+ var getValidSymbols = (asset) => ASSET_CONFIGS[asset]?.tokenSymbols ?? [];
899
+ var hasAssetOnSelectedChains = (protocol, chains, asset) => {
900
+ if (!protocol.assets || protocol.assets.length === 0) return true;
901
+ const validSymbols = getValidSymbols(asset);
902
+ return protocol.assets.some(
903
+ (a) => chains.includes(a.chainId) && validSymbols.includes(a.symbol)
904
+ );
905
+ };
906
+ var getMatchingProtocolIds = (protocols, internalStrategy, chains, asset) => {
907
+ if (chains.length === 0) return [];
908
+ return protocols.filter((protocol) => {
909
+ if (!protocol || !protocol.strategies) return false;
910
+ if (!protocol.chains?.some((c) => chains.includes(c))) return false;
911
+ if (!hasAssetOnSelectedChains(protocol, chains, asset)) return false;
912
+ if (internalStrategy === "degen_strategy") {
913
+ return protocol.strategies.includes("degen_strategy") || protocol.strategies.includes("safe_strategy");
914
+ }
915
+ return protocol.strategies.includes("safe_strategy");
916
+ }).map((protocol) => protocol.id);
917
+ };
918
+ var hasMatchingPool = (data, chains, asset) => {
919
+ if (!data || typeof data !== "object") return false;
920
+ const validSymbols = getValidSymbols(asset);
921
+ for (const [chainIdStr, chainData] of Object.entries(data)) {
922
+ const chainIdNum = Number.parseInt(chainIdStr, 10);
923
+ if (!chains.includes(chainIdNum)) continue;
924
+ if (!chainData || typeof chainData !== "object") continue;
925
+ for (const [tokenSymbol, tokenData] of Object.entries(chainData)) {
926
+ if (!validSymbols.includes(tokenSymbol)) continue;
927
+ const pools = tokenData?.pools;
928
+ if (Array.isArray(pools) && pools.length > 0) return true;
929
+ }
930
+ }
931
+ return false;
932
+ };
933
+
896
934
  // src/core/ZyfaiSDK.ts
897
935
  import { SiweMessage } from "siwe";
898
936
  var _ZyfaiSDK = class _ZyfaiSDK {
@@ -1518,6 +1556,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1518
1556
  chainConfig.publicClient
1519
1557
  );
1520
1558
  if (alreadyDeployed) {
1559
+ await this.updateUserProtocols(chainId, strategy);
1521
1560
  let sessionKeyCreated2 = false;
1522
1561
  if (createSessionKey) {
1523
1562
  try {
@@ -1557,6 +1596,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1557
1596
  initError.message
1558
1597
  );
1559
1598
  }
1599
+ await this.updateUserProtocols(chainId, strategy);
1560
1600
  let sessionKeyCreated = false;
1561
1601
  if (createSessionKey) {
1562
1602
  try {
@@ -1648,9 +1688,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1648
1688
  if (!signatureResult.signature) {
1649
1689
  throw new Error("Failed to obtain session key signature");
1650
1690
  }
1651
- await this.updateUserProtocols(chainId);
1652
1691
  const signer = sessions[0].sessionValidator;
1653
- console.log("Session validator:", signer);
1654
1692
  const activation = await this.activateSessionKey(
1655
1693
  signer,
1656
1694
  signatureResult.signature,
@@ -1721,35 +1759,95 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1721
1759
  }
1722
1760
  }
1723
1761
  /**
1724
- * Update user protocols with available protocols from the chain
1725
- * This method is automatically called before activating session key
1762
+ * Patch the user's protocol selection for the given chain + strategy on
1763
+ * both USDC and WETH. Mirrors the front-end customization flow:
1764
+ * 1. Merge existing chains from `getUserDetails` with the new `chainId`
1765
+ * (never overwrite already-configured chains).
1766
+ * 2. Filter protocols by strategy, chain and asset support.
1767
+ * 3. Drop protocols that don't have any pools available for the
1768
+ * asset/chain/strategy combo.
1769
+ * 4. Persist via `updateUserProfile` (writes `assetTypeSettings`).
1770
+ *
1771
+ * Called from `deploySafe` — SDK consumers don't handle protocols manually.
1726
1772
  *
1727
- * @param chainId - Target chain ID
1728
1773
  * @internal
1729
1774
  */
1730
- async updateUserProtocols(chainId) {
1775
+ async updateUserProtocols(chainId, strategy) {
1731
1776
  try {
1732
- const protocolsResponse = await this.getAvailableProtocols(chainId);
1733
- const userDetails = await this.getUserDetails();
1734
- const filteredProtocols = userDetails.strategy ? protocolsResponse.protocols.filter((p) => p.strategies?.includes(userDetails.strategy)) : protocolsResponse.protocols;
1735
- if (!filteredProtocols || filteredProtocols.length === 0) {
1736
- console.warn(`No protocols available for chain ${chainId}`);
1737
- return;
1777
+ const allProtocols = await this.httpClient.get(
1778
+ ENDPOINTS.PROTOCOLS()
1779
+ );
1780
+ for (const asset of ["USDC", "WETH"]) {
1781
+ try {
1782
+ await this.updateUserProtocolsForAsset(
1783
+ asset,
1784
+ chainId,
1785
+ strategy,
1786
+ allProtocols
1787
+ );
1788
+ } catch (assetError) {
1789
+ console.warn(
1790
+ `Failed to update ${asset} protocols: ${assetError.message}`
1791
+ );
1792
+ }
1738
1793
  }
1739
- const protocolIds = filteredProtocols.map((p) => p.id);
1740
- await this.updateUserProfile({
1741
- protocols: protocolIds
1742
- });
1743
- await this.updateUserProfile({
1744
- protocols: protocolIds,
1745
- asset: "WETH"
1746
- });
1747
1794
  } catch (error) {
1748
1795
  console.warn(
1749
1796
  `Failed to update user protocols: ${error.message}`
1750
1797
  );
1751
1798
  }
1752
1799
  }
1800
+ /**
1801
+ * Compute and persist the protocol selection for a single asset.
1802
+ * @internal
1803
+ */
1804
+ async updateUserProtocolsForAsset(asset, chainId, strategy, allProtocols) {
1805
+ const userDetails = await this.getUserDetails(asset);
1806
+ const existingChains = userDetails.chains ?? [];
1807
+ const effectiveChains = Array.from(
1808
+ /* @__PURE__ */ new Set([...existingChains, chainId])
1809
+ );
1810
+ const publicStrategy = strategy ?? (isValidPublicStrategy(userDetails.strategy ?? "") ? userDetails.strategy : "conservative");
1811
+ const internalStrategy = toInternalStrategy(publicStrategy);
1812
+ const matching = getMatchingProtocolIds(
1813
+ allProtocols,
1814
+ internalStrategy,
1815
+ effectiveChains,
1816
+ asset
1817
+ );
1818
+ const withPools = await this.filterProtocolIdsWithPools(
1819
+ matching,
1820
+ effectiveChains,
1821
+ asset
1822
+ );
1823
+ console.log("withPools", withPools, "effectiveChains", effectiveChains, "asset", asset);
1824
+ await this.updateUserProfile({
1825
+ asset,
1826
+ protocols: withPools,
1827
+ chains: effectiveChains
1828
+ });
1829
+ }
1830
+ /**
1831
+ * Drop protocols that have no pools on any of the selected chains for the
1832
+ * requested asset. Uses the /customization/pools endpoint with
1833
+ * `degen_strategy` as the master strategy so the response includes both
1834
+ * safe and degen pools — mirrors the front-end behavior.
1835
+ * @internal
1836
+ */
1837
+ async filterProtocolIdsWithPools(protocolIds, chains, asset) {
1838
+ if (protocolIds.length === 0) return [];
1839
+ const results = await Promise.allSettled(
1840
+ protocolIds.map(async (id) => {
1841
+ const poolsData = await this.httpClient.get(
1842
+ ENDPOINTS.CUSTOMIZATION_POOLS(id, "degen_strategy")
1843
+ );
1844
+ return { id, hasPool: hasMatchingPool(poolsData, chains, asset) };
1845
+ })
1846
+ );
1847
+ return results.flatMap(
1848
+ (r) => r.status === "fulfilled" && r.value.hasPool ? [r.value.id] : []
1849
+ );
1850
+ }
1753
1851
  /**
1754
1852
  * Activate session key via Zyfai API
1755
1853
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zyfai/sdk",
3
- "version": "0.2.40",
3
+ "version": "0.2.42",
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",