Quote and route through the Counterbook pool like any Uniswap v4 dynamic-fee pool, read the fee and NAV with viem, and follow orders from event to HyperCore.
The Counterbook pool is a standard Uniswap v4 dynamic-fee pool on Uniswap's own PoolManager. Routers quote it with Uniswap's V4Quoter and swap through it with the Universal Router, with nothing custom to integrate. The hook ignores hookData; pass 0x.
The samples use viem and @counterbook/sdk, the TypeScript package in this repository. Every address comes from the SDK or from the deployment record, never from hand-typed constants.
Before deployment
getDeployment(chainId) returns null until a deployment is recorded. Show an explicit "not deployed" state in that case, never placeholder numbers. Current status is on the contracts page.
| Field | Value |
|---|---|
| PoolManager (999) | 0x12D4Fd9C5DeDd00ab8a0bCe2CF0167bbf94b6B1F, Uniswap's deployment |
currency0 | Native HYPE, address(0), 18 decimals |
currency1 | USDC, 0xb88339CB7199b77E23DB6E890353E22632Ba630f on 999, 6 decimals |
fee | 0x800000, Uniswap's DYNAMIC_FEE_FLAG. The hook sets the actual fee on every swap. |
tickSpacing, hooks | Read from vault.poolKey() or the deployment record |
import { createPublicClient, http } from "viem";
import { getDeployment, getNetworkConfig } from "@counterbook/sdk";
const chainId = 999; // 998 for HyperEVM testnet
const network = getNetworkConfig(chainId);
const client = createPublicClient({ chain: network.chain, transport: http(undefined, { batch: true }) });
const deployment = getDeployment(chainId);
if (!deployment) throw new Error(`Counterbook is not deployed on chain ${chainId} yet`);getNetworkConfig holds the chain, the mandate constants and the Uniswap v4 addresses for each network. On 998, where Uniswap has no v4 deployment, the v4 addresses come from Counterbook's own deployment record.
The V4Quoter simulates the swap inside a PoolManager unlock and is not a view function, so call it with eth_call through simulateContract. The quote includes the hook's dynamic fee.
import { parseEther } from "viem";
import { counterbookVaultAbi, v4QuoterAbi } from "@counterbook/sdk";
const poolKey = await client.readContract({
address: deployment.vault,
abi: counterbookVaultAbi,
functionName: "poolKey",
});
const quoter = network.v4?.quoter;
if (!quoter) throw new Error("No V4Quoter on this network");
const {
result: [amountOut, gasEstimate],
} = await client.simulateContract({
address: quoter, // 0x108Bfe38532C98f8Cd8D7Ab49c9dDAa3675a1c5e on 999
abi: v4QuoterAbi,
functionName: "quoteExactInputSingle",
args: [{ poolKey, zeroForOne: true, exactAmount: parseEther("1"), hookData: "0x" }],
});
// amountOut: USDC base units (6 decimals) for selling 1 HYPEcontracts/test/Quoter.t.sol runs Uniswap's V4Quoter against the hook's pool and checks that each quote equals what the swap then delivers, in both directions and after the vault is skewed, when the inventory term changes the fee. A quote holds for the block it was taken in; the hook prices the swap again in the block where it lands.
quoteFee runs the same math as beforeSwap, on the current block's HyperCore state.
import { counterbookHookAbi, REGIME_NAMES, formatFeeBps } from "@counterbook/sdk";
const [fee, regime, gapPips, spreadPips, skewPips] = await client.readContract({
address: deployment.hook,
abi: counterbookHookAbi,
functionName: "quoteFee",
args: [true], // true: a trader selling HYPE to the pool
});
console.log(`${formatFeeBps(fee)}, ${REGIME_NAMES[regime]}`); // e.g. "5.03 bp, CALM"
const nav = await client.readContract({
address: deployment.vault,
abi: counterbookVaultAbi,
functionName: "nav",
});
if (!nav.ok) {
// A HyperCore read failed or a guard is tripped: show "NAV unavailable", not a number.
} else {
// nav.navQuote is USDC base units; nav.pool0 / nav.core0 / ... split it by venue.
}Deposits are proportional to the vault's current composition, so size them with quoteDeposit first. It returns the shares and the amounts the vault would actually take in the current block.
import { parseEther, parseUnits } from "viem";
import { counterbookVaultAbi, erc20Abi } from "@counterbook/sdk";
const amount0Max = parseEther("1"); // HYPE, sent as msg.value
const amount1Max = parseUnits("100", 6); // USDC
const [shares, used0, used1] = await client.readContract({
address: deployment.vault,
abi: counterbookVaultAbi,
functionName: "quoteDeposit",
args: [amount0Max, amount1Max],
});
// The limiting side sets `shares`; used0 / used1 follow the vault's ratio.
// `wallet` is a viem WalletClient on network.chain with an account attached.
await wallet.writeContract({
address: network.addresses.usdc,
abi: erc20Abi,
functionName: "approve",
args: [deployment.vault, amount1Max], // only used1 is pulled
});
await wallet.writeContract({
address: deployment.vault,
abi: counterbookVaultAbi,
functionName: "deposit",
args: [amount0Max, amount1Max, (shares * 995n) / 1000n, wallet.account.address], // minShares: 0.5% tolerance
value: amount0Max, // must equal amount0Max; unused HYPE is refunded
});For redemptions, set min0 and min1 by simulating redeem from the holder's address. The immediate amounts come out of the pool position at the pool price, not the book mid, so an estimate from nav() can be off by the gap. The book-leg part becomes a claim: claimOf(owner) shows it, and claim(to) pays as much as HyperEVM balances cover.
readMarketSnapshot reads the BBO (0x80e), the perp oracle (0x807) and the spot price (0x808) in one batch and never throws: failed reads are listed in failures. computeFee is a bit-exact port of FeeMath.quote.
import { computeFee, feeParamsFromChain, readMarketSnapshot, stateViewAbi } from "@counterbook/sdk";
const snapshot = await readMarketSnapshot(client, network.mandate);
if (!snapshot.feeReadsOk) console.warn("HyperCore read failed:", snapshot.failures);
const stateView = network.v4?.stateView;
if (!stateView) throw new Error("No StateView on this network");
const [params, fallbackFee, slot0, live] = await Promise.all([
// the hook's copy of the active parameters and its fallback fee: exactly what beforeSwap uses
client.readContract({ address: deployment.hook, abi: counterbookHookAbi, functionName: "hookParams" }),
client.readContract({ address: deployment.hook, abi: counterbookHookAbi, functionName: "fallbackFee" }),
client.readContract({ address: stateView, abi: stateViewAbi, functionName: "getSlot0", args: [deployment.poolId] }),
client.readContract({ address: deployment.hook, abi: counterbookHookAbi, functionName: "liveOrder" }),
]);
const result = computeFee(feeParamsFromChain(params, fallbackFee), {
bid: snapshot.raw.bid ?? 0n,
ask: snapshot.raw.ask ?? 0n,
oraclePx: snapshot.raw.oraclePx ?? 0n,
sqrtPriceX96: slot0[0],
zeroForOne: true,
skewPips, // the skew the hook prices with, from quoteFee above
liveOrder: live.cloid !== 0n,
readFailed: snapshot.readFailed,
});
// result.fee equals quoteFee's fee for the same block; result.terms shows each term in pips.network.mandate is MANDATE_HYPE_USDC on 999 and MANDATE_HYPE_USDC_TESTNET on 998 (@1035, perp 135).
Each order the hook places carries a client order id (cloid). Join it with HyperCore's info API for the CoreAgent address.
import { cloidToHex, hyperCore, hyperCoreTestnet } from "@counterbook/sdk";
const info = chainId === 999 ? hyperCore : hyperCoreTestnet;
const unwatch = client.watchContractEvent({
address: deployment.hook,
abi: counterbookHookAbi,
eventName: "MakerOrderPlaced",
strict: true,
onLogs: async (logs) => {
for (const log of logs) {
// HyperCore executes the order a few seconds after this transaction.
const status = await info.orderStatus(deployment.coreAgent, cloidToHex(log.args.cloid));
console.log(log.transactionHash, log.args.tif === 1 ? "ALO" : "IOC", status);
}
},
});info.openOrders(deployment.coreAgent) and info.userFills(deployment.coreAgent) give the resting orders and fills of the vault's HyperCore account.
liveOrder() keeps the hook's record until HyperCore shows nothing on hold, even after a cancel. Two getters on the hook implementation show the rest of the bookkeeping. They are not part of ICounterbookHook, so they are not in counterbookHookAbi:
import { parseAbi } from "viem";
const hookBookkeeping = parseAbi([
"function cancelSentBlock() view returns (uint64)", // block a cancel was last sent, 0 = none
"function placedCoreBalance() view returns (uint128)", // HyperCore total of the sold token at placement, EVM units
]);
const cancelSentBlock = await client.readContract({
address: deployment.hook,
abi: hookBookkeeping,
functionName: "cancelSentBlock",
});A SwapPriced event carries everything needed to check the fee the PoolManager charged. verifySwapPriced reapplies steps 8 to 10 of the fee function with the parameters active at that block. The event has no oracle or pool price, so for DISLOCATED and FALLBACK it trusts the emitted regime and checks the fee against maxFee or the fallback fee.
import { feeParamsFromChain, verifySwapPriced } from "@counterbook/sdk";
const STEP = 1_000n; // pick a block range your RPC accepts
const latest = await client.getBlockNumber();
const logs = await client.getContractEvents({
address: deployment.hook,
abi: counterbookHookAbi,
eventName: "SwapPriced",
fromBlock: latest - STEP,
toBlock: latest,
strict: true,
});
for (const log of logs) {
const at = { blockNumber: log.blockNumber };
const [params, fallbackFee] = await Promise.all([
client.readContract({ ...at, address: deployment.hook, abi: counterbookHookAbi, functionName: "hookParams" }),
client.readContract({ ...at, address: deployment.hook, abi: counterbookHookAbi, functionName: "fallbackFee" }),
]);
const { expectedFee, matches, regimeConsistent } = verifySwapPriced(
feeParamsFromChain(params, fallbackFee),
log.args,
);
console.log(log.transactionHash, matches ? "fee verified" : `expected ${expectedFee}, got ${log.args.fee}`, regimeConsistent);
}For a full check, compare fee with the fee field of the PoolManager's Swap(id, sender, amount0, amount1, sqrtPriceX96, liquidity, tick, fee) event in the same transaction.
| Event | Emitted by | When |
|---|---|---|
SwapPriced(zeroForOne, fee, gapPips, spreadPips, skewPips, regime, bid, ask) | Hook | Every swap, with every input of the fee |
ReadFailed(precompile) | Hook | A HyperCore read failed; the swap paid the fallback fee |
MakerOrderPlaced(cloid, isBuy, limitPx, sz, tif, refPx) | Hook | The fast loop sent an order. limitPx, sz and refPx are 1e8-scaled. |
MakerOrderCancelled(cloid, reason) | Hook | 1: too old. 2: price moved. 3: nothing on hold any more (filled, or rejected after ttlBlocks), inferred. 4: the order still rests after a cancel, so the cancel was sent again. |
CoreActionSent(actionId, data) | CoreAgent | Raw bytes of every CoreWriter action sent |
BridgedToCore(base, evmAmount) | CoreAgent | Tokens bridged from HyperEVM to HyperCore |
Deposited(sender, to, amount0, amount1, shares, navQuote) | Vault | A deposit |
Redeemed(owner, to, shares, out0, out1, claim0, claim1) | Vault | A redemption, with the reserved book-leg claim |
Claimed(owner, to, amount0, amount1) | Vault | A claim was paid out |
Recentered(tickLower, tickUpper, liquidity, sqrtPriceRefX96) | Vault | The position moved to a new range |
Swept(token, amount, toCore) | Vault | Tokens moved between venues |
Crystallized(feeShares, ppsX18, benchmarkX18) | Vault | The performance fee was settled |
ParamsProposed(paramsHash, activatesAt) | Vault | The curator proposed parameters |
ParamsActivated(paramsHash) | Vault | Proposed parameters took effect |
DepositsPausedSet(paused) | Vault | The curator paused or resumed deposits |
beforeSwap reverts with InsufficientGas if less than 100,000 gas remains when it starts, so a caller cannot starve the HyperCore reads to force the fallback fee. A swap with less gas could not complete anyway.afterSwap only runs when the swap still has at least minGasForLoop gas (650,000 in both presets), at most once per cooldown. Otherwise the swap simply skips it. Wallets that estimate gas usually send less than that, so in practice the loop mostly runs through poke(), which anyone can call.beforeSwap alone 88,306; a whole swap without a dispatch 226,465; a swap that dispatches a maker order 458,503; a poke() that dispatches 294,653. The mocks do not charge HyperEVM's precompile cost, per read, or CoreWriter's own cost, so treat these as relative figures. forge snapshot reproduces them.