JavaScript / TypeScript
End-to-end examples using the Hydrex SDK with viem. The SDK is framework-agnostic — swap out viem for ethers.js or wagmi by adapting the injected read functions.
Setup with viem
typescript
import { createPublicClient, createWalletClient, http } from 'viem';
import { base } from 'viem/chains';
import { privateKeyToAccount } from 'viem/accounts';
import type { ReadContractFunction, ReadContractsFunction } from '@hydrexfi/hydrex-sdk';
const publicClient = createPublicClient({ chain: base, transport: http() });
const account = privateKeyToAccount('0xYourPrivateKey');
const walletClient = createWalletClient({ account, chain: base, transport: http() });
// Inject read functions
const readContract: ReadContractFunction = ({ functionName, args }) =>
publicClient.readContract({ address: contractAddress, abi, functionName, args });
const readContracts: ReadContractsFunction = (calls) =>
Promise.all(calls.map(({ functionName, args }) =>
publicClient.readContract({ address: contractAddress, abi, functionName, args })
));ℹ
Library-agnostic reads
The SDK's injected read pattern means you only need to adapt the
readContract and readContracts functions. All SDK business logic remains the same.Execute a Swap
typescript
import {
Token, Pool, Route, Trade, TradeType,
SwapRouter, ChainId, WNATIVE, Percent, CurrencyAmount,
SWAP_ROUTER_ADDRESSES, POOL_DEPLOYER_ADDRESSES,
INITIAL_POOL_FEE, DEFAULT_TICK_SPACING,
} from '@hydrexfi/hydrex-sdk';
const USDC = new Token(ChainId.Base, '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', 6, 'USDC');
const WETH = WNATIVE[ChainId.Base];
// Fetch pool data from chain
const [sqrtPriceX96, liquidity, tickCurrent] = await Promise.all([
publicClient.readContract({ ...poolContract, functionName: 'globalState' }),
publicClient.readContract({ ...poolContract, functionName: 'liquidity' }),
// ...
]);
const pool = new Pool(USDC, WETH, INITIAL_POOL_FEE, sqrtPriceX96,
POOL_DEPLOYER_ADDRESSES[ChainId.Base], liquidity, tickCurrent, DEFAULT_TICK_SPACING);
// Build trade
const trade = await Trade.exactIn(
new Route([pool], USDC, WETH),
CurrencyAmount.fromRawAmount(USDC, '1000000') // 1 USDC
);
// Get calldata
const { calldata, value } = SwapRouter.swapCallParameters(trade, {
slippageTolerance: new Percent(50, 10_000),
recipient: account.address,
deadline: Math.floor(Date.now() / 1000) + 1200,
});
// Send transaction
const hash = await walletClient.sendTransaction({
to: SWAP_ROUTER_ADDRESSES[ChainId.Base],
data: calldata as `0x${string}`,
value: BigInt(value),
});Stake LP Tokens
typescript
import { Gauge } from '@hydrexfi/hydrex-sdk';
// First: approve the gauge to spend your LP tokens
// (get stake token address)
const stakeToken = await Gauge.getStakeToken(readContract); // bound to gauge address
// Build deposit calldata
const { calldata } = Gauge.depositCallParameters('1000000000000000000');
// Send to the gauge contract
const hash = await walletClient.sendTransaction({
to: gaugeAddress,
data: calldata as `0x${string}`,
});