Agent Reference
Reference for building automated agents, bots, and conduit integrations on the Hydrex protocol. Covers epoch management, voting power, automation history, and utility functions.
Epochs
The Hydrex governance system operates in weekly epochs. Use Voter.getEpochDetails to read current epoch timing from the chain, or buildEpochDetails to construct epoch data from known parameters.
import { Voter, buildEpochDetails } from '@hydrexfi/hydrex-sdk';
import type { EpochDetails } from '@hydrexfi/hydrex-sdk';
// Read current epoch from chain
const epoch: EpochDetails = await Voter.getEpochDetails(readContracts);
// epoch.epochNumber, .epochStart, .epochEnd, .epochDuration, .nextEpochStart
// Or build from known parameters
const epoch2: EpochDetails = buildEpochDetails(epochDuration, epochTimestamp);Voting Power Breakdown
When building automation agents, you often need to separate automated conduit power from manual user power to avoid double-voting or incorrect status reporting.
import { Voter, VeNFTLens } from '@hydrexfi/hydrex-sdk';
// Get all veNFT accounts for a wallet
const result = await VeNFTLens.getAccountsByAddress('0xOwnerWallet', readContract);
// Split power into manual vs automated
const breakdown = Voter.getVotePowerBreakdown(result.accounts, {
conduitAddresses: ['0xConduit1', '0xConduit2'],
// treatUnknownDelegateesAsAutomated: true, // optional heuristic
});
// breakdown.totalVotingPower
// breakdown.manualVotingPower
// breakdown.automatedVotingPower
// Derive vote status
const snapshot = await VeNFTLens.getUserVoteSnapshot('0xOwnerWallet', readContract);
const epoch = await Voter.getEpochDetails(readContracts);
const status = Voter.getUserVoteStatus(snapshot, epoch, breakdown);Conduit addresses
conduitAddresses to correctly classify automated power. Accounts delegated to conduits will be marked as automatedVotingPower.Automation Job History
The protocol API tracks completed automation jobs. Use AccountAutomation.getAutomationHistoryByOwner to fetch a full history for a wallet, grouped by token ID.
import { AccountAutomation } from '@hydrexfi/hydrex-sdk';
const history = await AccountAutomation.getAutomationHistoryByOwner(
'0xOwnerWallet',
{ baseUrl: 'https://api.hydrex.fi' }
);
for (const [tokenId, entries] of Object.entries(history.historyByTokenId)) {
const totalUsdEarned = entries.reduce((acc, e) => acc + parseFloat(e.totalUsd), 0);
console.log(`Token ${tokenId}: $${totalUsdEarned.toFixed(2)} earned`);
entries.forEach(entry => {
// entry.isVeMaxi — true for Anchor Club conduit jobs
// entry.distributed — [{ token, symbol, amount, usd }]
// entry.transactionHash
// entry.timestamp
});
}Tick Utilities
Helpers for converting between ticks, prices, and sqrt ratios.
import {
nearestUsableTick, tickToPrice, priceToClosestTick,
getTickToPrice, TickMath,
} from '@hydrexfi/hydrex-sdk';
// Snap a raw tick to the pool's tick spacing grid
nearestUsableTick(rawTick, tickSpacing)
// Price at a given tick
const price = tickToPrice(token0, token1, tick)
// Nearest tick to a Price object
const tick = priceToClosestTick(price)
// TickMath — low-level sqrt price math
TickMath.getSqrtRatioAtTick(tick) // JSBI sqrtRatioX96
TickMath.getTickAtSqrtRatio(sqrtRatio) // tick numberPool Math & Parsing Utilities
Low-level math helpers and parsing utilities for amounts, prices, and tick encoding.
import {
encodeSqrtRatioX96,
encodeRouteToPath,
maxLiquidityForAmounts,
tryParseAmount,
tryParsePrice,
tryParseTick,
maxAmountSpend,
unwrappedToken,
} from '@hydrexfi/hydrex-sdk';
// Compute sqrtRatioX96 from token amounts
const sqrtRatio = encodeSqrtRatioX96(amount1, amount0)
// Encode multi-hop path bytes for SwapRouter
const path = encodeRouteToPath(route, exactOutput)
// Max liquidity for token amounts
const liquidity = maxLiquidityForAmounts(sqrtRatio, ...)
// Amount parsing helpers
tryParseAmount('1.5', USDC) // CurrencyAmount | undefined
tryParsePrice(USDC, WETH, '0.0005') // Price | undefined
tryParseTick(USDC, WETH, fee, '0.0005') // number | undefined
// Gas reserve for native ETH — subtracts ~0.01 ETH
maxAmountSpend(ethAmount)
// Maps WNATIVE → Native; other tokens unchanged
unwrappedToken(WETH)Retry Utility
The retry utility runs an async function with exponential backoff. Throw RetryableError inside to signal a transient failure. Returns a { promise, cancel } object.
import { retry, RetryableError } from '@hydrexfi/hydrex-sdk';
import type { RetryOptions } from '@hydrexfi/hydrex-sdk';
const { promise, cancel } = retry(
async () => {
const result = await fetchSomeData();
if (!result) throw new RetryableError('No result yet');
return result;
},
{ n: 3, minWait: 500, maxWait: 2000 } satisfies RetryOptions
);
const result = await promise;
// cancel() to abort earlyRetryOptions
| Parameter | Type | Required | Description |
|---|---|---|---|
n | number | required | Maximum number of attempts. |
minWait | number | required | Minimum backoff delay in milliseconds. |
maxWait | number | required | Maximum backoff delay in milliseconds. |
Formatting & Display Utilities
The SDK exports a suite of formatting helpers for building dashboards and UIs.
import {
formatCurrencyAmount, formatPrice, formatPercent, formatNumber,
formatNumberScale, formatBalance, formatK, shortenAddress, shortenString,
capitalize, formatDateAgo, formatEpochDuration, formatTimeUntilEpochFlip,
} from '@hydrexfi/hydrex-sdk';
// Display helpers
formatDateAgo(timestamp) // "2 hours ago"
formatEpochDuration(epochDuration) // "7d 0h 0m"
formatTimeUntilEpochFlip(epoch) // "3d 14h 22m"
formatCurrencyAmount(amount, 4) // "1.2345"
formatPercent(percent, 2) // "60.00%"
formatNumber(1234567.89, 2) // "1,234,567.89"
formatNumberScale(1500000) // "1.5M"
formatBalance(amount, decimals)
formatK(value) // compact K/M/B notation
shortenAddress('0x1234...abcd') // "0x1234...abcd"
shortenString('long string', 10)
capitalize('hello world') // "Hello World"Internal Math Exports
| Export | Description |
|---|---|
FullMath | Overflow-safe 256-bit multiply / divide |
SqrtPriceMath | Amount deltas from sqrt price movement |
SwapMath | Compute swap step within a tick range |
LiquidityMath | Add / subtract signed liquidity |
TickMath | getSqrtRatioAtTick / getTickAtSqrtRatio |
TickList | Sorted tick array operations |
mostSignificantBit | MSB of a JSBI |
sqrt | Integer square root |
NEGATIVE_ONE, ZERO, ONE, Q96, Q192, MaxUint256 | Common JSBI constants |
MAX_SAFE_INTEGER | JS Number.MAX_SAFE_INTEGER as JSBI |
Enums Reference
| Enum | Values |
|---|---|
TradeType | EXACT_INPUT = 0, EXACT_OUTPUT = 1 |
Rounding | ROUND_DOWN, ROUND_HALF_UP, ROUND_UP |
Field | CURRENCY_A, CURRENCY_B |
Bound | LOWER, UPPER |
BoostedRouteStepType | WRAP, SWAP, UNWRAP |
Strategist | API alignment enum for automation conduit types |
StrategyType | Strategy flavor identifier (lending, LP, etc.) |
LiquidityType | Liquidity provision type identifier |