Skip to navigation

Swapping from Contracts

A contract cannot call the HyperFlow API itself, so swaps from a contract always have two parts:

  1. Off-chain, your keeper or backend calls GET /swap with receiver set to your contract’s address, and gets the router and the transaction data.
  2. On-chain, it passes those to your contract, which approves the input token, calls the router with that data, and checks how much it received.

The contract never builds router calldata itself — the data from /swap is the only supported way to call the routers.

What your contract must do

RuleWhy
Call only routers on an allowlist the owner can updateThe data is opaque to the contract; the allowlist stops it being sent anywhere else. Router addresses can change, so do not make the list immutable
Restrict who can call the swap functionAnyone who can call it chooses the route and the minimum output for your funds
Approve exactly amountIn, then reset the approval to 0No standing allowance is left on the router
Measure the output as the change in your own balance, and require it to be at least your minimumDo not rely on the router’s return value. For meaningful amounts, derive the minimum from your own price source (an oracle or TWAP), not only from the API’s minAmountOut
For native HYPE input, send value = amountIn from the contract’s own HYPE balance (fund it first) and use tokenIn = 0xEeee…EEeEThe router takes HYPE as call value
For native HYPE output, implement receive()Otherwise the swap reverts with TransferHelper: ETH_TRANSFER_FAILED
Approve through a helper that tolerates tokens whose approve returns nothing (as in the example, or OpenZeppelin SafeERC20.forceApprove)A plain IERC20.approve call reverts on such tokens, USDT among them
Give the owner a way to withdrawOtherwise funds can only leave the contract through another swap

How long the data stays valid

  • Each /swap response encodes a deadline: by default 20 minutes after the call. Executing after it reverts. Pass deadline (Unix seconds) to shorten it — for a keeper that executes immediately, 1–2 minutes is enough. A deadline in the past is ignored and the default applies.
  • Each response also encodes a minimum output. Pass your own minAmountOut (in wei) to set it; /swap returns 400 if it is above the current quote less slippage, so you find out before spending gas.
  • Prices move. Request /swap right before executing, not ahead of time.

Example contract

A minimal swapper, run against both routers on an Elysium fork in both directions (HYPE to USDC with an integrator fee, and USDC to HYPE). Adapt the access control and withdrawals to your vault.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
interface IERC20 {
function balanceOf(address) external view returns (uint256);
function approve(address, uint256) external returns (bool);
function transfer(address, uint256) external returns (bool);
}
contract HyperFlowSwapper {
address constant NATIVE = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public immutable owner;
mapping(address => bool) public isRouter;
error NotOwner();
error UnknownRouter();
error SwapFailed(bytes reason);
error InsufficientOutput(uint256 received, uint256 minOut);
error ApproveFailed();
error TransferFailed();
constructor(address[] memory routers) {
owner = msg.sender;
for (uint256 i; i < routers.length; i++) isRouter[routers[i]] = true;
}
function setRouter(address router, bool allowed) external {
if (msg.sender != owner) revert NotOwner();
isRouter[router] = allowed;
}
// `router` and `data` come from GET /swap called with receiver = address(this).
function swap(address router, bytes calldata data, address tokenIn, uint256 amountIn, address tokenOut, uint256 minOut)
external
returns (uint256 received)
{
if (msg.sender != owner) revert NotOwner();
if (!isRouter[router]) revert UnknownRouter();
uint256 before = _balance(tokenOut);
uint256 value;
if (tokenIn == NATIVE) value = amountIn;
else _approve(tokenIn, router, amountIn);
(bool ok, bytes memory reason) = router.call{value: value}(data);
if (!ok) revert SwapFailed(reason);
if (tokenIn != NATIVE) _approve(tokenIn, router, 0);
received = _balance(tokenOut) - before;
if (received < minOut) revert InsufficientOutput(received, minOut);
}
function withdraw(address token, address to, uint256 amount) external {
if (msg.sender != owner) revert NotOwner();
bool ok;
if (token == NATIVE) (ok,) = to.call{value: amount}("");
else {
bytes memory ret;
(ok, ret) = token.call(abi.encodeCall(IERC20.transfer, (to, amount)));
ok = ok && (ret.length == 0 || abi.decode(ret, (bool)));
}
if (!ok) revert TransferFailed();
}
// Tolerates tokens like USDT whose approve returns nothing.
function _approve(address token, address spender, uint256 amount) private {
(bool ok, bytes memory ret) = token.call(abi.encodeCall(IERC20.approve, (spender, amount)));
if (!ok || (ret.length != 0 && !abi.decode(ret, (bool)))) revert ApproveFailed();
}
function _balance(address token) private view returns (uint256) {
return token == NATIVE ? address(this).balance : IERC20(token).balanceOf(address(this));
}
receive() external payable {}
}

Deploy it with the routers of your chain from Smart Contracts: the standard router, plus the integrator-fee router if you charge a fee.

Keeper side

API=https://ag-api.hyperflow.fun/v1/elysium # or /v1/hyperevm
RPC=https://rpc.elysium.kinetiq.xyz # or https://rpc.hyperliquid.xyz/evm (rate-limited)
VAULT=0xYourContract
DEADLINE=$(( $(date +%s) + 120 ))
S=$(curl -s "$API/swap?tokenIn=$TOKEN_IN&tokenOut=$TOKEN_OUT&amountIn=$AMOUNT_IN&slippage=0.005&receiver=$VAULT&deadline=$DEADLINE")
ROUTER=$(echo "$S" | jq -r .tx.router)
DATA=$(echo "$S" | jq -r .tx.data)
MIN_OUT=$(echo "$S" | jq -r .quote.minAmountOut)
cast send $VAULT "swap(address,bytes,address,uint256,address,uint256)" \
$ROUTER $DATA $TOKEN_IN $AMOUNT_IN $TOKEN_OUT $MIN_OUT \
--rpc-url $RPC --account <keeper-keystore>

Check the HTTP status and body before sending — see Errors.

Estimate gas for every transaction instead of setting a fixed limit. The quote’s totalGas covers the route only, not your contract’s own approvals and balance checks, and actual usage varies by route.

Integrator fee from a contract

To charge a fee, add feeBps and feeReceiver to the /swap call. The response then names the integrator-fee router, so that router must be on your allowlist. The fee is paid to feeReceiver inside the same transaction; your contract receives amountOut, which is already net of the fee. See Integrator fee.