@zyfai/sdk 0.2.23 → 0.2.25

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.js CHANGED
@@ -66,8 +66,8 @@ var ENDPOINTS = {
66
66
  // Data (v1)
67
67
  DATA_POSITION: (walletAddress) => `/data/position?walletAddress=${walletAddress}`,
68
68
  DATA_HISTORY: (walletAddress, chainId) => `/data/history?walletAddress=${walletAddress}&chainId=${chainId}`,
69
- DATA_TVL: "/data/tvl",
70
- DATA_VOLUME: "/data/volume",
69
+ DATA_TVL: "/data/usd-tvl",
70
+ DATA_VOLUME: (assetType) => `/data/volume?assetType=${assetType}`,
71
71
  DATA_FIRST_TOPUP: (walletAddress, chainId) => `/data/first-topup?walletAddress=${walletAddress}&chainId=${chainId}`,
72
72
  DATA_ACTIVE_WALLETS: (chainId) => `/data/active-wallets?chainId=${chainId}`,
73
73
  DATA_BY_EOA: (address) => `/data/by-eoa?address=${address}`,
@@ -86,25 +86,48 @@ var DATA_ENDPOINTS = {
86
86
  // User Initialization
87
87
  USER_INITIALIZE: "/api/earnings/initialize",
88
88
  // Earnings
89
- ONCHAIN_EARNINGS: (walletAddress) => `/usercheck/onchain-earnings?walletAddress=${walletAddress}`,
90
- CALCULATE_ONCHAIN_EARNINGS: "/usercheck/calculate-onchain-earnings",
89
+ ONCHAIN_EARNINGS: (walletAddress) => `/onchain-earnings/onchain-earnings?walletAddress=${walletAddress}`,
90
+ CALCULATE_ONCHAIN_EARNINGS: "/onchain-earnings/calculate-onchain-earnings",
91
91
  DAILY_EARNINGS: (walletAddress, startDate, endDate) => {
92
- let url = `/usercheck/daily-earnings?walletAddress=${walletAddress}`;
92
+ let url = `/onchain-earnings/daily-earnings?walletAddress=${walletAddress}`;
93
93
  if (startDate) url += `&startDate=${startDate}`;
94
94
  if (endDate) url += `&endDate=${endDate}`;
95
95
  return url;
96
96
  },
97
- // Portfolio
98
- DEBANK_PORTFOLIO_MULTICHAIN: (address) => `/debank/portfolio/multichain/${address}`,
99
97
  // Opportunities
100
- OPPORTUNITIES_SAFE: (chainId) => chainId ? `/opportunities/safe?chainId=${chainId}` : "/opportunities/safe",
101
- OPPORTUNITIES_DEGEN: (chainId) => chainId ? `/opportunities/degen-strategies?chainId=${chainId}` : "/opportunities/degen-strategies",
98
+ OPPORTUNITIES_SAFE: (chainId, asset, status) => {
99
+ const params = [];
100
+ if (chainId !== void 0) params.push(`chainId=${chainId}`);
101
+ if (asset) params.push(`asset=${asset}`);
102
+ if (status) params.push(`status=${status}`);
103
+ return params.length > 0 ? `/opportunities/safe?${params.join("&")}` : "/opportunities/safe";
104
+ },
105
+ OPPORTUNITIES_DEGEN: (chainId, asset, status) => {
106
+ const params = [];
107
+ if (chainId !== void 0) params.push(`chainId=${chainId}`);
108
+ if (asset) params.push(`asset=${asset}`);
109
+ if (status) params.push(`status=${status}`);
110
+ return params.length > 0 ? `/opportunities/degen-strategies?${params.join("&")}` : "/opportunities/degen-strategies";
111
+ },
102
112
  // APY History
103
- DAILY_APY_HISTORY_WEIGHTED: (walletAddress, days) => `/daily-apy-history/weighted/${walletAddress}${days ? `?days=${days}` : ""}`,
113
+ DAILY_APY_HISTORY_WEIGHTED: (walletAddress, days) => `/daily-apy-history/weighted-multi-asset/${walletAddress}${days ? `?days=${days}` : ""}`,
104
114
  // Rebalance
105
- REBALANCE_INFO: (isCrossChain) => isCrossChain !== void 0 ? `/rebalance/rebalance-info?isCrossChain=${isCrossChain}` : "/rebalance/rebalance-info",
115
+ REBALANCE_INFO: (options) => {
116
+ const params = [];
117
+ if (options?.isCrossChain !== void 0) params.push(`isCrossChain=${options.isCrossChain}`);
118
+ if (options?.tokenSymbol) params.push(`tokenSymbol=${options.tokenSymbol}`);
119
+ return params.length > 0 ? `/rebalance/rebalance-info?${params.join("&")}` : "/rebalance/rebalance-info";
120
+ },
106
121
  // APY Per Strategy
107
- APY_PER_STRATEGY: (isCrossChain = false, days = 7, strategy = "safe") => `/rebalance/rebalance-info?isCrossChain=${isCrossChain}&days=${days}&strategy=${strategy}`
122
+ APY_PER_STRATEGY: (options = {}) => {
123
+ const params = [];
124
+ if (options.isCrossChain !== void 0) params.push(`isCrossChain=${options.isCrossChain}`);
125
+ if (options.days !== void 0) params.push(`days=${options.days}`);
126
+ if (options.strategy) params.push(`strategy=${options.strategy}`);
127
+ if (options.chainId !== void 0) params.push(`chainId=${options.chainId}`);
128
+ if (options.tokenSymbol) params.push(`tokenSymbol=${options.tokenSymbol}`);
129
+ return params.length > 0 ? `/rebalance/rebalance-info?${params.join("&")}` : "/rebalance/rebalance-info";
130
+ }
108
131
  };
109
132
 
110
133
  // src/utils/http-client.ts
@@ -403,8 +426,71 @@ var DEFAULT_TOKEN_ADDRESSES = {
403
426
  9745: "0xB8CE59FC3717ada4C02eaDF9682A9e934F625ebb"
404
427
  // USDT on Plasma
405
428
  };
406
- var getDefaultTokenAddress = (chainId) => {
407
- const address = DEFAULT_TOKEN_ADDRESSES[chainId];
429
+ var ASSET_CONFIGS = {
430
+ USDC: {
431
+ symbol: "USDC",
432
+ assetType: "usdc",
433
+ displayName: "USDC",
434
+ icon: "/ai-dashboard/usdc-token.png",
435
+ decimals: 6,
436
+ tokenSymbols: ["USDC", "USDC.e", "USDT", "USDT0"],
437
+ tokenSymbolsByChainId: {
438
+ 8453: "USDC",
439
+ 42161: "USDC",
440
+ 9745: "USDT0",
441
+ 146: "USDC.e",
442
+ 1: "USDC"
443
+ },
444
+ addresses: {
445
+ 8453: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
446
+ // Base
447
+ 42161: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
448
+ // Arbitrum
449
+ 9745: "0xb8ce59fc3717ada4c02eadf9682a9e934f625ebb",
450
+ // Plasma
451
+ 146: "0x29219dd400f2bf60e5a23d13be72b486d4038894",
452
+ // Sonic
453
+ 59144: "0x176211869ca2b568f2a7d4ee941e073a821ee1ff",
454
+ // Linea
455
+ 1: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"
456
+ // Ethereum
457
+ },
458
+ enabled: true
459
+ },
460
+ WETH: {
461
+ symbol: "WETH",
462
+ assetType: "eth",
463
+ displayName: "WETH",
464
+ icon: "/ai-dashboard/eth-token.png",
465
+ decimals: 18,
466
+ tokenSymbols: ["WETH", "ETH"],
467
+ tokenSymbolsByChainId: {
468
+ 8453: "WETH",
469
+ 42161: "WETH",
470
+ 9745: "WETH",
471
+ 146: "WETH",
472
+ 59144: "WETH",
473
+ 1: "WETH"
474
+ },
475
+ addresses: {
476
+ 8453: "0x4200000000000000000000000000000000000006",
477
+ // Base
478
+ 42161: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
479
+ // Arbitrum
480
+ 9745: "0x4200000000000000000000000000000000000006",
481
+ // Plasma
482
+ 146: "0x039e64f90d4199560e7533692f69448878db85c7",
483
+ // Sonic
484
+ 59144: "0xe5d7c2a44ffddf6b295a15c148167daaaf5cf34f",
485
+ // Linea
486
+ 1: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
487
+ // Ethereum
488
+ },
489
+ enabled: true
490
+ }
491
+ };
492
+ var getDefaultTokenAddress = (chainId, asset) => {
493
+ const address = ASSET_CONFIGS[asset || "USDC"]?.addresses[chainId];
408
494
  if (!address || address === "0x0000000000000000000000000000000000000000") {
409
495
  throw new Error(
410
496
  `Default token address not configured for chain ${chainId}. Please provide tokenAddress explicitly.`
@@ -683,6 +769,15 @@ function convertStrategyToPublic(obj) {
683
769
  return result;
684
770
  }
685
771
  }
772
+ function convertAssetInternally(asset) {
773
+ if (asset === "USDC") {
774
+ return "usdc";
775
+ }
776
+ if (asset === "WETH") {
777
+ return "eth";
778
+ }
779
+ throw new Error(`Invalid asset: ${asset}. Must be "USDC" or "WETH".`);
780
+ }
686
781
  function convertStrategiesToPublic(array) {
687
782
  return array.map((item) => convertStrategyToPublic(item));
688
783
  }
@@ -822,38 +917,40 @@ var _ZyfaiSDK = class _ZyfaiSDK {
822
917
  async updateUserProfile(request) {
823
918
  try {
824
919
  await this.authenticateUser();
825
- const payload = { ...request };
826
- if (payload.strategy) {
827
- if (!isValidPublicStrategy(payload.strategy)) {
920
+ const asset = request.asset || "USDC";
921
+ const internalAsset = convertAssetInternally(asset);
922
+ let rebalanceStrategy;
923
+ if (request.strategy) {
924
+ if (!isValidPublicStrategy(request.strategy)) {
828
925
  throw new Error(
829
- `Invalid strategy: ${payload.strategy}. Must be "conservative" or "aggressive".`
926
+ `Invalid strategy: ${request.strategy}. Must be "conservative" or "aggressive".`
830
927
  );
831
928
  }
832
- payload.strategy = toInternalStrategy(
833
- payload.strategy
929
+ rebalanceStrategy = toInternalStrategy(
930
+ request.strategy
834
931
  );
835
932
  }
836
- const response = await this.httpClient.patch(
933
+ const assetSettings = {};
934
+ if (rebalanceStrategy !== void 0) assetSettings.rebalanceStrategy = rebalanceStrategy;
935
+ if (request.autocompounding !== void 0) assetSettings.autocompounding = request.autocompounding;
936
+ if (request.crosschainStrategy !== void 0) assetSettings.crosschainStrategy = request.crosschainStrategy;
937
+ if (request.splitting !== void 0) assetSettings.splitting = request.splitting;
938
+ if (request.minSplits !== void 0) assetSettings.minSplits = request.minSplits;
939
+ if (request.chains !== void 0) assetSettings.chains = request.chains;
940
+ if (request.autoSelectProtocols !== void 0) assetSettings.autoSelectProtocols = request.autoSelectProtocols;
941
+ if (request.protocols !== void 0) assetSettings.protocols = request.protocols;
942
+ const payload = {
943
+ assetTypeSettings: {
944
+ [internalAsset]: assetSettings
945
+ }
946
+ };
947
+ if (request.omniAccount !== void 0) payload.omniAccount = request.omniAccount;
948
+ if (request.agentName !== void 0) payload.agentName = request.agentName;
949
+ await this.httpClient.patch(
837
950
  ENDPOINTS.USER_ME,
838
951
  payload
839
952
  );
840
- return {
841
- success: true,
842
- userId: response.userId || response.id,
843
- smartWallet: response.smartWallet,
844
- chains: response.chains,
845
- strategy: response.strategy,
846
- protocols: response.protocols,
847
- autoSelectProtocols: response.autoSelectProtocols,
848
- omniAccount: response.omniAccount,
849
- autocompounding: response.autocompounding,
850
- agentName: response.agentName,
851
- crosschainStrategy: response.crosschainStrategy,
852
- executorProxy: response.executorProxy,
853
- splitting: response.splitting,
854
- minSplits: response.minSplits,
855
- customization: response.customization
856
- };
953
+ return await this.getUserDetails(asset);
857
954
  } catch (error) {
858
955
  throw new Error(
859
956
  `Failed to update user profile: ${error.message}`
@@ -880,7 +977,12 @@ var _ZyfaiSDK = class _ZyfaiSDK {
880
977
  */
881
978
  async pauseAgent() {
882
979
  try {
980
+ await this.updateUserProfile({
981
+ asset: "USDC",
982
+ protocols: []
983
+ });
883
984
  const response = await this.updateUserProfile({
985
+ asset: "WETH",
884
986
  protocols: []
885
987
  });
886
988
  return response;
@@ -889,49 +991,58 @@ var _ZyfaiSDK = class _ZyfaiSDK {
889
991
  }
890
992
  }
891
993
  /**
892
- * Pause the agent by clearing all protocols
893
- * Sets the user's protocols to an empty array, effectively pausing automated operations
894
- *
895
- * @returns Response indicating success and updated user details
896
- *
897
- * @example
898
- * ```typescript
899
- * const sdk = new ZyfaiSDK({ apiKey: 'your-api-key' });
900
- *
901
- * // Connect account first
902
- * await sdk.connectAccount();
903
- *
904
- * // Pause the agent
905
- * const result = await sdk.pauseAgent();
906
- * console.log('Agent paused:', result.success);
907
- * ```
908
- */
994
+ * Resume the agent by restoring protocols based on user's strategy for each asset
995
+ * Fetches available protocols and assigns them based on each asset's strategy
996
+ *
997
+ * @returns Response indicating success and updated user details
998
+ *
999
+ * @example
1000
+ * ```typescript
1001
+ * const sdk = new ZyfaiSDK({ apiKey: 'your-api-key' });
1002
+ *
1003
+ * // Connect account first
1004
+ * await sdk.connectAccount();
1005
+ *
1006
+ * // Resume the agent
1007
+ * const result = await sdk.resumeAgent();
1008
+ * console.log('Agent resumed:', result.success);
1009
+ * ```
1010
+ */
909
1011
  async resumeAgent() {
910
1012
  try {
911
- const userDetails = await this.getUserDetails();
912
- const userChains = userDetails.user.chains;
913
- const strategy = userDetails.user.strategy || "safe_strategy";
914
- const convertedStrategy = toInternalStrategy(strategy);
915
- const chains = userChains && userChains.length > 0 ? userChains : [8453, 42161];
1013
+ const userDetailsUSDC = await this.getUserDetails("USDC");
1014
+ const userDetailsETH = await this.getUserDetails("WETH");
1015
+ const chains = userDetailsUSDC.chains && userDetailsUSDC.chains.length > 0 ? userDetailsUSDC.chains : [8453, 42161];
916
1016
  const allProtocols = await this.httpClient.get(
917
1017
  ENDPOINTS.PROTOCOLS()
918
1018
  );
919
- const filteredProtocolIds = allProtocols.filter((protocol) => {
920
- const hasMatchingChain = protocol.chains.some(
921
- (chain) => chains.includes(chain)
922
- );
923
- if (!hasMatchingChain) {
924
- return false;
925
- }
926
- if (convertedStrategy === "degen_strategy") {
927
- return protocol.strategies?.includes("safe_strategy") || protocol.strategies?.includes("degen_strategy");
928
- }
929
- return protocol.strategies?.includes("safe_strategy");
930
- }).map((protocol) => protocol.id);
931
- const response = await this.updateUserProfile({
932
- protocols: filteredProtocolIds
1019
+ const usdcStrategy = userDetailsUSDC.strategy || "safe_strategy";
1020
+ const ethStrategy = userDetailsETH.strategy || "safe_strategy";
1021
+ const filterProtocolsByStrategy = (strategy) => {
1022
+ return allProtocols.filter((protocol) => {
1023
+ const hasMatchingChain = protocol.chains.some(
1024
+ (chain) => chains.includes(chain)
1025
+ );
1026
+ if (!hasMatchingChain) {
1027
+ return false;
1028
+ }
1029
+ if (strategy === "degen_strategy") {
1030
+ return protocol.strategies?.includes("safe_strategy") || protocol.strategies?.includes("degen_strategy");
1031
+ }
1032
+ return protocol.strategies?.includes("safe_strategy");
1033
+ }).map((protocol) => protocol.id);
1034
+ };
1035
+ const usdcProtocols = filterProtocolsByStrategy(usdcStrategy);
1036
+ const ethProtocols = filterProtocolsByStrategy(ethStrategy);
1037
+ await this.updateUserProfile({
1038
+ asset: "USDC",
1039
+ protocols: usdcProtocols
933
1040
  });
934
- return response;
1041
+ const updatedUserDetailsETH = await this.updateUserProfile({
1042
+ asset: "WETH",
1043
+ protocols: ethProtocols
1044
+ });
1045
+ return updatedUserDetailsETH;
935
1046
  } catch (error) {
936
1047
  throw new Error(`Failed to resume agent: ${error.message}`);
937
1048
  }
@@ -1518,14 +1629,20 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1518
1629
  async updateUserProtocols(chainId) {
1519
1630
  try {
1520
1631
  const protocolsResponse = await this.getAvailableProtocols(chainId);
1521
- if (!protocolsResponse.protocols || protocolsResponse.protocols.length === 0) {
1632
+ const userDetails = await this.getUserDetails();
1633
+ const filteredProtocols = userDetails.strategy ? protocolsResponse.protocols.filter((p) => p.strategies?.includes(userDetails.strategy)) : protocolsResponse.protocols;
1634
+ if (!filteredProtocols || filteredProtocols.length === 0) {
1522
1635
  console.warn(`No protocols available for chain ${chainId}`);
1523
1636
  return;
1524
1637
  }
1525
- const protocolIds = protocolsResponse.protocols.map((p) => p.id);
1638
+ const protocolIds = filteredProtocols.map((p) => p.id);
1526
1639
  await this.updateUserProfile({
1527
1640
  protocols: protocolIds
1528
1641
  });
1642
+ await this.updateUserProfile({
1643
+ protocols: protocolIds,
1644
+ asset: "WETH"
1645
+ });
1529
1646
  } catch (error) {
1530
1647
  console.warn(
1531
1648
  `Failed to update user protocols: ${error.message}`
@@ -1587,7 +1704,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1587
1704
  * );
1588
1705
  * ```
1589
1706
  */
1590
- async depositFunds(userAddress, chainId, amount) {
1707
+ async depositFunds(userAddress, chainId, amount, asset) {
1591
1708
  try {
1592
1709
  if (!userAddress) {
1593
1710
  throw new Error("User address is required");
@@ -1598,7 +1715,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1598
1715
  if (!amount || isNaN(Number(amount)) || Number(amount) <= 0) {
1599
1716
  throw new Error("Valid amount is required");
1600
1717
  }
1601
- const token = getDefaultTokenAddress(chainId);
1718
+ const token = getDefaultTokenAddress(chainId, asset);
1602
1719
  const walletClient = this.getWalletClient();
1603
1720
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
1604
1721
  const safeAddress = await getDeterministicSafeAddress({
@@ -1740,7 +1857,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1740
1857
  * );
1741
1858
  * ```
1742
1859
  */
1743
- async withdrawFunds(userAddress, chainId, amount) {
1860
+ async withdrawFunds(userAddress, chainId, amount, tokenSymbol) {
1744
1861
  try {
1745
1862
  if (!userAddress) {
1746
1863
  throw new Error("User address is required");
@@ -1782,12 +1899,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1782
1899
  if (amount) {
1783
1900
  response = await this.httpClient.post(ENDPOINTS.PARTIAL_WITHDRAW, {
1784
1901
  chainId,
1785
- amount
1902
+ amount,
1903
+ tokenSymbol
1786
1904
  });
1787
1905
  } else {
1906
+ console.log("Full withdrawal", tokenSymbol);
1788
1907
  response = await this.httpClient.get(ENDPOINTS.USER_WITHDRAW, {
1789
- params: { chainId }
1908
+ params: { chainId, tokenSymbol }
1790
1909
  });
1910
+ console.log(JSON.stringify(response, null, 2));
1791
1911
  }
1792
1912
  const success = response?.success ?? true;
1793
1913
  const message = response?.message || "Withdrawal request sent";
@@ -1898,35 +2018,28 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1898
2018
  * console.log("Chains:", user.user.chains);
1899
2019
  * ```
1900
2020
  */
1901
- async getUserDetails() {
2021
+ async getUserDetails(asset = "USDC") {
1902
2022
  try {
1903
2023
  await this.authenticateUser();
1904
2024
  const response = await this.httpClient.get(ENDPOINTS.USER_ME);
2025
+ const internalAsset = convertAssetInternally(asset);
1905
2026
  const convertedResponse = convertStrategyToPublic(response);
1906
2027
  return {
1907
2028
  success: true,
1908
- user: {
1909
- id: convertedResponse.id,
1910
- address: convertedResponse.address,
1911
- smartWallet: convertedResponse.smartWallet,
1912
- chains: convertedResponse.chains || [],
1913
- protocols: convertedResponse.protocols || [],
1914
- hasActiveSessionKey: convertedResponse.hasActiveSessionKey || false,
1915
- email: convertedResponse.email,
1916
- strategy: convertedResponse.strategy,
1917
- telegramId: convertedResponse.telegramId,
1918
- walletType: convertedResponse.walletType,
1919
- autoSelectProtocols: convertedResponse.autoSelectProtocols || false,
1920
- autocompounding: convertedResponse.autocompounding,
1921
- omniAccount: convertedResponse.omniAccount,
1922
- crosschainStrategy: convertedResponse.crosschainStrategy,
1923
- agentName: convertedResponse.agentName,
1924
- customization: convertedResponse.customization,
1925
- executorProxy: convertedResponse.executorProxy,
1926
- splitting: convertedResponse.splitting,
1927
- minSplits: convertedResponse.minSplits,
1928
- registered: convertedResponse.registered
1929
- }
2029
+ agentName: convertedResponse.agentName,
2030
+ smartWallet: convertedResponse.smartWallet,
2031
+ chains: convertedResponse.assetTypeSettings?.[internalAsset]?.chains || [],
2032
+ hasActiveSessionKey: convertedResponse.hasActiveSessionKey || false,
2033
+ omniAccount: convertedResponse.omniAccount,
2034
+ asset,
2035
+ autoSelectProtocols: convertedResponse.assetTypeSettings?.[internalAsset]?.autoSelectProtocols,
2036
+ strategy: convertedResponse.assetTypeSettings?.[internalAsset]?.rebalanceStrategy,
2037
+ autocompounding: convertedResponse.assetTypeSettings?.[internalAsset]?.autocompounding,
2038
+ crosschainStrategy: convertedResponse.assetTypeSettings?.[internalAsset]?.crosschainStrategy,
2039
+ splitting: convertedResponse.assetTypeSettings?.[internalAsset]?.splitting,
2040
+ minSplits: convertedResponse.assetTypeSettings?.[internalAsset]?.minSplits || 0,
2041
+ protocols: convertedResponse.assetTypeSettings?.[internalAsset]?.protocols || [],
2042
+ customization: convertedResponse.customization
1930
2043
  };
1931
2044
  } catch (error) {
1932
2045
  throw new Error(
@@ -1951,18 +2064,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1951
2064
  async getTVL() {
1952
2065
  try {
1953
2066
  const response = await this.httpClient.get(ENDPOINTS.DATA_TVL);
1954
- const byChain = {};
1955
- for (const key of Object.keys(response)) {
1956
- const numKey = parseInt(key, 10);
1957
- if (!isNaN(numKey) && typeof response[key] === "number") {
1958
- byChain[numKey] = response[key];
1959
- }
1960
- }
1961
2067
  return {
1962
2068
  success: true,
1963
- totalTvl: response.total || response.totalTvl || response.tvl || 0,
1964
- byChain,
1965
- breakdown: response.breakdown
2069
+ totalTvl: response.total || 0
1966
2070
  };
1967
2071
  } catch (error) {
1968
2072
  throw new Error(`Failed to get TVL: ${error.message}`);
@@ -1977,20 +2081,28 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1977
2081
  * @param crossChain - Whether to get cross-chain APY (true = omni account, false = simple account)
1978
2082
  * @param days - Time period: 7, 14, or 30
1979
2083
  * @param strategy - Strategy type: "conservative" (default) or "aggressive"
2084
+ * @param chainId - Optional chain ID filter
2085
+ * @param tokenSymbol - Optional token symbol filter (e.g. "USDC", "WETH", "WBTC")
1980
2086
  * @returns APY per strategy for a specific chain
1981
2087
  *
1982
2088
  * @example
1983
2089
  * ```typescript
1984
- * const apyPerStrategy = await sdk.getAPYPerStrategy(false, 7, "conservative");
2090
+ * const apyPerStrategy = await sdk.getAPYPerStrategy(false, 7, "conservative", 8453, "USDC");
1985
2091
  * console.log("APY per strategy per chain:", apyPerStrategy.data);
1986
2092
  * ```
1987
2093
  */
1988
- async getAPYPerStrategy(crossChain = false, days = 7, strategy = "conservative") {
2094
+ async getAPYPerStrategy(crossChain = false, days = 7, strategy = "conservative", chainId, tokenSymbol) {
1989
2095
  try {
1990
2096
  const internalStrategy = toInternalStrategy(strategy);
1991
2097
  const internalStrategyShort = internalStrategy === "safe_strategy" ? "safe" : "degen";
1992
2098
  const response = await this.httpClient.dataGet(
1993
- DATA_ENDPOINTS.APY_PER_STRATEGY(crossChain, days, internalStrategyShort)
2099
+ DATA_ENDPOINTS.APY_PER_STRATEGY({
2100
+ isCrossChain: crossChain,
2101
+ days,
2102
+ strategy: internalStrategyShort,
2103
+ chainId,
2104
+ tokenSymbol
2105
+ })
1994
2106
  );
1995
2107
  const convertedData = convertStrategiesToPublicAndNaming(
1996
2108
  response.data || []
@@ -2017,9 +2129,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2017
2129
  * console.log("Total Volume:", volume.volumeInUSD);
2018
2130
  * ```
2019
2131
  */
2020
- async getVolume() {
2132
+ async getVolume(assetType = "usdc") {
2021
2133
  try {
2022
- const response = await this.httpClient.get(ENDPOINTS.DATA_VOLUME);
2134
+ const response = await this.httpClient.get(ENDPOINTS.DATA_VOLUME(assetType));
2023
2135
  return {
2024
2136
  success: true,
2025
2137
  volumeInUSD: response.volumeInUSD || "0"
@@ -2186,12 +2298,12 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2186
2298
  * Get onchain earnings for a wallet
2187
2299
  *
2188
2300
  * @param walletAddress - Smart wallet address
2189
- * @returns Onchain earnings data including total, current, and lifetime
2301
+ * @returns Onchain earnings data with per-token breakdowns
2190
2302
  *
2191
2303
  * @example
2192
2304
  * ```typescript
2193
2305
  * const earnings = await sdk.getOnchainEarnings("0x...");
2194
- * console.log("Total earnings:", earnings.data.totalEarnings);
2306
+ * console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
2195
2307
  * ```
2196
2308
  */
2197
2309
  async getOnchainEarnings(walletAddress) {
@@ -2206,13 +2318,12 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2206
2318
  success: true,
2207
2319
  data: {
2208
2320
  walletAddress,
2209
- totalEarnings: response.total_earnings || response.totalEarnings || 0,
2210
- currentEarnings: response.current_earnings || response.currentEarnings || 0,
2211
- lifetimeEarnings: response.lifetime_earnings || response.lifetimeEarnings || 0,
2212
- unrealizedEarnings: response.unrealized_earnings,
2213
- currentEarningsByChain: response.current_earnings_by_chain,
2214
- unrealizedEarningsByChain: response.unrealized_earnings_by_chain,
2215
- lastCheckTimestamp: response.last_check_timestamp
2321
+ totalEarningsByToken: response.total_earnings_by_token || {},
2322
+ lifetimeEarningsByToken: response.lifetime_earnings_by_token || {},
2323
+ currentEarningsByChain: response.current_earnings_by_chain || {},
2324
+ unrealizedEarnings: response.unrealized_earnings || {},
2325
+ lastCheckTimestamp: response.last_check_timestamp,
2326
+ lastLogDate: response.last_log_date
2216
2327
  }
2217
2328
  };
2218
2329
  } catch (error) {
@@ -2226,12 +2337,12 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2226
2337
  * This triggers a recalculation of earnings on the backend
2227
2338
  *
2228
2339
  * @param walletAddress - Smart wallet address
2229
- * @returns Updated onchain earnings data
2340
+ * @returns Updated onchain earnings data with per-token breakdowns
2230
2341
  *
2231
2342
  * @example
2232
2343
  * ```typescript
2233
2344
  * const earnings = await sdk.calculateOnchainEarnings("0x...");
2234
- * console.log("Calculated earnings:", earnings.data.totalEarnings);
2345
+ * console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
2235
2346
  * ```
2236
2347
  */
2237
2348
  async calculateOnchainEarnings(walletAddress) {
@@ -2248,11 +2359,12 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2248
2359
  success: true,
2249
2360
  data: {
2250
2361
  walletAddress,
2251
- totalEarnings: data.total_earnings || data.totalEarnings || 0,
2252
- currentEarnings: data.current_earnings || data.currentEarnings || 0,
2253
- lifetimeEarnings: data.lifetime_earnings || data.lifetimeEarnings || 0,
2254
- unrealizedEarnings: data.unrealized_earnings,
2255
- lastCheckTimestamp: data.last_check_timestamp
2362
+ totalEarningsByToken: data.total_earnings_by_token || {},
2363
+ lifetimeEarningsByToken: data.lifetime_earnings_by_token || {},
2364
+ currentEarningsByChain: data.current_earnings_by_chain || {},
2365
+ unrealizedEarnings: data.unrealized_earnings || {},
2366
+ lastCheckTimestamp: data.last_check_timestamp,
2367
+ lastLogDate: data.last_log_date
2256
2368
  }
2257
2369
  };
2258
2370
  } catch (error) {
@@ -2272,7 +2384,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2272
2384
  * @example
2273
2385
  * ```typescript
2274
2386
  * const daily = await sdk.getDailyEarnings("0x...", "2024-01-01", "2024-01-31");
2275
- * daily.data.forEach(d => console.log(d.date, d.earnings));
2387
+ * daily.data.forEach(d => console.log(d.snapshot_date, d.total_earnings_by_token));
2276
2388
  * ```
2277
2389
  */
2278
2390
  async getDailyEarnings(walletAddress, startDate, endDate) {
@@ -2300,61 +2412,25 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2300
2412
  }
2301
2413
  }
2302
2414
  // ============================================================================
2303
- // Portfolio Methods (Data API v2)
2304
- // ============================================================================
2305
- /**
2306
- * Get Debank portfolio for a wallet across multiple chains
2307
- * Note: This is a paid endpoint and may require authorization
2308
- *
2309
- * @param walletAddress - Smart wallet address
2310
- * @returns Multi-chain portfolio data
2311
- *
2312
- * @example
2313
- * ```typescript
2314
- * const portfolio = await sdk.getDebankPortfolio("0x...");
2315
- * console.log("Total value:", portfolio.totalValueUsd);
2316
- * ```
2317
- */
2318
- async getDebankPortfolio(walletAddress) {
2319
- try {
2320
- if (!walletAddress) {
2321
- throw new Error("Wallet address is required");
2322
- }
2323
- const response = await this.httpClient.dataGet(
2324
- DATA_ENDPOINTS.DEBANK_PORTFOLIO_MULTICHAIN(walletAddress)
2325
- );
2326
- const data = response.data || response;
2327
- return {
2328
- success: true,
2329
- walletAddress,
2330
- totalValueUsd: data.totalValueUsd || 0,
2331
- chains: data.chains || data
2332
- };
2333
- } catch (error) {
2334
- throw new Error(
2335
- `Failed to get Debank portfolio: ${error.message}`
2336
- );
2337
- }
2338
- }
2339
- // ============================================================================
2340
2415
  // Opportunities Methods (Data API v2)
2341
2416
  // ============================================================================
2342
2417
  /**
2343
2418
  * Get conservative (low-risk) yield opportunities
2344
2419
  *
2345
2420
  * @param chainId - Optional chain ID filter
2421
+ * @param asset - Optional asset filter (e.g. "USDC", "WETH", "WBTC")
2346
2422
  * @returns List of conservative yield opportunities
2347
2423
  *
2348
2424
  * @example
2349
2425
  * ```typescript
2350
- * const opportunities = await sdk.getConservativeOpportunities(8453);
2426
+ * const opportunities = await sdk.getConservativeOpportunities(8453, "USDC");
2351
2427
  * opportunities.data.forEach(o => console.log(o.protocolName, o.apy));
2352
2428
  * ```
2353
2429
  */
2354
- async getConservativeOpportunities(chainId) {
2430
+ async getConservativeOpportunities(chainId, asset, status) {
2355
2431
  try {
2356
2432
  const response = await this.httpClient.dataGet(
2357
- DATA_ENDPOINTS.OPPORTUNITIES_SAFE(chainId)
2433
+ DATA_ENDPOINTS.OPPORTUNITIES_SAFE(chainId, asset, status)
2358
2434
  );
2359
2435
  const data = response.data || response || [];
2360
2436
  return {
@@ -2367,7 +2443,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2367
2443
  protocolName: o.protocol_name || o.protocolName,
2368
2444
  poolName: o.pool_name || o.poolName,
2369
2445
  chainId: o.chain_id || o.chainId,
2370
- apy: o.apy || o.pool_apy || 0,
2446
+ apy: o.combined_apy || 0,
2371
2447
  tvl: o.tvl || o.zyfiTvl,
2372
2448
  asset: o.asset || o.underlying_token,
2373
2449
  risk: o.risk,
@@ -2385,18 +2461,19 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2385
2461
  * Get aggressive (high-risk, high-reward) yield opportunities
2386
2462
  *
2387
2463
  * @param chainId - Optional chain ID filter
2464
+ * @param asset - Optional asset filter (e.g. "USDC", "WETH", "WBTC")
2388
2465
  * @returns List of aggressive opportunities
2389
2466
  *
2390
2467
  * @example
2391
2468
  * ```typescript
2392
- * const opportunities = await sdk.getAggressiveOpportunities(8453);
2469
+ * const opportunities = await sdk.getAggressiveOpportunities(8453, "WETH");
2393
2470
  * opportunities.data.forEach(o => console.log(o.protocolName, o.apy));
2394
2471
  * ```
2395
2472
  */
2396
- async getAggressiveOpportunities(chainId) {
2473
+ async getAggressiveOpportunities(chainId, asset, status) {
2397
2474
  try {
2398
2475
  const response = await this.httpClient.dataGet(
2399
- DATA_ENDPOINTS.OPPORTUNITIES_DEGEN(chainId)
2476
+ DATA_ENDPOINTS.OPPORTUNITIES_DEGEN(chainId, asset, status)
2400
2477
  );
2401
2478
  const data = response.data || response || [];
2402
2479
  return {
@@ -2409,7 +2486,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2409
2486
  protocolName: o.protocol_name || o.protocolName,
2410
2487
  poolName: o.pool_name || o.poolName,
2411
2488
  chainId: o.chain_id || o.chainId,
2412
- apy: o.apy || o.pool_apy || 0,
2489
+ apy: o.combined_apy || 0,
2413
2490
  tvl: o.tvl || o.zyfiTvl,
2414
2491
  asset: o.asset || o.underlying_token,
2415
2492
  risk: o.risk,
@@ -2428,6 +2505,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2428
2505
  * Returns pool info, liquidity depth (true if > 1M), utilization rate, stability metrics, avg APY, and collateral
2429
2506
  *
2430
2507
  * @param chainId - Optional chain ID filter
2508
+ * @param asset - Optional asset filter (e.g. "USDC", "WETH", "WBTC")
2431
2509
  * @returns Active conservative opportunities with risk data
2432
2510
  *
2433
2511
  * @example
@@ -2436,10 +2514,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2436
2514
  * console.log(JSON.stringify(opps, null, 2));
2437
2515
  * ```
2438
2516
  */
2439
- async getActiveConservativeOppsRisk(chainId) {
2517
+ async getActiveConservativeOppsRisk(chainId, asset) {
2440
2518
  try {
2441
2519
  const response = await this.httpClient.dataGet(
2442
- DATA_ENDPOINTS.OPPORTUNITIES_SAFE(chainId)
2520
+ DATA_ENDPOINTS.OPPORTUNITIES_SAFE(chainId, asset)
2443
2521
  );
2444
2522
  const data = response.data || response || [];
2445
2523
  const active = Array.isArray(data) ? data.filter((o) => o.status === "live").map((o) => {
@@ -2473,6 +2551,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2473
2551
  * Returns pool info, liquidity depth (true if > 1M), utilization rate, stability metrics, avg APY, and collateral
2474
2552
  *
2475
2553
  * @param chainId - Optional chain ID filter
2554
+ * @param asset - Optional asset filter (e.g. "USDC", "WETH", "WBTC")
2476
2555
  * @returns Active aggressive opportunities with risk data
2477
2556
  *
2478
2557
  * @example
@@ -2481,10 +2560,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2481
2560
  * console.log(JSON.stringify(opps, null, 2));
2482
2561
  * ```
2483
2562
  */
2484
- async getActiveAggressiveOppsRisk(chainId) {
2563
+ async getActiveAggressiveOppsRisk(chainId, asset) {
2485
2564
  try {
2486
2565
  const response = await this.httpClient.dataGet(
2487
- DATA_ENDPOINTS.OPPORTUNITIES_DEGEN(chainId)
2566
+ DATA_ENDPOINTS.OPPORTUNITIES_DEGEN(chainId, asset)
2488
2567
  );
2489
2568
  const data = response.data || response || [];
2490
2569
  const active = Array.isArray(data) ? data.filter((o) => o.status === "live").map((o) => {
@@ -2518,10 +2597,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2518
2597
  * Builds on getActiveConservativeOppsRisk and computes higher-level status indicators
2519
2598
  *
2520
2599
  * @param chainId - Optional chain ID filter
2600
+ * @param asset - Optional asset filter (e.g. "USDC", "WETH", "WBTC")
2521
2601
  * @returns Conservative pools with status data
2522
2602
  */
2523
- async getConservativePoolStatus(chainId) {
2524
- const pools = await this.getActiveConservativeOppsRisk(chainId);
2603
+ async getConservativePoolStatus(chainId, asset) {
2604
+ const pools = await this.getActiveConservativeOppsRisk(chainId, asset);
2525
2605
  return pools.map((p) => this.derivePoolStatus(p));
2526
2606
  }
2527
2607
  /**
@@ -2529,10 +2609,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2529
2609
  * Builds on getActiveAggressiveOppsRisk and computes higher-level status indicators
2530
2610
  *
2531
2611
  * @param chainId - Optional chain ID filter
2612
+ * @param asset - Optional asset filter (e.g. "USDC", "WETH", "WBTC")
2532
2613
  * @returns Aggressive pools with status data
2533
2614
  */
2534
- async getAggressivePoolStatus(chainId) {
2535
- const pools = await this.getActiveAggressiveOppsRisk(chainId);
2615
+ async getAggressivePoolStatus(chainId, asset) {
2616
+ const pools = await this.getActiveAggressiveOppsRisk(chainId, asset);
2536
2617
  return pools.map((p) => this.derivePoolStatus(p));
2537
2618
  }
2538
2619
  derivePoolStatus(p) {
@@ -2581,12 +2662,12 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2581
2662
  *
2582
2663
  * @param walletAddress - Smart wallet address
2583
2664
  * @param days - Period: "7D", "14D", or "30D" (default: "7D")
2584
- * @returns Daily APY history with weighted averages
2665
+ * @returns Daily APY history with per-position breakdowns and weighted averages
2585
2666
  *
2586
2667
  * @example
2587
2668
  * ```typescript
2588
2669
  * const apyHistory = await sdk.getDailyApyHistory("0x...", "30D");
2589
- * console.log("Average APY:", apyHistory.averageWeightedApy);
2670
+ * console.log("Weighted APY after fee:", apyHistory.weightedApyAfterFee); // { "USDC": 4.64, "WETH": 1.94 }
2590
2671
  * ```
2591
2672
  */
2592
2673
  async getDailyApyHistory(walletAddress, days = "7D") {