### Example: Get Swap Quote and Log Details Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/api-reference/AlphalendClient.md Demonstrates how to get a swap quote and log the estimated output amount, fee, and USD value. This example requires a configured AlphalendClient instance. ```typescript const quote = await client.getSwapQuote( "0x2::sui::SUI", "0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::USDC", "1000000000" ); if (quote) { console.log(`Output: ${quote.estimatedAmountOut}`); console.log(`Fee: ${quote.estimatedFeeAmount}`); console.log(`USD Value: $${quote.estimatedAmountOutInUSD}`); } ``` -------------------------------- ### Build Local SDK for Examples Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/examples/README.md Builds the local SDK from the root directory. This is required before running examples that use the local build, resolving 'Cannot find module ../dist/esm/index.js' errors. ```bash cd .. npm run build cd examples ``` -------------------------------- ### Install Published SDK Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/examples/README.md Installs the published SDK version from npm. This is used for testing the official release. ```bash cd examples npm install ``` -------------------------------- ### Install AlphaLend SDK and Sui Dependencies Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/README.md Install the AlphaLend SDK using npm and ensure the peer dependency @mysten/sui is installed with the specified version. Requires Node.js >= 22.14.0 and TypeScript 5.0+. ```bash npm install @alphafi/alphalend-sdk # Peer dependency (you must provide) npm install @mysten/sui@^2.17.0 ``` -------------------------------- ### Install AlphaLend SDK Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/README.md Install the AlphaLend SDK package using npm. This command adds the SDK to your project's dependencies. ```bash npm install @alphafi/alphalend-sdk ``` -------------------------------- ### Example Usage of Protocol Constants Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/DOCUMENTATION_INDEX.md Demonstrates how to access and use various protocol constants, such as coin types and object IDs. Crucial for interacting with the protocol. ```javascript // Example: Accessing a coin type constant const suiCoinType = constants.COIN_TYPES.SUI; ``` ```javascript // Example: Accessing a protocol object ID const protocolObjectId = constants.PROTOCOL_OBJECTS.PACKAGE_ID; ``` -------------------------------- ### Run Get User Portfolio (Local Build) Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/examples/README.md Executes a script to fetch a user's portfolio using the local SDK build. Requires building the SDK first and setting the USER_ADDRESS environment variable. ```bash # First build the SDK cd .. npm run build # Then run the example cd examples USER_ADDRESS=0x... node getUserPortfolioLocal.mjs ``` -------------------------------- ### Zap-in Withdraw Example Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/README.md Withdraw collateral and swap to a desired token in a single transaction. Use MAX_U64 to withdraw all collateral. ```typescript import { Transaction } from "@mysten/sui/transactions"; import { MAX_U64 } from "alphalend-sdk"; // Withdraw collateral and swap to desired token in a single transaction const zapOutWithdrawParams = { marketId: "1", // Market ID from which to withdraw amount: 500000000n, // Amount to withdraw (in mists) marketCoinType: "0x2::sui::SUI", // Market's collateral token type (SUI) outputCoinType: "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC", // Token to swap to (USDC) slippage: 0.01, // Maximum allowed slippage (1%) positionCapId: "0xYOUR_POSITION_CAP_ID", // Your position capability address: "0xYOUR_ADDRESS", // Address of the user priceUpdateCoinTypes: [ "0x2::sui::SUI", "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC", ], // Coin types to update prices for }; // To withdraw all collateral and swap, use MAX_U64 const zapOutWithdrawAllParams = { marketId: "1", amount: MAX_U64, // Special value to withdraw all collateral marketCoinType: "0x2::sui::SUI", outputCoinType: "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC", slippage: 0.01, positionCapId: "0xYOUR_POSITION_CAP_ID", address: "0xYOUR_ADDRESS", priceUpdateCoinTypes: [ "0x2::sui::SUI", "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC", ], }; // Create zap-out withdraw transaction const zapOutWithdrawTx = await alphalendClient.zapOutWithdraw(zapOutWithdrawParams); if (zapOutWithdrawTx) { // Execute the transaction await wallet.signAndExecuteTransaction(zapOutWithdrawTx); } else { console.error("Failed to create zap-out withdraw transaction"); } ``` -------------------------------- ### Run Get User Portfolio (Published SDK) Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/examples/README.md Executes a script to fetch a user's portfolio using the published SDK version from npm. Requires setting the USER_ADDRESS environment variable. ```bash cd examples npm install USER_ADDRESS=0x... node getUserPortfolioPublished.mjs ``` -------------------------------- ### Get User Portfolio Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/README.md Retrieves the user's portfolio information, including their supplied and borrowed assets. ```APIDOC ## Get User Portfolio ### Description Fetches the user's portfolio details, including supplied assets, borrowed assets, and borrowing power. ### Method `client.getUserPortfolioFromPosition(positionId)` ### Parameters #### Path Parameters - **positionId** (string) - Required - The ID of the user's position. #### Query Parameters None #### Request Body None ### Request Example ```typescript import type { UserPortfolio } from "@alphafi/alphalend-sdk"; const portfolio: UserPortfolio | undefined = await client.getUserPortfolioFromPosition(posId); ``` ### Response #### Success Response - **UserPortfolio | undefined** - The user's portfolio data if the position is found, otherwise undefined. #### Response Example `UserPortfolio` or `undefined` ERROR HANDLING: - Methods throw Error objects. Check messages for specific issues. ``` -------------------------------- ### Run Get User Portfolio (Local Build) with npm script Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/examples/README.md Executes a script to fetch a user's portfolio using the local SDK build via an npm script. Requires building the SDK first and setting the USER_ADDRESS environment variable. ```bash cd examples USER_ADDRESS=0x... npm run test:local ``` -------------------------------- ### Run Get User Portfolio (Published SDK) with npm script Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/examples/README.md Executes a script to fetch a user's portfolio using the published SDK version via an npm script. Requires setting the USER_ADDRESS environment variable. ```bash cd examples npm install USER_ADDRESS=0x... npm run test:published ``` -------------------------------- ### Get All Markets Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/README.md Retrieve data for all available markets in the protocol. This includes information such as price, APR, and utilization rates. ```typescript const markets = await client.getAllMarkets(); // Returns: MarketData[] with price, APR, utilization, etc. ``` -------------------------------- ### Get User Portfolio Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/DOCUMENTATION_INDEX.md The primary interface for retrieving a user's portfolio data. Essential for displaying user-specific financial information. ```javascript const portfolio = await position.getUserPortfolio(userAddress); ``` -------------------------------- ### Get User Portfolio With Cached Markets Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/README.md Retrieves user portfolio data efficiently by using cached market information. ```APIDOC ## Get User Portfolio With Cached Markets ### Description Fetches the user's portfolio data, optimizing the process by using pre-fetched (cached) market information. ### Method `client.getUserPortfolioWithCachedMarkets(address, cachedMarkets)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **address** (string) - Required - The user's wallet address. - **cachedMarkets** (MarketData[]) - Required - An array of market data objects obtained from `getMarketsChain()` or similar. ### Request Example ```typescript // Fetch markets once const cachedMarkets = await client.getMarketsChain(); // Reuse in multiple calls const portfolio = await client.getUserPortfolioWithCachedMarkets(address, cachedMarkets); ``` ### Response #### Success Response - **UserPortfolio | undefined** - The user's portfolio data or undefined if not found. #### Response Example `UserPortfolio` or `undefined` ERROR HANDLING: - Methods throw Error objects. Check messages for specific issues. ``` -------------------------------- ### Get All Markets Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/README.md Retrieves comprehensive data for all available markets, including pricing, Annual Percentage Rate (APR), and utilization rates. ```APIDOC ## Get All Markets ### Description Fetches data for all available markets on the Alphalend protocol. ### Method `client.getAllMarkets()` ### Parameters None ### Request Example ```typescript const markets = await client.getAllMarkets(); ``` ### Response #### Success Response - **MarketData[]** - An array of market data objects, each containing price, APR, utilization, and other relevant statistics. #### Response Example `MarketData[]` ERROR HANDLING: - Methods throw Error objects. Check messages for specific issues. ``` -------------------------------- ### Claim Rewards Example Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/README.md Claim accrued rewards, with options to claim and deposit Alpha and other reward tokens. Ensure you have the correct position capability and user address. ```typescript import { Transaction } from "@mysten/sui/transactions"; // Claim accrued rewards const claimRewardsParams = { positionCapId: "0xYOUR_POSITION_CAP_ID", // Your position capability address: "0xYOUR_ADDRESS", // Address of the user claiming rewards claimAndDepositAlpha: true, // Whether to claim and deposit Alpha token rewards claimAndDepositAll: true, // Whether to claim and deposit all other reward tokens // DEPRECATED: Use claimAndDepositAlpha and claimAndDepositAll instead // claimAlpha: true, // ⚠️ DEPRECATED - use claimAndDepositAlpha instead // claimAll: true, // ⚠️ DEPRECATED - use claimAndDepositAll instead }; // Create claim rewards transaction const claimRewardsTx = await alphalendClient.claimRewards(claimRewardsParams); // Execute the transaction await wallet.signAndExecuteTransaction(claimRewardsTx); ``` -------------------------------- ### Get User Portfolio Snapshot Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/api-reference/Position.md Calculates and retrieves a comprehensive portfolio snapshot for a given position, including net worth, earnings, APR, and detailed supply/borrow/reward breakdowns. Requires current market data. ```typescript const position = positions[0]; const markets = await client.getMarketsChain(); const portfolio = await position.getUserPortfolio(markets); console.log(`Position ID: ${portfolio.positionId}`); console.log(`Net Worth: $${portfolio.netWorth.toString()}`); console.log(`Daily Earnings: $${portfolio.dailyEarnings.toString()}`); console.log(`Net APR: ${portfolio.netApr.toNumber() * 100}%`); console.log(`Borrow Limit Used: ${portfolio.borrowLimitUsed.toNumber() * 100}%`); console.log(`Safe Borrow Limit: $${portfolio.safeBorrowLimit.toString()}`); console.log(`Total Supplied: $${portfolio.totalSuppliedUsd.toString()}`); console.log(`Total Borrowed: $${portfolio.totalBorrowedUsd.toString()}`); console.log(`Unclaimed Rewards: $${portfolio.rewardsToClaimUsd.toString()}`); // View detailed supply/borrow by market for (const [marketId, amount] of portfolio.suppliedAmounts) { console.log(` Market ${marketId} Supplied: ${amount.toString()}`); } for (const [marketId, amount] of portfolio.borrowedAmounts) { console.log(` Market ${marketId} Borrowed: ${amount.toString()}`); } // View detailed rewards for (const reward of portfolio.rewardsToClaim) { console.log(` ${reward.coinType}: ${reward.rewardAmount.toString()}`); } ``` -------------------------------- ### Handle Insufficient Collateral Error Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/errors.md This example shows how to catch and handle the 'Insufficient collateral' error, which arises when the computed withdraw amount is zero or negative. It suggests increasing slippage or collateral. ```typescript try { const tx = await client.flashRepay({ slippage: 0.01, // Try increasing slippage // ... other params }); } catch (error) { if (error instanceof Error && error.message.includes("Insufficient collateral")) { console.error("Not enough collateral to repay. Increase supplied collateral."); } } ``` -------------------------------- ### Accessing Constants via AlphalendClient Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/api-reference/constants.md Illustrates how to access various constants, such as protocol and package IDs, directly from an initialized AlphalendClient instance. This is a convenient way to get network-specific constants. ```typescript import { AlphalendClient } from "@alphafi/alphalend-sdk"; const client = new AlphalendClient("mainnet"); // Access via client const protocolId = client.constants.LENDING_PROTOCOL_ID; const packageId = client.constants.ALPHALEND_LATEST_PACKAGE_ID; const suiCoinType = client.constants.SUI_COIN_TYPE; ``` -------------------------------- ### Get User Portfolio Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/README.md Retrieves detailed information about a user's portfolio, including supplied and borrowed assets, net worth, and risk parameters. Requires the user's address. ```typescript // Get user portfolio information including supplied/borrowed assets const userPortfolio = await alphalendClient.getUserPortfolio("0xUSER_ADDRESS"); console.log(userPortfolio); // Example output: // [ // { // positionId: "0x...", // netWorth: new Decimal("1500.00"), // dailyEarnings: new Decimal("0.82"), // netApr: new Decimal("0.02"), // safeBorrowLimit: new Decimal("700.00"), // borrowLimitUsed: new Decimal("0.35"), // liquidationThreshold: new Decimal("800.00"), // totalSuppliedUsd: new Decimal("1000.00"), // aggregatedSupplyApr: new Decimal("0.04"), // totalBorrowedUsd: new Decimal("300.00"), // aggregatedBorrowApr: new Decimal("0.08"), // suppliedAmounts: new Map([ // [1, new Decimal("100000000000")], // Key is marketId, value is amount // [3, new Decimal("50000000")] // ]), // borrowedAmounts: new Map([ // [2, new Decimal("300000000")] // ]), // rewardsToClaimUsd: new Decimal("5.72"), // rewardsToClaim: [ // { // coinType: "0x..::alpha::ALPHA", // rewardAmount: new Decimal("10.5") // } // ] // } // ] ``` -------------------------------- ### Get Swap Quote with Automatic Gateway Selection Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/configuration.md Retrieve a swap quote, and the SDK will automatically select the best gateway (Cetus, 7k, or Deepbook) based on the provided token pair and amount. ```typescript const quote = await client.getSwapQuote( "0x2::sui::SUI", "0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::USDC", "1000000000" ); console.log(`Gateway: ${quote.gateway}`); // "cetus" or "7k" or "deepbook" ``` -------------------------------- ### Test Local Build with Testnet Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/examples/README.md Demonstrates how to test the local SDK build with a specific Testnet address. Requires building the SDK first and setting both USER_ADDRESS and NETWORK environment variables. ```bash # Build SDK first cd .. npm run build # Run example cd examples USER_ADDRESS=0x742ce1243c22e38ec338293847a2b4c4e5d3f8a2c1a8e9f0b2c3d4e5f6 NETWORK=testnet node getUserPortfolioLocal.mjs ``` -------------------------------- ### Build and Test SDK Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/CLAUDE.md After updating constants and type definitions, run tests and build the SDK. This verifies the changes and prepares the SDK for use. ```bash npm test npm run build ``` -------------------------------- ### Get User's First Position Capability ID Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/api-reference/position-functions.md Fetches a user's first position capability ID. This is the most commonly used function for getting a user's primary position. If a user has multiple positions, use `getUserPositionCapIds()` to fetch all. ```typescript async function getUserPositionCapId( blockchain: Blockchain, userAddress: string ): Promise ``` ```typescript import { getUserPositionCapId } from "@alphafi/alphalend-sdk"; const posCapId = await getUserPositionCapId(blockchain, "0xUSER_ADDRESS"); if (posCapId) { console.log(`User's Position Cap: ${posCapId}`); } else { console.log("User has no positions yet"); } ``` -------------------------------- ### Get Estimated Gas Budget Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/README.md Estimates the gas budget required for a given transaction. ```APIDOC ## Get Estimated Gas Budget ### Description Estimates the gas budget required to execute a given transaction. This is useful for setting appropriate gas limits. ### Method `client.getEstimatedGasBudget(tx, address)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **tx** (object) - Required - The transaction object for which to estimate gas. - **address** (string) - Required - The user's wallet address. ### Request Example ```typescript const tx = await client.supply(params); const estimatedGas = await client.getEstimatedGasBudget(tx, address); ``` ### Response #### Success Response - **estimatedGas** (number) - The estimated gas budget required for the transaction. #### Response Example `number` ERROR HANDLING: - Methods throw Error objects. Check messages for specific issues. ``` -------------------------------- ### Get Markets Chain Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/README.md Fetches market data directly from the chain, useful for caching. ```APIDOC ## Get Markets Chain ### Description Fetches the latest market data directly from the blockchain. This is useful for caching market data to reduce redundant calls. ### Method `client.getMarketsChain()` ### Parameters None ### Request Example ```typescript const cachedMarkets = await client.getMarketsChain(); ``` ### Response #### Success Response - **MarketData[]** - An array of market data objects. #### Response Example `MarketData[]` ERROR HANDLING: - Methods throw Error objects. Check messages for specific issues. ``` -------------------------------- ### Get Specific Market Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/README.md Fetches detailed data for a single market identified by its ID. ```APIDOC ## Get Specific Market ### Description Retrieves detailed data for a specific market identified by its unique ID. ### Method `client.getMarketDataFromId(marketId)` ### Parameters #### Path Parameters - **marketId** (string) - Required - The ID of the market to retrieve data for. #### Query Parameters None #### Request Body None ### Request Example ```typescript const market = await client.getMarketDataFromId(1); ``` ### Response #### Success Response - **MarketData | undefined** - A single market data object if found, otherwise undefined. #### Response Example `MarketData` or `undefined` ERROR HANDLING: - Methods throw Error objects. Check messages for specific issues. ``` -------------------------------- ### Run Diagnose Initialization Issues with npm script Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/examples/README.md Runs a diagnostic script to test SDK initialization and coin metadata fetching using an npm script. This helps identify and resolve initialization problems. ```bash cd examples npm run diagnose ``` -------------------------------- ### Get Specific Market Data Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/README.md Fetch detailed data for a specific market identified by its ID. ```typescript const market = await client.getMarketDataFromId(1); // Returns: Single MarketData or undefined ``` -------------------------------- ### Run Diagnose Initialization Issues Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/examples/README.md Runs a diagnostic script to test SDK initialization and coin metadata fetching. This helps identify and resolve initialization problems. ```bash cd examples node diagnoseInit.mjs ``` -------------------------------- ### Get All Position IDs Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/DOCUMENTATION_INDEX.md Retrieves all position IDs for a user. Useful for iterating through all of a user's positions. ```javascript const positionIds = helperFunctions.getUserPositionIds(userAddress); ``` -------------------------------- ### Test Published SDK with Mainnet Address Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/examples/README.md Demonstrates how to test the published SDK with a specific Mainnet address. Ensures the SDK functions correctly with live network data. ```bash cd examples npm install USER_ADDRESS=0x742ce1243c22e38ec338293847a2b4c4e5d3f8a2c1a8e9f0b2c3d4e5f6 node getUserPortfolioPublished.mjs ``` -------------------------------- ### Get Protocol Stats With Cached Markets Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/README.md Retrieves protocol statistics efficiently by utilizing cached market data. ```APIDOC ## Get Protocol Stats With Cached Markets ### Description Fetches protocol statistics, optimizing the process by using pre-fetched (cached) market information. ### Method `client.getProtocolStatsWithCachedMarkets(cachedMarkets)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **cachedMarkets** (MarketData[]) - Required - An array of market data objects obtained from `getMarketsChain()` or similar. ### Request Example ```typescript // Fetch markets once const cachedMarkets = await client.getMarketsChain(); // Reuse in multiple calls const stats = await client.getProtocolStatsWithCachedMarkets(cachedMarkets); ``` ### Response #### Success Response - **{ totalSuppliedUsd, totalBorrowedUsd }** - An object containing the total value supplied and borrowed in USD. #### Response Example `{ totalSuppliedUsd: string, totalBorrowedUsd: string }` ERROR HANDLING: - Methods throw Error objects. Check messages for specific issues. ``` -------------------------------- ### Build Local SDK Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/examples/README.md Builds the SDK from the local development version. This is used for testing changes before publishing. ```bash # From the root SDK directory npm install npm run build ``` -------------------------------- ### Get All Markets With Cached Markets Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/README.md Retrieves all market data using pre-fetched (cached) market information for efficiency. ```APIDOC ## Get All Markets With Cached Markets ### Description Retrieves all market data by utilizing previously fetched (cached) market information. This improves performance by avoiding repeated on-chain calls for market data. ### Method `client.getAllMarketsWithCachedMarkets(cachedMarkets)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **cachedMarkets** (MarketData[]) - Required - An array of market data objects obtained from `getMarketsChain()` or similar. ### Request Example ```typescript // Fetch markets once const cachedMarkets = await client.getMarketsChain(); // Reuse in multiple calls const allMarkets = await client.getAllMarketsWithCachedMarkets(cachedMarkets); ``` ### Response #### Success Response - **MarketData[]** - An array of market data objects. #### Response Example `MarketData[]` ERROR HANDLING: - Methods throw Error objects. Check messages for specific issues. ``` -------------------------------- ### Get Protocol Statistics Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/README.md Retrieve overall protocol statistics, including the total value supplied and borrowed in USD. ```typescript const stats = await client.getProtocolStats(); // Returns: { totalSuppliedUsd, totalBorrowedUsd } ``` -------------------------------- ### Get Market Data Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/DOCUMENTATION_INDEX.md Retrieves a complete snapshot of market data. Useful for understanding the current state of all markets. ```javascript const marketData = await market.getMarketData(); ``` -------------------------------- ### Market Constructor Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/api-reference/Market.md Creates a Market instance from raw market data and coin metadata. This is typically done internally by the AlphalendClient but can be instantiated directly. ```APIDOC ## constructor(market, coinMetadataMap) ### Description Creates a Market instance from raw market data. ### Parameters #### Path Parameters - **market** (MarketType) - Required - Parsed market data from GraphQL - **coinMetadataMap** (Map) - Required - Coin metadata for decimal and pricing lookups ### Request Example ```typescript import { Market } from "@alphafi/alphalend-sdk"; const market = new Market(marketData, coinMetadataMap); const marketInfo = await market.getMarketData(); ``` ``` -------------------------------- ### Initialize AlphalendClient with Prebuilt Coin Metadata Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/configuration.md Configure the AlphalendClient for offline testing by providing a map of custom coin metadata during initialization. ```typescript import { CoinMetadata } from "@alphafi/alphalend-sdk"; const coinMetadata: Map = new Map([ [ "0x2::sui::SUI", { coinType: "0x2::sui::SUI", pythPriceFeedId: "0x23...", pythPriceInfoObjectId: "0x9a...", decimals: 9, pythSponsored: true, symbol: "SUI", coingeckoPrice: "2.50", pythPrice: "2.48", }, ], [ "0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::USDC", { coinType: "0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::USDC", pythPriceFeedId: "0x2...", pythPriceInfoObjectId: "0x7c...", decimals: 6, pythSponsored: true, symbol: "USDC", coingeckoPrice: "1.00", pythPrice: "1.00", }, ], ]); const client = new AlphalendClient("mainnet", undefined, { coinMetadataMap: coinMetadata, }); ``` -------------------------------- ### Mainnet-Specific Client Initialization and Feature Check Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/configuration.md Initialize the Alphalend client for the mainnet and conditionally enable features like Deepbook pool support for USDC. ```typescript const client = new AlphalendClient("mainnet"); // Deepbook pools for USDC if (client.network === "mainnet") { // dbUSDC (Deepbook-staked USDC) support available const zapTx = await client.zapInSupply({ marketId: "DBUSDC_MARKET_ID", // ... }); } ``` -------------------------------- ### AlphalendClient User Portfolio Methods Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/DOCUMENTATION_INDEX.md Documentation for methods related to fetching user portfolio data from the AlphalendClient, including methods for retrieving portfolio details from various sources. ```APIDOC ## AlphalendClient User Portfolio Methods ### Description Documentation for methods related to fetching user portfolio data from the AlphalendClient, including methods for retrieving portfolio details from various sources. ### Methods - `getUserPortfolio()` - `getUserPortfolioWithCachedMarkets()` - `getUserPortfolioFromPosition()` - `getUserPortfolioFromPositionCapId()` ### Parameters Each method is documented with a parameter table specifying input types, requirements, and descriptions, referencing `types.md`. ### Return Type These methods return detailed user portfolio information, with specific types defined in `types.md`. ### Examples Usage examples are provided to demonstrate how to retrieve user portfolio data effectively. ### Cross-references - `types.md` for return type definitions. ``` -------------------------------- ### Get Swap Quote Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/README.md Calculates a quote for swapping one token for another, providing details on the amount, fees, and slippage. ```APIDOC ## Get Swap Quote ### Description Obtain a quote for a token swap, including the amount of the received token, associated fees, and slippage. ### Method `client.getSwapQuote(fromCoinType, toCoinType, amount)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **fromCoinType** (string) - Required - The type of the coin to swap from. - **toCoinType** (string) - Required - The type of the coin to swap to. - **amount** (string) - Required - The amount of the `fromCoinType` to swap. ### Request Example ```typescript const quote = await client.getSwapQuote( "0x2::sui::SUI", "0xdba34672...::usdc::USDC", "1000000000" ); ``` ### Response #### Success Response - **quoteObject** - An object containing swap details: `amount`, `fee`, `slippage`, `gateway`. #### Response Example `quoteObject` ERROR HANDLING: - Methods throw Error objects. Check messages for specific issues. ``` -------------------------------- ### Initialize AlphalendClient using Environment Variables Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/configuration.md Instantiate the AlphalendClient, dynamically setting the network and GraphQL endpoint based on environment variables. ```typescript const graphqlUrl = process.env.GRAPHQL_URL; const network = (process.env.SUI_NETWORK || "mainnet") as Network; const client = new AlphalendClient(network, graphqlUrl); ``` -------------------------------- ### Get Protocol Stats Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/README.md Retrieves overall statistics for the Alphalend protocol, including total supplied and borrowed amounts in USD. ```APIDOC ## Get Protocol Stats ### Description Fetches key statistics for the entire Alphalend protocol. ### Method `client.getProtocolStats()` ### Parameters None ### Request Example ```typescript const stats = await client.getProtocolStats(); ``` ### Response #### Success Response - **{ totalSuppliedUsd, totalBorrowedUsd }** - An object containing the total value supplied and borrowed in USD. #### Response Example `{ totalSuppliedUsd: string, totalBorrowedUsd: string }` ERROR HANDLING: - Methods throw Error objects. Check messages for specific issues. ``` -------------------------------- ### Instantiate Market Class Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/api-reference/Market.md Demonstrates how to create a new Market instance. Market instances are typically managed internally by AlphalendClient but can be instantiated directly for specific use cases. ```typescript import { Market } from "@alphafi/alphalend-sdk"; // Market instances are typically created internally by AlphalendClient // but can be instantiated directly if needed: const market = new Market(marketData, coinMetadataMap); const marketInfo = await market.getMarketData(); ``` -------------------------------- ### Get Network-Specific Constants Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/DOCUMENTATION_INDEX.md Fetches protocol constants tailored to a specific network. Essential for ensuring correct network configurations. ```javascript const constants = constantsModule.getConstants('mainnet'); ``` -------------------------------- ### Using Coin Types in Supply and Borrow Operations Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/api-reference/constants.md Demonstrates how to use predefined coin types from the SDK's constants for supplying and borrowing assets in the Alphalend protocol. Ensure the client is initialized with the correct network. ```typescript const constants = client.constants; // Use coin types in supply/borrow operations const supplyTx = await client.supply({ coinType: constants.SUI_COIN_TYPE, marketId: "1", amount: 1000000000n, address: userAddress, }); const borrowTx = await client.borrow({ coinType: constants.USDC_COIN_TYPE, marketId: "2", amount: 500000000n, positionCapId: posCapId, address: userAddress, priceUpdateCoinTypes: [ constants.SUI_COIN_TYPE, constants.USDC_COIN_TYPE, ], }); ``` -------------------------------- ### Get Protocol Constants for a Network Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/api-reference/constants.md Fetches protocol constants for a specific network. Use this to retrieve network-specific IDs and configuration. ```typescript import { getConstants, Network } from "@alphafi/alphalend-sdk"; const network: Network = "mainnet"; const constants = getConstants(network); console.log(`Lending Protocol ID: ${constants.LENDING_PROTOCOL_ID}`); console.log(`Package ID: ${constants.ALPHALEND_LATEST_PACKAGE_ID}`); ``` -------------------------------- ### Estimate Gas Budget for Transaction Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/configuration.md Build a transaction, estimate the gas budget required, and then set the gas budget with a buffer before executing the transaction. ```typescript const tx = new Transaction(); // Build transaction const supplyTx = await client.supply({ marketId: "1", amount: 1000000000n, coinType: "0x2::sui::SUI", address: "0xYOUR_ADDRESS", tx: tx, }); // Estimate gas before execution const estimatedGas = await client.getEstimatedGasBudget( supplyTx, "0xYOUR_ADDRESS" ); supplyTx.setGasBudget(Math.ceil(estimatedGas * 1.2)); // Add 20% buffer await wallet.signAndExecuteTransaction(supplyTx); ``` -------------------------------- ### Initialize AlphalendClient Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/README.md Initialize the AlphalendClient with the desired network, such as 'mainnet'. This is the main entry point for all protocol operations. ```typescript import { AlphalendClient } from "@alphafi/alphalend-sdk"; const client = new AlphalendClient("mainnet"); ``` -------------------------------- ### Configure SDK with Environment Variables Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/configuration.md Set environment variables to customize the GraphQL endpoint and logging level for the SDK. ```bash # Set custom GraphQL endpoint GRAPHQL_URL=https://my-endpoint.example.com/graphql # Configure logging DEBUG=alphalend:* # Set Sui network SUI_NETWORK=mainnet ``` -------------------------------- ### Get User Portfolio by Position ID Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/api-reference/AlphalendClient.md Fetches the portfolio for a specific position ID. Use this when you have the direct ID of a user's position. ```typescript async getUserPortfolioFromPosition( positionId: string ): Promise ``` -------------------------------- ### AlphalendClient Core Protocol Methods Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/DOCUMENTATION_INDEX.md Reference for the core methods of the AlphalendClient class used for interacting with the lending protocol, including supplying, withdrawing, borrowing, repaying, claiming rewards, liquidating, and updating prices. ```APIDOC ## AlphalendClient Core Protocol Methods ### Description Reference for the core methods of the AlphalendClient class used for interacting with the lending protocol, including supplying, withdrawing, borrowing, repaying, claiming rewards, liquidating, and updating prices. ### Methods - `supply()` - `withdraw()` - `borrow()` - `repay()` - `claimRewards()` - `liquidate()` - `updatePrices()` ### Parameters Each method includes a detailed parameter table with field name, type, required status, and description, cross-referenced to type definitions in `types.md`. ### Return Type Each method returns a specific type detailing the outcome of the operation, with descriptions provided in the full method documentation. ### Examples Real-world usage examples are provided for each method to demonstrate practical application. ### Cross-references - `types.md` for parameter and return type definitions. - `configuration.md` for client initialization and network setup. ``` -------------------------------- ### Get Swap Quote Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/README.md Obtain a quote for a token swap, including the amount, fee, and slippage. This is useful for estimating swap outcomes before execution. ```typescript const quote = await client.getSwapQuote( "0x2::sui::SUI", "0xdba34672...::usdc::USDC", "1000000000" ); // Returns: quoteObject with amount, fee, slippage, gateway ``` -------------------------------- ### Get Complete Position Object Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/DOCUMENTATION_INDEX.md Fetches the complete position object using a position ID. Provides detailed information about a specific position. ```javascript const position = helperFunctions.getUserPosition(userAddress, positionId); ``` -------------------------------- ### Set Gas Budget with Buffer Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/README.md Ensure transaction success by setting an adequate gas budget. Estimate the gas required and add a safety margin (e.g., 20%) using Math.ceil. ```typescript const tx = await client.supply(params); const estimatedGas = await client.getEstimatedGasBudget(tx, address); tx.setGasBudget(Math.ceil(estimatedGas * 1.2)); // Add 20% safety margin ``` -------------------------------- ### Get Position ID from Cap Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/DOCUMENTATION_INDEX.md Derives a position ID from a given position cap ID. Useful for linking caps to their respective positions. ```javascript const positionId = helperFunctions.getUserPositionId(userAddress, capId); ``` -------------------------------- ### Instantiate Position Class Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/api-reference/Position.md Demonstrates how to create a Position instance. Position instances are typically managed internally by AlphalendClient but can be instantiated directly with parsed position data and coin metadata. ```typescript import { Position } from "@alphafi/alphalend-sdk"; // Position instances are typically created internally by AlphalendClient // but can be instantiated directly if needed: const position = new Position(positionData, coinMetadataMap); const portfolio = await position.getUserPortfolio(markets); ``` -------------------------------- ### Get All Position Cap IDs Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/DOCUMENTATION_INDEX.md Retrieves all position cap IDs for a user, sorted by creation time. Useful for managing multiple positions. ```javascript const capIds = helperFunctions.getUserPositionCapIds(userAddress); ``` -------------------------------- ### Testnet Configuration Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/README.md Initialize the AlphalendClient for the testnet environment. Use testnet-specific coin types and market IDs for transactions. ```typescript const testnetClient = new AlphalendClient("testnet"); // Use testnet coin types and market IDs const tx = await testnetClient.supply({ marketId: "1", amount: 100_000_000n, coinType: "0x2::sui::SUI", address: testAddress, }); ``` -------------------------------- ### Configure Custom Flash Repay Options Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/configuration.md Execute a flash repay operation with custom parameters, including specific markets, position caps, slippage tolerance, and optional partial repayment amounts. ```typescript const flashTx = await client.flashRepay({ withdrawCoinType: "0x2::sui::SUI", withdrawMarketId: "1", repayCoinType: "0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::USDC", repayMarketId: "2", positionCapId: "0xPOS_CAP_ID", address: "0xUSER_ADDRESS", slippage: 0.05, // 5% slippage tolerance repayAmountBaseUnits: "500000000", // Partial repay (optional) }); ``` -------------------------------- ### Get First Position Cap ID Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/DOCUMENTATION_INDEX.md Retrieves the ID of the first position cap associated with a user. Useful for identifying specific positions. ```javascript const capId = helperFunctions.getUserPositionCapId(userAddress); ``` -------------------------------- ### Get User's First Position ID Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/api-reference/position-functions.md Fetches the position ID from the first position capability for a user. Returns undefined if not found. ```typescript async function getUserPositionId( blockchain: Blockchain, userAddress: string ): Promise ``` ```typescript import { getUserPositionId } from "@alphafi/alphalend-sdk"; const posId = await getUserPositionId(blockchain, "0xUSER_ADDRESS"); if (posId) { // Use position ID directly for lower-level operations const portfolio = await client.getUserPortfolioFromPosition(posId); } ``` -------------------------------- ### Fetch Coin Metadata at Runtime Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/configuration.md Asynchronously fetch the coin metadata map from the SDK and iterate through it to display coin symbols and prices. ```typescript const client = new AlphalendClient("mainnet"); const metadata = await client.fetchCoinMetadataMap(); for (const [coinType, data] of metadata) { console.log(`${data.symbol}: $${data.pythPrice || data.coingeckoPrice}`); } ``` -------------------------------- ### Handling Network Differences in Constants Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/api-reference/constants.md Explains that constants can vary between networks (e.g., mainnet vs. testnet) and demonstrates how to check for network-specific features like Deepbook support. Always ensure you are using constants for the correct network. ```typescript // Mainnet has Deepbook support const mainnetConstants = getConstants("mainnet"); const hasDeepbook = !!mainnetConstants.DEEPBOOK_UPGRADE_CAP_ID; // Testnet/devnet may not const testnetConstants = getConstants("testnet"); // Always use the configured network const client = new AlphalendClient(network); console.log(`Using constants for ${client.network}`); ``` -------------------------------- ### Get User Portfolio by Position Capability ID Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/api-reference/AlphalendClient.md Fetches the portfolio using a position capability ID. This is useful when interacting with positions through their capability identifiers. ```typescript async getUserPortfolioFromPositionCapId( positionCapId: string ): Promise ``` -------------------------------- ### Offline Testing with Prebuilt Metadata Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/README.md Configure the AlphalendClient for offline testing by providing a map of coin metadata. This allows the SDK to function without direct network access to fetch metadata. ```typescript import { CoinMetadata, AlphalendClient } from "@alphafi/alphalend-sdk"; const metadata: Map = new Map([ ["0x2::sui::SUI", { coinType: "0x2::sui::SUI", decimals: 9, symbol: "SUI", pythPrice: "2.50", // ... other fields }], ]); const client = new AlphalendClient("mainnet", undefined, { coinMetadataMap: metadata, }); ``` -------------------------------- ### Get Protocol Statistics Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/README.md Fetches overall statistics for the Alphalend protocol, including total supplied and borrowed values in USD. Useful for dashboard overviews. ```typescript // Get protocol statistics const stats = await alphalendClient.getProtocolStats(); console.log(stats); // Example output: // { // totalSuppliedUsd: "1000000.00", // Total value supplied across all markets (USD) // totalBorrowedUsd: "500000.00" // Total value borrowed across all markets (USD) // } ``` -------------------------------- ### Get Market Data by ID Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/README.md Retrieves specific market data for a single market identified by its ID. Use this when you need details for a particular asset. ```typescript // Get market data for a particular market const marketData = await alphalendClient.getMarketDataFromId(1); ``` -------------------------------- ### Connect to Pyth Oracle and Fetch Prices Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/api-reference/constants.md Establishes a connection to the Pyth Mainnet API endpoint and fetches the latest price feeds for specified identifiers. ```typescript const pythConnection = new SuiPriceServiceConnection( constants.PYTH_MAINNET_API_ENDPOINT ); // Fetch latest prices from Pyth const prices = await pythConnection.getLatestPriceFeeds([ feedId1, feedId2, ]); ``` -------------------------------- ### Get Flash Loan Fee Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/DOCUMENTATION_INDEX.md Retrieves the fee for a flash loan for a specific coin type. Essential for calculating the total cost of a flash loan. ```javascript const fee = await utilities.getNaviFlashLoanFeeForCoinType(coinType); ``` -------------------------------- ### AlphalendClient Preferred Method Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/api-reference/position-functions.md Demonstrates the preferred, higher-level method for obtaining user portfolio data using AlphalendClient, which abstracts away the need to directly call individual position functions like getUserPositionCapId. ```typescript // Instead of: const posCapId = await getUserPositionCapId(blockchain, address); const portfolio = await client.getUserPortfolioFromPositionCapId(posCapId); // Prefer: const portfolios = await client.getUserPortfolio(address); ``` -------------------------------- ### Cache Markets for Multiple Portfolio Queries Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/api-reference/Position.md When querying multiple user portfolios, cache the markets first for efficiency. This avoids redundant market data fetching. ```typescript const markets = await client.getMarketsChain(); const portfolio1 = await client.getUserPortfolioWithCachedMarkets( address1, markets ); const portfolio2 = await client.getUserPortfolioWithCachedMarkets( address2, markets ); ``` -------------------------------- ### Access and Log Active Markets Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/api-reference/constants.md Retrieves the list of active market IDs and logs them. It also shows an example of fetching market data for each active market. ```typescript const activeMarkets = constants.ACTIVE_MARKETS; console.log(`Active markets: ${activeMarkets.join(", ")}`); // [1, 3] // Only operate on active markets for (const marketId of activeMarkets) { const market = await client.getMarketDataFromId(marketId); } ``` -------------------------------- ### Deepbook Integration for Mainnet Swaps Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/api-reference/constants.md Shows how to use Deepbook constants for zap-in supply operations, specifically for USDC-to-dbUSDC swaps on the mainnet. This feature is only available on the mainnet. ```typescript if (client.network === "mainnet") { // Deepbook features only available on mainnet const zapTx = await client.zapInSupply({ marketId: "DBUSDC_MARKET_ID", marketCoinType: constants.DBUSDC_COIN_TYPE, inputCoinType: constants.USDC_COIN_TYPE, inputAmount: 1000000n, address: userAddress, slippage: 0.01, }); } ``` -------------------------------- ### Initialize AlphalendClient with Network Source: https://github.com/alphafitech/alphalend-sdk-js/blob/main/_autodocs/configuration.md Instantiate the AlphalendClient for a specific network, using the default public GraphQL endpoint. ```typescript import { AlphalendClient } from "@alphafi/alphalend-sdk"; // Uses default public GraphQL endpoint const client = new AlphalendClient("mainnet"); ```