Build with Custos
Read and write from the app
The app reads and writes the contracts through Scaffold-HBAR's typed hooks, fed by a generated file of addresses and ABIs. Every snippet on this page is the pattern a page in the app already uses.
Addresses and ABIs#
packages/nextjs/contracts/deployedContracts.ts holds the address and ABI of PriceGuard, LiquidityPool, PerpMarket and HbarDepositZap on chain 296 (Hedera testnet). Don't edit it by hand: yarn custos:deploy:testnet regenerates it through scripts-js/generateTsAbis.js after a deploy of the default market. Third-party contracts (the two oracles) are in externalContracts.ts.
Hooks look contracts up by name, so contractName and functionName are type-checked against the ABI, and so are args and return values.
The hooks#
| Hook | Import from | Use it for |
|---|---|---|
useScaffoldReadContract | ~~/hooks/scaffold-hbar | One view call |
useScaffoldWriteContract | ~~/hooks/scaffold-hbar | Transactions, with toasts |
useDeployedContractInfo | ~~/hooks/scaffold-hbar | A contract's address and ABI |
useTargetNetwork | ~~/hooks/scaffold-hbar | The chain the app points at |
useKeeper | ~~/hooks/custos/useKeeper | nextRunAt, lastRunAt, interval, runCount, runsLeft |
usePool | ~~/hooks/custos/usePool | Everything the pool page reads |
useTradeAction | ~~/hooks/custos/useTradeAction | PerpMarket writes, with errors in plain words |
useHtsToken | ~~/hooks/custos/useHtsToken | Token balance, allowance, association; associate() and approve() |
useKeeperActivity | ~~/hooks/custos/useKeeperActivity | Keeper history from the mirror node |
Read the contracts#
The keeper's schedule
nextRunAt and runsLeft come from PerpMarket, which is the keeper. This is what useKeeper does:
import { POLL } from "~~/hooks/custos/poll";
import { useScaffoldReadContract } from "~~/hooks/scaffold-hbar";
const { data: nextRunAt } = useScaffoldReadContract({
contractName: "PerpMarket",
functionName: "nextRunAt",
...POLL,
});
const { data: runsLeft } = useScaffoldReadContract({
contractName: "PerpMarket",
functionName: "runsLeft",
...POLL,
});
// Both are bigint: nextRunAt in unix seconds, runsLeft a count of full gas holds.Or take them ready-made: const { nextRunAt, runsLeft, interval } = useKeeper(); returns numbers.
The pool's value
const { data: totalAssets } = useScaffoldReadContract({
contractName: "LiquidityPool",
functionName: "totalAssets",
...POLL,
});
// USDC, 6 decimals: formatUnits(totalAssets, 6)A read with arguments passes args, as usePool does for the connected LP:
const { data: maxRedeem } = useScaffoldReadContract({
contractName: "LiquidityPool",
functionName: "maxRedeem",
args: [owner],
...POLL,
});Write to the contracts#
/trade sends every PerpMarket transaction through useTradeAction. Its run simulates the call first, so a revert comes back as a sentence before the wallet opens; then it estimates gas plus 30% (falling back to known-good limits, since Hedera's estimates fall short for HTS calls) and sends through the scaffold transactor, which shows a toast with a HashScan link.
Open with USDC
import { useTradeAction } from "~~/hooks/custos/useTradeAction";
const action = useTradeAction();
// collateral is USDC with 6 decimals; approve the market for it first (see below)
const ok = await action.run(
{ functionName: "open", args: [isLong, collateral, BigInt(leverage)] },
"The market couldn't take your USDC. Check your balance, approval and association.",
);
// ok is false on a revert; action.error then holds one plain sentence to renderOpen with HBAR
The amount the user types is in HBAR with 8 decimals (tinybars), and that is what the quote takes. The transaction's value is not: the JSON-RPC relay takes value with 18 decimals (weibars), so TradeOpenForm multiplies by WEIBARS_PER_TINYBAR (10¹⁰).
import { WEIBARS_PER_TINYBAR, minOutAfterSlippage } from "~~/utils/custos/perpMath";
// tinybars: the HBAR amount with 8 decimals
const { data: quote } = useScaffoldReadContract({
contractName: "PerpMarket",
functionName: "quoteHbarToUsdc",
args: [tinybars],
...POLL,
});
const minCollateral = quote !== undefined ? minOutAfterSlippage(quote, 100n) : undefined; // 1%
await action.run({
functionName: "openWithHbar",
args: [isLong, BigInt(leverage), minCollateral!],
value: tinybars * WEIBARS_PER_TINYBAR,
});Close to HBAR
closeToHbar(minHbarOut) takes its minimum in tinybars. TradePositionCard quotes the expected USDC payout and subtracts slippage:
const { data: hbarQuote } = useScaffoldReadContract({
contractName: "PerpMarket",
functionName: "quoteUsdcToHbar",
args: [payout], // USDC, 6 decimals
...POLL,
});
const minHbarOut = hbarQuote !== undefined ? minOutAfterSlippage(hbarQuote, 100n) : undefined;
await action.run({ functionName: "closeToHbar", args: [minHbarOut ?? 0n] });
// or, paid in USDC: await action.run({ functionName: "close" });A plain write
For a contract useTradeAction doesn't cover, use useScaffoldWriteContract. This is KeeperActions on /keeper, with explicit gas (revive() books a schedule, which alone costs about 1.41M gas):
import { parseEther } from "viem";
import { useScaffoldWriteContract } from "~~/hooks/scaffold-hbar";
const { writeContractAsync } = useScaffoldWriteContract({ contractName: "PerpMarket" });
await writeContractAsync({ functionName: "fund", value: parseEther(amount), gas: 100_000n });
await writeContractAsync({ functionName: "revive", gas: 2_000_000n });Deposit with HBAR through the zap
The pool page calls HbarDepositZap through usePoolWrite().depositWithHbar (app/pool/_lib/usePoolWrite.ts), which simulates first so a revert reaches the page as words. It's the same pattern as openWithHbar: quote in tinybars, send value in weibars, and the caller must already be associated with cUSDC-LP. The bare version:
const { data: usdcQuote } = useScaffoldReadContract({
contractName: "HbarDepositZap",
functionName: "quote",
args: [tinybars],
...POLL,
});
const { writeContractAsync } = useScaffoldWriteContract({ contractName: "HbarDepositZap" });
await writeContractAsync({
functionName: "depositWithHbar",
args: [minOutAfterSlippage(usdcQuote!, 100n)], // the oracle floor applies on top
value: tinybars * WEIBARS_PER_TINYBAR,
});Associate and approve tokens#
USDC and cUSDC-LP are Hedera Token Service tokens. An account must be associated with one before it can receive it, and a contract must be approved before it can pull it. useHtsToken handles both for any token, and checks association on the mirror node. usePool returns it for USDC (spender: the pool) and for the share token:
import { usePool } from "~~/hooks/custos/usePool";
import { usePoolWrite } from "~~/app/pool/_lib/usePoolWrite";
const { usdc, shares } = usePool(address);
const { deposit, redeem } = usePoolWrite(address);
// Deposit: associate with USDC and cUSDC-LP, approve USDC, deposit
if (usdc.association === "not-associated") await usdc.associate();
if (shares.association === "not-associated") await shares.associate();
if ((usdc.allowance ?? 0n) < amount) await usdc.approve(amount); // exact amount, never unlimited
await deposit(amount);
// Redeem: the pool pulls the shares and burns them, so approve it on cUSDC-LP first
await shares.approve(sharesToRedeem);
await redeem(sharesToRedeem);/trade does the same with the market as spender: usdc.associate(), then usdc.approve(amount), then open. closeToHbar and openWithHbar need no approval. usePoolWrite simulates each pool call first so a revert reaches the page as a named error. An association of "auto" means the account has unlimited auto-associations and needs no step.
History from the mirror node#
The public relay limits eth_getLogs ranges, so the app reads history from the Hedera mirror node instead. useKeeperActivity looks up the market's Hedera id, then pages through:
/api/v1/contracts/<id>/results/logs, decoded against thePerpMarketABI with viem'sdecodeEventLog;/api/v1/transactions?account.id=<id>, whosescheduled: truemarks a run the Schedule Service executed, and whose result shows failed runs (which leave no log).
import { useKeeperActivity } from "~~/hooks/custos/useKeeperActivity";
const { entries, loadMore, hasMore } = useKeeperActivity();
// entries: { timestamp, events, scheduled, result, feePaidByContract }[], newest firstusePoolEarnings reads the pool's flows the same way, and useHcsAuditLog reads the keeper's audit log from HCS topic messages. Errors from any of these calls are listed in Troubleshooting.