Stock pools
Swap and integrate
Integrate stock-token/USDG swaps on Robinhood Chain through MakerHook.swap or any Uniswap v4 router, with pool keys, quotes, fees in pips and reverts.
On this page
This guide shows how to swap a Stock Token against USDG in a PropAMM pool. You can call the hook's own swap (route A) or any Uniswap v4 router that goes through the PoolManager (route B). Both routes enforce the DOMAIN_ENTRY pause, apply the same dynamic LP fee stack (fair-value shield, swap guard and calendar floor), and emit SwapFeeCharged.
Prerequisites
- A wallet on Robinhood Chain (4663) with ETH for gas and the token you sell.
- The
MakerHookaddress. Addresses publish at launch on Network; the examples useMAKER_HOOK.
Find the pool and build its key#
There is exactly one pool per stock. MakerHook.poolOfStock(stock) returns its id, which is the standard v4 PoolId. The key is:
| Field | Value |
|---|---|
currency0, currency1 | The stock and USDG, sorted by address |
fee | 0x800000 (v4 dynamic fee flag) |
tickSpacing | MakerHook.tickSpacing(), one value for every pool of the hook |
hooks | MAKER_HOOK |
import { createPublicClient, defineChain, encodeAbiParameters, http, keccak256, parseAbi } from "viem";
export const robinhood = defineChain({
id: 4663,
name: "Robinhood Chain",
nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
rpcUrls: { default: { http: ["https://rpc.mainnet.chain.robinhood.com"] } },
});
export const pub = createPublicClient({ chain: robinhood, transport: http() });
export const MAKER_HOOK = "0x..."; // addresses publish at launch
export const STOCK = "0x..."; // the stock token you trade
export const hookAbi = parseAbi([
"function poolOfStock(address stock) view returns (bytes32)",
"function tickSpacing() view returns (int24)",
"function usdg() view returns (address)",
"function poolManager() view returns (address)",
"function swap(bytes32 poolId, bool buyStock, uint256 amountIn, uint256 minOut, uint64 deadline) returns (uint256 amountOut)",
]);
export const poolId = await pub.readContract({ address: MAKER_HOOK, abi: hookAbi, functionName: "poolOfStock", args: [STOCK] });
export const usdg = await pub.readContract({ address: MAKER_HOOK, abi: hookAbi, functionName: "usdg" });
const tickSpacing = await pub.readContract({ address: MAKER_HOOK, abi: hookAbi, functionName: "tickSpacing" });
const [currency0, currency1] = BigInt(STOCK) < BigInt(usdg) ? [STOCK, usdg] : [usdg, STOCK];
export const key = { currency0, currency1, fee: 0x800000, tickSpacing, hooks: MAKER_HOOK } as const;
// The hook's id is keccak256(abi.encode(key)), the same as v4's PoolIdLibrary.
const id = keccak256(encodeAbiParameters(
[{ type: "address" }, { type: "address" }, { type: "uint24" }, { type: "int24" }, { type: "address" }],
[key.currency0, key.currency1, key.fee, key.tickSpacing, key.hooks],
));
if (id !== poolId) throw new Error("pool key mismatch");cast call $MAKER_HOOK "poolOfStock(address)(bytes32)" $STOCK --rpc-url $RH_RPC
cast call $MAKER_HOOK "tickSpacing()(int24)" --rpc-url $RH_RPC
cast call $MAKER_HOOK "usdg()(address)" --rpc-url $RH_RPCA zero id means the stock has no pool.
Quote the swap#
Fees are in pips: 1,000,000 pips is 100%, so 3,000 pips is 0.30%. A swap's fee depends on the side, the trade size, the pool's inventory, the fair-value shield and the calendar, so the reliable quote runs the real swap path. You can either call immutable MakerQuoter.quoteExactInput(poolId, buyStock, amountIn) (or quoteExactOutput) via eth_call with no token approval required, or approve the hook and simulate MakerHook.swap with minOut = 0, then apply your own slippage margin to the result.
The fee can rise during closed hours and right after a reopen auction starts. See Stock pools for each part.
import { createWalletClient, http, parseAbi, parseUnits } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { MAKER_HOOK, hookAbi, poolId, pub, robinhood, usdg } from "./pool";
const account = privateKeyToAccount(process.env.PK as `0x${string}`);
const wallet = createWalletClient({ account, chain: robinhood, transport: http() });
const erc20 = parseAbi(["function approve(address spender, uint256 amount) returns (bool)"]);
const amountIn = parseUnits("250", 6); // 250 USDG in, buying the stock
await wallet.writeContract({ address: usdg, abi: erc20, functionName: "approve", args: [MAKER_HOOK, amountIn] });
const { result: quoted } = await pub.simulateContract({
account, address: MAKER_HOOK, abi: hookAbi, functionName: "swap",
args: [poolId, true, amountIn, 0n, 0n],
});
const minOut = (quoted * 9_950n) / 10_000n; // 0.5% marginRoute A: swap through MakerHook.swap#
swap(poolId, buyStock, amountIn, minOut, deadline) is exact-in and all-or-nothing. buyStock = true spends USDG; false sells the stock. MakerHook.swap checks the DOMAIN_ENTRY pause directly, pulls amountIn from you, computes the pool's dynamic LP fee (fair-value shield, swap guard and calendar floor), emits SwapFeeCharged with sender set to the hook itself, swaps through the PoolManager, and sends the output to you. Pass deadline = 0 for no deadline.
Reverts:
DeadlineExpiredafterdeadline.ZeroAmountforamountIn = 0;UnknownPoolfor a bad id.DomainErrorwhileDOMAIN_ENTRYis paused;EmptyPoolwhen full-range liquidity is zero.Slippageif the output is belowminOut.ExactValueMismatchif the input token takes a transfer fee or the swap cannot fill in full.
const deadline = BigInt(Math.floor(Date.now() / 1000) + 300);
const hash = await wallet.writeContract({
address: MAKER_HOOK, abi: hookAbi, functionName: "swap",
args: [poolId, true, amountIn, minOut, deadline],
});
await pub.waitForTransactionReceipt({ hash });cast send $USDG "approve(address,uint256)" $MAKER_HOOK 250000000 --private-key $PK --rpc-url $RH_RPC
cast send $MAKER_HOOK "swap(bytes32,bool,uint256,uint256,uint64)" $POOL_ID true 250000000 $MIN_OUT 0 \
--private-key $PK --rpc-url $RH_RPCRoute B: swap through any v4 router#
Any contract that calls PoolManager.unlock and then swap on the key from step 1 works, exact-in or exact-out. The calling contract is the sender the hook sees, so a router discount set with setRouterDiscount(router, bps) applies to that router's flow. The discount applies only while the fair tick is fresh and the trade is not arbitrage.
This minimal exact-in router shows the calls. In v4, a negative amountSpecified means exact input.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {IUnlockCallback} from "@uniswap/v4-core/src/interfaces/callback/IUnlockCallback.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract ExactInSwapper is IUnlockCallback {
IPoolManager public immutable manager;
constructor(IPoolManager manager_) {
manager = manager_;
}
function swapExactIn(PoolKey calldata key, bool zeroForOne, uint128 amountIn, uint128 minOut)
external
returns (uint256 out)
{
bytes memory data = abi.encode(msg.sender, key, zeroForOne, amountIn, minOut);
out = abi.decode(manager.unlock(data), (uint256));
}
function unlockCallback(bytes calldata data) external returns (bytes memory) {
require(msg.sender == address(manager), "only manager");
(address payer, PoolKey memory key, bool zeroForOne, uint128 amountIn, uint128 minOut) =
abi.decode(data, (address, PoolKey, bool, uint128, uint128));
BalanceDelta d = manager.swap(
key,
IPoolManager.SwapParams({
zeroForOne: zeroForOne,
amountSpecified: -int256(uint256(amountIn)),
sqrtPriceLimitX96: zeroForOne ? TickMath.MIN_SQRT_PRICE + 1 : TickMath.MAX_SQRT_PRICE - 1
}),
""
);
(Currency tokenIn, Currency tokenOut) =
zeroForOne ? (key.currency0, key.currency1) : (key.currency1, key.currency0);
uint256 paid = uint256(uint128(-(zeroForOne ? d.amount0() : d.amount1())));
uint256 out = uint256(uint128(zeroForOne ? d.amount1() : d.amount0()));
require(out >= minOut, "slippage");
manager.sync(tokenIn);
IERC20(Currency.unwrap(tokenIn)).transferFrom(payer, address(manager), paid);
manager.settle();
manager.take(tokenOut, payer, out);
return abi.encode(out);
}
}zeroForOne is true when you sell currency0. If the stock sorts first, selling the stock is zeroForOne = true.
Read the fee you paid#
Every swap emits SwapFeeCharged from the hook with the parts of its fee: fee (charged), base (engine ask or bid), arb (shield surcharge), size, inventory and least (calendar floor). MakerHook.swap also emits Swapped(poolId, account, buyStock, amountIn, amountOut).
import { parseEventLogs, parseAbi } from "viem";
const events = parseAbi([
"event SwapFeeCharged(bytes32 indexed poolId, address indexed sender, bool zeroForOne, int256 amountSpecified, (uint24 fee, uint24 base, uint24 arb, uint24 size, uint24 inventory, uint24 least, uint16 tradeSizeBps, int16 invSkewBps) parts)",
]);
const receipt = await pub.getTransactionReceipt({ hash });
const [charged] = parseEventLogs({ abi: events, logs: receipt.logs, eventName: "SwapFeeCharged" });
console.log(`fee ${Number(charged.args.parts.fee) / 10_000}%`);Handle pauses, closed hours and empty pools#
ENTRYpaused. Every swap reverts withDomainError. On route A,MakerHook.swapchecksDOMAIN_ENTRYbefore unlocking and revertsDomainErrordirectly. On route B,PoolManagercallsbeforeSwap, soDomainErrorreaches you wrapped in v4'sWrappedError(target, selector, reason, details); decodereasonto seeDomainError. Retry after the council resumes.- Closed hours. Swaps do not revert. Outside the pool's trading sessions the fee is at least
closedFeePips(up to 10%), so a tightminOutfails withSlippageon route A. Re-quote before you send. - Reopen auctions. At each scheduled auction time the fee floor starts at the armed start fee (up to 20%) and falls to zero over
auctionDuration. The floor drops every second, so a later swap in the window meets a lower floor. - Empty pool. Both routes revert with
EmptyPoolwhile the full-range position holds no liquidity.
