Loading...
Loading...
© 2026 Hydrex. All rights reserved.
Complete swap execution example using web3.py.
import os, requests
from web3 import Web3
BASE_URL = "https://router.api.hydrex.fi"
MAX_UINT256 = 2**256 - 1
ERC20_ABI = [
{
"name": "allowance",
"type": "function",
"stateMutability": "view",
"inputs": [
{"name": "owner", "type": "address"},
{"name": "spender", "type": "address"},
],
"outputs": [{"type": "uint256"}],
},
{
"name": "approve",
"type": "function",
"stateMutability": "nonpayable",
"inputs": [
{"name": "spender", "type": "address"},
{"name": "amount", "type": "uint256"},
],
"outputs": [{"type": "bool"}],
},
]
def get_quote(
from_token,
to_token,
amount,
taker,
slippage=50,
referral=None,
referral_fee_bps=0,
origin="my-app"
):
params = {
"fromTokenAddress": from_token,
"toTokenAddress": to_token,
"amount": str(amount),
"chainId": "8453",
"taker": taker,
"slippage": slippage,
"origin": origin,
**({"referral": referral, "referralFeeBps": referral_fee_bps} if referral else {}),
}
resp = requests.get(f"{BASE_URL}/quote", params=params)
resp.raise_for_status()
return resp.json()
def ensure_allowance(w3, acct, token_address, spender, amount):
ETH = "0x0000000000000000000000000000000000000000"
if token_address.lower() == ETH:
return
token = w3.eth.contract(address=token_address, abi=ERC20_ABI)
current = token.functions.allowance(acct.address, spender).call()
if current < int(amount):
tx = token.functions.approve(spender, MAX_UINT256).build_transaction({
"from": acct.address,
"nonce": w3.eth.get_transaction_count(acct.address),
"gasPrice": w3.eth.gas_price,
"chainId": 8453,
})
signed = acct.sign_transaction(tx)
tx_hash = w3.eth.send_raw_transaction(signed.raw_transaction)
w3.eth.wait_for_transaction_receipt(tx_hash)
# Initialize Web3
w3 = Web3(Web3.HTTPProvider("https://mainnet.base.org"))
acct = w3.eth.account.from_key(os.getenv("PRIVATE_KEY"))
FROM_TOKEN = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" # USDC
# Get quote
quote = get_quote(
from_token=FROM_TOKEN,
to_token="0x4200000000000000000000000000000000000006", # WETH
amount="100000000", # 100 USDC
taker=acct.address,
referral="0xYourReferralWallet",
referral_fee_bps=10,
)
# Approve router to spend input token (ERC-20 only)
ensure_allowance(
w3, acct,
FROM_TOKEN,
quote["transaction"]["to"],
quote["amountIn"],
)
# Execute swap
tx_hash = w3.eth.send_raw_transaction(
acct.sign_transaction({
"to": quote["transaction"]["to"],
"data": quote["transaction"]["data"],
"value": int(quote["transaction"]["value"]),
"gasPrice": w3.eth.gas_price,
"nonce": w3.eth.get_transaction_count(acct.address),
"chainId": 8453,
}).raw_transaction
)
print("Tx:", tx_hash.hex())Fetches the best swap route from the Router API. Uses Python's requests library for HTTP calls and includes proper error handling.
Checks the current ERC-20 allowance for the router contract and approves MAX_UINT256 if insufficient. Skips the check for native ETH swaps.
Uses web3.py's account signing to create signed transactions. The private key is loaded from environment variables for security.
Gas limit is omitted from the transaction, allowing the RPC provider to estimate it automatically.
Tip: Compare amountOut against an independent price oracle before executing swaps to protect users from unfavorable trades.