UNPKG

@cyberk/hyperion-sdk

Version:

Hyperion SDK from Cyberk

697 lines (535 loc) 27.8 kB
# TS Utils ## Hooks This section provides guidance on using the React hooks available in the `hyperion-sdk` package. ### `useAllPairs` Fetches information about all liquidity pairs available in a specific Hyperion Swap factory contract. **Purpose:** Retrieves an array of `PairInfo` objects, each containing details about a liquidity pair, such as the contract address and the assets involved. **Usage:** ```typescript import { useAllPairs } from '@cyberk/hyperion-sdk'; import { CHAIN_IDS } from '@cyberk/hyperion-sdk/constants'; const factoryAddress = 'your_factory_contract_address'; // Replace with the actual factory address const chainId = CHAIN_IDS.TITAN_TESTNET; // Or the relevant chain ID const { data: pairs, isLoading, error } = useAllPairs({ factoryAddress, chainId, // Optional react-query options options: { staleTime: 5 * 60 * 1000, // 5 minutes } }); // Now you can use `pairs`, `isLoading`, and `error` variables. ``` **Parameters:** * `factoryAddress` (string, required): The address of the Hyperion Swap factory contract to query. * `chainId` (`CHAIN_IDS`, required): The identifier of the target blockchain (e.g., `CHAIN_IDS.TITAN_TESTNET`). You'll need to import `CHAIN_IDS` from the constants. * `options` (object, optional): Optional configuration object passed directly to `react-query`'s `useQuery`. Allows customization of caching, refetching behavior, etc. See `@tanstack/react-query` documentation for details. **Returns:** Returns a `react-query` query object containing: * `data` (`PairInfo[] | undefined`): An array of `PairInfo` objects when the query is successful, otherwise `undefined`. The `PairInfo` type contains details like `contractAddr`, `liquidityToken`, and `assetInfos` (which contains transformed asset information). * `isLoading` (boolean): True while the query is fetching data. * `error` (Error | null): An error object if the query failed, otherwise `null`. * ... other `react-query` properties (`status`, `refetch`, etc.). ### `useRegisteredNativeTokenDecimals` Fetches the registered decimal value for a specific native token from the factory contract. **Purpose:** Retrieves the number of decimals for a given native token's denomination (`denom`). This is useful for UI formatting and calculations. **Usage:** ```typescript import { useRegisteredNativeTokenDecimals } from '@cyberk/hyperion-sdk'; import { CHAIN_IDS } from '@cyberk/hyperion-sdk/constants'; const factoryAddress = 'your_factory_contract_address'; // Replace with the actual factory address const chainId = CHAIN_IDS.TITAN_TESTNET; // Or the relevant chain ID const denom = 'your_native_token_denom'; // The denom of the native token to look up const { data: decimals, isLoading, error } = useRegisteredNativeTokenDecimals({ factoryAddress, chainId, denom, // Optional react-query options options: { staleTime: 5 * 60 * 1000, // 5 minutes } }); // Now you can use `decimals`, `isLoading`, and `error` variables. ``` **Parameters:** * `factoryAddress` (string, required): The address of the Hyperion Swap factory contract to query. * `chainId` (`CHAIN_IDS`, required): The identifier of the target blockchain (e.g., `CHAIN_IDS.TITAN_TESTNET`). * `denom` (string, required): The denomination of the native token. * `options` (object, optional): Optional configuration object passed directly to `react-query`'s `useQuery`. Allows customization of caching, refetching behavior, etc. See `@tanstack/react-query` documentation for details. **Returns:** Returns a `react-query` query object containing: * `data` (`number | undefined`): The number of decimals for the token when the query is successful, otherwise `undefined`. * `isLoading` (boolean): True while the query is fetching data. * `error` (Error | null): An error object if the query failed, otherwise `null`. * ... other `react-query` properties (`status`, `refetch`, etc.). ### `useQuote` Fetches a quote for a swap operation by simulating the swap on the Hyperion Swap router contract. **Purpose:** Retrieves simulation results for a potential swap operation, including the expected return amount and other swap details. **Usage:** ```typescript import { useQuote } from '@cyberk/hyperion-sdk'; import { CHAIN_IDS } from '@cyberk/hyperion-sdk/constants'; const { data: simulateSwapOperations, isLoading, isFetching, isError, error, } = useQuote({ chainId: CHAIN_IDS.TITAN_TESTNET, routerContract: "titan1kadsh3puymfd9dvtm6uncpwrfq97wzgrv6cacnyllkf6ydj90uaq9kvs7q", offerAmount: (1e18).toString(), offerAsset: "atkx", askAsset: "ibc/7C0807A56073C4A27B0DE1C21BA3EB75DF75FD763F4AD37BC159917FC01145F0", }); ``` **Parameters:** * `chainId` (`CHAIN_IDS`, required): The identifier of the target blockchain (e.g., `CHAIN_IDS.TITAN_TESTNET`). * `routerContract` (string, required): The address of the Hyperion Swap router contract. * `offerAmount` (string, required): The amount of the asset being offered for the swap, in string format. * `offerAsset` (string, required): The identifier of the asset being offered (e.g., "atkx"). * `askAsset` (string, required): The identifier of the asset being requested in return. * `options` (object, optional): Optional configuration object passed directly to `react-query`'s `useQuery`. Allows customization of caching, refetching behavior, etc. **Returns:** Returns a `react-query` query object containing: * `data` (`SimulationResponse | undefined`): The simulation response containing swap details when the query is successful, otherwise `undefined`. * `isLoading` (boolean): True while the query is fetching data. * `isFetching` (boolean): True while the query is fetching data, even if there is cached data. * `isError` (boolean): True if the query resulted in an error. * `error` (Error | null): An error object if the query failed, otherwise `null`. * ... other `react-query` properties (`status`, `refetch`, etc.). ### `useSimulateSwap` Simulates a swap operation to estimate the gas cost before executing the actual swap. **Purpose:** Estimates the gas cost (in bigint) for a potential swap operation without actually executing the transaction. **Usage:** ```typescript import { useSimulateSwap } from '@cyberk/hyperion-sdk'; import { SigningClient } from "@titanlabjs/cosmos/signing-client"; const { mutate: simulateSwap, data: estimatedGas, isLoading, isError, error, } = useSimulateSwap({ onSuccess: (gas) => { console.log('Estimated gas:', gas); }, }); // Call the simulation simulateSwap({ signingClient: signingClient, // SigningClient instance signerAddress: "titan1...", // Address of the signer routerAddress: "titan1kadsh3puymfd9dvtm6uncpwrfq97wzgrv6cacnyllkf6ydj90uaq9kvs7q", offerAmount: (1e18).toString(), offerAsset: "atkx", askAsset: "ibc/7C0807A56073C4A27B0DE1C21BA3EB75DF75FD763F4AD37BC159917FC01145F0", minimumReceiveAmount: "1000000", // Minimum amount to receive from the swap memo: "Optional memo for the transaction", }); ``` **Parameters:** * `options` (object, optional): Optional configuration object passed directly to `react-query`'s `useMutation`. Allows customization of mutation behavior, success/error callbacks, etc. **Swap Parameters:** * `signingClient` (SigningClient, required): The SigningClient instance for interacting with the blockchain. * `signerAddress` (string, required): The address of the signer who will execute the swap. * `routerAddress` (string, required): The address of the Hyperion Swap router contract. * `offerAmount` (string, required): The amount of the asset being offered for the swap. * `offerAsset` (string, required): The identifier of the asset being offered. * `askAsset` (string, required): The identifier of the asset being requested in return. * `minimumReceiveAmount` (string, required): The minimum amount expected to receive from the swap. * `memo` (string, optional): Optional memo for the transaction. * `to` (string, optional): Optional recipient address for the swap. * `deadline` (number, optional): Optional deadline timestamp for the swap. **Returns:** Returns a `react-query` mutation object containing: * `mutate` (function): Function to trigger the simulation with swap parameters. * `data` (`bigint | undefined`): The estimated gas cost when the simulation is successful, otherwise `undefined`. * `isLoading` (boolean): True while the simulation is in progress. * `isError` (boolean): True if the simulation resulted in an error. * `error` (Error | null): An error object if the simulation failed, otherwise `null`. * ... other `react-query` mutation properties. ### `useExecuteSwap` Executes a swap operation on the Hyperion Swap router contract. **Purpose:** Performs the actual swap transaction on the blockchain, returning the transaction response. **Usage:** ```typescript import { useExecuteSwap } from '@cyberk/hyperion-sdk'; import { SigningClient } from "@titanlabjs/cosmos/signing-client"; import type { StdFee } from "@titanlabjs/titan-types/types"; const { mutate: executeSwap, data: txResponse, isLoading, isError, error, } = useExecuteSwap({ onSuccess: (response) => { console.log('Swap executed:', response); }, }); // Execute the swap executeSwap({ signingClient: signingClient, // SigningClient instance signerAddress: "titan1...", // Address of the signer routerAddress: "titan1kadsh3puymfd9dvtm6uncpwrfq97wzgrv6cacnyllkf6ydj90uaq9kvs7q", offerAmount: (1e18).toString(), offerAsset: "atkx", askAsset: "ibc/7C0807A56073C4A27B0DE1C21BA3EB75DF75FD763F4AD37BC159917FC01145F0", minimumReceiveAmount: "1000000", // Minimum amount to receive from the swap fee: { amount: [{ denom: "atkx", amount: "1000000" }], gas: "200000" }, // Required StdFee for the transaction memo: "Optional memo for the transaction", }); ``` **Parameters:** * `options` (object, optional): Optional configuration object passed directly to `react-query`'s `useMutation`. Allows customization of mutation behavior, success/error callbacks, etc. **Swap Parameters:** * `signingClient` (SigningClient, required): The SigningClient instance for interacting with the blockchain. * `signerAddress` (string, required): The address of the signer who will execute the swap. * `routerAddress` (string, required): The address of the Hyperion Swap router contract. * `offerAmount` (string, required): The amount of the asset being offered for the swap. * `offerAsset` (string, required): The identifier of the asset being offered. * `askAsset` (string, required): The identifier of the asset being requested in return. * `minimumReceiveAmount` (string, required): The minimum amount expected to receive from the swap. * `fee` (StdFee, required): The fee configuration for the transaction. * `memo` (string, optional): Optional memo for the transaction. * `to` (string, optional): Optional recipient address for the swap. * `deadline` (number, optional): Optional deadline timestamp for the swap. **Returns:** Returns a `react-query` mutation object containing: * `mutate` (function): Function to trigger the swap execution with swap parameters. * `data` (`DeliverTxResponse | undefined`): The transaction response when the swap is successful, otherwise `undefined`. * `isLoading` (boolean): True while the swap transaction is in progress. * `isError` (boolean): True if the swap execution resulted in an error. * `error` (Error | null): An error object if the swap failed, otherwise `null`. * ... other `react-query` mutation properties. ### `useSimulateCreatePair` Simulates a create pair operation to estimate the gas cost before executing the actual creation. **Purpose:** Estimates the gas cost (in bigint) for creating a new liquidity pair without actually executing the transaction. **Usage:** ```typescript import { useSimulateCreatePair } from '@cyberk/hyperion-sdk'; import { SigningClient } from "@titanlabjs/cosmos/signing-client"; import type { Coin } from "@titanlabjs/titan-types/types"; const { mutate: simulateCreatePair, data: estimatedGas, isLoading, isError, error, } = useSimulateCreatePair({ onSuccess: (gas) => { console.log('Estimated gas:', gas); }, }); // Call the simulation simulateCreatePair({ signingClient: signingClient, // SigningClient instance signerAddress: "titan1...", // Address of the signer factoryAddress: "titan1...", // Factory contract address assets: [ { denom: "atkx", amount: "0" }, { denom: "ibc/7C0807A56073C4A27B0DE1C21BA3EB75DF75FD763F4AD37BC159917FC01145F0", amount: "0" } ] as [Coin, Coin], memo: "Optional memo for the transaction", }); ``` **Parameters:** * `options` (object, optional): Optional configuration object passed directly to `react-query`'s `useMutation`. Allows customization of mutation behavior, success/error callbacks, etc. **Create Pair Parameters:** * `signingClient` (SigningClient, required): The SigningClient instance for interacting with the blockchain. * `signerAddress` (string, required): The address of the signer who will create the pair. * `factoryAddress` (string, required): The address of the Hyperion Swap factory contract. * `assets` ([Coin, Coin], required): A tuple of two Coin objects representing the assets to create the pair with. * `memo` (string, optional): Optional memo for the transaction. **Returns:** Returns a `react-query` mutation object containing: * `mutate` (function): Function to trigger the simulation with create pair parameters. * `data` (`bigint | undefined`): The estimated gas cost when the simulation is successful, otherwise `undefined`. * `isLoading` (boolean): True while the simulation is in progress. * `isError` (boolean): True if the simulation resulted in an error. * `error` (Error | null): An error object if the simulation failed, otherwise `null`. * ... other `react-query` mutation properties. ### `useExecuteCreatePair` Executes a create pair operation on the Hyperion Swap factory contract. **Purpose:** Creates a new liquidity pair on the blockchain, returning the transaction response. **Usage:** ```typescript import { useExecuteCreatePair } from '@cyberk/hyperion-sdk'; import { SigningClient } from "@titanlabjs/cosmos/signing-client"; import type { Coin, StdFee } from "@titanlabjs/titan-types/types"; const { mutate: executeCreatePair, data: txResponse, isLoading, isError, error, } = useExecuteCreatePair({ onSuccess: (response) => { console.log('Pair created:', response); }, }); // Execute the create pair executeCreatePair({ signingClient: signingClient, // SigningClient instance signerAddress: "titan1...", // Address of the signer factoryAddress: "titan1...", // Factory contract address assets: [ { denom: "atkx", amount: "0" }, { denom: "ibc/7C0807A56073C4A27B0DE1C21BA3EB75DF75FD763F4AD37BC159917FC01145F0", amount: "0" } ] as [Coin, Coin], fee: { amount: [{ denom: "atkx", amount: "1000000" }], gas: "200000" }, // Required StdFee for the transaction memo: "Optional memo for the transaction", }); ``` **Parameters:** * `options` (object, optional): Optional configuration object passed directly to `react-query`'s `useMutation`. Allows customization of mutation behavior, success/error callbacks, etc. **Create Pair Parameters:** * `signingClient` (SigningClient, required): The SigningClient instance for interacting with the blockchain. * `signerAddress` (string, required): The address of the signer who will create the pair. * `factoryAddress` (string, required): The address of the Hyperion Swap factory contract. * `assets` ([Coin, Coin], required): A tuple of two Coin objects representing the assets to create the pair with. * `fee` (StdFee, required): The fee configuration for the transaction. * `memo` (string, optional): Optional memo for the transaction. **Returns:** Returns a `react-query` mutation object containing: * `mutate` (function): Function to trigger the create pair execution with parameters. * `data` (`DeliverTxResponse | undefined`): The transaction response when the pair creation is successful, otherwise `undefined`. * `isLoading` (boolean): True while the create pair transaction is in progress. * `isError` (boolean): True if the create pair execution resulted in an error. * `error` (Error | null): An error object if the create pair failed, otherwise `null`. * ... other `react-query` mutation properties. ### `useSimulateProvideLiquidity` Simulates a provide liquidity operation to estimate the gas cost before executing the actual transaction. **Purpose:** Estimates the gas cost (in bigint) for providing liquidity to an existing pair without actually executing the transaction. **Usage:** ```typescript import { useSimulateProvideLiquidity } from '@cyberk/hyperion-sdk'; import { SigningClient } from "@titanlabjs/cosmos/signing-client"; import type { Coin } from "@titanlabjs/titan-types/types"; const { mutate: simulateProvideLiquidity, data: estimatedGas, isLoading, isError, error, } = useSimulateProvideLiquidity({ onSuccess: (gas) => { console.log('Estimated gas for providing liquidity:', gas); }, }); // Call the simulation // Note: The order of assets must match the order in the pair contract. simulateProvideLiquidity({ signingClient: signingClient, // SigningClient instance signerAddress: "titan1...", // Address of the signer pairAddress: "titan1...pair_contract_address...", // Address of the pair contract assets: [ { denom: "token_A_denom", amount: "1000000" }, // Ensure this is asset1 of the pair { denom: "token_B_denom", amount: "500000" } // Ensure this is asset2 of the pair ] as [Coin, Coin], memo: "Optional memo for the transaction", // Optional: slippageTolerance, receiver, deadline }); ``` **Parameters:** * `options` (object, optional): Optional configuration object passed directly to `react-query`'s `useMutation`. Allows customization of mutation behavior, success/error callbacks, etc. **Provide Liquidity Parameters:** * `signingClient` (SigningClient, required): The SigningClient instance for interacting with the blockchain. * `signerAddress` (string, required): The address of the signer providing liquidity. * `pairAddress` (string, required): The contract address of the liquidity pair. * `assets` ([Coin, Coin], required): A tuple of two Coin objects representing the assets to provide. **Important:** The order of assets in this array must match the order of assets defined in the pair contract. * `slippageTolerance` (string, optional): The maximum allowed slippage tolerance (as a decimal string, e.g., "0.01" for 1%). * `receiver` (string, optional): An optional address to receive the LP tokens. Defaults to the `signerAddress` if not provided. * `deadline` (number, optional): A Unix timestamp (in seconds) after which the transaction is no longer valid. * `memo` (string, optional): Optional memo for the transaction. **Returns:** Returns a `react-query` mutation object containing: * `mutate` (function): Function to trigger the simulation with provide liquidity parameters. * `data` (`bigint | undefined`): The estimated gas cost when the simulation is successful, otherwise `undefined`. * `isLoading` (boolean): True while the simulation is in progress. * `isError` (boolean): True if the simulation resulted in an error. * `error` (Error | null): An error object if the simulation failed, otherwise `null`. * ... other `react-query` mutation properties. ### `useExecuteProvideLiquidity` Executes a provide liquidity operation on the Hyperion Swap pair contract. **Purpose:** Adds liquidity to an existing pair on the blockchain, returning the transaction response. **Usage:** ```typescript import { useExecuteProvideLiquidity } from '@cyberk/hyperion-sdk'; import { SigningClient } from "@titanlabjs/cosmos/signing-client"; import type { Coin, StdFee } from "@titanlabjs/titan-types/types"; const { mutate: executeProvideLiquidity, data: txResponse, isLoading, isError, error, } = useExecuteProvideLiquidity({ onSuccess: (response) => { console.log('Liquidity provided:', response); }, }); // Execute the provide liquidity // Note: The order of assets must match the order in the pair contract. executeProvideLiquidity({ signingClient: signingClient, // SigningClient instance signerAddress: "titan1...", // Address of the signer pairAddress: "titan1...pair_contract_address...", // Address of the pair contract assets: [ { denom: "token_A_denom", amount: "1000000" }, // Ensure this is asset1 of the pair { denom: "token_B_denom", amount: "500000" } // Ensure this is asset2 of the pair ] as [Coin, Coin], fee: { amount: [{ denom: "atkx", amount: "100000" }], gas: "300000" }, // Required StdFee for the transaction memo: "Optional memo for the transaction", // Optional: slippageTolerance, receiver, deadline }); ``` **Parameters:** * `options` (object, optional): Optional configuration object passed directly to `react-query`'s `useMutation`. Allows customization of mutation behavior, success/error callbacks, etc. **Provide Liquidity Parameters:** * `signingClient` (SigningClient, required): The SigningClient instance for interacting with the blockchain. * `signerAddress` (string, required): The address of the signer providing liquidity. * `pairAddress` (string, required): The contract address of the liquidity pair. * `assets` ([Coin, Coin], required): A tuple of two Coin objects representing the assets to provide. **Important:** The order of assets in this array must match the order of assets defined in the pair contract. * `fee` (StdFee, required): The fee configuration for the transaction. * `slippageTolerance` (string, optional): The maximum allowed slippage tolerance (as a decimal string, e.g., "0.01" for 1%). * `receiver` (string, optional): An optional address to receive the LP tokens. Defaults to the `signerAddress` if not provided. * `deadline` (number, optional): A Unix timestamp (in seconds) after which the transaction is no longer valid. * `memo` (string, optional): Optional memo for the transaction. **Returns:** Returns a `react-query` mutation object containing: * `mutate` (function): Function to trigger the provide liquidity execution with parameters. * `data` (`DeliverTxResponse | undefined`): The transaction response when liquidity provision is successful, otherwise `undefined`. * `isLoading` (boolean): True while the transaction is in progress. * `isError` (boolean): True if the execution resulted in an error. * `error` (Error | null): An error object if the execution failed, otherwise `null`. * ... other `react-query` mutation properties. ### `useSimulateAddNativeTokenDecimals` Simulates an `add_native_token_decimals` operation to estimate the gas cost. **Purpose:** Estimates the gas cost (in bigint) for adding or updating the decimals for a native token in the factory/relevant contract without actually executing the transaction. **Usage:** ```typescript import { useSimulateAddNativeTokenDecimals } from '@cyberk/hyperion-sdk'; import { SigningClient } from "@titanlabjs/cosmos/signing-client"; const { mutate: simulateAddNativeTokenDecimals, data: estimatedGas, isLoading, isError, error, } = useSimulateAddNativeTokenDecimals({ onSuccess: (gas) => { console.log('Estimated gas for adding native token decimals:', gas); }, }); // Call the simulation simulateAddNativeTokenDecimals({ signingClient: signingClient, // SigningClient instance signerAddress: "titan1...", // Address of the signer factoryAddress: "titan1...factory_contract_address...", // Address of the factory or relevant contract denom: "newNativeToken", decimals: 18, memo: "Optional memo for the transaction", }); ``` **Parameters:** * `options` (object, optional): Optional configuration object passed directly to `react-query`'s `useMutation`. Allows customization of mutation behavior, success/error callbacks, etc. **Add Native Token Decimals Parameters:** * `signingClient` (SigningClient, required): The SigningClient instance for interacting with the blockchain. * `signerAddress` (string, required): The address of the signer performing the operation. * `factoryAddress` (string, required): The contract address that handles the `add_native_token_decimals` message (e.g., a factory contract). * `denom` (string, required): The denomination of the native token. * `decimals` (number, required): The number of decimals for the token (uint8). * `memo` (string, optional): Optional memo for the transaction. **Returns:** Returns a `react-query` mutation object containing: * `mutate` (function): Function to trigger the simulation. * `data` (`bigint | undefined`): The estimated gas cost when the simulation is successful, otherwise `undefined`. * `isLoading` (boolean): True while the simulation is in progress. * `isError` (boolean): True if the simulation resulted in an error. * `error` (Error | null): An error object if the simulation failed, otherwise `null`. * ... other `react-query` mutation properties. ### `useExecuteAddNativeTokenDecimals` Executes an `add_native_token_decimals` operation on the relevant contract. **Purpose:** Adds or updates the decimals for a specified native token denomination in the factory or relevant contract. **Usage:** ```typescript import { useExecuteAddNativeTokenDecimals } from '@cyberk/hyperion-sdk'; import { SigningClient } from "@titanlabjs/cosmos/signing-client"; import type { StdFee } from "@titanlabjs/titan-types/types"; const { mutate: executeAddNativeTokenDecimals, data: txResponse, isLoading, isError, error, } = useExecuteAddNativeTokenDecimals({ onSuccess: (response) => { console.log('Native token decimals added/updated:', response); }, }); // Execute the operation executeAddNativeTokenDecimals({ signingClient: signingClient, // SigningClient instance signerAddress: "titan1...", // Address of the signer factoryAddress: "titan1...factory_contract_address...", // Address of the factory or relevant contract denom: "newNativeToken", decimals: 18, fee: { amount: [{ denom: "atkx", amount: "50000" }], gas: "200000" }, // Required StdFee for the transaction memo: "Optional memo for the transaction", }); ``` **Parameters:** * `options` (object, optional): Optional configuration object passed directly to `react-query`'s `useMutation`. Allows customization of mutation behavior, success/error callbacks, etc. **Add Native Token Decimals Parameters:** * `signingClient` (SigningClient, required): The SigningClient instance for interacting with the blockchain. * `signerAddress` (string, required): The address of the signer performing the operation. * `factoryAddress` (string, required): The contract address that handles the `add_native_token_decimals` message (e.g., a factory contract). * `denom` (string, required): The denomination of the native token. * `decimals` (number, required): The number of decimals for the token (uint8). * `fee` (StdFee, required): The fee configuration for the transaction. * `memo` (string, optional): Optional memo for the transaction. **Returns:** Returns a `react-query` mutation object containing: * `mutate` (function): Function to trigger the execution. * `data` (`DeliverTxResponse | undefined`): The transaction response when the operation is successful, otherwise `undefined`. * `isLoading` (boolean): True while the transaction is in progress. * `isError` (boolean): True if the execution resulted in an error. * `error` (Error | null): An error object if the execution failed, otherwise `null`. * ... other `react-query` mutation properties.