@zyfai/sdk 0.2.38 → 0.2.40

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.d.mts CHANGED
@@ -422,6 +422,46 @@ interface SdkKeyTVLResponse {
422
422
  walletsCount: number;
423
423
  };
424
424
  }
425
+ interface UserPosition {
426
+ protocol: string;
427
+ pool: string;
428
+ tvl: number;
429
+ }
430
+ interface SimulateBestPositionsParams {
431
+ amount: number;
432
+ token: string;
433
+ networks: number | number[];
434
+ strategy: "conservative" | "aggressive";
435
+ minSplit?: number;
436
+ protocols?: string[];
437
+ pools?: string[];
438
+ userPositions?: UserPosition[];
439
+ }
440
+ interface SimulateCalldataItem {
441
+ contract_address: Address;
442
+ function_name: string;
443
+ parameters: string[];
444
+ value: string;
445
+ description: string;
446
+ }
447
+ interface SimulatedPosition {
448
+ protocol: string;
449
+ pool: string;
450
+ simulated_apy: number;
451
+ combined_apy: number;
452
+ amount: number;
453
+ amount_raw: string;
454
+ url: string;
455
+ tvl: number;
456
+ liquidity: number;
457
+ averageCombinedApy30Days: number;
458
+ calldata: SimulateCalldataItem[];
459
+ }
460
+ interface SimulateBestPositionsResponse {
461
+ success: boolean;
462
+ data: Record<string, SimulatedPosition[]>;
463
+ messages: Record<string, string>;
464
+ }
425
465
  interface OpportunityPosition {
426
466
  protocol: string;
427
467
  pool: string;
@@ -551,6 +591,50 @@ interface VaultSharesResponse {
551
591
  shares: bigint;
552
592
  symbol: string;
553
593
  }
594
+ interface DepegEvent {
595
+ token: string;
596
+ price: number;
597
+ deviation: number;
598
+ severity: "warning" | "critical";
599
+ previousSeverity?: string;
600
+ affectedPools: {
601
+ protocol: string;
602
+ pool: string;
603
+ chain: string;
604
+ }[];
605
+ timestamp: string;
606
+ }
607
+ interface NewCollateralDetectedEvent {
608
+ protocol: string;
609
+ pool: string;
610
+ chain: string;
611
+ asset: string;
612
+ exposureUsd: number;
613
+ percentOfTvl: number;
614
+ timestamp: string;
615
+ }
616
+ interface LiquidityDropEvent {
617
+ protocol: string;
618
+ pool: string;
619
+ chain: string;
620
+ asset: string;
621
+ previousLiquidityUsd: number;
622
+ currentLiquidityUsd: number;
623
+ dropPercent: number;
624
+ windowMinutes: number;
625
+ timestamp: string;
626
+ }
627
+ interface ZyfaiEventFilters {
628
+ chains?: string[];
629
+ protocols?: string[];
630
+ pools?: string[];
631
+ }
632
+ interface ZyfaiEventHandlers {
633
+ onDepeg?: (data: DepegEvent) => void;
634
+ onNewCollateralDetected?: (data: NewCollateralDetectedEvent) => void;
635
+ onLiquidityDrop?: (data: LiquidityDropEvent) => void;
636
+ onError?: (error: unknown) => void;
637
+ }
554
638
 
555
639
  /**
556
640
  * Chain Configuration for Zyfai SDK
@@ -1354,6 +1438,31 @@ declare class ZyfaiSDK {
1354
1438
  * ```
1355
1439
  */
1356
1440
  getAvailablePools(protocolId: string, strategy?: "conservative" | "aggressive"): Promise<GetPoolsResponse>;
1441
+ /**
1442
+ * Simulate the best yield positions for a given amount, splitting it across
1443
+ * the top-ranked pools (up to minSplit positions) for the requested chains/strategy.
1444
+ *
1445
+ * Returns ready-to-execute calldata (approve + deposit) per position. The deposit
1446
+ * calldata contains a "<RECEIVER>" placeholder that must be replaced with the
1447
+ * actual receiving address (e.g. the user's Safe) before sending the transaction.
1448
+ *
1449
+ * @param params - Simulation parameters
1450
+ * @returns Chain-keyed map of simulated positions with calldata
1451
+ *
1452
+ * @example
1453
+ * ```typescript
1454
+ * const result = await sdk.simulateBestPositions({
1455
+ * amount: 3000,
1456
+ * token: "USDC",
1457
+ * networks: 8453,
1458
+ * strategy: "conservative",
1459
+ * minSplit: 3,
1460
+ * protocols: ["aave", "compound", "morpho"],
1461
+ * });
1462
+ * console.log(result.data["8453"]);
1463
+ * ```
1464
+ */
1465
+ simulateBestPositions(params: SimulateBestPositionsParams): Promise<SimulateBestPositionsResponse>;
1357
1466
  /**
1358
1467
  * Get currently selected pools for a protocol on a specific chain.
1359
1468
  *
@@ -1478,6 +1587,31 @@ declare class ZyfaiSDK {
1478
1587
  * ```
1479
1588
  */
1480
1589
  getVaultShares(userAddress?: string, chainId?: SupportedChainId): Promise<VaultSharesResponse>;
1590
+ /**
1591
+ * Subscribe to real-time Zyfai risk and liquidity events via WebSocket.
1592
+ *
1593
+ * Events: depeg, liquidity_trap, liquidity_restored, pool_status_change,
1594
+ * new_collateral_detected, liquidity_drop.
1595
+ *
1596
+ * @param handlers - Callback per event type, plus onError
1597
+ * @param filters - Optional protocol/pool filter sent to the server on subscribe
1598
+ * @returns Cleanup function — call it to close the connection
1599
+ *
1600
+ * @example
1601
+ * ```typescript
1602
+ * const unsubscribe = sdk.subscribeToEvents(
1603
+ * {
1604
+ * onDepeg: (data) => console.log("Depeg detected:", data.token, data.severity),
1605
+ * onLiquidityDrop: (data) => console.log("Liquidity drop:", data.pool, data.dropPercent),
1606
+ * },
1607
+ * { protocols: ["morpho"], pools: ["gauntlet usdc core"] }
1608
+ * );
1609
+ *
1610
+ * // Later, close the connection:
1611
+ * unsubscribe();
1612
+ * ```
1613
+ */
1614
+ subscribeToEvents(handlers: ZyfaiEventHandlers, filters?: ZyfaiEventFilters): () => void;
1481
1615
  }
1482
1616
 
1483
1617
  /**
@@ -1541,4 +1675,4 @@ type BankrProvider = ReturnType<typeof createBankrProvider>;
1541
1675
 
1542
1676
  declare const VAULT_ADDRESS: "0xD580071c47d4a667858B5FafAb85BC9C609beC5D";
1543
1677
 
1544
- 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 DeploySafeResponse, type DepositResponse, type ERC7739Context, type ERC7739Data, type FirstTopupResponse, type GetPoolsResponse, type GetSelectedPoolsResponse, type Hex, type HistoryEntry, type HistoryPosition, type HistoryResponse, type LogDepositResponse, 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 SmartWalletByEOAResponse, type SmartWalletResponse, type Strategy, type SupportedChainId, type TVLResponse, type TokenApy, type TokenEarnings, type UpdateUserProfileRequest, type UpdateUserProfileResponse, VAULT_ADDRESS, type VaultAsset, type VaultClaimResponse, type VaultDepositResponse, type VaultSharesResponse, type VaultWithdrawResponse, type VaultWithdrawStatusResponse, type VolumeResponse, type WalletTVL, type WithdrawResponse, ZyfaiSDK, createBankrProvider, getChainConfig, getDefaultTokenAddress, getSupportedChainIds, isSupportedChain };
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 };
package/dist/index.d.ts CHANGED
@@ -422,6 +422,46 @@ interface SdkKeyTVLResponse {
422
422
  walletsCount: number;
423
423
  };
424
424
  }
425
+ interface UserPosition {
426
+ protocol: string;
427
+ pool: string;
428
+ tvl: number;
429
+ }
430
+ interface SimulateBestPositionsParams {
431
+ amount: number;
432
+ token: string;
433
+ networks: number | number[];
434
+ strategy: "conservative" | "aggressive";
435
+ minSplit?: number;
436
+ protocols?: string[];
437
+ pools?: string[];
438
+ userPositions?: UserPosition[];
439
+ }
440
+ interface SimulateCalldataItem {
441
+ contract_address: Address;
442
+ function_name: string;
443
+ parameters: string[];
444
+ value: string;
445
+ description: string;
446
+ }
447
+ interface SimulatedPosition {
448
+ protocol: string;
449
+ pool: string;
450
+ simulated_apy: number;
451
+ combined_apy: number;
452
+ amount: number;
453
+ amount_raw: string;
454
+ url: string;
455
+ tvl: number;
456
+ liquidity: number;
457
+ averageCombinedApy30Days: number;
458
+ calldata: SimulateCalldataItem[];
459
+ }
460
+ interface SimulateBestPositionsResponse {
461
+ success: boolean;
462
+ data: Record<string, SimulatedPosition[]>;
463
+ messages: Record<string, string>;
464
+ }
425
465
  interface OpportunityPosition {
426
466
  protocol: string;
427
467
  pool: string;
@@ -551,6 +591,50 @@ interface VaultSharesResponse {
551
591
  shares: bigint;
552
592
  symbol: string;
553
593
  }
594
+ interface DepegEvent {
595
+ token: string;
596
+ price: number;
597
+ deviation: number;
598
+ severity: "warning" | "critical";
599
+ previousSeverity?: string;
600
+ affectedPools: {
601
+ protocol: string;
602
+ pool: string;
603
+ chain: string;
604
+ }[];
605
+ timestamp: string;
606
+ }
607
+ interface NewCollateralDetectedEvent {
608
+ protocol: string;
609
+ pool: string;
610
+ chain: string;
611
+ asset: string;
612
+ exposureUsd: number;
613
+ percentOfTvl: number;
614
+ timestamp: string;
615
+ }
616
+ interface LiquidityDropEvent {
617
+ protocol: string;
618
+ pool: string;
619
+ chain: string;
620
+ asset: string;
621
+ previousLiquidityUsd: number;
622
+ currentLiquidityUsd: number;
623
+ dropPercent: number;
624
+ windowMinutes: number;
625
+ timestamp: string;
626
+ }
627
+ interface ZyfaiEventFilters {
628
+ chains?: string[];
629
+ protocols?: string[];
630
+ pools?: string[];
631
+ }
632
+ interface ZyfaiEventHandlers {
633
+ onDepeg?: (data: DepegEvent) => void;
634
+ onNewCollateralDetected?: (data: NewCollateralDetectedEvent) => void;
635
+ onLiquidityDrop?: (data: LiquidityDropEvent) => void;
636
+ onError?: (error: unknown) => void;
637
+ }
554
638
 
555
639
  /**
556
640
  * Chain Configuration for Zyfai SDK
@@ -1354,6 +1438,31 @@ declare class ZyfaiSDK {
1354
1438
  * ```
1355
1439
  */
1356
1440
  getAvailablePools(protocolId: string, strategy?: "conservative" | "aggressive"): Promise<GetPoolsResponse>;
1441
+ /**
1442
+ * Simulate the best yield positions for a given amount, splitting it across
1443
+ * the top-ranked pools (up to minSplit positions) for the requested chains/strategy.
1444
+ *
1445
+ * Returns ready-to-execute calldata (approve + deposit) per position. The deposit
1446
+ * calldata contains a "<RECEIVER>" placeholder that must be replaced with the
1447
+ * actual receiving address (e.g. the user's Safe) before sending the transaction.
1448
+ *
1449
+ * @param params - Simulation parameters
1450
+ * @returns Chain-keyed map of simulated positions with calldata
1451
+ *
1452
+ * @example
1453
+ * ```typescript
1454
+ * const result = await sdk.simulateBestPositions({
1455
+ * amount: 3000,
1456
+ * token: "USDC",
1457
+ * networks: 8453,
1458
+ * strategy: "conservative",
1459
+ * minSplit: 3,
1460
+ * protocols: ["aave", "compound", "morpho"],
1461
+ * });
1462
+ * console.log(result.data["8453"]);
1463
+ * ```
1464
+ */
1465
+ simulateBestPositions(params: SimulateBestPositionsParams): Promise<SimulateBestPositionsResponse>;
1357
1466
  /**
1358
1467
  * Get currently selected pools for a protocol on a specific chain.
1359
1468
  *
@@ -1478,6 +1587,31 @@ declare class ZyfaiSDK {
1478
1587
  * ```
1479
1588
  */
1480
1589
  getVaultShares(userAddress?: string, chainId?: SupportedChainId): Promise<VaultSharesResponse>;
1590
+ /**
1591
+ * Subscribe to real-time Zyfai risk and liquidity events via WebSocket.
1592
+ *
1593
+ * Events: depeg, liquidity_trap, liquidity_restored, pool_status_change,
1594
+ * new_collateral_detected, liquidity_drop.
1595
+ *
1596
+ * @param handlers - Callback per event type, plus onError
1597
+ * @param filters - Optional protocol/pool filter sent to the server on subscribe
1598
+ * @returns Cleanup function — call it to close the connection
1599
+ *
1600
+ * @example
1601
+ * ```typescript
1602
+ * const unsubscribe = sdk.subscribeToEvents(
1603
+ * {
1604
+ * onDepeg: (data) => console.log("Depeg detected:", data.token, data.severity),
1605
+ * onLiquidityDrop: (data) => console.log("Liquidity drop:", data.pool, data.dropPercent),
1606
+ * },
1607
+ * { protocols: ["morpho"], pools: ["gauntlet usdc core"] }
1608
+ * );
1609
+ *
1610
+ * // Later, close the connection:
1611
+ * unsubscribe();
1612
+ * ```
1613
+ */
1614
+ subscribeToEvents(handlers: ZyfaiEventHandlers, filters?: ZyfaiEventFilters): () => void;
1481
1615
  }
1482
1616
 
1483
1617
  /**
@@ -1541,4 +1675,4 @@ type BankrProvider = ReturnType<typeof createBankrProvider>;
1541
1675
 
1542
1676
  declare const VAULT_ADDRESS: "0xD580071c47d4a667858B5FafAb85BC9C609beC5D";
1543
1677
 
1544
- 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 DeploySafeResponse, type DepositResponse, type ERC7739Context, type ERC7739Data, type FirstTopupResponse, type GetPoolsResponse, type GetSelectedPoolsResponse, type Hex, type HistoryEntry, type HistoryPosition, type HistoryResponse, type LogDepositResponse, 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 SmartWalletByEOAResponse, type SmartWalletResponse, type Strategy, type SupportedChainId, type TVLResponse, type TokenApy, type TokenEarnings, type UpdateUserProfileRequest, type UpdateUserProfileResponse, VAULT_ADDRESS, type VaultAsset, type VaultClaimResponse, type VaultDepositResponse, type VaultSharesResponse, type VaultWithdrawResponse, type VaultWithdrawStatusResponse, type VolumeResponse, type WalletTVL, type WithdrawResponse, ZyfaiSDK, createBankrProvider, getChainConfig, getDefaultTokenAddress, getSupportedChainIds, isSupportedChain };
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 };
package/dist/index.js CHANGED
@@ -47,6 +47,7 @@ var import_axios = __toESM(require("axios"));
47
47
  // src/config/endpoints.ts
48
48
  var API_ENDPOINT = "https://api.zyf.ai";
49
49
  var DATA_API_ENDPOINT = "https://defiapi.zyf.ai";
50
+ var WS_ENDPOINT = "wss://defiapi.zyf.ai/ws/events";
50
51
  var API_VERSION = "/api/v1";
51
52
  var DATA_API_VERSION = "/api/v2";
52
53
  var ENDPOINTS = {
@@ -80,6 +81,21 @@ var ENDPOINTS = {
80
81
  SDK_TVL: "/data/sdk-tvl",
81
82
  // Agent Identity Registry
82
83
  AGENT_TOKEN_URI: "/users/me/agent-token-uri",
84
+ // Simulation
85
+ SIMULATE_BEST_POSITIONS: (params) => {
86
+ const networks = Array.isArray(params.networks) ? params.networks.join(",") : params.networks;
87
+ const query = [
88
+ `amount=${params.amount}`,
89
+ `token=${params.token}`,
90
+ `networks=${networks}`,
91
+ `strategy=${params.strategy}`
92
+ ];
93
+ if (params.minSplit !== void 0) query.push(`minSplit=${params.minSplit}`);
94
+ if (params.protocols?.length) query.push(`protocols=${params.protocols.join(",")}`);
95
+ if (params.pools?.length) query.push(`pools=${params.pools.join(",")}`);
96
+ if (params.userPositions?.length) query.push(`userPositions=${encodeURIComponent(JSON.stringify(params.userPositions))}`);
97
+ return `/simulate/best-positions?${query.join("&")}`;
98
+ },
83
99
  // Customization
84
100
  CUSTOMIZE_BATCH: "/customization/customize-batch",
85
101
  CUSTOMIZATION_POOLS: (protocolId, strategy) => `/customization/pools?protocolId=${protocolId}${strategy ? `&strategy=${strategy}` : ""}`,
@@ -479,15 +495,21 @@ var VAULT_ADDRESS = "0xD580071c47d4a667858B5FafAb85BC9C609beC5D";
479
495
  // src/config/constants.ts
480
496
  var MIN_PORTFOLIO_BALANCE = {
481
497
  1: {
482
- USDC: 10000n * 10n ** 6n,
483
- // 10,000 USDC (6 decimals)
484
- WETH: 5n * 10n ** 18n
485
- // 5 WETH (18 decimals)
498
+ USDC: 100n * 10n ** 6n,
499
+ // 100 USDC (6 decimals)
500
+ WETH: 5n * 10n ** 15n
501
+ // 0.005 WETH (18 decimals)
486
502
  }
487
503
  };
488
504
  var formatMinPortfolioLabel = (raw, decimals, symbol) => {
489
- const whole = raw / 10n ** BigInt(decimals);
490
- return `${whole.toString()} ${symbol}`;
505
+ const base2 = 10n ** BigInt(decimals);
506
+ const whole = raw / base2;
507
+ const fraction = raw % base2;
508
+ if (fraction === 0n) {
509
+ return `${whole.toString()} ${symbol}`;
510
+ }
511
+ const fractionStr = fraction.toString().padStart(decimals, "0").replace(/0+$/, "");
512
+ return `${whole.toString()}.${fractionStr} ${symbol}`;
491
513
  };
492
514
 
493
515
  // src/core/ZyfaiSDK.ts
@@ -3095,6 +3117,54 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3095
3117
  );
3096
3118
  }
3097
3119
  }
3120
+ // ============================================================================
3121
+ // Simulation
3122
+ // ============================================================================
3123
+ /**
3124
+ * Simulate the best yield positions for a given amount, splitting it across
3125
+ * the top-ranked pools (up to minSplit positions) for the requested chains/strategy.
3126
+ *
3127
+ * Returns ready-to-execute calldata (approve + deposit) per position. The deposit
3128
+ * calldata contains a "<RECEIVER>" placeholder that must be replaced with the
3129
+ * actual receiving address (e.g. the user's Safe) before sending the transaction.
3130
+ *
3131
+ * @param params - Simulation parameters
3132
+ * @returns Chain-keyed map of simulated positions with calldata
3133
+ *
3134
+ * @example
3135
+ * ```typescript
3136
+ * const result = await sdk.simulateBestPositions({
3137
+ * amount: 3000,
3138
+ * token: "USDC",
3139
+ * networks: 8453,
3140
+ * strategy: "conservative",
3141
+ * minSplit: 3,
3142
+ * protocols: ["aave", "compound", "morpho"],
3143
+ * });
3144
+ * console.log(result.data["8453"]);
3145
+ * ```
3146
+ */
3147
+ async simulateBestPositions(params) {
3148
+ try {
3149
+ if (!isValidPublicStrategy(params.strategy)) {
3150
+ throw new Error(
3151
+ `Invalid strategy: ${params.strategy}. Must be "conservative" or "aggressive".`
3152
+ );
3153
+ }
3154
+ const internalStrategy = toInternalStrategy(params.strategy);
3155
+ const response = await this.httpClient.get(
3156
+ ENDPOINTS.SIMULATE_BEST_POSITIONS({
3157
+ ...params,
3158
+ strategy: internalStrategy
3159
+ })
3160
+ );
3161
+ return response;
3162
+ } catch (error) {
3163
+ throw new Error(
3164
+ `Failed to simulate best positions: ${error.message}`
3165
+ );
3166
+ }
3167
+ }
3098
3168
  /**
3099
3169
  * Get currently selected pools for a protocol on a specific chain.
3100
3170
  *
@@ -3537,6 +3607,78 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3537
3607
  symbol: tokenSymbol
3538
3608
  };
3539
3609
  }
3610
+ // ============================================================================
3611
+ // WebSocket Event Stream
3612
+ // ============================================================================
3613
+ /**
3614
+ * Subscribe to real-time Zyfai risk and liquidity events via WebSocket.
3615
+ *
3616
+ * Events: depeg, liquidity_trap, liquidity_restored, pool_status_change,
3617
+ * new_collateral_detected, liquidity_drop.
3618
+ *
3619
+ * @param handlers - Callback per event type, plus onError
3620
+ * @param filters - Optional protocol/pool filter sent to the server on subscribe
3621
+ * @returns Cleanup function — call it to close the connection
3622
+ *
3623
+ * @example
3624
+ * ```typescript
3625
+ * const unsubscribe = sdk.subscribeToEvents(
3626
+ * {
3627
+ * onDepeg: (data) => console.log("Depeg detected:", data.token, data.severity),
3628
+ * onLiquidityDrop: (data) => console.log("Liquidity drop:", data.pool, data.dropPercent),
3629
+ * },
3630
+ * { protocols: ["morpho"], pools: ["gauntlet usdc core"] }
3631
+ * );
3632
+ *
3633
+ * // Later, close the connection:
3634
+ * unsubscribe();
3635
+ * ```
3636
+ */
3637
+ subscribeToEvents(handlers, filters) {
3638
+ let ws = null;
3639
+ let closed = false;
3640
+ const connect = () => {
3641
+ ws = new globalThis.WebSocket(WS_ENDPOINT);
3642
+ ws.onopen = () => {
3643
+ const msg = { type: "subscribe" };
3644
+ if (filters && (filters.chains?.length || filters.protocols?.length || filters.pools?.length)) {
3645
+ msg.filters = filters;
3646
+ }
3647
+ ws.send(JSON.stringify(msg));
3648
+ };
3649
+ ws.onmessage = (event) => {
3650
+ try {
3651
+ const msg = JSON.parse(event.data);
3652
+ if (msg.type !== "event") return;
3653
+ switch (msg.eventType) {
3654
+ case "depeg":
3655
+ handlers.onDepeg?.(msg.data);
3656
+ break;
3657
+ case "new_collateral_detected":
3658
+ handlers.onNewCollateralDetected?.(msg.data);
3659
+ break;
3660
+ case "liquidity_drop":
3661
+ handlers.onLiquidityDrop?.(msg.data);
3662
+ break;
3663
+ }
3664
+ } catch {
3665
+ }
3666
+ };
3667
+ ws.onerror = (error) => {
3668
+ handlers.onError?.(error);
3669
+ };
3670
+ ws.onclose = () => {
3671
+ if (!closed) {
3672
+ setTimeout(connect, 3e3);
3673
+ }
3674
+ };
3675
+ };
3676
+ connect();
3677
+ return () => {
3678
+ closed = true;
3679
+ ws?.close();
3680
+ };
3681
+ }
3540
3682
  };
3541
3683
  // ============================================================================
3542
3684
  // Agent Identity Registry
package/dist/index.mjs CHANGED
@@ -4,6 +4,7 @@ import axios from "axios";
4
4
  // src/config/endpoints.ts
5
5
  var API_ENDPOINT = "https://api.zyf.ai";
6
6
  var DATA_API_ENDPOINT = "https://defiapi.zyf.ai";
7
+ var WS_ENDPOINT = "wss://defiapi.zyf.ai/ws/events";
7
8
  var API_VERSION = "/api/v1";
8
9
  var DATA_API_VERSION = "/api/v2";
9
10
  var ENDPOINTS = {
@@ -37,6 +38,21 @@ var ENDPOINTS = {
37
38
  SDK_TVL: "/data/sdk-tvl",
38
39
  // Agent Identity Registry
39
40
  AGENT_TOKEN_URI: "/users/me/agent-token-uri",
41
+ // Simulation
42
+ SIMULATE_BEST_POSITIONS: (params) => {
43
+ const networks = Array.isArray(params.networks) ? params.networks.join(",") : params.networks;
44
+ const query = [
45
+ `amount=${params.amount}`,
46
+ `token=${params.token}`,
47
+ `networks=${networks}`,
48
+ `strategy=${params.strategy}`
49
+ ];
50
+ if (params.minSplit !== void 0) query.push(`minSplit=${params.minSplit}`);
51
+ if (params.protocols?.length) query.push(`protocols=${params.protocols.join(",")}`);
52
+ if (params.pools?.length) query.push(`pools=${params.pools.join(",")}`);
53
+ if (params.userPositions?.length) query.push(`userPositions=${encodeURIComponent(JSON.stringify(params.userPositions))}`);
54
+ return `/simulate/best-positions?${query.join("&")}`;
55
+ },
40
56
  // Customization
41
57
  CUSTOMIZE_BATCH: "/customization/customize-batch",
42
58
  CUSTOMIZATION_POOLS: (protocolId, strategy) => `/customization/pools?protocolId=${protocolId}${strategy ? `&strategy=${strategy}` : ""}`,
@@ -436,15 +452,21 @@ var VAULT_ADDRESS = "0xD580071c47d4a667858B5FafAb85BC9C609beC5D";
436
452
  // src/config/constants.ts
437
453
  var MIN_PORTFOLIO_BALANCE = {
438
454
  1: {
439
- USDC: 10000n * 10n ** 6n,
440
- // 10,000 USDC (6 decimals)
441
- WETH: 5n * 10n ** 18n
442
- // 5 WETH (18 decimals)
455
+ USDC: 100n * 10n ** 6n,
456
+ // 100 USDC (6 decimals)
457
+ WETH: 5n * 10n ** 15n
458
+ // 0.005 WETH (18 decimals)
443
459
  }
444
460
  };
445
461
  var formatMinPortfolioLabel = (raw, decimals, symbol) => {
446
- const whole = raw / 10n ** BigInt(decimals);
447
- return `${whole.toString()} ${symbol}`;
462
+ const base2 = 10n ** BigInt(decimals);
463
+ const whole = raw / base2;
464
+ const fraction = raw % base2;
465
+ if (fraction === 0n) {
466
+ return `${whole.toString()} ${symbol}`;
467
+ }
468
+ const fractionStr = fraction.toString().padStart(decimals, "0").replace(/0+$/, "");
469
+ return `${whole.toString()}.${fractionStr} ${symbol}`;
448
470
  };
449
471
 
450
472
  // src/core/ZyfaiSDK.ts
@@ -3071,6 +3093,54 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3071
3093
  );
3072
3094
  }
3073
3095
  }
3096
+ // ============================================================================
3097
+ // Simulation
3098
+ // ============================================================================
3099
+ /**
3100
+ * Simulate the best yield positions for a given amount, splitting it across
3101
+ * the top-ranked pools (up to minSplit positions) for the requested chains/strategy.
3102
+ *
3103
+ * Returns ready-to-execute calldata (approve + deposit) per position. The deposit
3104
+ * calldata contains a "<RECEIVER>" placeholder that must be replaced with the
3105
+ * actual receiving address (e.g. the user's Safe) before sending the transaction.
3106
+ *
3107
+ * @param params - Simulation parameters
3108
+ * @returns Chain-keyed map of simulated positions with calldata
3109
+ *
3110
+ * @example
3111
+ * ```typescript
3112
+ * const result = await sdk.simulateBestPositions({
3113
+ * amount: 3000,
3114
+ * token: "USDC",
3115
+ * networks: 8453,
3116
+ * strategy: "conservative",
3117
+ * minSplit: 3,
3118
+ * protocols: ["aave", "compound", "morpho"],
3119
+ * });
3120
+ * console.log(result.data["8453"]);
3121
+ * ```
3122
+ */
3123
+ async simulateBestPositions(params) {
3124
+ try {
3125
+ if (!isValidPublicStrategy(params.strategy)) {
3126
+ throw new Error(
3127
+ `Invalid strategy: ${params.strategy}. Must be "conservative" or "aggressive".`
3128
+ );
3129
+ }
3130
+ const internalStrategy = toInternalStrategy(params.strategy);
3131
+ const response = await this.httpClient.get(
3132
+ ENDPOINTS.SIMULATE_BEST_POSITIONS({
3133
+ ...params,
3134
+ strategy: internalStrategy
3135
+ })
3136
+ );
3137
+ return response;
3138
+ } catch (error) {
3139
+ throw new Error(
3140
+ `Failed to simulate best positions: ${error.message}`
3141
+ );
3142
+ }
3143
+ }
3074
3144
  /**
3075
3145
  * Get currently selected pools for a protocol on a specific chain.
3076
3146
  *
@@ -3513,6 +3583,78 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3513
3583
  symbol: tokenSymbol
3514
3584
  };
3515
3585
  }
3586
+ // ============================================================================
3587
+ // WebSocket Event Stream
3588
+ // ============================================================================
3589
+ /**
3590
+ * Subscribe to real-time Zyfai risk and liquidity events via WebSocket.
3591
+ *
3592
+ * Events: depeg, liquidity_trap, liquidity_restored, pool_status_change,
3593
+ * new_collateral_detected, liquidity_drop.
3594
+ *
3595
+ * @param handlers - Callback per event type, plus onError
3596
+ * @param filters - Optional protocol/pool filter sent to the server on subscribe
3597
+ * @returns Cleanup function — call it to close the connection
3598
+ *
3599
+ * @example
3600
+ * ```typescript
3601
+ * const unsubscribe = sdk.subscribeToEvents(
3602
+ * {
3603
+ * onDepeg: (data) => console.log("Depeg detected:", data.token, data.severity),
3604
+ * onLiquidityDrop: (data) => console.log("Liquidity drop:", data.pool, data.dropPercent),
3605
+ * },
3606
+ * { protocols: ["morpho"], pools: ["gauntlet usdc core"] }
3607
+ * );
3608
+ *
3609
+ * // Later, close the connection:
3610
+ * unsubscribe();
3611
+ * ```
3612
+ */
3613
+ subscribeToEvents(handlers, filters) {
3614
+ let ws = null;
3615
+ let closed = false;
3616
+ const connect = () => {
3617
+ ws = new globalThis.WebSocket(WS_ENDPOINT);
3618
+ ws.onopen = () => {
3619
+ const msg = { type: "subscribe" };
3620
+ if (filters && (filters.chains?.length || filters.protocols?.length || filters.pools?.length)) {
3621
+ msg.filters = filters;
3622
+ }
3623
+ ws.send(JSON.stringify(msg));
3624
+ };
3625
+ ws.onmessage = (event) => {
3626
+ try {
3627
+ const msg = JSON.parse(event.data);
3628
+ if (msg.type !== "event") return;
3629
+ switch (msg.eventType) {
3630
+ case "depeg":
3631
+ handlers.onDepeg?.(msg.data);
3632
+ break;
3633
+ case "new_collateral_detected":
3634
+ handlers.onNewCollateralDetected?.(msg.data);
3635
+ break;
3636
+ case "liquidity_drop":
3637
+ handlers.onLiquidityDrop?.(msg.data);
3638
+ break;
3639
+ }
3640
+ } catch {
3641
+ }
3642
+ };
3643
+ ws.onerror = (error) => {
3644
+ handlers.onError?.(error);
3645
+ };
3646
+ ws.onclose = () => {
3647
+ if (!closed) {
3648
+ setTimeout(connect, 3e3);
3649
+ }
3650
+ };
3651
+ };
3652
+ connect();
3653
+ return () => {
3654
+ closed = true;
3655
+ ws?.close();
3656
+ };
3657
+ }
3516
3658
  };
3517
3659
  // ============================================================================
3518
3660
  // Agent Identity Registry
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zyfai/sdk",
3
- "version": "0.2.38",
3
+ "version": "0.2.40",
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",