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.

typescript
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.

typescript
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

Supply all known conduit contract addresses in 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.

typescript
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.

typescript
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 number

Pool Math & Parsing Utilities

Low-level math helpers and parsing utilities for amounts, prices, and tick encoding.

typescript
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.

typescript
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 early

RetryOptions

ParameterTypeRequiredDescription
nnumberrequiredMaximum number of attempts.
minWaitnumberrequiredMinimum backoff delay in milliseconds.
maxWaitnumberrequiredMaximum backoff delay in milliseconds.

Formatting & Display Utilities

The SDK exports a suite of formatting helpers for building dashboards and UIs.

typescript
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

ExportDescription
FullMathOverflow-safe 256-bit multiply / divide
SqrtPriceMathAmount deltas from sqrt price movement
SwapMathCompute swap step within a tick range
LiquidityMathAdd / subtract signed liquidity
TickMathgetSqrtRatioAtTick / getTickAtSqrtRatio
TickListSorted tick array operations
mostSignificantBitMSB of a JSBI
sqrtInteger square root
NEGATIVE_ONE, ZERO, ONE, Q96, Q192, MaxUint256Common JSBI constants
MAX_SAFE_INTEGERJS Number.MAX_SAFE_INTEGER as JSBI

Enums Reference

EnumValues
TradeTypeEXACT_INPUT = 0, EXACT_OUTPUT = 1
RoundingROUND_DOWN, ROUND_HALF_UP, ROUND_UP
FieldCURRENCY_A, CURRENCY_B
BoundLOWER, UPPER
BoostedRouteStepTypeWRAP, SWAP, UNWRAP
StrategistAPI alignment enum for automation conduit types
StrategyTypeStrategy flavor identifier (lending, LP, etc.)
LiquidityTypeLiquidity provision type identifier
Hydrex

Hydrex is an Omni-Liquidity MetaDEX built on Base for Base, designed to bring new users onchain.

Paragraph

© 2026 Hydrex. All rights reserved.