@zyfai/sdk 0.2.38 → 0.2.39

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}` : ""}`,
@@ -3095,6 +3111,54 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3095
3111
  );
3096
3112
  }
3097
3113
  }
3114
+ // ============================================================================
3115
+ // Simulation
3116
+ // ============================================================================
3117
+ /**
3118
+ * Simulate the best yield positions for a given amount, splitting it across
3119
+ * the top-ranked pools (up to minSplit positions) for the requested chains/strategy.
3120
+ *
3121
+ * Returns ready-to-execute calldata (approve + deposit) per position. The deposit
3122
+ * calldata contains a "<RECEIVER>" placeholder that must be replaced with the
3123
+ * actual receiving address (e.g. the user's Safe) before sending the transaction.
3124
+ *
3125
+ * @param params - Simulation parameters
3126
+ * @returns Chain-keyed map of simulated positions with calldata
3127
+ *
3128
+ * @example
3129
+ * ```typescript
3130
+ * const result = await sdk.simulateBestPositions({
3131
+ * amount: 3000,
3132
+ * token: "USDC",
3133
+ * networks: 8453,
3134
+ * strategy: "conservative",
3135
+ * minSplit: 3,
3136
+ * protocols: ["aave", "compound", "morpho"],
3137
+ * });
3138
+ * console.log(result.data["8453"]);
3139
+ * ```
3140
+ */
3141
+ async simulateBestPositions(params) {
3142
+ try {
3143
+ if (!isValidPublicStrategy(params.strategy)) {
3144
+ throw new Error(
3145
+ `Invalid strategy: ${params.strategy}. Must be "conservative" or "aggressive".`
3146
+ );
3147
+ }
3148
+ const internalStrategy = toInternalStrategy(params.strategy);
3149
+ const response = await this.httpClient.get(
3150
+ ENDPOINTS.SIMULATE_BEST_POSITIONS({
3151
+ ...params,
3152
+ strategy: internalStrategy
3153
+ })
3154
+ );
3155
+ return response;
3156
+ } catch (error) {
3157
+ throw new Error(
3158
+ `Failed to simulate best positions: ${error.message}`
3159
+ );
3160
+ }
3161
+ }
3098
3162
  /**
3099
3163
  * Get currently selected pools for a protocol on a specific chain.
3100
3164
  *
@@ -3537,6 +3601,78 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3537
3601
  symbol: tokenSymbol
3538
3602
  };
3539
3603
  }
3604
+ // ============================================================================
3605
+ // WebSocket Event Stream
3606
+ // ============================================================================
3607
+ /**
3608
+ * Subscribe to real-time Zyfai risk and liquidity events via WebSocket.
3609
+ *
3610
+ * Events: depeg, liquidity_trap, liquidity_restored, pool_status_change,
3611
+ * new_collateral_detected, liquidity_drop.
3612
+ *
3613
+ * @param handlers - Callback per event type, plus onError
3614
+ * @param filters - Optional protocol/pool filter sent to the server on subscribe
3615
+ * @returns Cleanup function — call it to close the connection
3616
+ *
3617
+ * @example
3618
+ * ```typescript
3619
+ * const unsubscribe = sdk.subscribeToEvents(
3620
+ * {
3621
+ * onDepeg: (data) => console.log("Depeg detected:", data.token, data.severity),
3622
+ * onLiquidityDrop: (data) => console.log("Liquidity drop:", data.pool, data.dropPercent),
3623
+ * },
3624
+ * { protocols: ["morpho"], pools: ["gauntlet usdc core"] }
3625
+ * );
3626
+ *
3627
+ * // Later, close the connection:
3628
+ * unsubscribe();
3629
+ * ```
3630
+ */
3631
+ subscribeToEvents(handlers, filters) {
3632
+ let ws = null;
3633
+ let closed = false;
3634
+ const connect = () => {
3635
+ ws = new globalThis.WebSocket(WS_ENDPOINT);
3636
+ ws.onopen = () => {
3637
+ const msg = { type: "subscribe" };
3638
+ if (filters && (filters.chains?.length || filters.protocols?.length || filters.pools?.length)) {
3639
+ msg.filters = filters;
3640
+ }
3641
+ ws.send(JSON.stringify(msg));
3642
+ };
3643
+ ws.onmessage = (event) => {
3644
+ try {
3645
+ const msg = JSON.parse(event.data);
3646
+ if (msg.type !== "event") return;
3647
+ switch (msg.eventType) {
3648
+ case "depeg":
3649
+ handlers.onDepeg?.(msg.data);
3650
+ break;
3651
+ case "new_collateral_detected":
3652
+ handlers.onNewCollateralDetected?.(msg.data);
3653
+ break;
3654
+ case "liquidity_drop":
3655
+ handlers.onLiquidityDrop?.(msg.data);
3656
+ break;
3657
+ }
3658
+ } catch {
3659
+ }
3660
+ };
3661
+ ws.onerror = (error) => {
3662
+ handlers.onError?.(error);
3663
+ };
3664
+ ws.onclose = () => {
3665
+ if (!closed) {
3666
+ setTimeout(connect, 3e3);
3667
+ }
3668
+ };
3669
+ };
3670
+ connect();
3671
+ return () => {
3672
+ closed = true;
3673
+ ws?.close();
3674
+ };
3675
+ }
3540
3676
  };
3541
3677
  // ============================================================================
3542
3678
  // 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}` : ""}`,
@@ -3071,6 +3087,54 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3071
3087
  );
3072
3088
  }
3073
3089
  }
3090
+ // ============================================================================
3091
+ // Simulation
3092
+ // ============================================================================
3093
+ /**
3094
+ * Simulate the best yield positions for a given amount, splitting it across
3095
+ * the top-ranked pools (up to minSplit positions) for the requested chains/strategy.
3096
+ *
3097
+ * Returns ready-to-execute calldata (approve + deposit) per position. The deposit
3098
+ * calldata contains a "<RECEIVER>" placeholder that must be replaced with the
3099
+ * actual receiving address (e.g. the user's Safe) before sending the transaction.
3100
+ *
3101
+ * @param params - Simulation parameters
3102
+ * @returns Chain-keyed map of simulated positions with calldata
3103
+ *
3104
+ * @example
3105
+ * ```typescript
3106
+ * const result = await sdk.simulateBestPositions({
3107
+ * amount: 3000,
3108
+ * token: "USDC",
3109
+ * networks: 8453,
3110
+ * strategy: "conservative",
3111
+ * minSplit: 3,
3112
+ * protocols: ["aave", "compound", "morpho"],
3113
+ * });
3114
+ * console.log(result.data["8453"]);
3115
+ * ```
3116
+ */
3117
+ async simulateBestPositions(params) {
3118
+ try {
3119
+ if (!isValidPublicStrategy(params.strategy)) {
3120
+ throw new Error(
3121
+ `Invalid strategy: ${params.strategy}. Must be "conservative" or "aggressive".`
3122
+ );
3123
+ }
3124
+ const internalStrategy = toInternalStrategy(params.strategy);
3125
+ const response = await this.httpClient.get(
3126
+ ENDPOINTS.SIMULATE_BEST_POSITIONS({
3127
+ ...params,
3128
+ strategy: internalStrategy
3129
+ })
3130
+ );
3131
+ return response;
3132
+ } catch (error) {
3133
+ throw new Error(
3134
+ `Failed to simulate best positions: ${error.message}`
3135
+ );
3136
+ }
3137
+ }
3074
3138
  /**
3075
3139
  * Get currently selected pools for a protocol on a specific chain.
3076
3140
  *
@@ -3513,6 +3577,78 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3513
3577
  symbol: tokenSymbol
3514
3578
  };
3515
3579
  }
3580
+ // ============================================================================
3581
+ // WebSocket Event Stream
3582
+ // ============================================================================
3583
+ /**
3584
+ * Subscribe to real-time Zyfai risk and liquidity events via WebSocket.
3585
+ *
3586
+ * Events: depeg, liquidity_trap, liquidity_restored, pool_status_change,
3587
+ * new_collateral_detected, liquidity_drop.
3588
+ *
3589
+ * @param handlers - Callback per event type, plus onError
3590
+ * @param filters - Optional protocol/pool filter sent to the server on subscribe
3591
+ * @returns Cleanup function — call it to close the connection
3592
+ *
3593
+ * @example
3594
+ * ```typescript
3595
+ * const unsubscribe = sdk.subscribeToEvents(
3596
+ * {
3597
+ * onDepeg: (data) => console.log("Depeg detected:", data.token, data.severity),
3598
+ * onLiquidityDrop: (data) => console.log("Liquidity drop:", data.pool, data.dropPercent),
3599
+ * },
3600
+ * { protocols: ["morpho"], pools: ["gauntlet usdc core"] }
3601
+ * );
3602
+ *
3603
+ * // Later, close the connection:
3604
+ * unsubscribe();
3605
+ * ```
3606
+ */
3607
+ subscribeToEvents(handlers, filters) {
3608
+ let ws = null;
3609
+ let closed = false;
3610
+ const connect = () => {
3611
+ ws = new globalThis.WebSocket(WS_ENDPOINT);
3612
+ ws.onopen = () => {
3613
+ const msg = { type: "subscribe" };
3614
+ if (filters && (filters.chains?.length || filters.protocols?.length || filters.pools?.length)) {
3615
+ msg.filters = filters;
3616
+ }
3617
+ ws.send(JSON.stringify(msg));
3618
+ };
3619
+ ws.onmessage = (event) => {
3620
+ try {
3621
+ const msg = JSON.parse(event.data);
3622
+ if (msg.type !== "event") return;
3623
+ switch (msg.eventType) {
3624
+ case "depeg":
3625
+ handlers.onDepeg?.(msg.data);
3626
+ break;
3627
+ case "new_collateral_detected":
3628
+ handlers.onNewCollateralDetected?.(msg.data);
3629
+ break;
3630
+ case "liquidity_drop":
3631
+ handlers.onLiquidityDrop?.(msg.data);
3632
+ break;
3633
+ }
3634
+ } catch {
3635
+ }
3636
+ };
3637
+ ws.onerror = (error) => {
3638
+ handlers.onError?.(error);
3639
+ };
3640
+ ws.onclose = () => {
3641
+ if (!closed) {
3642
+ setTimeout(connect, 3e3);
3643
+ }
3644
+ };
3645
+ };
3646
+ connect();
3647
+ return () => {
3648
+ closed = true;
3649
+ ws?.close();
3650
+ };
3651
+ }
3516
3652
  };
3517
3653
  // ============================================================================
3518
3654
  // 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.39",
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",