### Install Hyperion SDK using PNPM Source: https://docs.hyperion.xyz/developer/via-sdk/prerequisites Installs the Hyperion XYZ SDK package using the pnpm package manager. This is a prerequisite for using the SDK in your project. ```sh $ pnpm i @hyperionxyz/sdk ``` -------------------------------- ### Initialize Hyperion SDK in TypeScript Source: https://docs.hyperion.xyz/developer/via-sdk/prerequisites Initializes the Hyperion SDK for use with either the mainnet or testnet. Requires an Aptos API key for accessing public services. The SDK provides a default initialization method for quick setup. ```typescript import { Network } from "@aptos-labs/ts-sdk"; import { initHyperionSDK } from '@hyperionxyz/sdk' const sdk = initHyperionSDK({ network: Network.MAINNET, APTOS_API_KEY: "Your APTOS API key" }) ``` -------------------------------- ### Example Project Package Configuration (TOML) Source: https://docs.hyperion.xyz/developer/via-contract/get-started This TOML snippet demonstrates a complete package configuration for a project named 'hyperfluid_example'. It includes package metadata, dependencies (specifically 'dex-interface'), and an address definition. ```toml [package] name= "hyperfluid_example" version = "0.0.1" [dependencies] dex-interface = { git = "https://github.com/Hyperfluid/hyperfluid-interface" } [address] hyperfluid_example = "0x0" ``` -------------------------------- ### Calculate Tick Boundaries and Estimate Currency B Amount using Hyperion SDK (TypeScript) Source: https://docs.hyperion.xyz/developer/via-sdk/features-available/create-pool This snippet demonstrates how to calculate tick boundaries based on a fee tier and estimate the amount of Currency B required for a liquidity pool transaction using the Hyperion SDK. It utilizes constants for fee tiers and functions for price-to-tick conversion and amount estimation. Dependencies include the '@hyperionxyz/sdk' package. ```typescript import { FeeTierIndex, HighestTickByStep, LowestTickByStep, priceToTick, } from "@hyperionxyz/sdk" const currencyAAmount = Math.pow(10, 8); // currencyA's decimals is 8 // currencyB's decimals is 6 const decimalsRatio = Math.pow(10, 8 - 6); const feeTierIndex = FeeTierIndex["PER_0.05_SPACING_5"] // To get the tick boundary of this feeTier const lowerTick = LowestTickByStep[feeTierIndex]; const upperTick = HighestTickByStep[feeTierIndex]; // 1 -443630 443630 console.log(feeTierIndex, lowerTick, upperTick); // Or To calculate tick by price const currentPriceTick = priceToTick({ price: 995, feeTierIndex, decimalsRatio, }) const tickLower = priceToTick({ price: 992, feeTierIndex, decimalsRatio, }) const tickUpper = priceToTick({ price: 1336, feeTierIndex, decimalsRatio, }) const [_, currencyBAmount] = await sdk.Pool.estCurrencyBAmountFromA({ // address here mus be fa type currencyA: "0xa", currencyB: "0xc5bcdea4d8a9f5809c5c945a3ff5698a347afb982c7389a335100e1b0043d115", currencyAAmount, feeTierIndex, tickLower, tickUpper, currentPriceTick, }); ``` -------------------------------- ### Generate Create Pool Transaction Payload using Hyperion SDK (TypeScript) Source: https://docs.hyperion.xyz/developer/via-sdk/features-available/create-pool This snippet shows how to generate a transaction payload for creating a liquidity pool using the Hyperion SDK. It covers two scenarios: one for specific token addresses and another for default Aptos coins. The function takes parameters like token amounts, fee tiers, tick boundaries, and slippage. The output is a JSON object representing the transaction payload. ```typescript const params = { currencyA: "0x1::aptos_coin::AptosCoin", currencyB: "0x6926bff1eab5554fa72ae167ed736acf623ab17fe81ebf2ea0d2138f8c533f77::type::T", currencyAAmount, currencyBAmount, feeTierIndex, currentPriceTick, tickLower, tickUpper, slippage: 0.1 }; // generate payload const payload = await sdk.Pool.createPoolTransactionPayload(params) // payload example /* { "function": "0xdd8d1a676801c6789fac9a06b8f6ced76f766c798f7e5ea276f25d80b9aa0af0::router_adapter::create_liquidity_entry", "typeArguments": [], "functionArguments": [ // Token A FA type '0xa', // Token B FA type '0xb', // feeTierIndex: it can be found from the table above. 1, // Pool Type: a constant value, just set it to false false, // the ticks must be greater and equal to 0 // If you want to pass a negative integer, please convert it to a unsigned integer. // low price's tick 22410, // high price's tick 25930, // current price's tick 22940, // Token A amount 100000000, // Token B amount 200287120, // Token A amount * (1 - slippage) 99900000, // Token B amount * (1 - slippage) 200086833, // Expiration time in second 4891474469 ] } */ // or /* { "function": "0xdd8d1a676801c6789fac9a06b8f6ced76f766c798f7e5ea276f25d80b9aa0af0::router_adapter::create_liquidity_both_coin_entry", "typeArguments": [ "0x1::aptos_coin::AptosCoin", "0x6926bff1eab5554fa72ae167ed736acf623ab17fe81ebf2ea0d2138f8c533f77::type::T" ], "functionArguments": [ // feeTierIndex: it can be found from the table above. 1, // Pool Type: a constant value, just set it to false false, // the ticks must be greater and equal to 0 // If you want to pass a negative integer, please convert it to a unsigned integer. // low price's tick 22410, // high price's tick 25930, // current price's tick 22940, // Token A amount 100000000, // Token B amount 200287120, // Token A amount * (1 - slippage) 99900000, // Token B amount * (1 - slippage) 200086833, // Expiration time in second 4891474469 ] } */ ``` -------------------------------- ### Batch Get Ticks by Pool ID (TypeScript) Source: https://docs.hyperion.xyz/developer/via-sdk/features-available/get-ticks Fetches a batch of ticks for a given pool ID using the `sdk.Pool.fetchTicks` method. This function requires the pool object ID as input and returns a list of ticks. Ensure the SDK is properly initialized before use. ```typescript async function fetchTicksByPoolId() { await ticks = await sdk.Pool.fetchTicks({ poolId: '' }) } ``` -------------------------------- ### Get Pool Stat Source: https://docs.hyperion.xyz/developer/via-api Retrieve statistical information about a specific pool or all pools using the Hyperion GraphQL API. ```APIDOC ## GET /v1/graphql ### Description This endpoint allows you to retrieve statistical data for one or more liquidity pools. You can query for a specific pool by providing its ID, or omit the `$poolId` parameter to get statistics for all pools. ### Method POST ### Endpoint `https://hyperfluid-api.alcove.pro/v1/graphql` ### Parameters #### Query Parameters - **poolId** (String) - Optional - The unique identifier for the pool for which to retrieve statistics. ### Request Body ```graphql query MyQuery($poolId: String = "") { api { getPoolStat(poolId: $poolId) { dailyVolumeUSD // 24 hour volume in USD farmAPR // reward APR, % feeAPR // fee APR, % feesUSD // fee in USD id // pool id tvlUSD // TVL in USD pool { currentTick // current tick activeLpAmount // active lp amount feeRate // fee rata, 100 = 0.01% sqrtPrice // current sqrt price token1 // token1 FA address token2 // token2 FA address } } } } ``` ### Request Example ```json { "query": "query MyQuery($poolId: String = \"\") { api { getPoolStat(poolId: $poolId) { dailyVolumeUSD farmAPR feeAPR feesUSD id tvlUSD pool { currentTick activeLpAmount feeRate sqrtPrice token1 token2 } } } }", "variables": { "poolId": "0x123..." } } ``` ### Response #### Success Response (200) - **dailyVolumeUSD** (Float) - The 24-hour trading volume for the pool in USD. - **farmAPR** (Float) - The Annual Percentage Rate for farming rewards. - **feeAPR** (Float) - The Annual Percentage Rate for trading fees. - **feesUSD** (Float) - The total fees generated by the pool in USD. - **id** (String) - The unique identifier of the pool. - **tvlUSD** (Float) - The total value locked in the pool in USD. - **pool** (Object) - Contains detailed information about the pool's internal state. - **currentTick** (Int) - The current tick of the liquidity pool. - **activeLpAmount** (Float) - The amount of active liquidity provider tokens. - **feeRate** (Int) - The fee rate, where 100 represents 0.01%. - **sqrtPrice** (String) - The current square root of the pool's price. - **token1** (String) - The FA address of the first token in the pool. - **token2** (String) - The FA address of the second token in the pool. #### Response Example ```json { "data": { "api": { "getPoolStat": [ { "dailyVolumeUSD": 12345.67, "farmAPR": 5.5, "feeAPR": 1.2, "feesUSD": 500.75, "id": "0xabc...", "tvlUSD": 1000000.00, "pool": { "currentTick": 12345, "activeLpAmount": 98765.43, "feeRate": 100, "sqrtPrice": "1.00000000000000000000000000000000", "token1": "0xtoken1...", "token2": "0xtoken2..." } } ] } } } ``` ``` -------------------------------- ### Exact Input Swap Entry Function (Move) Source: https://docs.hyperion.xyz/developer/via-contract/features-available/swap The `exact_input_swap_entry` function enables direct token swaps where the input amount is precisely defined. It takes parameters like fee tier, input amount, minimum output amount, price limit, token metadata, recipient address, and deadline. Dependencies include the signer, metadata objects, and address types. ```move public entry fun exact_input_swap_entry( user: &signer, fee_tier: u8, amount_in: u64, amount_out_min: u64, sqrt_price_limit: u128, from_token: Object, to_token: Object, recipient: address, _deadline: u64 ) { ... } ``` -------------------------------- ### Exact Output Swap Entry Function (Move) Source: https://docs.hyperion.xyz/developer/via-contract/features-available/swap The `exact_output_swap_entry` function facilitates token swaps aiming for a specific output amount. It requires parameters such as fee tier, maximum input amount, desired output amount, price limit, token metadata, recipient address, and deadline. The function ensures that the output is at least the specified amount, with a cap on the input. ```move public entry fun exact_output_swap_entry( user: &signer, fee_tier: u8, amount_in_max: u64, amount_out: u64, sqrt_price_limit: u128, from_token: Object, to_token: Object, recipient: address, _deadline: u64 ) { ... } ``` -------------------------------- ### Estimate Swap Amounts and Generate Transaction Payload (TypeScript) Source: https://docs.hyperion.xyz/developer/via-sdk/features-available/swap This snippet demonstrates how to estimate the output amount for a token swap and then generate the transaction payload for the swap. It utilizes `sdk.Swap.estToAmount` for estimation and `sdk.Swap.swapTransactionPayload` for payload generation. Ensure that the `from` and `to` token addresses are valid and that `poolRoute` is correctly obtained from the estimation step. The `slippage` parameter controls the acceptable price deviation. ```typescript const currencyAAmount = Math.pow(10,7) const { amountOut: currencyBAmount, path: poolRoute} = await sdk.Swap.estToAmount({ amount: currencyAAmount, from: "0xa", to: "0xc5bcdea4d8a9f5809c5c945a3ff5698a347afb982c7389a335100e1b0043d115", // safeMode // if safeMode is true, only few swap token pairs will return path route // default: true. support from (v0.0.12) safeMode: false }) /* { "amountOut": "10000000", // This is for toAmount "amountIn": "1279371", // This is for fromAmount // swap path route "path": [ "0x0d21c2f5628db619957703e90ab07bcb2b13ad6983da2b5d721f24523cae29ff" ] } */ const params = { // here must be fa type currencyA: '0xa', currencyB: "0xc5bcdea4d8a9f5809c5c945a3ff5698a347afb982c7389a335100e1b0043d115", currencyAAmount, currencyBAmount, slippage: 0.1, poolRoute, recipient: '', } const payload = await sdk.Swap.swapTransactionPayload(params) console.log(payload) ``` -------------------------------- ### Fetch All Pools using SDK (TypeScript) Source: https://docs.hyperion.xyz/developer/via-sdk/features-available/get-pools Retrieves all available pools from the Hyperion XYZ platform using the `sdk.Pool.fetchAllPools` method. This function is asynchronous and logs the retrieved pool items to the console. It has no specific input parameters. ```typescript async function fetchAllPools() { const poolItems = await sdk.Pool.fetchAllPools(); console.log(poolItems) } ``` -------------------------------- ### Open Position Function in Pool V3 Source: https://docs.hyperion.xyz/developer/via-contract/features-available/open-position The `open_position` function in the `pool_v3` module is used to open new empty positions. It requires a signer, two token metadata objects, a fee tier, and the lower and upper tick bounds for the position. It returns information about the created position. ```Sol public fun open_position( user: &signer, token_a: Object, token_b: Object, fee_tier: u8, tick_lower: u32, tick_upper: u32, ): Object { ... } ``` -------------------------------- ### Create Add Liquidity Transaction Payload Source: https://docs.hyperion.xyz/developer/via-sdk/features-available/add-liquidity Generates the transaction payload for adding liquidity to a position. Requires details about the position, token amounts, fee tier, and slippage. Ensure correct currency types and amounts are provided. ```typescript const currencyAAmount = Math.pow(10, 8); // currencyA's decimals is 8 // currencyB's decimals is 6 const decimalsRatio = Math.pow(10, 8 - 6); const feeTierIndex = FeeTierIndex["PER_0.05_SPACING_5"]; const currentPriceTick = priceToTick({ price: 995, feeTierIndex, decimalsRatio, }); const tickLower = priceToTick({ price: 992, feeTierIndex, decimalsRatio, }); const tickUpper = priceToTick({ price: 1336, feeTierIndex, decimalsRatio, }); const [_, currencyBAmount] = await sdk.Pool.estCurrencyBAmountFromA({ // address here mus be fa type currencyA: "0xa", currencyB: "0xc5bcdea4d8a9f5809c5c945a3ff5698a347afb982c7389a335100e1b0043d115", currencyAAmount, feeTierIndex, tickLower, tickUpper, currentPriceTick, }); const params = { positionId: '', currencyA: "0x1::aptos_coin::AptosCoin", currencyB: "0x6926bff1eab5554fa72ae167ed736acf623ab17fe81ebf2ea0d2138f8c533f77::type::T", currencyAAmount, currencyBAmount, slippage: 0.1, feeTierIndex, }; const payload = await sdk.Position.addLiquidityTransactionPayload(params); ``` -------------------------------- ### Create Pool Function Signature - Kotlin Source: https://docs.hyperion.xyz/developer/via-contract/features-available/create-pool Defines the signature for the `create_pool` function in the `pool_v3` module. This function is used to create a new liquidity pool with specified token pairs, fee tier, and initial tick. It returns an `Object` representing the created pool. ```Kotlin public fun create_pool( token_a: Object, token_b: Object, fee_tier: u8, tick: u32, ): Object { ... } ``` -------------------------------- ### Fetch All Positions by Owner Address (TypeScript) Source: https://docs.hyperion.xyz/developer/via-sdk/features-available/get-positions Retrieves all positions owned by a specific address using the `sdk.Position.fetchAllPositionsByAddress` method. This function takes the owner's address as input and returns an array of position objects. The output includes details about position activity, value, subsidies, fees (claimed and unclaimed), and position-specific pool information. ```typescript async function fetchPositionsByAddress() { const positions = await sdk.Position.fetchAllPositionsByAddress({ address: '0x7fd8...aedc1' }) } ``` -------------------------------- ### Fetch Position Fee History (TypeScript) Source: https://docs.hyperion.xyz/developer/via-sdk/features-available/get-positions Retrieves the fee history for a specific position using its `positionId` and the owner's `address`. The `sdk.Position.fetchFeeHistory` method allows users to query historical fee data associated with their positions. This function requires both `positionId` and `address` as input parameters. ```typescript async function fetchFeeHistory() { const feeHistory = await sdk.Position.fetchFeeHistory({ positionId: '', address: '', }) console.log(feeHistory); } ``` -------------------------------- ### Define DEX Interface Dependency (TOML) Source: https://docs.hyperion.xyz/developer/via-contract/get-started This snippet shows how to declare the 'dex-interface' dependency in a TOML file, specifically for use with Git repositories. It is commonly used in Rust projects for managing external libraries. ```toml dex-interface = { git = "https://github.com/Hyperfluid/hyperfluid-interface" } ``` -------------------------------- ### Generate Swap Transaction Payload with Partnership (TypeScript) Source: https://docs.hyperion.xyz/developer/via-sdk/features-available/swap This snippet illustrates how to generate a transaction payload for a token swap that includes a partnership. It first estimates the swap amounts using `sdk.Swap.estToAmount` and then generates the payload with partnership details using `sdk.Swap.swapWithPartnershipTransactionPayload`. This function is available from v0.0.17. Ensure the `partnership` string is replaced with your actual platform name. ```typescript const currencyAAmount = Math.pow(10,7) const { amountOut: currencyBAmount, path: poolRoute} = await sdk.Swap.estToAmount({ amount: currencyAAmount, from: "0xa", to: "0xc5bcdea4d8a9f5809c5c945a3ff5698a347afb982c7389a335100e1b0043d115", // safeMode // if safeMode is true, only few swap token pairs will return path route // default: true. support from (v0.0.12) safeMode: false }) /* { "amountOut": "10000000", // This is for toAmount "amountIn": "1279371", // This is for fromAmount // swap path route "path": [ "0x0d21c2f5628db619957703e90ab07bcb2b13ad6983da2b5d721f24523cae29ff" ] } */ const params = { // here must be fa type currencyA: '0xa', currencyB: '0xc5bcdea4d8a9f5809c5c945a3ff5698a347afb982c7389a335100e1b0043d115', currencyAAmount, currencyBAmount, slippage: 0.1, poolRoute, partnership: 'your_platform_name' } const payload = await sdk.Swap.swapWithPartnershipTransactionPayload(params) console.log(payload) ``` -------------------------------- ### Define Rewarder Structures (Move) Source: https://docs.hyperion.xyz/developer/via-contract/data-structure Defines the data structures for managing rewards in Hyperion. Includes `RewarderManager` to oversee multiple rewarders, `Rewarder` for individual reward configurations and state, and `PositionReward` to track rewards specific to a user's position. These are part of the Aptos framework. ```move struct RewarderManager has store { rewarders: vector, last_updated_time: u64, pause: bool } struct Rewarder has copy, drop, store { reward_store: Object, emissions_per_second: u64, emissions_per_second_max: u64, emissions_per_liquidity_start: u128, emissions_per_liquidity_latest: u128, user_owed: u64, pause: bool } /// The Position's rewarder record struct PositionReward has drop, copy, store { emissions_per_liquidity_inside: u128, amount_owned: u64, } ``` -------------------------------- ### Define Liquidity Pool V3 Structure (Move) Source: https://docs.hyperion.xyz/developer/via-contract/data-structure Defines the `LiquidityPoolV3` struct, representing a liquidity pool in the Hyperion protocol. It includes fields for token liquidity, fees, price, tick information, observation data, fee rates, and rewarder management. This structure is part of the Aptos framework. ```move #[resource_group_member(group = aptos_framework::object::ObjectGroup)] struct LiquidityPoolV3 has key { token_a_liquidity: Object, token_b_liquidity: Object, token_a_fee: Object, token_b_fee: Object, // the current price sqrt_price: u128, // liquidity current tick liquidity: u128, // the current tick tick: I32, // the most-recently updated index of the observations array observation_index: u64, // the current maximum number of observations that are being stored observation_cardinality: u64, // the next maximum number of observations to store, triggered in observations.write observation_cardinality_next: u64, /// The numerator of fee rate, the denominator is 1_000_000. fee_rate: u64, // the current protocol fee as a percentage of the swap fee taken on withdrawal // the denominator is 1_000_000. fee_protocol: u64, // whether the pool is locked unlocked: bool, fee_growth_global_a: u128, fee_growth_global_b: u128, seconds_per_liquidity_oracle: u128, seconds_per_liquidity_incentive: u128, position_blacklist: PositionBlackList, last_update_timestamp: u64, tick_info: SmartTable, tick_map: BitMap, tick_spacing: u32, protocol_fees: ProtocolFees, lp_token_refs: LPTokenRefs, max_liquidity_per_tick: u128, rewarder_manager: RewarderManager } ``` -------------------------------- ### Define Position Information Structure (Move) Source: https://docs.hyperion.xyz/developer/via-contract/data-structure Defines the `Info` struct for user positions within a liquidity pool. It tracks liquidity amounts, tick ranges, fee growth, owed fees, associated tokens, fee tier, and associated rewards. This structure is part of the Aptos framework. ```move #[resource_group_member(group = aptos_framework::object::ObjectGroup)] struct Info has key { // whether inited after migration initialized: bool, // the amount of liquidity owned by this position liquidity: u128, tick_lower: I32, tick_upper: I32, // fee growth per unit of liquidity as of the last update to liquidity or fees owed fee_growth_inside_a_last: u128, fee_growth_inside_b_last: u128, // the fees owed to the position owner in token0/token1 fee_owed_a: u64, fee_owed_b: u64, token_a: Object, token_b: Object, fee_tier: u8, rewards: vector, } ``` -------------------------------- ### Fetch Pool by Token Pair and Fee Tier using SDK (JavaScript) Source: https://docs.hyperion.xyz/developer/via-sdk/features-available/get-pools Retrieves a specific pool based on its token asset types and fee tier using the `sdk.Pool.getPoolByTokenPairAndFeeTier` method. This function, available from v0.0.7, requires `token1`, `token2`, and `feeTier` as input parameters. The `feeTier` is an enum value. ```javascript async function fetchOnePool() { const pool = await sdk.Pool.getPoolByTokenPairAndFeeTier({ token1: '0x1::aptos_coin::AptosCoin', token2: '0x6926bff1eab5554fa72ae167ed736acf623ab17fe81ebf2ea0d2138f8c533f77::type::T', feeTier: FeeTierIndex["PER_0.01_SPACING_1"], }) } ``` -------------------------------- ### TypeScript Interface for Token Information Source: https://docs.hyperion.xyz/developer/via-sdk/features-available/types Specifies the detailed information for a token, including its asset type, market cap ID, symbol, decimals, logo, and website URL. This interface is essential for displaying token details and facilitating token-related operations. ```typescript interface TokenInfo { assetType: string; bridge: string | null; coinMarketcapId: string; coinType: string; coingeckoId: string; decimals: number; faType: string; hyperfluidSymbol: string; logoUrl: string; name: string; symbol: string; isBanned: boolean; websiteUrl: string | null; } ``` -------------------------------- ### TypeScript Interface for Pool Details Source: https://docs.hyperion.xyz/developer/via-sdk/features-available/types Defines the detailed structure of a liquidity pool, including its tick, fee rate, ID, sender address, square root price, and information about the two tokens it comprises. This interface is fundamental for understanding pool mechanics and trading operations. ```typescript interface Pool { currentTick: number; feeRate: string; feeTier: number; poolId: string; senderAddress: string; sqrtPrice: string; token1: string; token2: string; token1Info: TokenInfo; token2Info: TokenInfo; } ``` -------------------------------- ### Fetch Pool by ID using SDK (TypeScript) Source: https://docs.hyperion.xyz/developer/via-sdk/features-available/get-pools Fetches a single pool by its unique identifier using the `sdk.Pool.fetchPoolById` method. This asynchronous function requires a `poolId` as input and returns the details of the specified pool. The `poolId` is a string representing the pool's address. ```typescript async function fetchOnePool() { const pool = await sdk.Pool.fetchPoolById({ poolId: '0xf108...876b5' }) } ``` -------------------------------- ### Fetch Single Position by ID (TypeScript) Source: https://docs.hyperion.xyz/developer/via-sdk/features-available/get-positions Fetches a specific position using its unique `positionId` and the owner's `address`. This method, `sdk.Position.fetchPositionById`, is useful for retrieving detailed information about a single, identified position. Both `positionId` and `address` are required parameters. ```typescript async function fetchPositionById() { const pool = await sdk.Position.fetchPositionById({ positionId: '', address: '', }) console.log(pool); } ``` -------------------------------- ### TypeScript Interfaces for Fee and Subsidy Structures Source: https://docs.hyperion.xyz/developer/via-sdk/features-available/types Defines the structures for `Subsidy` and `Fee` objects, each containing arrays for claimed and unclaimed amounts. These interfaces are used to track financial distributions and transaction fees within the platform. ```typescript interface Subsidy { claimed: Array<{ amount: string; amountUSD: string; token: string; }>; unclaimed: Array<{ amount: string; amountUSD: string; token: string; }>; } interface Fee { claimed: Array<{ amount: string; amountUSD: string; token: string; }>; unclaimed: Array<{ amount: string; amountUSD: string; token: string; }>; } ``` -------------------------------- ### Add Liquidity Function Signature - Move Source: https://docs.hyperion.xyz/developer/via-contract/features-available/add-liquidity The `add_liquidity` function in the `pool_v3` module is used to add liquidity to an existing position. It requires the user's signer, the position details, the amount of liquidity to add, and the fungible assets for token A and token B. It returns the new position ID, amount of token A and B added, and the remaining fungible assets. ```move public fun add_liquidity( user: &signer, position: Object, liquidity_delta: u128, fa_a: FungibleAsset, fa_b: FungibleAsset ):(u64, u64, FungibleAsset, FungibleAsset) { ... } ``` -------------------------------- ### TypeScript Interface for Pool Item Data Source: https://docs.hyperion.xyz/developer/via-sdk/features-available/types Defines the structure for a pool item, containing essential financial metrics like APR, volume, fees, TVL, and a reference to the Pool object. This interface is crucial for displaying and managing individual liquidity pool data. ```typescript interface PoolItem { id: string; aprUSD: string; dailyVolumeUSD: string; feesUSD: string; tvlUSD: string; pool: Pool; } ``` -------------------------------- ### Fetch Pool Statistics via GraphQL API Source: https://docs.hyperion.xyz/developer/via-api This GraphQL query retrieves detailed statistics for a specific pool or all pools if no pool ID is provided. It returns data such as daily volume, APRs, fees, TVL, and pool-specific details like current tick and token information. Requires access to the Hyperion GraphQL API endpoint. ```graphql query MyQuery($poolId: String = "") { api { getPoolStat(poolId: $poolId) { dailyVolumeUSD // 24 hour volume in USD farmAPR // reward APR, % feeAPR // fee APR, % feesUSD // fee in USD id // pool id tvlUSD // TVL in USD pool { currentTick // current tick activeLpAmount // active lp amount feeRate // fee rata, 100 = 0.01% sqrtPrice // current sqrt price token1 // token1 FA address token2 // token2 FA address } } } } ``` -------------------------------- ### Add Liquidity Single (Zap In) - Rust Source: https://docs.hyperion.xyz/developer/via-contract/features-available/add-liquidity-zap-in The `add_liquidity_single` function allows users to add liquidity to a position using a single asset. The contract automatically swaps a portion of the input asset for the other token in the pair to create a balanced liquidity position. It includes parameters for slippage tolerance and swap ratio thresholds to manage price risk and prevent unbalanced deposits. ```rust public entry fun add_liquidity_single( lp: &signer, lp_object: Object, from_a: Object, to_b: Object, amount_in: u64, slippage_numerators: u256, slippage_denominator: u256, threshold_numerator: u256, threshold_denominator: u256 ) { // ... function body ... } ``` -------------------------------- ### Claim Rewards Function in Kotlin Source: https://docs.hyperion.xyz/developer/via-contract/features-available/collect-rewards This function allows users to claim rewards associated with a specific position. It takes a signer representing the user and an object representing the position as input, and returns a vector of FungibleAsset upon successful reward claim. Dependencies include the position_v3 module. ```Kotlin public fun claim_rewards( user: &signer, position: Object ): vector { ... } ``` -------------------------------- ### Generate All Rewards Claim Payload - TypeScript Source: https://docs.hyperion.xyz/developer/via-sdk/features-available/fee-and-rewards Generates a transaction payload for claiming all rewards associated with a specific position ID. This function requires the position's ID and the recipient's address for the reward distribution. Ensure valid inputs are provided to generate a correct payload. ```typescript const payload = sdk.Position.claimAllRewardsTransactionPayload({ positionId: '', recipient: '' }) ``` -------------------------------- ### Remove Liquidity Single (Zap Out) Source: https://docs.hyperion.xyz/developer/via-contract/features-available/remove-liquidity-zap-out This endpoint allows you to withdraw liquidity from a position and receive the entire value in a single specified token. It simplifies the process by automatically swapping one of the withdrawn assets if necessary. ```APIDOC ## POST /remove_liquidity_single ### Description Withdraws liquidity from a position and receives the funds as a single asset (a "zap out" transaction). This function removes liquidity from the pool and automatically swaps one of the assets for the other, so you receive the entire value in a single, specified token. ### Method POST ### Endpoint /remove_liquidity_single ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **lp** (signer) - Required - The signer of the transaction, representing the liquidity provider who owns the position. - **lp_object** (Object) - Required - The liquidity position object from which you are withdrawing. - **liquidity_delta** (u128) - Required - The amount of liquidity units to remove. This is **not a token amount** but an abstract `u128` value representing your share in the pool. To withdraw everything, use the full `liquidity` value from your `lp_object`. - **to_meta** (Object) - Required - The metadata of the **single token** you wish to receive as output. - **slippage_numerators** (u256) - Required - The numerator for calculating slippage tolerance on the internal swap required to consolidate your assets. For a 1% slippage, this would be `99`. - **slippage_denominator** (u256) - Required - The denominator for calculating slippage tolerance, typically `100`. ### Request Example ```json { "lp": "0x123...", "lp_object": "0x456...", "liquidity_delta": 1000000000000000000, "to_meta": "0x789...", "slippage_numerators": 99, "slippage_denominator": 100 } ``` ### Response #### Success Response (200) - **transaction_status** (string) - Indicates the success or failure of the transaction. #### Response Example ```json { "transaction_status": "success" } ``` ### Detailed Parameter Explanation #### **Liquidity Delta (`liquidity_delta`)** This is the most critical parameter to understand correctly. * **What it is**: `liquidity_delta` represents the "amount of liquidity" you want to remove, which is an abstract unit calculated by the protocol. It is **not** an amount of Token A or Token B. * **How to get it**: You typically read the current `liquidity` value from your `lp_object`. If you want to withdraw all your funds, you would pass this full value as the `liquidity_delta`. If you only want to withdraw a portion (e.g., 50%), you would pass half of that value. #### **Slippage Tolerance (`slippage_numerators` / `slippage_denominator`)** This setting is crucial because the function performs an internal swap. * **Example**: Imagine your position is in a APT/USDT pool. When you call this function and set `to_meta` to be USDT's metadata, the function does the following: 1. Removes your proportional share of APT and USDT from the pool. 2. Internally swaps the APT portion for USDT. 3. Sends you the total amount of USDT. * **Meaning**: The slippage tolerance applies to step 2. Setting `slippage_numerators` to `99` and `slippage_denominator` to `100` means you are willing to accept up to 1% negative slippage on the APT-to-USDT swap. If the price impact is worse than that, the transaction will fail, protecting your funds. ``` -------------------------------- ### Generate Fee Claim Payload - TypeScript Source: https://docs.hyperion.xyz/developer/via-sdk/features-available/fee-and-rewards Generates a transaction payload for claiming transaction fees for a specific position. The function requires the position ID and the recipient's address where the fees should be sent. This is useful for harvesting fees separately from rewards. ```typescript const payload = sdk.Position.claimFeeTransactionPayload({ positionId: '', recipient: '' }) ``` -------------------------------- ### Generate Reward Claim Payload - TypeScript Source: https://docs.hyperion.xyz/developer/via-sdk/features-available/fee-and-rewards Generates a transaction payload for claiming a specific reward for a given position. This method requires the position ID and the recipient's address. It allows for granular control over reward claims. ```typescript const payload = sdk.Position.claimRewardTransactionPayload({ positionId: '', recipient: '' }) ``` -------------------------------- ### Rust: Remove Liquidity Single Entry Function Source: https://docs.hyperion.xyz/developer/via-contract/features-available/remove-liquidity-zap-out The `remove_liquidity_single` function in the `router_v3` module allows users to withdraw liquidity from a position and receive the assets as a single token. It handles the internal swapping of one asset for another to consolidate the output. Key parameters include the liquidity position object, the amount of liquidity to remove, the metadata of the desired output token, and slippage tolerance settings. ```rust public entry fun remove_liquidity_single( lp: &signer, lp_object: Object, liquidity_delta: u128, to_meta: Object, slippage_numerators: u256, slippage_denominator: u256 ) { // ... function body ... } ``` -------------------------------- ### Remove Liquidity Transaction Payload in TypeScript Source: https://docs.hyperion.xyz/developer/via-sdk/features-available/remove-liquidity This TypeScript snippet demonstrates how to construct a transaction payload for removing liquidity from a position. It involves fetching existing position details, calculating the amounts to remove based on a ratio, and then calling the `removeLiquidityTransactionPayload` method with the necessary parameters. Ensure that `sdk`, `positionId`, `accountAddress`, and `position` are correctly initialized. ```typescript const position = await sdk.Position.fetchPositionById({ positionId: '', address: '', }) /* [ { "objectId": "0x4b65447d775934596686ef643ad10f3f552b35ff5c2d1bf992c616e4b527fe77", "poolId": "0xf1083e26e765506c9360d6b07c1478e6bc40376848b4ee44f4f3c729cf2876b5", "txnTimestamp": "2024-12-23T16:36:49.417659+08:00", "currentAmount": 396855612, "position": { "tickLower": 22410, "tickUpper": 25930 }, "pool": [ { "currentTick": 22971, "feeRate": 500, "feeTier": 1, "poolId": "0xf1083e26e765506c9360d6b07c1478e6bc40376848b4ee44f4f3c729cf2876b5", "senderAddress": "0xa5647cdb26df359efb506b5e06a320349b34bbc995314a35f3670a98a210afc6", "sqrtPrice": 58172517897304750000, "token1": "0x000000000000000000000000000000000000000000000000000000000000000a", "token2": "0xc5bcdea4d8a9f5809c5c945a3ff5698a347afb982c7389a335100e1b0043d115", "token1Info": { "assetType": "0x000000000000000000000000000000000000000000000000000000000000000a", "bridge": null, "coinMarketcapId": "21794", "coinType": "0x1::aptos_coin::AptosCoin", "coingeckoId": "", "decimals": 8, "faType": "0xa", "hyperfluidSymbol": "APT", "logoUrl": "https://hyperfluid.xyz/aptos-token/main/logos/APT.svg", "name": "Aptos Coin", "symbol": "APT", "isBanned": false, "websiteUrl": "https://aptosfoundation.org" }, "token2Info": { "assetType": "0xc5bcdea4d8a9f5809c5c945a3ff5698a347afb982c7389a335100e1b0043d115", "bridge": null, "coinMarketcapId": "", "coinType": "0x6926bff1eab5554fa72ae167ed736acf623ab17fe81ebf2ea0d2138f8c533f77::type::T", "coingeckoId": "", "decimals": 6, "faType": "0xc5bcdea4d8a9f5809c5c945a3ff5698a347afb982c7389a335100e1b0043d115", "hyperfluidSymbol": "hfShaq", "logoUrl": "", "name": "Shaq", "symbol": "hfShaq", "isBanned": false, "websiteUrl": null } } ] } ] */ const [currencyAAmount, currencyBAmount] = await sdk.Position.fetchTokensAmountByPositionId({ positionId, }) const removeRatio = 0.5 const params = { positionId, currencyA: "0x1::aptos_coin::AptosCoin", currencyB: "0x6926bff1eab5554fa72ae167ed736acf623ab17fe81ebf2ea0d2138f8c533f77::type::T", currencyAAmount: parseInt(currencyAAmount * removeRatio), currencyBAmount: parseInt(currencyBAmount * removeRatio), deltaLiquidity: parseInt(position[0].currentAmount * removeRatio), slippage: 0.1, recipient: accountAddress, } const payload = await sdk.Position.removeLiquidityTransactionPayload(params) console.log(payload) ``` -------------------------------- ### Remove Liquidity Function (Move) Source: https://docs.hyperion.xyz/developer/via-contract/features-available/remove-liquidity The `remove_liquidity` function is used to remove a specified amount of liquidity from a position in the pool_v3 module. It takes a signer for the user, the position object, and the liquidity delta as input. It returns a tuple of optional fungible assets representing the removed liquidity. ```move public fun remove_liquidity( user: &signer, position: Object, liquidity_delta: u128 ): (Option, Option) { ```