UNPKG

@defindex/sdk

Version:

Official TypeScript SDK for DeFindex API

520 lines 22.4 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DefindexSDK = void 0; const http_client_1 = require("./clients/http-client"); /** * DeFindex SDK - TypeScript client for DeFindex API * * @example * ```typescript * // Basic initialization with default network * const sdk = new DefindexSDK({ * baseUrl: 'https://api.defindex.io', * defaultNetwork: SupportedNetworks.TESTNET * }); * * // With API key authentication * const sdk = new DefindexSDK({ * apiKey: 'sk_your_api_key_here', * baseUrl: 'https://api.defindex.io', * defaultNetwork: SupportedNetworks.MAINNET * }); * * // Now you can call methods without specifying network * const vaultInfo = await sdk.getVaultInfo('CVAULT...'); * * // Or override for a specific call * const testnetInfo = await sdk.getVaultInfo('CVAULT...', SupportedNetworks.TESTNET); * ``` */ class DefindexSDK { /** * Create a new DeFindex SDK instance * @param config - SDK configuration options */ constructor(config) { this.config = config; this.defaultNetwork = config.defaultNetwork; this.httpClient = new http_client_1.HttpClient(config.baseUrl || 'https://api.defindex.io', config.apiKey || '', // API key or empty string config.timeout || 30000); } /** * Get the network to use for a request * @param network - Optional network override * @returns The network to use (provided network or default) * @throws Error if no network is provided and no default is set */ getNetwork(network) { const resolvedNetwork = network ?? this.defaultNetwork; if (!resolvedNetwork) { throw new Error('No network specified. Either provide a network parameter or set defaultNetwork in SDK config.'); } return resolvedNetwork; } /** * Get the current default network * @returns The default network or undefined if not set */ getDefaultNetwork() { return this.defaultNetwork; } /** * Set the default network for all operations * @param network - The network to use as default */ setDefaultNetwork(network) { this.defaultNetwork = network; } //======================================================================= // System Operations //======================================================================= /** * Check API health status * @returns Health status information * @example * ```typescript * const health = await sdk.healthCheck(); * if (health.status.reachable) { * console.log('API is healthy'); * } * ``` */ async healthCheck() { return this.httpClient.get('/health'); } //======================================================================= // Factory Operations //======================================================================= /** * Get the factory contract address for a specific network * @param network - Stellar network (optional, uses default if not specified) * @returns Factory contract address * @example * ```typescript * const factory = await sdk.getFactoryAddress(); * console.log('Factory address:', factory.address); * ``` */ async getFactoryAddress(network) { const resolvedNetwork = this.getNetwork(network); return this.httpClient.get(`/factory/address?network=${resolvedNetwork}`); } /** * Create a new vault (requires Vault Manager role) * @param vaultConfig - Vault configuration including assets, fees, and roles * @param network - Stellar network (optional, uses default if not specified) * @returns Transaction XDR for vault creation * @example * ```typescript * const vaultConfig = { * roles: { "0": "GMANAGER...", "1": "CFEE..." }, * vault_fee_bps: 100, // 1% * assets: [{ address: "CASSET...", strategies: [...] }], * name_symbol: { name: "My Vault", symbol: "MVLT" }, * upgradable: true, * caller: "GCALLER..." * }; * const response = await sdk.createVault(vaultConfig); * ``` */ async createVault(vaultConfig, network) { const resolvedNetwork = this.getNetwork(network); return this.httpClient.post(`/factory/create-vault?network=${resolvedNetwork}`, vaultConfig); } /** * Create a new vault with initial deposit in a single transaction * @param vaultConfig - Vault configuration with initial deposit amounts * @param network - Stellar network (optional, uses default if not specified) * @returns Transaction XDR for vault creation and deposit * @example * ```typescript * const vaultConfig = { * // ... vault config * deposit_amounts: [1000000, 2000000] // Initial deposit amounts * }; * const response = await sdk.createVaultWithDeposit(vaultConfig); * ``` */ async createVaultWithDeposit(vaultConfig, network) { const resolvedNetwork = this.getNetwork(network); return this.httpClient.post(`/factory/create-vault-deposit?network=${resolvedNetwork}`, vaultConfig); } /** * Create a new vault with auto-invest in a single atomic transaction * * This endpoint creates a batched transaction that: * 1. Creates the vault with initial deposit * 2. Invests funds in specified strategies (rebalance) * 3. Changes manager to the final address * * All operations are atomic - either all succeed or all fail. * * @param params - Auto-invest vault configuration with asset allocations and strategies * @param network - Stellar network (optional, uses default if not specified) * @returns Transaction XDR, predicted vault address, and warning about address prediction * @example * ```typescript * const params = { * caller: 'GCALLER...', * roles: { * emergencyManager: 'GEMERGENCY...', * rebalanceManager: 'GREBALANCE...', * feeReceiver: 'GFEE...', * manager: 'GMANAGER...' * }, * name: 'My Auto-Invest Vault', * symbol: 'MAIV', * vaultFee: 10, // 0.1% in basis points * upgradable: true, * assets: [{ * address: 'CASSET...', * symbol: 'XLM', * amount: 2000000000, // 200 XLM in stroops * strategies: [ * { address: 'CSTRAT1...', name: 'hodl_strategy', amount: 1000000000 }, * { address: 'CSTRAT2...', name: 'yield_strategy', amount: 1000000000 } * ] * }] * }; * const response = await sdk.createVaultAutoInvest(params); * console.log('Sign this XDR:', response.xdr); * console.log('Predicted vault address:', response.predictedVaultAddress); * ``` */ async createVaultAutoInvest(params, network) { const resolvedNetwork = this.getNetwork(network); return this.httpClient.post(`/factory/create-vault-auto-invest?network=${resolvedNetwork}`, params); } //======================================================================= // Vault Operations //======================================================================= /** * Get comprehensive vault information * @param vaultAddress - The vault contract address * @param network - Stellar network (optional, uses default if not specified) * @returns Vault metadata, assets, strategies, and TVL information * @example * ```typescript * const vaultInfo = await sdk.getVaultInfo('CVAULT...'); * console.log(`Vault: ${vaultInfo.name} (${vaultInfo.symbol})`); * console.log(`Total Assets: ${vaultInfo.totalAssets}`); * ``` */ async getVaultInfo(vaultAddress, network) { const resolvedNetwork = this.getNetwork(network); return this.httpClient.get(`/vault/${vaultAddress}?network=${resolvedNetwork}`); } /** * Get user's vault balance and shares * @param vaultAddress - The vault contract address * @param userAddress - User's wallet address * @param network - Stellar network (optional, uses default if not specified) * @returns User's vault shares and underlying asset values * @example * ```typescript * const balance = await sdk.getVaultBalance('CVAULT...', 'GUSER...'); * console.log(`Shares: ${balance.dfTokens}`); * console.log(`Underlying values: ${balance.underlyingBalance}`); * ``` */ async getVaultBalance(vaultAddress, userAddress, network) { const resolvedNetwork = this.getNetwork(network); return this.httpClient.get(`/vault/${vaultAddress}/balance?from=${userAddress}&network=${resolvedNetwork}`); } /** * Get vault report with transaction details * @param vaultAddress - The vault contract address * @param network - Stellar network (optional, uses default if not specified) * @returns Vault report with transaction XDR and simulation response * @example * ```typescript * const report = await sdk.getReport('CVAULT...'); * console.log(`Report XDR: ${report.xdr}`); * ``` */ async getReport(vaultAddress, network) { const resolvedNetwork = this.getNetwork(network); return this.httpClient.get(`/vault/${vaultAddress}/report?network=${resolvedNetwork}`); } /** * Deposit assets into a vault * @param vaultAddress - The vault contract address * @param depositData - Deposit parameters including amounts and caller address * @param network - Stellar network (optional, uses default if not specified) * @returns Transaction XDR for signing and simulation response */ async depositToVault(vaultAddress, depositData, network) { const resolvedNetwork = this.getNetwork(network); return this.httpClient.post(`/vault/${vaultAddress}/deposit?network=${resolvedNetwork}`, depositData); } /** * Withdraw specific asset amounts from vault * @param vaultAddress - The vault contract address * @param withdrawData - Withdrawal parameters including amounts and caller * @param network - Stellar network (optional, uses default if not specified) * @returns Transaction XDR for signing and simulation response * @example * ```typescript * const withdrawData = { * amounts: [500000, 1000000], * caller: 'GUSER...', * slippageBps: 100 // 1% slippage tolerance * }; * const response = await sdk.withdrawFromVault('CVAULT...', withdrawData); * ``` */ async withdrawFromVault(vaultAddress, withdrawData, network) { const resolvedNetwork = this.getNetwork(network); return this.httpClient.post(`/vault/${vaultAddress}/withdraw?network=${resolvedNetwork}`, withdrawData); } /** * Withdraw vault shares for underlying assets * @param vaultAddress - The vault contract address * @param shareData - Share withdrawal parameters including share amount and caller * @param network - Stellar network (optional, uses default if not specified) * @returns Transaction XDR for signing and simulation response */ async withdrawShares(vaultAddress, shareData, network) { const resolvedNetwork = this.getNetwork(network); return this.httpClient.post(`/vault/${vaultAddress}/withdraw-shares?network=${resolvedNetwork}`, shareData); } /** * Get vault's Annual Percentage Yield (APY) * @param vaultAddress - The vault contract address * @param network - Stellar network (optional, uses default if not specified) * @returns APY information including percentage and calculation period * @example * ```typescript * const apy = await sdk.getVaultAPY('CVAULT...'); * console.log(`APY: ${apy.apyPercent}% (calculated over ${apy.period})`); * ``` */ async getVaultAPY(vaultAddress, network) { const resolvedNetwork = this.getNetwork(network); return this.httpClient.get(`/vault/${vaultAddress}/apy?network=${resolvedNetwork}`); } //======================================================================= // Vault Management Operations //======================================================================= /** * Rebalance vault strategies (Rebalance Manager role required) * @param vaultAddress - The vault contract address * @param rebalanceData - Rebalance parameters including investment instructions * @param network - Stellar network (optional, uses default if not specified) * @returns Transaction XDR for Rebalance Manager signing * @example * ```typescript * const rebalanceData = { * caller: 'GREBALANCE_MANAGER...', * instructions: [ * { type: 'Unwind', strategy_address: 'CSTRATEGY1...', amount: 500000 }, * { type: 'Invest', strategy_address: 'CSTRATEGY2...', amount: 1000000 }, * { * type: 'SwapExactIn', * token_in: 'GTOKEN1...', * token_out: 'GTOKEN2...', * amount: 250000, * slippageToleranceBps: 100 * } * ] * }; * const response = await sdk.rebalanceVault('CVAULT...', rebalanceData); * ``` */ async rebalanceVault(vaultAddress, rebalanceData, network) { const resolvedNetwork = this.getNetwork(network); return this.httpClient.post(`/vault/${vaultAddress}/rebalance?network=${resolvedNetwork}`, rebalanceData); } /** * Emergency rescue assets from strategy (Emergency Manager role required) * @param vaultAddress - The vault contract address * @param rescueData - Rescue parameters including strategy address and caller * @param network - Stellar network (optional, uses default if not specified) * @returns Transaction XDR for Emergency Manager signing and rescued assets info * @example * ```typescript * const rescueData = { * strategy_address: 'CSTRATEGY...', * caller: 'GEMERGENCY_MANAGER...' * }; * const response = await sdk.emergencyRescue('CVAULT...', rescueData); * ``` */ async emergencyRescue(vaultAddress, rescueData, network) { const resolvedNetwork = this.getNetwork(network); return this.httpClient.post(`/vault/${vaultAddress}/rescue?network=${resolvedNetwork}`, rescueData); } /** * Pause a specific strategy (Strategy Manager role required) * @param vaultAddress - The vault contract address * @param strategyData - Strategy pause parameters * @param network - Stellar network (optional, uses default if not specified) * @returns Transaction XDR for Strategy Manager signing * @example * ```typescript * const strategyData = { * strategy_address: 'CSTRATEGY...', * caller: 'CSTRATEGY_MANAGER...' * }; * const response = await sdk.pauseStrategy('CVAULT...', strategyData); * ``` */ async pauseStrategy(vaultAddress, strategyData, network) { const resolvedNetwork = this.getNetwork(network); return this.httpClient.post(`/vault/${vaultAddress}/pause-strategy?network=${resolvedNetwork}`, strategyData); } /** * Unpause a specific strategy (Strategy Manager role required) * @param vaultAddress - The vault contract address * @param strategyData - Strategy unpause parameters * @param network - Stellar network (optional, uses default if not specified) * @returns Transaction XDR for Strategy Manager signing * @example * ```typescript * const strategyData = { * strategy_address: 'CSTRATEGY...', * caller: 'GSTRATEGY_MANAGER...' * }; * const response = await sdk.unpauseStrategy('CVAULT...', strategyData); * ``` */ async unpauseStrategy(vaultAddress, strategyData, network) { const resolvedNetwork = this.getNetwork(network); return this.httpClient.post(`/vault/${vaultAddress}/unpause-strategy?network=${resolvedNetwork}`, strategyData); } //======================================================================= // Role Operations //======================================================================= /** * Get a specific vault role address * @param vaultAddress - The vault contract address * @param roleToGet - The role to retrieve (manager, emergency_manager, rebalance_manager, fee_receiver) * @param network - Stellar network (optional, uses default if not specified) * @returns Role information with address * @example * ```typescript * const role = await sdk.getVaultRole('CVAULT...', VaultRoles.MANAGER); * console.log(`Manager address: ${role.address}`); * ``` */ async getVaultRole(vaultAddress, roleToGet, network) { const resolvedNetwork = this.getNetwork(network); return this.httpClient.get(`/vault/${vaultAddress}/get/${roleToGet}?network=${resolvedNetwork}`); } /** * Set a vault role to a new address (Manager role required) * @param vaultAddress - The vault contract address * @param roleToSet - The role to set * @param roleData - Role assignment parameters including new address and caller * @param network - Stellar network (optional, uses default if not specified) * @returns Transaction XDR for Manager signing * @example * ```typescript * const roleData = { * caller: 'GMANAGER...', * new_address: 'GNEW_MANAGER...' * }; * const response = await sdk.setVaultRole('CVAULT...', VaultRoles.MANAGER, roleData); * ``` */ async setVaultRole(vaultAddress, roleToSet, roleData, network) { const resolvedNetwork = this.getNetwork(network); return this.httpClient.post(`/vault/${vaultAddress}/set/${roleToSet}?network=${resolvedNetwork}`, roleData); } //======================================================================= // Vault Management Operations //======================================================================= /** * Lock vault fees and optionally update fee rate (Manager role required) * @param vaultAddress - The vault contract address * @param lockData - Lock fees parameters including optional new fee rate * @param network - Stellar network (optional, uses default if not specified) * @returns Transaction XDR for Manager signing * @example * ```typescript * const lockData = { * caller: 'GMANAGER...', * new_fee_bps: 150 // Optional: new fee rate in basis points (1.5%) * }; * const response = await sdk.lockVaultFees('CVAULT...', lockData); * ``` */ async lockVaultFees(vaultAddress, lockData, network) { const resolvedNetwork = this.getNetwork(network); return this.httpClient.post(`/vault/${vaultAddress}/lock-fees?network=${resolvedNetwork}`, lockData); } /** * Release fees from a specific strategy (Manager role required) * @param vaultAddress - The vault contract address * @param releaseData - Release fees parameters including strategy address and amount * @param network - Stellar network (optional, uses default if not specified) * @returns Transaction XDR for Manager signing * @example * ```typescript * const releaseData = { * caller: 'GMANAGER...', * strategy_address: 'CSTRATEGY...', * amount: 100000 * }; * const response = await sdk.releaseVaultFees('CVAULT...', releaseData); * ``` */ async releaseVaultFees(vaultAddress, releaseData, network) { const resolvedNetwork = this.getNetwork(network); return this.httpClient.post(`/vault/${vaultAddress}/release-fees?network=${resolvedNetwork}`, releaseData); } /** * Distribute accumulated vault fees to fee receiver (Manager role required) * @param vaultAddress - The vault contract address * @param distributeData - Distribution parameters including caller * @param network - Stellar network (optional, uses default if not specified) * @returns Transaction XDR for Manager signing * @example * ```typescript * const distributeData = { * caller: 'GMANAGER...' * }; * const response = await sdk.distributeVaultFees('CVAULT...', distributeData); * ``` */ async distributeVaultFees(vaultAddress, distributeData, network) { const resolvedNetwork = this.getNetwork(network); return this.httpClient.post(`/vault/${vaultAddress}/distribute-fees?network=${resolvedNetwork}`, distributeData); } /** * Upgrade vault WASM contract (Manager role required) * @param vaultAddress - The vault contract address * @param newWasmHash - Upgrade parameters including new WASM hash and caller * @param network - Stellar network (optional, uses default if not specified) * @returns Transaction XDR for Manager signing * @example * ```typescript * const upgradeData = { * caller: 'GMANAGER...', * new_wasm_hash: 'abcd1234...' // New WASM hash to upgrade to * }; * const response = await sdk.upgradeVaultWasm('CVAULT...', upgradeData); * ``` */ async upgradeVaultWasm(vaultAddress, newWasmHash, network) { const resolvedNetwork = this.getNetwork(network); return this.httpClient.post(`/vault/${vaultAddress}/upgrade?network=${resolvedNetwork}`, newWasmHash); } //======================================================================= // Transaction Operations //======================================================================= /** * Submit a signed transaction to the Stellar blockchain * @param xdr - Base64 encoded signed transaction XDR * @param network - Stellar network (optional, uses default if not specified) * @param launchtube - Whether to use LaunchTube service (defaults to false) * @returns Transaction response with hash and status */ async sendTransaction(xdr, network, launchtube) { const resolvedNetwork = this.getNetwork(network); const payload = { xdr, launchtube: launchtube ?? false }; return this.httpClient.post(`/send?network=${resolvedNetwork}`, payload); } } exports.DefindexSDK = DefindexSDK; //# sourceMappingURL=defindex-sdk.js.map