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

Source: https://docs.degenhive.ai/pools/swapping

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 `MakerHook` address. Addresses publish at launch on [Network](https://docs.degenhive.ai/network.md); the examples use `MAKER_HOOK`.

> [!IMPORTANT]
> These contracts are not deployed yet and not externally audited.

## Step 1: 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` |

**viem**

```ts
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**

```bash
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_RPC
```

A zero id means the stock has no pool.

## Step 2: 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](https://docs.degenhive.ai/pools.md#the-swap-fee) for each part.

**viem**

```ts
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% margin
```

## Step 3: Route 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:
- `DeadlineExpired` after `deadline`.
- `ZeroAmount` for `amountIn = 0`; `UnknownPool` for a bad id.
- `DomainError` while `DOMAIN_ENTRY` is paused; `EmptyPool` when full-range liquidity is zero.
- `Slippage` if the output is below `minOut`.
- `ExactValueMismatch` if the input token takes a transfer fee or the swap cannot fill in full.

**viem**

```ts
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**

```bash
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_RPC
```

## Step 4: Route 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.

`ExactInSwapper.sol`

```solidity
// 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`.

## Step 5: 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)`.

**viem**

```ts
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}%`);
```

## Step 6: Handle pauses, closed hours and empty pools

- **`ENTRY` paused.** Every swap reverts with `DomainError`. On route A, `MakerHook.swap` checks `DOMAIN_ENTRY` before unlocking and reverts `DomainError` directly. On route B, `PoolManager` calls `beforeSwap`, so `DomainError` reaches you wrapped in v4's `WrappedError(target, selector, reason, details)`; decode `reason` to see `DomainError`. 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 tight `minOut` fails with `Slippage` on 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 `EmptyPool` while the full-range position holds no liquidity.

> [!TIP]
> Read the current ask and bid floors with `MakerHook.pool(poolId)`. Its `askFee` and `bidFee` fields are the engine fee or the calendar floor, whichever is higher. The shield, size and inventory parts are added per trade.

## Step 7: Where to go next

- [Stock pools](https://docs.degenhive.ai/pools.md) The fee parts, the shield, the calendar and the breaker.
- [Networks & status](https://docs.degenhive.ai/network.md) Robinhood Chain RPC and deployment status.
- [Provide liquidity](https://docs.degenhive.ai/pools/liquidity.md) Earn the swap fees as a BookVault LP.
