@zyfai/sdk 0.2.40 → 0.2.41

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
@@ -909,13 +909,33 @@ declare class ZyfaiSDK {
909
909
  */
910
910
  private signSessionKey;
911
911
  /**
912
- * Update user protocols with available protocols from the chain
913
- * This method is automatically called before activating session key
912
+ * Patch the user's protocol selection for the given chain + strategy on
913
+ * both USDC and WETH. Mirrors the front-end customization flow:
914
+ * 1. Merge existing chains from `getUserDetails` with the new `chainId`
915
+ * (never overwrite already-configured chains).
916
+ * 2. Filter protocols by strategy, chain and asset support.
917
+ * 3. Drop protocols that don't have any pools available for the
918
+ * asset/chain/strategy combo.
919
+ * 4. Persist via `updateUserProfile` (writes `assetTypeSettings`).
920
+ *
921
+ * Called from `deploySafe` — SDK consumers don't handle protocols manually.
914
922
  *
915
- * @param chainId - Target chain ID
916
923
  * @internal
917
924
  */
918
925
  private updateUserProtocols;
926
+ /**
927
+ * Compute and persist the protocol selection for a single asset.
928
+ * @internal
929
+ */
930
+ private updateUserProtocolsForAsset;
931
+ /**
932
+ * Drop protocols that have no pools on any of the selected chains for the
933
+ * requested asset. Uses the /customization/pools endpoint with
934
+ * `degen_strategy` as the master strategy so the response includes both
935
+ * safe and degen pools — mirrors the front-end behavior.
936
+ * @internal
937
+ */
938
+ private filterProtocolIdsWithPools;
919
939
  /**
920
940
  * Activate session key via Zyfai API
921
941
  */
package/dist/index.d.ts CHANGED
@@ -909,13 +909,33 @@ declare class ZyfaiSDK {
909
909
  */
910
910
  private signSessionKey;
911
911
  /**
912
- * Update user protocols with available protocols from the chain
913
- * This method is automatically called before activating session key
912
+ * Patch the user's protocol selection for the given chain + strategy on
913
+ * both USDC and WETH. Mirrors the front-end customization flow:
914
+ * 1. Merge existing chains from `getUserDetails` with the new `chainId`
915
+ * (never overwrite already-configured chains).
916
+ * 2. Filter protocols by strategy, chain and asset support.
917
+ * 3. Drop protocols that don't have any pools available for the
918
+ * asset/chain/strategy combo.
919
+ * 4. Persist via `updateUserProfile` (writes `assetTypeSettings`).
920
+ *
921
+ * Called from `deploySafe` — SDK consumers don't handle protocols manually.
914
922
  *
915
- * @param chainId - Target chain ID
916
923
  * @internal
917
924
  */
918
925
  private updateUserProtocols;
926
+ /**
927
+ * Compute and persist the protocol selection for a single asset.
928
+ * @internal
929
+ */
930
+ private updateUserProtocolsForAsset;
931
+ /**
932
+ * Drop protocols that have no pools on any of the selected chains for the
933
+ * requested asset. Uses the /customization/pools endpoint with
934
+ * `degen_strategy` as the master strategy so the response includes both
935
+ * safe and degen pools — mirrors the front-end behavior.
936
+ * @internal
937
+ */
938
+ private filterProtocolIdsWithPools;
919
939
  /**
920
940
  * Activate session key via Zyfai API
921
941
  */
package/dist/index.js CHANGED
@@ -917,6 +917,43 @@ function convertStrategiesToPublicAndNaming(array) {
917
917
  return array.map((item) => convertStrategyToPublicAndNaming(item));
918
918
  }
919
919
 
920
+ // src/utils/protocol-selection.ts
921
+ var getValidSymbols = (asset) => ASSET_CONFIGS[asset]?.tokenSymbols ?? [];
922
+ var hasAssetOnSelectedChains = (protocol, chains, asset) => {
923
+ if (!protocol.assets || protocol.assets.length === 0) return true;
924
+ const validSymbols = getValidSymbols(asset);
925
+ return protocol.assets.some(
926
+ (a) => chains.includes(a.chainId) && validSymbols.includes(a.symbol)
927
+ );
928
+ };
929
+ var getMatchingProtocolIds = (protocols, internalStrategy, chains, asset) => {
930
+ if (chains.length === 0) return [];
931
+ return protocols.filter((protocol) => {
932
+ if (!protocol || !protocol.strategies) return false;
933
+ if (!protocol.chains?.some((c) => chains.includes(c))) return false;
934
+ if (!hasAssetOnSelectedChains(protocol, chains, asset)) return false;
935
+ if (internalStrategy === "degen_strategy") {
936
+ return protocol.strategies.includes("degen_strategy") || protocol.strategies.includes("safe_strategy");
937
+ }
938
+ return protocol.strategies.includes("safe_strategy");
939
+ }).map((protocol) => protocol.id);
940
+ };
941
+ var hasMatchingPool = (data, chains, asset) => {
942
+ if (!data || typeof data !== "object") return false;
943
+ const validSymbols = getValidSymbols(asset);
944
+ for (const [chainIdStr, chainData] of Object.entries(data)) {
945
+ const chainIdNum = Number.parseInt(chainIdStr, 10);
946
+ if (!chains.includes(chainIdNum)) continue;
947
+ if (!chainData || typeof chainData !== "object") continue;
948
+ for (const [tokenSymbol, tokenData] of Object.entries(chainData)) {
949
+ if (!validSymbols.includes(tokenSymbol)) continue;
950
+ const pools = tokenData?.pools;
951
+ if (Array.isArray(pools) && pools.length > 0) return true;
952
+ }
953
+ }
954
+ return false;
955
+ };
956
+
920
957
  // src/core/ZyfaiSDK.ts
921
958
  var import_siwe = require("siwe");
922
959
  var _ZyfaiSDK = class _ZyfaiSDK {
@@ -1542,6 +1579,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1542
1579
  chainConfig.publicClient
1543
1580
  );
1544
1581
  if (alreadyDeployed) {
1582
+ await this.updateUserProtocols(chainId, strategy);
1545
1583
  let sessionKeyCreated2 = false;
1546
1584
  if (createSessionKey) {
1547
1585
  try {
@@ -1581,6 +1619,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1581
1619
  initError.message
1582
1620
  );
1583
1621
  }
1622
+ await this.updateUserProtocols(chainId, strategy);
1584
1623
  let sessionKeyCreated = false;
1585
1624
  if (createSessionKey) {
1586
1625
  try {
@@ -1672,9 +1711,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1672
1711
  if (!signatureResult.signature) {
1673
1712
  throw new Error("Failed to obtain session key signature");
1674
1713
  }
1675
- await this.updateUserProtocols(chainId);
1676
1714
  const signer = sessions[0].sessionValidator;
1677
- console.log("Session validator:", signer);
1678
1715
  const activation = await this.activateSessionKey(
1679
1716
  signer,
1680
1717
  signatureResult.signature,
@@ -1745,35 +1782,95 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1745
1782
  }
1746
1783
  }
1747
1784
  /**
1748
- * Update user protocols with available protocols from the chain
1749
- * This method is automatically called before activating session key
1785
+ * Patch the user's protocol selection for the given chain + strategy on
1786
+ * both USDC and WETH. Mirrors the front-end customization flow:
1787
+ * 1. Merge existing chains from `getUserDetails` with the new `chainId`
1788
+ * (never overwrite already-configured chains).
1789
+ * 2. Filter protocols by strategy, chain and asset support.
1790
+ * 3. Drop protocols that don't have any pools available for the
1791
+ * asset/chain/strategy combo.
1792
+ * 4. Persist via `updateUserProfile` (writes `assetTypeSettings`).
1793
+ *
1794
+ * Called from `deploySafe` — SDK consumers don't handle protocols manually.
1750
1795
  *
1751
- * @param chainId - Target chain ID
1752
1796
  * @internal
1753
1797
  */
1754
- async updateUserProtocols(chainId) {
1798
+ async updateUserProtocols(chainId, strategy) {
1755
1799
  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;
1800
+ const allProtocols = await this.httpClient.get(
1801
+ ENDPOINTS.PROTOCOLS()
1802
+ );
1803
+ for (const asset of ["USDC", "WETH"]) {
1804
+ try {
1805
+ await this.updateUserProtocolsForAsset(
1806
+ asset,
1807
+ chainId,
1808
+ strategy,
1809
+ allProtocols
1810
+ );
1811
+ } catch (assetError) {
1812
+ console.warn(
1813
+ `Failed to update ${asset} protocols: ${assetError.message}`
1814
+ );
1815
+ }
1762
1816
  }
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
1817
  } catch (error) {
1772
1818
  console.warn(
1773
1819
  `Failed to update user protocols: ${error.message}`
1774
1820
  );
1775
1821
  }
1776
1822
  }
1823
+ /**
1824
+ * Compute and persist the protocol selection for a single asset.
1825
+ * @internal
1826
+ */
1827
+ async updateUserProtocolsForAsset(asset, chainId, strategy, allProtocols) {
1828
+ const userDetails = await this.getUserDetails(asset);
1829
+ const existingChains = userDetails.chains ?? [];
1830
+ const effectiveChains = Array.from(
1831
+ /* @__PURE__ */ new Set([...existingChains, chainId])
1832
+ );
1833
+ const publicStrategy = strategy ?? (isValidPublicStrategy(userDetails.strategy ?? "") ? userDetails.strategy : "conservative");
1834
+ const internalStrategy = toInternalStrategy(publicStrategy);
1835
+ const matching = getMatchingProtocolIds(
1836
+ allProtocols,
1837
+ internalStrategy,
1838
+ effectiveChains,
1839
+ asset
1840
+ );
1841
+ const withPools = await this.filterProtocolIdsWithPools(
1842
+ matching,
1843
+ effectiveChains,
1844
+ asset
1845
+ );
1846
+ console.log("withPools", withPools, "effectiveChains", effectiveChains, "asset", asset);
1847
+ await this.updateUserProfile({
1848
+ asset,
1849
+ protocols: withPools,
1850
+ chains: effectiveChains
1851
+ });
1852
+ }
1853
+ /**
1854
+ * Drop protocols that have no pools on any of the selected chains for the
1855
+ * requested asset. Uses the /customization/pools endpoint with
1856
+ * `degen_strategy` as the master strategy so the response includes both
1857
+ * safe and degen pools — mirrors the front-end behavior.
1858
+ * @internal
1859
+ */
1860
+ async filterProtocolIdsWithPools(protocolIds, chains, asset) {
1861
+ if (protocolIds.length === 0) return [];
1862
+ const results = await Promise.allSettled(
1863
+ protocolIds.map(async (id) => {
1864
+ const poolsData = await this.httpClient.get(
1865
+ ENDPOINTS.CUSTOMIZATION_POOLS(id, "degen_strategy")
1866
+ );
1867
+ return { id, hasPool: hasMatchingPool(poolsData, chains, asset) };
1868
+ })
1869
+ );
1870
+ return results.flatMap(
1871
+ (r) => r.status === "fulfilled" && r.value.hasPool ? [r.value.id] : []
1872
+ );
1873
+ }
1777
1874
  /**
1778
1875
  * Activate session key via Zyfai API
1779
1876
  */
package/dist/index.mjs CHANGED
@@ -893,6 +893,43 @@ function convertStrategiesToPublicAndNaming(array) {
893
893
  return array.map((item) => convertStrategyToPublicAndNaming(item));
894
894
  }
895
895
 
896
+ // src/utils/protocol-selection.ts
897
+ var getValidSymbols = (asset) => ASSET_CONFIGS[asset]?.tokenSymbols ?? [];
898
+ var hasAssetOnSelectedChains = (protocol, chains, asset) => {
899
+ if (!protocol.assets || protocol.assets.length === 0) return true;
900
+ const validSymbols = getValidSymbols(asset);
901
+ return protocol.assets.some(
902
+ (a) => chains.includes(a.chainId) && validSymbols.includes(a.symbol)
903
+ );
904
+ };
905
+ var getMatchingProtocolIds = (protocols, internalStrategy, chains, asset) => {
906
+ if (chains.length === 0) return [];
907
+ return protocols.filter((protocol) => {
908
+ if (!protocol || !protocol.strategies) return false;
909
+ if (!protocol.chains?.some((c) => chains.includes(c))) return false;
910
+ if (!hasAssetOnSelectedChains(protocol, chains, asset)) return false;
911
+ if (internalStrategy === "degen_strategy") {
912
+ return protocol.strategies.includes("degen_strategy") || protocol.strategies.includes("safe_strategy");
913
+ }
914
+ return protocol.strategies.includes("safe_strategy");
915
+ }).map((protocol) => protocol.id);
916
+ };
917
+ var hasMatchingPool = (data, chains, asset) => {
918
+ if (!data || typeof data !== "object") return false;
919
+ const validSymbols = getValidSymbols(asset);
920
+ for (const [chainIdStr, chainData] of Object.entries(data)) {
921
+ const chainIdNum = Number.parseInt(chainIdStr, 10);
922
+ if (!chains.includes(chainIdNum)) continue;
923
+ if (!chainData || typeof chainData !== "object") continue;
924
+ for (const [tokenSymbol, tokenData] of Object.entries(chainData)) {
925
+ if (!validSymbols.includes(tokenSymbol)) continue;
926
+ const pools = tokenData?.pools;
927
+ if (Array.isArray(pools) && pools.length > 0) return true;
928
+ }
929
+ }
930
+ return false;
931
+ };
932
+
896
933
  // src/core/ZyfaiSDK.ts
897
934
  import { SiweMessage } from "siwe";
898
935
  var _ZyfaiSDK = class _ZyfaiSDK {
@@ -1518,6 +1555,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1518
1555
  chainConfig.publicClient
1519
1556
  );
1520
1557
  if (alreadyDeployed) {
1558
+ await this.updateUserProtocols(chainId, strategy);
1521
1559
  let sessionKeyCreated2 = false;
1522
1560
  if (createSessionKey) {
1523
1561
  try {
@@ -1557,6 +1595,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1557
1595
  initError.message
1558
1596
  );
1559
1597
  }
1598
+ await this.updateUserProtocols(chainId, strategy);
1560
1599
  let sessionKeyCreated = false;
1561
1600
  if (createSessionKey) {
1562
1601
  try {
@@ -1648,9 +1687,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1648
1687
  if (!signatureResult.signature) {
1649
1688
  throw new Error("Failed to obtain session key signature");
1650
1689
  }
1651
- await this.updateUserProtocols(chainId);
1652
1690
  const signer = sessions[0].sessionValidator;
1653
- console.log("Session validator:", signer);
1654
1691
  const activation = await this.activateSessionKey(
1655
1692
  signer,
1656
1693
  signatureResult.signature,
@@ -1721,35 +1758,95 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1721
1758
  }
1722
1759
  }
1723
1760
  /**
1724
- * Update user protocols with available protocols from the chain
1725
- * This method is automatically called before activating session key
1761
+ * Patch the user's protocol selection for the given chain + strategy on
1762
+ * both USDC and WETH. Mirrors the front-end customization flow:
1763
+ * 1. Merge existing chains from `getUserDetails` with the new `chainId`
1764
+ * (never overwrite already-configured chains).
1765
+ * 2. Filter protocols by strategy, chain and asset support.
1766
+ * 3. Drop protocols that don't have any pools available for the
1767
+ * asset/chain/strategy combo.
1768
+ * 4. Persist via `updateUserProfile` (writes `assetTypeSettings`).
1769
+ *
1770
+ * Called from `deploySafe` — SDK consumers don't handle protocols manually.
1726
1771
  *
1727
- * @param chainId - Target chain ID
1728
1772
  * @internal
1729
1773
  */
1730
- async updateUserProtocols(chainId) {
1774
+ async updateUserProtocols(chainId, strategy) {
1731
1775
  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;
1776
+ const allProtocols = await this.httpClient.get(
1777
+ ENDPOINTS.PROTOCOLS()
1778
+ );
1779
+ for (const asset of ["USDC", "WETH"]) {
1780
+ try {
1781
+ await this.updateUserProtocolsForAsset(
1782
+ asset,
1783
+ chainId,
1784
+ strategy,
1785
+ allProtocols
1786
+ );
1787
+ } catch (assetError) {
1788
+ console.warn(
1789
+ `Failed to update ${asset} protocols: ${assetError.message}`
1790
+ );
1791
+ }
1738
1792
  }
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
1793
  } catch (error) {
1748
1794
  console.warn(
1749
1795
  `Failed to update user protocols: ${error.message}`
1750
1796
  );
1751
1797
  }
1752
1798
  }
1799
+ /**
1800
+ * Compute and persist the protocol selection for a single asset.
1801
+ * @internal
1802
+ */
1803
+ async updateUserProtocolsForAsset(asset, chainId, strategy, allProtocols) {
1804
+ const userDetails = await this.getUserDetails(asset);
1805
+ const existingChains = userDetails.chains ?? [];
1806
+ const effectiveChains = Array.from(
1807
+ /* @__PURE__ */ new Set([...existingChains, chainId])
1808
+ );
1809
+ const publicStrategy = strategy ?? (isValidPublicStrategy(userDetails.strategy ?? "") ? userDetails.strategy : "conservative");
1810
+ const internalStrategy = toInternalStrategy(publicStrategy);
1811
+ const matching = getMatchingProtocolIds(
1812
+ allProtocols,
1813
+ internalStrategy,
1814
+ effectiveChains,
1815
+ asset
1816
+ );
1817
+ const withPools = await this.filterProtocolIdsWithPools(
1818
+ matching,
1819
+ effectiveChains,
1820
+ asset
1821
+ );
1822
+ console.log("withPools", withPools, "effectiveChains", effectiveChains, "asset", asset);
1823
+ await this.updateUserProfile({
1824
+ asset,
1825
+ protocols: withPools,
1826
+ chains: effectiveChains
1827
+ });
1828
+ }
1829
+ /**
1830
+ * Drop protocols that have no pools on any of the selected chains for the
1831
+ * requested asset. Uses the /customization/pools endpoint with
1832
+ * `degen_strategy` as the master strategy so the response includes both
1833
+ * safe and degen pools — mirrors the front-end behavior.
1834
+ * @internal
1835
+ */
1836
+ async filterProtocolIdsWithPools(protocolIds, chains, asset) {
1837
+ if (protocolIds.length === 0) return [];
1838
+ const results = await Promise.allSettled(
1839
+ protocolIds.map(async (id) => {
1840
+ const poolsData = await this.httpClient.get(
1841
+ ENDPOINTS.CUSTOMIZATION_POOLS(id, "degen_strategy")
1842
+ );
1843
+ return { id, hasPool: hasMatchingPool(poolsData, chains, asset) };
1844
+ })
1845
+ );
1846
+ return results.flatMap(
1847
+ (r) => r.status === "fulfilled" && r.value.hasPool ? [r.value.id] : []
1848
+ );
1849
+ }
1753
1850
  /**
1754
1851
  * Activate session key via Zyfai API
1755
1852
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zyfai/sdk",
3
- "version": "0.2.40",
3
+ "version": "0.2.41",
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",