# Adapting an Existing AMM Source: https://docs.rialto.xyz/developers/adapting-an-existing-amm Front an AMM that uses different signatures with a thin adapter contract. ## When you need an adapter If your AMM already exposes different function names or argument orders, do not just rename functions and assume it works, because the settle selector is allowlisted onchain and the router patches the input amount at a fixed calldata offset that assumes amountIn is the second argument of swapExactIn. A different layout moves that offset. The clean path is a thin adapter contract that exposes exactly getAmountOut and swapExactIn and forwards to your AMM, roughly 30 lines. If adapters are a dealbreaker across several pairs, talk to Rialto; the selectors and the input-amount offset can be made configurable per pool on Rialto's side instead. ## Adapter skeleton ```solidity theme={null} // SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract MyPropPair { address public immutable token0; address public immutable token1; constructor(address _token0, address _token1) { token0 = _token0; token1 = _token1; } function getAmountOut(bool zeroForOne, uint256 amountIn) external view returns (uint256 amountOut) { amountOut = _price(zeroForOne, amountIn); } function swapExactIn( bool zeroForOne, uint256 amountIn, uint256 amountOutMin, address to, uint256 deadline ) external payable returns (uint256 amountOut) { if (deadline != 0) require(block.timestamp <= deadline, "expired"); (address tin, address tout) = zeroForOne ? (token0, token1) : (token1, token0); IERC20(tin).transferFrom(msg.sender, address(this), amountIn); amountOut = _price(zeroForOne, amountIn); require(amountOut >= amountOutMin, "slippage"); IERC20(tout).transfer(to, amountOut); } function _price(bool zeroForOne, uint256 amountIn) internal view returns (uint256) { // oracle / curve / inventory logic } } ``` # Authentication and API Keys Source: https://docs.rialto.xyz/developers/authentication How Rialto API keys work, how they are scoped and rate limited, and how to keep them safe. ## Bearer authentication Protected endpoints require an API key passed as a bearer token: ```http theme={null} Authorization: Bearer rialto_live_. ``` Token-discovery endpoints and wallet-signed integrator onboarding endpoints are public. Quote and gasless endpoints require a bearer API key with the relevant scope. ## Obtaining a key API keys are created through a wallet-signed onboarding flow. The wallet that applies becomes the owner of the integrator profile and the fee-recipient wallet. See [Integrator Onboarding](/developers/integrator-onboarding) for the full flow. The raw key is shown only once at creation, so store it securely when it is returned. ## Scopes A key is issued with one or more scopes that determine which endpoints it can call: | Scope | Grants | | --------------- | ------------------------------------ | | quote:read | Request quotes. | | swap:create | Submit gasless swaps to the relayer. | | swap:integrator | Apply an integrator fee to quotes. | A key without the required scope is rejected with 403. ## Rate limits and expiry Keys are rate limited per minute, with separate limits for quoting and for swap submission. The limits applied to a key are returned when it is created, for example a quote limit and a lower swap limit. Exceeding a limit returns 429. Keys may also be scoped to expire or be revoked, after which trading endpoints reject them. ## Key safety Keep API keys private. Do not expose them in public frontend code, mobile apps, source repositories, logs, or analytics tools. Anyone holding a key can act within its scopes. For integrator keys, fee payout and fee caps are bound to the key server-side, so a leaked key can never redirect fees to another wallet or raise the fee above the configured cap, but it should still be treated as a secret. # Errors Source: https://docs.rialto.xyz/developers/errors Error response shape and common status codes for the Quote API. ## Error shape Errors are returned as JSON: ```json theme={null} { "error": "" } ``` ## Status codes | Status | Example error | Meaning | | ------ | --------------------- | -------------------------------------------------------------------- | | 400 | varies | Invalid params, unsupported token, no route, or swap-building error. | | 401 | unauthorized | Missing, malformed, invalid, disabled, or expired API key. | | 403 | forbidden | API key is valid but not allowed to call this endpoint. | | 429 | rate limit exceeded | Per-key rate limit exceeded. | | 500 | internal server error | Unexpected backend error. | ## Notes * Integrator API keys are created through the wallet-signed onboarding flow and may require Rialto approval before activation. * API keys may be scoped to quote-only, execution, or integrator access, and may have rate limits or expiry. * Quotes depend on live liquidity and may become stale quickly. Request a fresh quote if the user waits. * In direct flow, submit transactions from the taker wallet. In gasless flow, the taker signs Permit2 and Rialto relays the transaction. # Executing a Quote Source: https://docs.rialto.xyz/developers/executing-a-quote Submit the transaction returned by a quote, with Permit2 or allowance settlement. ## The executable transaction The payload to send onchain lives in the quote's tx object: | Field | Description | | -------------------- | -------------------------------------------------------------------------------------------------------------------- | | tx.to | RialtoRouter contract address; the to of your transaction. | | tx.data | ABI-encoded calldata for the swap. | | tx.value | Native value to send. 0 for ERC20 sells; the sell amount for native ETH sells. | | tx.estimated\_gas | Backend gas estimate. Still run wallet or RPC gas estimation before sending. | | tx.signature\_offset | Byte offset in tx.data where the taker's 65-byte Permit2 signature is inserted. Present only for Permit2 settlement. | | permit2 | EIP-712 typed-data message the taker signs. Present only for Permit2 settlement. | The settlement field tells you which mode applies. Choose your handling from settlement, not from assumptions. You can influence that decision with the optional settlement request parameter on the quote: | Request value | Behavior | | ------------- | ---------------------------------------------------------------------------------------------------------------- | | auto | Default. Uses Permit2 for EOA ERC20 sells, and allowance mode for smart-wallet or native ETH sells. | | permit2 | Requires a Permit2 executable quote. Use this for gasless relays or integrations that specifically need Permit2. | | allowance | Requires router allowance mode. The response has no permit2 payload or tx.signature\_offset. | The response settlement is always the executable mode Rialto returned. Use that value for transaction handling even when you pass a request preference. See [Settlement Modes](/developers/settlement-modes) for details. Do not modify quote\_id, route, platform\_fee, permit2.message.witness, or tx.data except for replacing the Permit2 signature placeholder. A changed route or witness will not match the signed quote and may revert. Use the returned permit2 payload as the source of truth; do not recompute the bytes32 witness quoteId from the UUID yourself. ## Permit2 settlement Permit2 is the default for ERC20 sells. The taker authorizes a single exact transfer by signing an EIP-712 message bound to the precise swap, including recipient, buy token, minimum output, deadline, quote id, and the hash of the route actions. Steps: 1. If issues.allowance is non-null, ask the taker to approve issues.allowance.spender for at least sell\_amount. For Permit2 quotes this spender is the Permit2 contract. 2. Have the taker wallet sign the permit2 object as EIP-712 typed data. 3. Splice the returned 65-byte signature into tx.data at tx.signature\_offset. 4. Send the transaction from the taker wallet using to, the patched data, and value. Most wallet libraries accept the returned domain, types, primaryType, and message directly. If your library rejects EIP712Domain inside types, remove only that key before calling signTypedData; do not change the message or witness fields. ```ts theme={null} function splicePermit2Signature( txData: string, signatureOffset: number, signature: string ): string { const data = txData.startsWith("0x") ? txData.slice(2) : txData; const sig = signature.startsWith("0x") ? signature.slice(2) : signature; if (sig.length !== 130) { throw new Error("Permit2 signature must be 65 bytes"); } const start = signatureOffset * 2; return `0x${data.slice(0, start)}${sig}${data.slice(start + sig.length)}`; } ``` ## Allowance settlement A quote returns settlement: "allowance" with no permit2 object and no signature\_offset when Permit2 is not the right path, for example native ETH sells, or a flow where the taker already wants to use ERC20 allowance. * ERC20 sells. If issues.allowance is non-null, the taker approves issues.allowance.spender for at least the raw sell\_amount, then sends the transaction. Do not modify tx.data. * Native ETH sells. Send the transaction with tx.value; no ERC20 approval and no signature are needed. ## Simulation Every route Rialto returns is validated against live chain state before it is quoted, so the transaction in a quote is pre-validated. You can also simulate the returned transaction yourself before submitting. A successful simulation confirms the route still fills and the output meets min\_buy\_amount; a failure means the quote has gone stale, so request a fresh quote. ## Submission For the taker-submitted flow, submit the transaction from the taker wallet. The Rialto API does not sign or broadcast this direct-flow transaction. Quotes reflect live liquidity and can go stale quickly, so request a fresh quote if the user waits. ## Direct-flow checklist ```bash theme={null} API_KEY='rialto_live_example.redacted_secret' curl -sS 'https://rialto-trade-api.rialto.xyz/quote?sell_token=0x0Bd7D308f8E1639FAb988df18A8011f41EAcAD73&buy_token=0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168&sell_amount=0.01&taker=&slippage_bps=50' \ -H "Authorization: Bearer $API_KEY" -o quote.json # In your app: # - If quote.issues.balance is non-null, show an insufficient-balance error. # - If quote.issues.allowance is non-null, approve quote.issues.allowance.spender. # - Permit2: sign quote.permit2 as EIP-712, then splice the signature into # quote.tx.data at quote.tx.signature_offset. # - Allowance/native: use quote.tx.data as-is. # - Optional: eth_estimateGas / eth_call quote.tx from the taker. # - Direct flow: submit quote.tx from the taker wallet. # - Gasless flow: use POST /gasless/submit instead of sending quote.tx yourself. ``` # Gasless Relayer Source: https://docs.rialto.xyz/developers/gasless-relayer Let the taker sign Permit2 while Rialto submits the swap and pays gas. ## Overview The gasless flow lets the taker sign Permit2 while Rialto submits the onchain swap transaction. The taker still authorizes the exact swap with a Permit2 witness signature, but the relayer wallet pays the network gas. ## Constraints | Constraint | Behavior | | ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Settlement | Requires settlement: permit2 and a returned permit2 payload. Pass settlement=permit2 if you want the quote request to fail instead of falling back to allowance mode. | | Token type | ERC20 sells only. Native ETH sells require the taker-submitted flow. | | Permit owner | Pass permit2\_owner=taker on the quote. For gasless, permit2\_owner must equal taker. | | Relay opt-in | Pass gasless\_relay=true. Permit2 settlement alone does not authorize Rialto to relay the transaction. | | Recipient | The quote controls the recipient through the Permit2 witness. Do not edit it. | | Allowance | The taker must still approve Permit2 if issues.allowance is non-null. | | Balance | Do not submit if issues.balance is non-null. | ## Step 1: request a gasless quote Add `permit2_owner` and `gasless_relay=true` to the standard quote request: ```bash theme={null} API_KEY='rialto_live_example.redacted_secret' TAKER='' curl -sS "https://rialto-trade-api.rialto.xyz/quote?sell_token=0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168&buy_token=0xc93a8c440CEa26D7445dF01729f193b27965099f&sell_amount=1&taker=$TAKER&permit2_owner=$TAKER&gasless_relay=true&settlement=permit2&slippage_bps=50&chain_id=4663" \ -H "Authorization: Bearer $API_KEY" ``` The response includes quote\_id, the permit2 typed data, issues, and the tx Rialto will submit after receiving the signature. ## Step 2: approval and signature If issues.allowance is non-null, the taker approves issues.allowance.spender for at least the raw sell\_amount. For gasless Permit2 quotes the spender is the Permit2 contract. Then have the taker sign the permit2 typed data exactly as returned. ## Step 3: submit to the relayer ```http theme={null} POST /gasless/submit ``` Auth: requires an API key with swap access. | Field | Description | | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | quote\_id | UUID returned by the quote. The quote must have been requested with permit2\_owner. | | signature | 0x-prefixed 65-byte Permit2 signature over the typed data returned by the quote. | | idempotency\_key | Optional client-generated unique string for one relay attempt, such as your internal order id or a UUID. Reuse the same value only when retrying the same quote submission; do not reuse it across different quotes or users. | ```bash theme={null} curl -sS 'https://rialto-trade-api.rialto.xyz/gasless/submit' \ -H "Authorization: Bearer $API_KEY" \ -H 'Content-Type: application/json' \ -d '{ "quote_id": "b7b0a3d8-9f6a-4f4a-92d2-1b0e4b5d0c6a", "signature": "0xabc123...", "idempotency_key": "partner-order-123" }' ``` Example response: ```json theme={null} { "relay_id": "f3f6a35f-93b9-4629-9a2e-02d2b80648ef", "quote_id": "b7b0a3d8-9f6a-4f4a-92d2-1b0e4b5d0c6a", "status": "submitted", "chain_id": 4663, "tx_hash": "0x6b8f...", "error": null } ``` ## Step 4: poll relay status ```http theme={null} GET /gasless/status/{relay_id} ``` Auth: requires an API key with swap access. | Status | Meaning | | --------- | --------------------------------------------------------------- | | accepted | Request accepted and queued. | | submitted | Relayer broadcasted the transaction. | | confirmed | Transaction mined successfully. | | failed | Transaction was submitted but failed or could not be confirmed. | | expired | Request expired before successful relay. | | rejected | Request failed validation before relay. | ```bash theme={null} curl -sS 'https://rialto-trade-api.rialto.xyz/gasless/status/f3f6a35f-93b9-4629-9a2e-02d2b80648ef' \ -H "Authorization: Bearer $API_KEY" ``` ## Python example This example requests a gasless quote, signs Permit2, submits the signature, and polls until the relay reaches a terminal state. ```bash theme={null} python3 -m pip install requests web3 eth-account export API_KEY='rialto_live_example.redacted_secret' export RPC_URL='' export PRIVATE_KEY='0xREDACTED_TAKER_PRIVATE_KEY' python3 rialto_gasless_swap.py ``` ```python theme={null} import os import time from urllib.parse import urlencode import requests from eth_account import Account from eth_account.messages import encode_typed_data from web3 import Web3 API_BASE = "https://rialto-trade-api.rialto.xyz" CHAIN_ID = 4663 SELL_TOKEN = "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168" BUY_TOKEN = "0xc93a8c440CEa26D7445dF01729f193b27965099f" SELL_AMOUNT = "1" SLIPPAGE_BPS = 50 ERC20_ABI = [ { "name": "approve", "type": "function", "stateMutability": "nonpayable", "inputs": [ {"name": "spender", "type": "address"}, {"name": "value", "type": "uint256"}, ], "outputs": [{"name": "", "type": "bool"}], } ] def require_env(name): value = os.getenv(name) if not value: raise RuntimeError(f"missing {name}") return value def tx_fees(w3): latest = w3.eth.get_block("latest") priority = w3.to_wei("0.01", "gwei") return { "maxPriorityFeePerGas": priority, "maxFeePerGas": int(latest["baseFeePerGas"]) * 2 + priority, } api_key = require_env("API_KEY") private_key = require_env("PRIVATE_KEY") w3 = Web3(Web3.HTTPProvider(require_env("RPC_URL"))) taker = Account.from_key(private_key).address params = { "sell_token": SELL_TOKEN, "buy_token": BUY_TOKEN, "sell_amount": SELL_AMOUNT, "taker": taker, "permit2_owner": taker, "gasless_relay": True, "settlement": "permit2", "slippage_bps": SLIPPAGE_BPS, "chain_id": CHAIN_ID, } quote_response = requests.get( f"{API_BASE}/quote?{urlencode(params)}", headers={"Authorization": f"Bearer {api_key}"}, timeout=30, ) quote_response.raise_for_status() quote = quote_response.json() if quote.get("settlement") != "permit2" or not quote.get("permit2"): raise RuntimeError("gasless requires a Permit2 quote") if quote.get("issues", {}).get("balance"): raise RuntimeError(f"insufficient balance: {quote['issues']['balance']}") allowance = quote.get("issues", {}).get("allowance") if allowance: token = Web3.to_checksum_address(quote["sell_token"]) spender = Web3.to_checksum_address(allowance["spender"]) amount = int(quote["sell_amount"]) approve_tx = w3.eth.contract(address=token, abi=ERC20_ABI).functions.approve( spender, amount ).build_transaction( { "from": taker, "chainId": CHAIN_ID, "nonce": w3.eth.get_transaction_count(taker), **tx_fees(w3), } ) approve_tx["gas"] = int(w3.eth.estimate_gas(approve_tx) * 1.2) signed_approval = Account.sign_transaction(approve_tx, private_key) approval_hash = w3.eth.send_raw_transaction(signed_approval.raw_transaction) receipt = w3.eth.wait_for_transaction_receipt(approval_hash) if receipt.status != 1: raise RuntimeError(f"approval reverted: {approval_hash.hex()}") typed_data = { "domain": quote["permit2"]["domain"], "types": quote["permit2"]["types"], "primaryType": quote["permit2"]["primaryType"], "message": quote["permit2"]["message"], } signed_permit = Account.sign_message( encode_typed_data(full_message=typed_data), private_key, ) signature = "0x" + bytes(signed_permit.signature).hex() submit_response = requests.post( f"{API_BASE}/gasless/submit", headers={"Authorization": f"Bearer {api_key}"}, json={ "quote_id": quote["quote_id"], "signature": signature, "idempotency_key": f"partner-{quote['quote_id']}", }, timeout=60, ) submit_response.raise_for_status() relay = submit_response.json() print("relay_id:", relay["relay_id"]) print("initial_status:", relay["status"]) terminal = {"confirmed", "failed", "expired", "rejected"} while relay["status"] not in terminal: time.sleep(5) status_response = requests.get( f"{API_BASE}/gasless/status/{relay['relay_id']}", headers={"Authorization": f"Bearer {api_key}"}, timeout=30, ) status_response.raise_for_status() relay = status_response.json() print("status:", relay["status"], "tx_hash:", relay.get("tx_hash")) if relay["status"] != "confirmed": raise RuntimeError(f"relay did not confirm: {relay}") ``` A full runnable Python example for the gasless flow is in the API repo: [https://github.com/rialto-plds/rialto-api-docs/blob/main/RIALTO\_SWAP\_API.md](https://github.com/rialto-plds/rialto-api-docs/blob/main/RIALTO_SWAP_API.md) # Integrator Fees Source: https://docs.rialto.xyz/developers/integrator-fees Charge your own fee on top of Rialto's, paid to your wallet atomically on every swap. ## How it works Approved integrators can charge their own fee on top of Rialto's on every swap they route. The fee is collected as part of the swap and paid to your wallet in the same onchain transaction. There is no separate claim step, no fee contract to deploy, and no settlement to run yourself. 1. You request a quote with a swap\_fee\_bps value, your fee in basis points. 2. Rialto adds your fee on top of its own and returns the full breakdown. 3. The same quote includes one executable transaction that, on execution, pays both Rialto's treasury and your wallet atomically. 4. The taker signs or approves as needed, then submits the quote's tx directly or signs Permit2 for gasless relay. Your fee is additive. Rialto charges its standard fee, and your fee is taken on top. Rialto does not take any cut of your portion. ## What is bound to your key | Bound to your key | Meaning | | ------------------ | ------------------------------------------------------ | | Payout wallet | The address your fees are sent to. | | Maximum fee in bps | A per-key cap, the largest swap\_fee\_bps you may set. | | Integrator id | An identifier used to attribute the swaps you route. | Because these are bound to the key and not the request, a leaked or tampered request can never redirect your fees or raise your fee above your cap. ## Setting your fee Add swap\_fee\_bps to the standard quote request. Your payout wallet and cap come from your key, so you do not pass them on the request. | Param | Description | | -------------- | -------------------------------------------------------------------------------------------------- | | swap\_fee\_bps | Your fee in basis points, applied on top of Rialto's fee. 30 = 0.30%. swapFeeBps is also accepted. | ```bash theme={null} INTEGRATOR_KEY='rialto_live_integrator.redacted_secret' curl -sS 'https://rialto-trade-api.rialto.xyz/quote?sell_token=0x0Bd7D308f8E1639FAb988df18A8011f41EAcAD73&buy_token=0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168&sell_amount=0.01&taker=&slippage_bps=50&swap_fee_bps=30' \ -H "Authorization: Bearer $INTEGRATOR_KEY" ``` ## Reading the fee in the response A quote with an integrator fee gains two things: an integrator\_fee block echoing your fee, payout wallet, and integrator id; and extra entries in platform\_fee.fees, one line per recipient, each showing the token the fee is taken in and the exact amount. Rialto selects the most suitable fee token in the swap automatically, so you do not choose a fee token. ```json theme={null} { "buy_amount": "19800022", "platform_fee": { "total_bps": 35, "fees": [ { "side": "source", "token": "", "symbol": "WETH", "decimals": 18, "bps": "5", "amount": "50000000000000", "amount_decimal": "0.00005", "recipient": "" }, { "side": "source", "token": "", "symbol": "WETH", "decimals": 18, "bps": "30", "amount": "300000000000000", "amount_decimal": "0.0003", "recipient": "" } ] }, "integrator_fee": { "bps": 30, "recipient": "", "id": "your-integrator-id" } } ``` In this example Rialto's fee is 5 bps and your fee is 30 bps, for a combined total\_bps of 35. The recipient on the second line is your payout wallet. The token and amount fields tell you exactly which token the fee is taken in and how much. ## Python example This example requests a quote with an integrator fee, handles any approval, signs and inserts a Permit2 signature when required, and submits the returned transaction. ```bash theme={null} python3 -m pip install requests web3 eth-account export INTEGRATOR_API_KEY='rialto_live_integrator.redacted_secret' export RPC_URL='' export PRIVATE_KEY='0xREDACTED_PRIVATE_KEY' python3 rialto_integrator_quote.py ``` ```python theme={null} import os from urllib.parse import urlencode import requests from eth_account import Account from eth_account.messages import encode_typed_data from web3 import Web3 API_BASE = "https://rialto-trade-api.rialto.xyz" CHAIN_ID = 4663 SELL_TOKEN = "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168" BUY_TOKEN = "0xc93a8c440CEa26D7445dF01729f193b27965099f" SELL_AMOUNT = "0.532262" SLIPPAGE_BPS = 50 SWAP_FEE_BPS = 30 ERC20_ABI = [ { "name": "approve", "type": "function", "stateMutability": "nonpayable", "inputs": [ {"name": "spender", "type": "address"}, {"name": "value", "type": "uint256"}, ], "outputs": [{"name": "", "type": "bool"}], } ] def require_env(name: str) -> str: value = os.getenv(name) if not value: raise RuntimeError(f"missing {name}") return value def tx_fees(w3: Web3) -> dict: latest = w3.eth.get_block("latest") priority = w3.to_wei("0.01", "gwei") return { "maxPriorityFeePerGas": priority, "maxFeePerGas": int(latest["baseFeePerGas"]) * 2 + priority, } def patch_permit2_signature(tx_data: str, signature_offset: int, signature: bytes) -> str: data = bytearray(bytes.fromhex(tx_data.removeprefix("0x"))) if len(signature) != 65: raise RuntimeError("Permit2 signature must be 65 bytes") data[signature_offset : signature_offset + 65] = signature return "0x" + data.hex() api_key = require_env("INTEGRATOR_API_KEY") private_key = require_env("PRIVATE_KEY") w3 = Web3(Web3.HTTPProvider(require_env("RPC_URL"))) taker = Account.from_key(private_key).address params = { "sell_token": SELL_TOKEN, "buy_token": BUY_TOKEN, "sell_amount": SELL_AMOUNT, "taker": taker, "slippage_bps": SLIPPAGE_BPS, "chain_id": CHAIN_ID, "swapFeeBps": SWAP_FEE_BPS, } response = requests.get( f"{API_BASE}/quote?{urlencode(params)}", headers={"Authorization": f"Bearer {api_key}"}, timeout=30, ) response.raise_for_status() quote = response.json() print("quote_id:", quote["quote_id"]) print("buy_amount:", quote["buy_amount"]) print("min_buy_amount:", quote["min_buy_amount"]) print("integrator_fee:", quote.get("integrator_fee")) issues = quote.get("issues") or {} if issues.get("balance"): raise RuntimeError(f"insufficient balance: {issues['balance']}") if issues.get("allowance"): allowance = issues["allowance"] token = Web3.to_checksum_address(quote["sell_token"]) spender = Web3.to_checksum_address(allowance["spender"]) amount = int(quote["sell_amount"]) approve_tx = w3.eth.contract(address=token, abi=ERC20_ABI).functions.approve( spender, amount ).build_transaction( { "from": taker, "chainId": CHAIN_ID, "nonce": w3.eth.get_transaction_count(taker), **tx_fees(w3), } ) approve_tx["gas"] = int(w3.eth.estimate_gas(approve_tx) * 1.2) signed_approval = Account.sign_transaction(approve_tx, private_key) approval_hash = w3.eth.send_raw_transaction(signed_approval.raw_transaction) receipt = w3.eth.wait_for_transaction_receipt(approval_hash) if receipt.status != 1: raise RuntimeError(f"approval reverted: {approval_hash.hex()}") tx = quote["tx"] data = tx["data"] if quote.get("permit2"): typed_data = { "domain": quote["permit2"]["domain"], "types": quote["permit2"]["types"], "primaryType": quote["permit2"]["primaryType"], "message": quote["permit2"]["message"], } signed_permit = Account.sign_message( encode_typed_data(full_message=typed_data), private_key, ) data = patch_permit2_signature( tx["data"], int(tx["signature_offset"]), bytes(signed_permit.signature), ) swap_tx = { "from": taker, "to": Web3.to_checksum_address(tx["to"]), "data": data, "value": int(tx.get("value", "0")), "chainId": CHAIN_ID, "nonce": w3.eth.get_transaction_count(taker), **tx_fees(w3), } gas_estimate = w3.eth.estimate_gas(swap_tx) swap_tx["gas"] = int(gas_estimate * 1.3) signed_swap = Account.sign_transaction(swap_tx, private_key) swap_hash = w3.eth.send_raw_transaction(signed_swap.raw_transaction) print("swap_tx:", swap_hash.hex()) ``` ## Caps and rules | Rule | Behavior | | ------------------------ | ------------------------------------------------------------------------------------------------------------------------ | | Fee above your key's cap | swap\_fee\_bps greater than your configured maximum is rejected with 400. | | Combined fee too high | Rialto's fee plus your fee must not exceed the chain's configured protocol maximum. Over the limit is rejected with 400. | | Non-integrator key | A key without integrator access that sends swap\_fee\_bps is rejected with 403. | | No fee requested | Omit swap\_fee\_bps or send 0 for a standard swap with no integrator fee. | Execute an integrator-fee quote exactly like any other quote. The fee recipient and cap are key-bound server-side, and the fee split is encoded into the transaction Rialto returns. # Integrator Onboarding Source: https://docs.rialto.xyz/developers/integrator-onboarding Create an integrator profile and API key through the wallet-signed onboarding flow. ## Overview Integrator keys are created through a wallet-signed onboarding flow. The wallet that applies becomes the owner wallet for the integrator profile and must also be the fee-recipient wallet. The flow is: 1. Build the application payload and its payload\_hash. 2. Call POST /integrators/nonce with action create\_integrator\_application. 3. Sign the exact message returned by the nonce endpoint with the owner wallet. 4. Submit the signed application to POST /integrators/applications. 5. Wait for Rialto approval if the application returns status: "pending". 6. After approval, request another nonce for create\_integrator\_api\_key, sign it, and call POST /integrators/api-keys. 7. Store the returned api\_key immediately. It is shown once. Later profile reads only return a masked key. ## Payload hash format Mutable integrator actions require a payload\_hash: ```text theme={null} keccak256("field_name=:\n" for each field, in order) ``` Use UTF-8 byte length for each value. Optional fields are encoded as `none` or `some:`. ## Endpoint: create integrator nonce ```http theme={null} POST /integrators/nonce ``` Auth: public. | Field | Description | | ------------- | --------------------------------------------------------------------------------------------------------------------------------- | | chain\_id | Optional chain id. Use 4663 for Robinhood Chain. | | wallet | Owner wallet that will sign. | | action | One of create\_integrator\_application, create\_integrator\_api\_key, revoke\_integrator\_api\_key, or view\_integrator\_profile. | | payload\_hash | Required for create and revoke actions. Not required for view\_integrator\_profile. | Response includes message, nonce, issued\_at, and expiration\_time. Sign the exact message string. Do not reconstruct it client-side. ## Endpoint: submit application ```http theme={null} POST /integrators/applications ``` Auth: public. | Field | Description | | ---------------------------------------------- | ----------------------------------------------------------------------------- | | chain\_id | Optional chain id. | | owner\_wallet | Wallet that owns the integrator profile. | | display\_name | Human-readable partner or app name. | | slug | Lowercase unique id, 3-64 chars, lowercase letters, digits, and hyphens only. | | contact\_email | Required contact email. | | telegram\_handle | Required Telegram handle. | | app\_url | Required application URL. | | application\_description | Required description, at most 200 words. | | fee\_recipient | Wallet that receives integrator fees. Must equal owner\_wallet. | | requested\_max\_fee\_bps | Max fee cap requested for this key, in basis points. | | payload\_hash | Hash of the application fields. | | nonce, issued\_at, expiration\_time, signature | Fields from /integrators/nonce plus the wallet signature. | Example response: ```json theme={null} { "integrator_id": 12, "slug": "example-wallet", "status": "pending", "message": "Application submitted for review." } ``` If status is pending, the Rialto team will review your application. If approved, the profile status becomes active and you can create an API key for it. If the application response already returns active, you can create a key immediately. ## Endpoint: create API key ```http theme={null} POST /integrators/api-keys ``` Auth: public. | Field | Description | | ---------------------------------------------- | -------------------------------------------------------------------- | | chain\_id | Optional chain id. | | owner\_wallet | Integrator owner wallet. | | integrator\_id | Numeric id returned by the application endpoint. | | label | Human-readable key label. | | payload\_hash | Hash of action, chain\_id, owner\_wallet, integrator\_id, and label. | | nonce, issued\_at, expiration\_time, signature | Fields from /integrators/nonce plus the wallet signature. | Response: ```json theme={null} { "key_id": 34, "api_key": "rialto_live_example.redacted_secret", "masked_key": "rialto_live_example...cret", "prefix": "example", "scopes": ["quote:read", "swap:create", "swap:integrator"], "quote_rate_limit_per_minute": 6000, "swap_rate_limit_per_minute": 6000, "integrator_id": "example-wallet", "integrator_fee_recipient": "", "integrator_max_fee_bps": 50, "shown_once": true } ``` The api\_key is shown only once at creation. Store it securely when this response is returned. It cannot be retrieved again; /integrators/me only returns masked key metadata. ## Profile and key management | Endpoint | Purpose | | ---------------------------------- | ------------------------------------------------------------- | | POST /integrators/me | List profiles and masked keys for an owner wallet. | | POST /integrators/api-keys//revoke | Revoke a key. Revoked keys are rejected by trading endpoints. | Use action view\_integrator\_profile on /integrators/nonce, sign the returned message, then submit owner\_wallet, nonce fields, and signature to /integrators/me. Use action revoke\_integrator\_api\_key to revoke a key. Compute the payload\_hash from owner\_wallet, integrator\_id, and key\_id. ## Python example This example submits an application. If the application is already active, it also creates an API key. If it is pending, save the returned `integrator_id` and create the key after Rialto approves the application. ```bash theme={null} python3 -m pip install requests eth-account eth-utils export OWNER_PRIVATE_KEY='0xREDACTED_OWNER_PRIVATE_KEY' python3 rialto_request_integrator_key.py ``` ```python theme={null} import os import time import requests from eth_account import Account from eth_account.messages import encode_defunct from eth_utils import keccak API_BASE = "https://rialto-trade-api.rialto.xyz" CHAIN_ID = 4663 ACTION_CREATE_APPLICATION = "create_integrator_application" ACTION_CREATE_API_KEY = "create_integrator_api_key" def require_env(name): value = os.getenv(name) if not value: raise RuntimeError(f"missing {name}") return value def payload_hash(fields): canonical = "" for key, value in fields: value = str(value) canonical += f"{key}={len(value.encode('utf-8'))}:{value}\n" return "0x" + keccak(canonical.encode("utf-8")).hex() def sign_message(private_key, message): signed = Account.sign_message(encode_defunct(text=message), private_key) return "0x" + bytes(signed.signature).hex() def nonce(owner, action, hash_value=None): body = {"chain_id": CHAIN_ID, "wallet": owner, "action": action} if hash_value is not None: body["payload_hash"] = hash_value response = requests.post(f"{API_BASE}/integrators/nonce", json=body, timeout=30) response.raise_for_status() return response.json() private_key = require_env("OWNER_PRIVATE_KEY") owner = Account.from_key(private_key).address.lower() display_name = "Example Partner" slug = f"example-partner-{int(time.time())}" contact_email = "ops@example.com" telegram_handle = "@example_ops" app_url = "https://example.com" application_description = "We want to route user swaps through Rialto." fee_recipient = owner requested_max_fee_bps = 50 app_hash = payload_hash( [ ("action", ACTION_CREATE_APPLICATION), ("chain_id", CHAIN_ID), ("owner_wallet", owner), ("display_name", display_name), ("slug", slug), ("contact_email", contact_email), ("telegram_handle", telegram_handle), ("app_url", app_url), ("application_description", application_description), ("fee_recipient", fee_recipient), ("requested_max_fee_bps", requested_max_fee_bps), ] ) app_nonce = nonce(owner, ACTION_CREATE_APPLICATION, app_hash) app_body = { "chain_id": CHAIN_ID, "owner_wallet": owner, "display_name": display_name, "slug": slug, "contact_email": contact_email, "telegram_handle": telegram_handle, "app_url": app_url, "application_description": application_description, "fee_recipient": fee_recipient, "requested_max_fee_bps": requested_max_fee_bps, "payload_hash": app_hash, "nonce": app_nonce["nonce"], "issued_at": app_nonce["issued_at"], "expiration_time": app_nonce["expiration_time"], "signature": sign_message(private_key, app_nonce["message"]), } app_response = requests.post( f"{API_BASE}/integrators/applications", json=app_body, timeout=30, ) app_response.raise_for_status() application = app_response.json() print("application:", application) if application["status"] != "active": print("Application is pending approval. Create the API key after approval.") raise SystemExit(0) integrator_id = application["integrator_id"] label = "production-key" key_hash = payload_hash( [ ("action", ACTION_CREATE_API_KEY), ("chain_id", CHAIN_ID), ("owner_wallet", owner), ("integrator_id", integrator_id), ("label", label), ] ) key_nonce = nonce(owner, ACTION_CREATE_API_KEY, key_hash) key_body = { "chain_id": CHAIN_ID, "owner_wallet": owner, "integrator_id": integrator_id, "label": label, "payload_hash": key_hash, "nonce": key_nonce["nonce"], "issued_at": key_nonce["issued_at"], "expiration_time": key_nonce["expiration_time"], "signature": sign_message(private_key, key_nonce["message"]), } key_response = requests.post( f"{API_BASE}/integrators/api-keys", json=key_body, timeout=30, ) key_response.raise_for_status() created_key = key_response.json() print("raw API key; store now:", created_key["api_key"]) print("masked key:", created_key["masked_key"]) ``` # Developer Introduction Source: https://docs.rialto.xyz/developers/introduction Integrate Rialto as an execution venue, or list liquidity as a propAMM source. ## Overview Rialto is an onchain swap router. It takes a sell token, a buy token, and an amount, finds the best available execution across the liquidity sources it supports, and returns a ready-to-send transaction that settles the trade atomically onchain. Rialto's defining liquidity source are propAMMs: onchain market makers that quote a price from their own logic and inventory rather than from a passive constant-product pool. Rialto quotes every candidate source onchain at request time, ranks routes by output net of gas, and settles the winning route through the RialtoRouter settlement contract. propAMMs compete alongside conventional DEX pools on every quote, so takers get the best price without choosing a venue. ## Two ways to integrate There are two distinct developer integrations, covered as separate tracks in this section: 1. Quote API. For wallets, frontends, and other routers that want to use Rialto as an execution venue. You request a quote and submit the transaction Rialto returns. You never build route calldata, fee logic, slippage math, Permit2 witnesses, or settlement actions yourself. 2. propAMM integration. For onchain market makers that want to list liquidity on Rialto. You deploy a pair contract that exposes a quote function and an atomic settlement function, and Rialto routes order flow to it when it wins. ## Choosing a track * To let users trade through your app, use the Quote API. * To provide liquidity and receive order flow, integrate as a propAMM source. The two are independent. An integration can consume the Quote API, provide propAMM liquidity, or do both. # For Liquidators Source: https://docs.rialto.xyz/developers/liquidator-onboarding Use Rialto as the swap leg inside liquidation and executor contracts. Permit2 is the preferred flow for swap transactions through Rialto. Contract signers can also use Permit2 when they implement EIP-1271 signature validation. For legacy integrations that cannot provide a valid Permit2 signature, Rialto also supports allowance settlement. For integration instructions, see the Taker-submitted flow in the [Rialto API docs](https://github.com/rialto-plds/rialto-api-docs/blob/main/RIALTO_SWAP_API.md). ## Contract-based executors Most liquidation bots execute through an executor or liquidator contract. That contract may receive the seized collateral, approve a swap router, perform the swap, and then send the output to the bot, treasury, or another recipient. The example below shows allowance settlement for executors that cannot provide a valid Permit2 signature. In this flow, the quote can be executed after the contract approves the spender returned by Rialto. For allowance flow, the quote should have: * `settlement: "allowance"` * `taker` set to the account or contract that holds and pays the sell token * `tx.to` set to the active Rialto router * `tx.data` executable by the executor contract * `tx.value` set for native-token sells, or `0` for ERC20 sells * `issues.allowance.spender` set when an ERC20 approval is needed ## Integration flow 1. Detect a liquidatable position. 2. Estimate the collateral amount to sell and the token you want to receive. 3. Call `GET /quote` with the executor contract as the taker. 4. If `issues.balance` is present, do not execute the liquidation. 5. If `issues.allowance` is present, approve the returned spender from the executor contract for at least `sell_amount`, preferably within the same transaction. 6. Execute `tx.to`, `tx.data`, and `tx.value` from the executor contract. 7. Reset the token allowance to zero after execution, preferably within the same transaction. ## Quote request ```bash theme={null} curl -sS 'https://rialto-trade-api.rialto.xyz/quote?sell_token=0x0Bd7D308f8E1639FAb988df18A8011f41EAcAD73&buy_token=0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168&sell_amount=0.01&taker=&slippage_bps=50&chain_id=4663' \ -H "Authorization: Bearer $RIALTO_API_KEY" ``` Use the executor contract as `taker` when the executor will hold the sell token and submit the swap call. ## Response fields to use ```json theme={null} { "settlement": "allowance", "sell_token": "", "buy_token": "", "sell_amount": "10000000000000000", "buy_amount": "19800022", "min_buy_amount": "19701021", "issues": { "allowance": { "actual": "0", "spender": "" }, "balance": null, "simulationIncomplete": false }, "tx": { "to": "", "data": "0x...", "value": "0", "estimated_gas": 226046 } } ``` For allowance settlement, use `issues.allowance.spender` as the approval target. Use `tx.to`, `tx.data`, and `tx.value` as the swap call. Do not recompute the route, fee logic, slippage math, or calldata. The returned transaction is the integration boundary. ## Executor sketch ```solidity theme={null} // SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract LiquidationExecutor { address public owner; modifier onlyOwner() { require(msg.sender == owner, "not owner"); _; } constructor(address _owner) { owner = _owner; } function executeRialtoSwap( address sellToken, address spender, uint256 sellAmount, address rialtoRouter, bytes calldata rialtoData, uint256 value ) external payable onlyOwner { if (sellToken != address(0)) { IERC20(sellToken).approve(spender, sellAmount); } (bool ok, bytes memory result) = rialtoRouter.call{value: value}(rialtoData); if (!ok) { assembly { revert(add(result, 32), mload(result)) } } if (sellToken != address(0)) { IERC20(sellToken).approve(spender, 0); } } } ``` The executor should already include its liquidation logic, access control, profit checks, and token recovery functions. The example only shows the swap boundary. ## Q\&A ### What should the approval lifecycle be? For allowance settlement, use scoped approvals. Approve only the amount needed for the input token, execute the swap, then reset the allowance to zero, preferably within the same transaction. This reduces exposure from unused or stale allowances, in addition to the controls Rialto applies on its side. ### What should I do if the quote returns `issues`? If `issues.balance` is present, do not execute the swap. If `issues.allowance` is present for allowance settlement, approve the returned spender before execution. ## Safety checks Before executing a quote, liquidators should still check: * expected profit after gas * `min_buy_amount` * route freshness * slippage tolerance * token balances after liquidation * allowance reset after execution, for allowance settlement * whether the returned transaction still simulates successfully Quotes depend on live liquidity and may become stale quickly. Request a fresh quote close to execution time. # Onboarding Checklist Source: https://docs.rialto.xyz/developers/onboarding-checklist What Rialto needs to list your propAMM pair. ## What to send To list a pair, send Rialto: * A deployed, verified pair contract address implementing IPropPair. * The chain. * token0 and token1 addresses and symbols, in that order. * Confirmation that swapExactIn sends output to to and reverts below amountOutMin or past deadline. * A realistic gas estimate for your swapExactIn. Rialto calibrates the per-leg estimate from observed gas, roughly p90 plus 10% headroom. * Whether you want a native-ETH side. The default is ERC20/ERC20 only. ## What happens next Rialto adds the config entry and the owner allowlists the pool, and your liquidity starts competing on the next router cycle. Rialto quotes a few sizes against your pool and compares them to your expected fills before going live. # Complete Supported Tokens Universe Source: https://docs.rialto.xyz/developers/partner-supported-tokens Cache Rialto's complete supported-token universe and report genuine demand for unsupported tokens. This guide describes how a Partner should cache Rialto's current quote-admission list, avoid unnecessary quote work, and report genuine demand for tokens that are not yet supported so Rialto can auto-enable them once genuine demand is established. ## Endpoints Production API: ```text theme={null} https://rialto-trade-api.rialto.xyz ``` Supported-token snapshot: ```http theme={null} GET /tokens/quote-supported?chain_id=4663 ``` The snapshot endpoint does not require an API key. It is public-rate-limited, so the Partner should maintain one shared cache rather than polling it independently for every quote request or worker. ## Initial Snapshot: `200 OK` Request: ```bash theme={null} curl --compressed \ 'https://rialto-trade-api.rialto.xyz/tokens/quote-supported?chain_id=4663' ``` Response: ```http theme={null} HTTP/2 200 Content-Type: application/json Content-Encoding: gzip ETag: W/"4663-" Cache-Control: public, max-age=15, stale-while-revalidate=60 ``` ```json theme={null} { "schema_version": 2, "chain_id": 4663, "snapshot_id": "0x...", "count": 2, "addresses": [ "0x...", "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" ], "directional_support": [ { "address": "0x...", "can_buy": true, "can_sell": false } ] } ``` On `200 OK`, the Partner should: 1. Parse the response into a new lowercase address `HashSet`. 2. Verify `chain_id`, `schema_version`, and `count`. 3. Save the response `ETag`. 4. Atomically replace the previous `HashSet` only after parsing succeeds. `directional_support` contains overrides for tokens whose currently available directions are known. Respect `can_sell` when the token is the sell side and `can_buy` when it is the buy side. Addresses without an entry remain eligible for normal `/quote` routing in either position. The body is prebuilt by Rialto and gzip-compressed in transit. Local hash-set membership is constant-time and does not require another Rialto request. ## Conditional Refresh: `304 Not Modified` Poll once every 15-60 seconds using the last ETag: ```bash theme={null} curl --compressed -i \ -H 'If-None-Match: W/"4663-"' \ 'https://rialto-trade-api.rialto.xyz/tokens/quote-supported?chain_id=4663' ``` If the list is unchanged, Rialto returns: ```http theme={null} HTTP/2 304 ETag: W/"4663-" ``` The `304` response has no JSON body. The Partner should keep its existing `HashSet`. This avoids repeatedly downloading and parsing the full address list. If the list changed, Rialto returns `200 OK` with a new body and ETag. The Partner should build and atomically publish a replacement `HashSet`. ## Quote Flow For each genuine user quote request: ```text theme={null} Normalize sell and buy addresses | v Check both addresses in the Partner's local cache or snapshot HashSet | +-- both supported --> call /quote normally | +-- either unsupported --> optionally send one genuine demand probe ``` Snapshot inclusion means Rialto accepts the token for routing. It does not guarantee that every pair, amount, or market state has a viable route. Normal quote request: ```bash theme={null} curl --get 'https://rialto-trade-api.rialto.xyz/quote' \ -H "Authorization: Bearer $RIALTO_API_KEY" \ --data-urlencode 'chain_id=4663' \ --data-urlencode 'sell_token=0x...' \ --data-urlencode 'buy_token=0x...' \ --data-urlencode 'sell_amount=10' \ --data-urlencode 'taker=0x...' \ --data-urlencode 'slippage_bps=50' ``` ## Unsupported Demand Probes The Partner may send a `/quote` request for a token missing from its local snapshot when that request represents real user demand. Rialto returns an explicit unsupported-token response quickly. The response is an explicit unsupported-token error, for example: ```http theme={null} HTTP/2 400 ``` ```json theme={null} { "error": "unsupported buy_token" } ``` ## Probe and Quote Limits The Partner authenticates `/quote` with its existing API key and `quote:read` scope. There is no additional API-key scope to configure. Internally, Rialto uses two independent rate-limit buckets: | Bucket | Purpose | | ------------- | -------------------------------------------------------------------------------------- | | `quote_probe` | Authentication, parsing, in-memory token admission, and unsupported-demand observation | | `quote:read` | Expensive routing and quote execution after both tokens pass admission | The probe allowance is configured at up to 10 times the Partner's normal quote allowance over the same limiter interval. An unsupported request consumes the probe bucket but returns before consuming the expensive `quote:read` bucket. A supported request passes admission and then consumes the ordinary quote allowance as well. The probe bucket is still bounded and rate-limited. The Partner should send only genuine user demand, not synthetic loops or repeated requests intended only to force promotion. ## Recommended Client Behavior 1. Maintain one shared full snapshot per chain. 2. Fetch the full universe on startup. 3. Poll every 15-60 seconds with `If-None-Match`. 4. Keep the current `HashSet` on `304` or transient refresh failure. 5. Atomically replace it after a valid `200` response. 6. Call `/quote` normally when both addresses are present. 7. For genuine demand involving a missing address, send the quote once as an unsupported-demand probe and handle the explicit rejection. 8. Do not repeatedly probe the same unsupported request inside a retry loop. 9. After a later snapshot includes the token, process it through the normal supported quote path. Continue with the [Python reference implementation](/developers/partner-supported-tokens-python) for a complete cache, refresh, admission-check, and demand-probe example. # Supported Tokens: Python Reference Source: https://docs.rialto.xyz/developers/partner-supported-tokens-python A complete Python example for caching Rialto's supported-token list and handling quote admission. This example shows how an integrator can: * Fetch and cache Rialto's supported-token snapshot. * Refresh the cache efficiently with an `ETag`. * Check token support locally before requesting a quote. * Report genuine demand for an unsupported token without entering a retry loop. ## Requirements The example requires Python 3.10 or later and the `requests` package: ```bash theme={null} pip install requests ``` Set your Rialto API key before running it: ```bash theme={null} export API_KEY="" ``` ## Run the example Save the complete example below as `partner_supported_tokens_example.py`. Then provide the sell token, buy token, and optional sell amount: ```bash theme={null} python partner_supported_tokens_example.py \ --sell-token 0x... \ --buy-token 0x... \ --sell-amount 10 ``` To send one genuine unsupported-demand probe when either token is absent from the local snapshot, add `--report-unsupported-demand`. ## Complete example ```python theme={null} #!/usr/bin/env python3 """Minimal Partner example for caching Rialto's supported-token list.""" from __future__ import annotations import argparse import json import os import re import time from dataclasses import dataclass, field import requests API_URL = os.getenv("RIALTO_API_URL", "https://rialto-trade-api.rialto.xyz").rstrip("/") API_KEY = os.getenv("API_KEY", "") CHAIN_ID = 4663 TAKER = "0x0000000000000000000000000000000000000001" TIMEOUT_SECONDS = 30 REFRESH_SECONDS = 15 # Refresh the list every 15 seconds. ADDRESS_PATTERN = re.compile(r"0x[0-9a-fA-F]{40}") def normalize_address(address: str) -> str: if not ADDRESS_PATTERN.fullmatch(address): raise ValueError(f"invalid token address: {address}") return address.lower() HEADERS = { "Accept": "application/json", "Accept-Encoding": "gzip", "User-Agent": "partner-rialto-supported-token-example/1.0", } @dataclass class SupportedTokens: addresses: set[str] = field(default_factory=set) etag: str | None = None def refresh(self) -> None: headers = {"If-None-Match": self.etag} if self.etag else {} response = requests.get( f"{API_URL}/tokens/quote-supported", params={"chain_id": CHAIN_ID}, headers=HEADERS | headers, timeout=TIMEOUT_SECONDS, ) if response.status_code == 304: print(f"supported tokens: unchanged ({self.etag})") return response.raise_for_status() payload = response.json() addresses = {normalize_address(address) for address in payload["addresses"]} if ( payload["schema_version"] != 2 or payload["chain_id"] != CHAIN_ID or payload["count"] != len(addresses) ): raise RuntimeError("invalid supported-token snapshot") self.addresses = addresses self.etag = response.headers.get("ETag") print(f"supported tokens: loaded {len(addresses):,} ({self.etag})") def supports(self, token: str) -> bool: return normalize_address(token) in self.addresses def quote(sell_token: str, buy_token: str, sell_amount: str) -> requests.Response: if not API_KEY: raise RuntimeError("API_KEY is missing from the environment") return requests.get( f"{API_URL}/quote", params={ "chain_id": CHAIN_ID, "sell_token": sell_token, "buy_token": buy_token, "sell_amount": sell_amount, "taker": TAKER, "slippage_bps": 50, }, headers=HEADERS | {"Authorization": f"Bearer {API_KEY}"}, timeout=TIMEOUT_SECONDS, ) def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--sell-token", required=True) parser.add_argument("--buy-token", required=True) parser.add_argument("--sell-amount", default="10") parser.add_argument( "--report-unsupported-demand", action="store_true", help="Send genuine unsupported demand to Rialto instead of skipping it locally.", ) return parser.parse_args() def main() -> int: args = parse_args() sell_token = normalize_address(args.sell_token) buy_token = normalize_address(args.buy_token) supported = SupportedTokens() supported.refresh() time.sleep(REFRESH_SECONDS) supported.refresh() pair_supported = supported.supports(sell_token) and supported.supports(buy_token) print(f"pair supported: {pair_supported}") if not pair_supported and not args.report_unsupported_demand: print("quote skipped locally") return 0 # Genuine unsupported requests help Rialto discover demand. Repeated Partner # demand starts asynchronous validation; it does not guarantee admission. # These probes use a separate allowance of up to 10x the normal quote rate. response = quote(sell_token, buy_token, args.sell_amount) print(f"quote: HTTP {response.status_code}") print(json.dumps(response.json(), indent=2)) if pair_supported: return 0 if response.ok else 1 return 0 if response.status_code in {400, 404, 422} else 1 if __name__ == "__main__": try: raise SystemExit(main()) except (requests.RequestException, RuntimeError, ValueError) as error: raise SystemExit(f"error: {error}") from error ``` The first refresh downloads the current snapshot and saves its `ETag`. Each later refresh sends that saved value in `If-None-Match`. On `304 Not Modified`, keep using the existing snapshot and `ETag`. On `200 OK`, replace the snapshot and save the new `ETag` returned in the response. # propAMM Integration Overview Source: https://docs.rialto.xyz/developers/propamm-integration-overview List an onchain propAMM as a competing liquidity source on the Rialto Router. ## Who this is for This track is for onchain market makers that expose an onchain quote function and settle atomically in the same transaction. You deploy a contract that Rialto quotes and settles against; Rialto routes order flow to it whenever it wins. ## How Rialto sources liquidity Rialto's router quotes every candidate pool onchain at request time, picks the best route net of gas, then settles the chosen route atomically through the RialtoRouter settlement contract. A propAMM plugs in as one more candidate pool: * Quote time, read-only. Rialto calls your getAmountOut view function. Your quote competes on output net of gas. * Settle time, one transaction. If your pool wins a leg, RialtoRouter calls your swapExactIn via a generic RawCall action, with onchain slippage and output checks. The model is an onchain, batch-sampleable quote plus an atomic settlement entrypoint. Everything stays onchain and trustless, with no signing service or quote API to run, unlike off-chain RFQ. ## Reference material * Integration guide: [https://github.com/rialto-plds/rialto-api-docs/blob/main/PROP\_AMM\_INTEGRATION.md](https://github.com/rialto-plds/rialto-api-docs/blob/main/PROP_AMM_INTEGRATION.md) * Runnable sample implementation: [https://github.com/rialto-plds/sample-propamm](https://github.com/rialto-plds/sample-propamm) The pages that follow cover the standard interface, the quote and settlement functions, adapting an existing AMM, the reference implementation, the onboarding checklist, and the security model. # Quoting (getAmountOut) Source: https://docs.rialto.xyz/developers/quoting Implement the read-only quote function Rialto samples at request time. ## Parameters | Param | Type | Meaning | | ---------- | ------- | --------------------------------------------------------------------------- | | zeroForOne | bool | true = sell token0, buy token1; false = the reverse. | | amountIn | uint256 | Exact input amount, in the input token's smallest units. | | returns | uint256 | Output amount you would deliver now, in smallest units of the output token. | ## Requirements * View and read-only. getAmountOut must not write state. * Exact-in only. There is no exact-out path today. * Unsupported sizes. For an amountIn or pair you cannot fill, return 0 or revert. Do not return a price you will not honor. * Self-consistent with settlement. The price getAmountOut returns is what Rialto routes on. Occasional slips from volatility between quote and settle are expected, but quotes and swaps should generally agree. Quote your currently executable price; if it is oracle-driven, quote from the same oracle you settle against. * Gas. Rialto assigns your leg a gas estimate when ranking routes net of gas, calibrated from observed usage at roughly p90 plus 10% headroom. Give a realistic gas figure for your swapExactIn; an unrealistically cheap estimate makes your route look better than it settles. # Reference Implementation Source: https://docs.rialto.xyz/developers/reference-implementation A minimal, runnable propAMM that plugs into the Rialto Router. ## Overview The sample-propamm repository is a minimal, self-contained reference implementation of an onchain propAMM that plugs into the Rialto Router as a liquidity source. Use it as a starting skeleton: copy it, replace the pricing logic with your own, and keep the two integration entrypoints, getAmountOut and swapExactIn, matching the standard interface. Repository: [https://github.com/rialto-plds/sample-propamm](https://github.com/rialto-plds/sample-propamm) This is sample code for integration purposes only. It is not audited and not production-ready. Do not deploy it as-is with real funds. ## Contracts * PropPair. An inventory-backed pair contract with quoting and exact-input swaps. This is the contract Rialto integrates with, one per token pair. * PropOracle. An example price source with owner-gated updates and a pause switch. This stands in for your own pricing source; replace it with whatever drives your quotes. One PropOracle can store prices for many pair contracts. Each PropPair represents one market, such as TSLA/USDC. The oracle is the shared price source; the pair holds inventory and executes quotes and swaps for its own market. ## Price format PropOracle stores price as priceX18, the token1 amount per 1 token0, scaled by 1e18. For example, 2e18 means 1 token0 quotes to 2 token1, and 5e17 means 1 token0 quotes to 0.5 token1. ## Example flow 1. Deploy PropOracle. 2. Deploy PropPair with owner, token0, token1, and the oracle address. 3. Call PropOracle.setPrice(pair, priceX18). 4. Approve and fund both pair reserves with PropPair.fund. 5. Quote with PropPair.getAmountOut. 6. Settle via PropPair.swapExactIn, in production called by the Rialto Router. ## Build and test ```bash theme={null} forge install # fetch the forge-std submodule, first time only forge build forge test ``` When adapting to production, use a SafeERC20-style wrapper for non-standard tokens such as USDT, and guard price staleness: quote from the same price source you settle against. # Requesting a Quote Source: https://docs.rialto.xyz/developers/requesting-a-quote Request a firm quote and receive an executable transaction for an exact-input swap. ## Endpoint ```http theme={null} GET /quote ``` Auth: requires an API key with quote access. Returns the best route, expected output, route legs, platform fee, estimated network fee, and an executable transaction for an exact-input swap. ## Required parameters | Param | Description | | ------------- | ---------------------------------------------------------------- | | sell\_token | Canonical `0x`-prefixed token address. Symbols are not accepted. | | buy\_token | Canonical `0x`-prefixed token address. Symbols are not accepted. | | sell\_amount | Human decimal sell amount, for example 0.01. | | taker | Non-zero wallet address that will receive output. | | slippage\_bps | Max slippage in basis points. 50 means 0.50%. | slippageBps is also accepted as an alias for slippage\_bps. Pass the canonical `address` returned by a token-discovery endpoint. Symbol values such as `WETH` or `USDG` are rejected because symbols are not unique. ## Optional parameters | Param | Description | | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | | chain\_id | Chain id. Defaults to the server's configured chain. | | max\_hops | Route-depth hint; final route policy is controlled server-side. | | permit2\_owner | Non-zero Permit2 token owner for gasless or relayed ERC20 swaps. For gasless, this must equal taker. Also accepts permit2Owner and permitOwner. | | settlement | Fund-pull preference: auto, permit2, or allowance. Defaults to auto. Also accepts settlementPreference. | | swap\_fee\_bps | Integrator fee in basis points. Requires an integrator key. | | swap\_fee\_token | Accepted for API compatibility; current routing selects the fee token. | | swap\_fee\_recipient | Ignored. The payout wallet is bound to the API key. | | gasless\_relay | Set to true only when Rialto will submit the transaction through `/gasless/submit`. Also accepts gaslessRelay. | ## Example ```bash theme={null} API_KEY='rialto_live_example.redacted_secret' curl -sS 'https://rialto-trade-api.rialto.xyz/quote?sell_token=0x0Bd7D308f8E1639FAb988df18A8011f41EAcAD73&buy_token=0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168&sell_amount=0.01&taker=&slippage_bps=50' \ -H "Authorization: Bearer $API_KEY" ``` ## Example response ```json theme={null} { "quote_id": "b7b0a3d8-9f6a-4f4a-92d2-1b0e4b5d0c6a", "settlement": "permit2", "tx": { "to": "", "data": "0xdbefe2d6...", "value": "0", "estimated_gas": 255053, "signature_offset": 548 }, "permit2": { "domain": { "name": "Permit2", "chainId": 4663, "verifyingContract": "" }, "types": { "EIP712Domain": [ { "name": "name", "type": "string" }, { "name": "chainId", "type": "uint256" }, { "name": "verifyingContract", "type": "address" } ], "PermitWitnessTransferFrom": [ { "name": "permitted", "type": "TokenPermissions" }, { "name": "spender", "type": "address" }, { "name": "nonce", "type": "uint256" }, { "name": "deadline", "type": "uint256" }, { "name": "witness", "type": "RialtoSwap" } ], "TokenPermissions": [ { "name": "token", "type": "address" }, { "name": "amount", "type": "uint256" } ], "RialtoSwap": [ { "name": "recipient", "type": "address" }, { "name": "buyToken", "type": "address" }, { "name": "minBuyAmount", "type": "uint256" }, { "name": "deadline", "type": "uint64" }, { "name": "feeRecipient", "type": "address" }, { "name": "srcBps", "type": "uint16" }, { "name": "dstBps", "type": "uint16" }, { "name": "referralCode", "type": "bytes32" }, { "name": "quoteId", "type": "bytes32" }, { "name": "actionsHash", "type": "bytes32" } ] }, "primaryType": "PermitWitnessTransferFrom", "message": { "permitted": { "token": "", "amount": "10000000000000000" }, "spender": "", "nonce": "102222442441090043455808165797985926558", "deadline": "1780300214", "witness": { "recipient": "", "buyToken": "", "minBuyAmount": "19701021", "deadline": 1780300214, "feeRecipient": "", "srcBps": 0, "dstBps": 5, "referralCode": "", "quoteId": "", "actionsHash": "" } }, "nonce": "102222442441090043455808165797985926558", "deadline": 1780300214 }, "issues": { "allowance": { "actual": "0", "spender": "" }, "balance": null, "simulationIncomplete": false, "invalidSourcesPassed": [] }, "chain_id": 4663, "sell_token": "", "buy_token": "", "sell_amount": "10000000000000000", "buy_amount": "19800022", "min_buy_amount": "19701021", "platform_fee": { "total_bps": 5, "fees": [ { "side": "destination", "token": "", "symbol": "USDG", "decimals": 6, "bps": "5", "bps_x100": 500, "amount": "9900", "amount_decimal": "0.0099", "recipient": "" } ] }, "network_fee": { "token": "", "symbol": "ETH", "decimals": 18, "gas": "226046", "gas_price": "20000000", "gas_price_gwei": "0.02", "amount": "4520920000000", "amount_gwei": "4520.92", "amount_eth": "0.00000452092" }, "taker": "", "slippage_bps": 50, "candidate_paths": 8, "successful_routes": 7, "failed_routes": 1, "route": { "sell_amount": "10000000000000000", "buy_amount": "19800022", "gas_estimate": 106046, "legs": [ { "pool_id": "uniswap-v3:chain-4663::100", "sell_token": "", "buy_token": "", "sell_amount": "10000000000000000", "buy_amount": "19809926" } ] } } ``` Exact amounts and route legs depend on live liquidity. ## Key response fields | Field | Description | | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | chain\_id | Chain id for the quote. | | quote\_id | UUID handle for the server-stored quote. Bound into the Permit2 witness as a bytes32 quoteId, so the signature is tied to this exact quote. | | settlement | Execution mode: permit2 or allowance. | | tx | Ready-to-send transaction object. In direct flow, send this from the taker wallet after any required approval or signature step. In gasless flow, Rialto submits this transaction after /gasless/submit. | | permit2 | EIP-712 typed-data payload. Present only for Permit2 settlement. The `permit2_owner` requested for a gasless quote must sign it. | | issues | Frontend blockers and execution hints for balance and allowance. | | sell\_token | Sell token address. | | buy\_token | Buy token address. | | sell\_amount | Raw integer sell amount in token smallest units. | | buy\_amount | Expected raw integer buy amount before slippage. | | min\_buy\_amount | Slippage-protected raw minimum buy amount encoded into tx.data. | | platform\_fee | Platform fee breakdown. | | integrator\_fee | Present when an integrator fee was accepted for this key. | | referral / referral\_fee | Present when referral attribution or referral fee policy applies. | | network\_fee | Estimated transaction gas cost, if available. | | taker | Recipient/taker address. | | slippage\_bps | Slippage tolerance used for quote. | | route.legs | Ordered route legs and pools. | ## The issues object Inspect issues before submitting. It flags conditions that should block or gate execution. | Field | Meaning | | --------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | issues.balance | Non-null when the taker lacks enough sell-token balance. Do not submit. | | issues.allowance | Non-null when an ERC20 approval is needed before submitting tx. Approve issues.allowance.spender for at least sell\_amount. | | issues.simulationIncomplete | true when the backend could not complete all quote simulation checks. | | issues.invalidSourcesPassed | Reserved field; currently an empty array. | ## Notes Quotes depend on live liquidity and can go stale quickly. Request a fresh quote if the user waits. The exact amounts and route legs depend on live liquidity at request time. Use the returned settlement mode as the source of truth when executing a quote. See [Settlement Modes](/developers/settlement-modes) for when to request Permit2 or allowance mode explicitly. # Router Registries Source: https://docs.rialto.xyz/developers/router-registries Discover the active Rialto router for taker-submitted and gasless swap flows. ## Overview Rialto publishes Router Registry contracts so partners can discover the active Rialto router instead of hardcoding router addresses. Use feature id `2` when you submit the transaction returned by `GET /quote` from the taker wallet. Use feature id `3` when you use Rialto's gasless relayer flow through `POST /gasless/submit`. | Feature id | Flow | | ---------- | ------------------------------ | | `2` | Taker-submitted or normal swap | | `3` | Gasless or relayed swap | ## Registry deployments | Chain | Chain id | API access | Router Registry | | -------- | -------- | -------------------------- | -------------------------------------------- | | RH Chain | `4663` | `` | `0x71a120CbBf3Ce7cD910a3c50fF77aFc62735687E` | ## Registry reads | Function | Meaning | | ------------------------------- | ------------------------------------------------------------------------------------------------- | | `ownerOf(uint256 featureId)` | Current active router for the feature. Reverts when the feature is paused or uninitialized. | | `prev(uint128 featureId)` | Previous router accepted during a migration dwell window. Reverts when no previous router is set. | | `next(uint128 featureId)` | Staged next router, or the zero address when none is staged. | | `getFeature(uint128 featureId)` | One-call read returning `(previous, current, next, paused)`. | In this registry, "owner" means the router address currently assigned to a feature id. It is not the registry admin owner. ## JSON-RPC examples ```bash theme={null} # Robinhood Chain: # Use your own Robinhood Chain RPC endpoint if you need direct registry reads. # RPC_URL='' # REGISTRY_ADDRESS='0x71a120CbBf3Ce7cD910a3c50fF77aFc62735687E' # Feature 2 = taker-submitted quote transaction. # Feature 3 = gasless relayer flow. FEATURE_ID=2 FEATURE_HEX=$(printf '%064x' "$FEATURE_ID") # Current router: ownerOf(uint256) DATA="0x6352211e${FEATURE_HEX}" curl -sS "$RPC_URL" \ -H 'Content-Type: application/json' \ -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"eth_call\",\"params\":[{\"to\":\"$REGISTRY_ADDRESS\",\"data\":\"$DATA\"},\"latest\"]}" # Previous router: prev(uint128) DATA="0xe2603dc2${FEATURE_HEX}" curl -sS "$RPC_URL" \ -H 'Content-Type: application/json' \ -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"eth_call\",\"params\":[{\"to\":\"$REGISTRY_ADDRESS\",\"data\":\"$DATA\"},\"latest\"]}" # Staged next router: next(uint128) DATA="0x74bcde51${FEATURE_HEX}" curl -sS "$RPC_URL" \ -H 'Content-Type: application/json' \ -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"eth_call\",\"params\":[{\"to\":\"$REGISTRY_ADDRESS\",\"data\":\"$DATA\"},\"latest\"]}" # Full feature state: getFeature(uint128) DATA="0x46df01a4${FEATURE_HEX}" curl -sS "$RPC_URL" \ -H 'Content-Type: application/json' \ -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"eth_call\",\"params\":[{\"to\":\"$REGISTRY_ADDRESS\",\"data\":\"$DATA\"},\"latest\"]}" ``` `eth_call` returns ABI-encoded hex. For single-address calls, the address is the last 20 bytes of the returned 32-byte word. For `getFeature`, decode four ABI words as `(address previous, address current, address next, bool paused)`. # Security Model Source: https://docs.rialto.xyz/developers/security-model What Rialto's settlement contract guarantees around your swapExactIn call. ## Guarantees * Allowlisted, single-function. The router can only RawCall the exact pair and swapExactIn selector that Rialto allowlists, no other function and no arbitrary calldata. A pair address allowlisted as a call target cannot also be a routable token, and vice versa. * Output-verified. Settlement reverts unless the router's measured output-token balance increases by at least amountOutMin. You cannot be paid without delivering. * Approvals are scoped and revoked. The router approves exactly amountIn and resets to 0 around each call, so a stale or oversized allowance cannot be drained later. * You hold your own inventory and risk. Rialto never custodies your funds; your contract prices and fills from its own balances. Your getAmountOut is your price; your swapExactIn is your fill. # Settlement (swapExactIn) Source: https://docs.rialto.xyz/developers/settlement Implement the atomic settlement function RialtoRouter calls when your pool wins. ## Runtime behavior RialtoRouter settles a winning leg by calling swapExactIn through a generic RawCall action: 1. Input delivery. For ERC20 input, the router approves your contract for exactly amountIn immediately before the call, so you pull it with transferFrom(router, you, amountIn). The router revokes the approval to 0 right after. For native-ETH input, the router calls `swapExactIn{value: amountIn}`, so the function is payable. 2. Honor the amountIn parameter. It is the authoritative input amount for this fill. Pull and price against exactly the amountIn passed in; do not assume a fixed or pre-agreed size. 3. Output delivery. Send the output token to to, which is the RialtoRouter address. The router measures its own balance delta of the output token and requires received >= amountOutMin, reverting the whole swap otherwise. 4. deadline. Unix seconds. Enforcing it on your side is optional, since Rialto already bounds the swap's validity window. Treat 0 as no deadline. 5. Refunds. If you pull less than amountIn, the router refunds the unspent input, but the cleanest contract pulls and uses exactly amountIn. ## Parameters | Param | Type | Meaning | | ------------ | ------- | ------------------------------------------------------- | | zeroForOne | bool | Same convention as the quote. | | amountIn | uint256 | Exact input to pull, router-supplied and authoritative. | | amountOutMin | uint256 | Revert if you cannot deliver at least this. | | to | address | Recipient of the output, always the RialtoRouter. | | deadline | uint256 | Unix-seconds expiry. | | returns | uint256 | Actual output delivered. | ## Approval and transfer pattern (ERC20) ```solidity theme={null} // Router, before the call: IERC20(tokenIn).approve(you, amountIn); // You, inside swapExactIn: IERC20(tokenIn).transferFrom(msg.sender, address(this), amountIn); // ... your pricing/inventory logic ... // IERC20(tokenOut).transfer(to, amountOut); // to == router // Router, after the call: IERC20(tokenIn).approve(you, 0); ``` ## Native ETH Native ETH is optional and advanced; most propAMM pairs are ERC20/ERC20, for example WETH/USDC. If you want a native-ETH side, accept msg.value on input and send ETH to to on output. Pick one convention across all your pairs, either ETH/token everywhere or WETH/token everywhere, and represent native ETH with the 0xEeee...EEeE sentinel. Confirm the wiring with Rialto. # Settlement Modes Source: https://docs.rialto.xyz/developers/settlement-modes Choose between automatic, Permit2, and allowance settlement when requesting a quote. ## Overview The quote response's `settlement` field tells you which execution mode Rialto returned. Always use the response value for transaction handling, even when you send a request preference. You can influence the backend's choice with the optional `settlement` query parameter on `GET /quote`. | Request value | Behavior | | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `auto` | Default. Uses Permit2 for EOA ERC20 sells, and allowance mode for smart-wallet or native ETH sells. | | `permit2` | Requires a Permit2 executable quote. Use this for gasless relays or integrations that specifically need Permit2. Native ETH sells and smart-wallet takers cannot use this mode. | | `allowance` | Requires router allowance mode. The response has no `permit2` payload or `tx.signature_offset`; ERC20 users approve the router spender in `issues.allowance.spender`. | `settlementPreference` is also accepted as an alias for `settlement`. ## Response modes | Response value | What to do | | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `permit2` | Have the taker sign the returned `permit2` typed data, splice the 65-byte signature into `tx.data` at `tx.signature_offset`, then submit the transaction from the taker wallet or through the gasless relayer. | | `allowance` | If `issues.allowance` is non-null, approve `issues.allowance.spender` for at least the raw `sell_amount`, then submit `tx.to`, `tx.data`, and `tx.value` without modifying calldata. | ## When to request Permit2 Request `settlement=permit2` when a flow specifically needs a Permit2 quote, such as gasless relay submission. Pass `settlement=permit2` if you want the quote request to fail instead of falling back to allowance mode. For Rialto to submit the transaction, also pass `gasless_relay=true`; Permit2 settlement alone does not authorize relay submission. ```bash theme={null} API_KEY='rialto_live_example.redacted_secret' TAKER='' curl -sS "https://rialto-trade-api.rialto.xyz/quote?sell_token=0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168&buy_token=0xc93a8c440CEa26D7445dF01729f193b27965099f&sell_amount=1&taker=$TAKER&permit2_owner=$TAKER&settlement=permit2&slippage_bps=50&chain_id=4663" \ -H "Authorization: Bearer $API_KEY" ``` ## Handling rules Choose your handling from `settlement`, not from assumptions. Do not modify `quote_id`, `route`, `platform_fee`, `permit2.message.witness`, or `tx.data` except for replacing the Permit2 signature placeholder. A changed route or witness will not match the signed quote and may revert. # Standard Interface Source: https://docs.rialto.xyz/developers/standard-interface The two-function interface a propAMM pair implements for Rialto. ## What you implement Deploy one contract per token pair implementing the standard Rialto propAMM interface: a getAmountOut quote and a swapExactIn settle. Rialto calls them by their 4-byte selector, so match these signatures, or put a thin adapter in front if your AMM already exposes different ones. token0() and token1() are optional; Rialto never calls them, since the pair and ordering come from Rialto's config. ```solidity theme={null} interface IPropPair { /// OPTIONAL — Rialto never calls these; pair & ordering come from config. function token0() external view returns (address); function token1() external view returns (address); /// QUOTE (read-only view). Exact-in only. /// zeroForOne = true -> selling token0, receiving token1 /// zeroForOne = false -> selling token1, receiving token0 function getAmountOut(bool zeroForOne, uint256 amountIn) external view returns (uint256 amountOut); /// SETTLE (state-changing). Called by RialtoRouter only. function swapExactIn( bool zeroForOne, uint256 amountIn, uint256 amountOutMin, address to, uint256 deadline ) external payable returns (uint256 amountOut); } ``` getAmountOut is sampled at quote time; swapExactIn settles. The trade direction zeroForOne is fixed by Rialto's config ordering, not by token0() or token1(): zeroForOne = true means sell config-token0 and buy config-token1. ## Why the shape matters The interface is a convention Rialto standardizes on, not a protocol constraint, but two things are coupled to the exact shape: * The settle selector is allowlisted onchain per pool, and the router patches the real input amount into the calldata at a fixed offset that assumes swapExactIn(bool, uint256 amountIn, ...) with amountIn as the second argument. A different argument layout moves that offset. * The quote and settle selectors are currently a single shared interface across all propAMM pools. payable is part of the standard signature so native-ETH pairs are possible. # Supported Tokens Source: https://docs.rialto.xyz/developers/supported-tokens Search for tokens and cache Rialto's quote-supported universe. Rialto provides two token-discovery endpoints for integrators: | Endpoint | Use it for | | ----------------------------- | ------------------------------------------------------------------------- | | `GET /tokens/search` | Look up a specific token address on demand. | | `GET /tokens/quote-supported` | Download the full quote-supported universe as a gzip-compressed snapshot. | ## Token fields | Field | Description | | -------------- | --------------------------------------------------------------- | | name | Token display name. | | symbol | Token symbol. | | address | Token contract address. | | decimals | Token decimals. | | source | How the token entered the supported set. | | type | stable or non\_stable. | | category | crypto, stock, or etf. | | liquid | Whether the token currently has an enabled route. | | can\_buy | Whether the router can currently buy the token from an anchor. | | can\_sell | Whether the router can currently sell the token into an anchor. | | liquidity\_usd | Known aggregate liquidity, when available. | ## Search for one token Use the search endpoint when you need to check a specific token without loading the full supported-token universe: ```http theme={null} GET /tokens/search?query=&limit=1 ``` ```bash theme={null} curl -sS \ 'https://rialto-trade-api.rialto.xyz/tokens/search?query=&limit=1' ``` Example response: ```json theme={null} { "chain_id": 4663, "tokens": [ { "name": "Wrapped Ether", "symbol": "WETH", "address": "0x0bd7d308f8e1639fab988df18a8011f41eacad73", "decimals": 18, "source": "whitelist", "type": "non_stable", "category": "crypto", "liquid": true, "can_buy": true, "can_sell": true, "liquidity_usd": "" } ] } ``` Cache search results by chain and lowercase token address. This makes the lookup an on-demand operation on the first request for an address, rather than an API call before every quote. | Result | Recommended cache duration | | ----------------- | -------------------------- | | Supported token | 5 to 15 minutes | | Unsupported token | 30 to 60 minutes | Refresh the cached result after an unexpected quote rejection, even if its normal cache duration has not elapsed. ## Full supported-token universe Use the full snapshot when a shared service wants to maintain a local set of all supported addresses: ```http theme={null} GET /tokens/quote-supported?chain_id=4663 ``` ```bash theme={null} curl --compressed \ 'https://rialto-trade-api.rialto.xyz/tokens/quote-supported?chain_id=4663' ``` The response is gzip-compressed. Keep one shared cache per chain instead of downloading and parsing the full universe for every request or worker. See [Complete Supported Tokens Universe](/developers/partner-supported-tokens) for snapshot refresh and caching guidance. ## Using tokens in quotes `GET /quote` accepts canonical `0x`-prefixed token addresses only. Pass the `address` returned by either endpoint. Symbols such as `WETH` or `USDG` are not accepted because symbols are not unique. # Quote API Overview Source: https://docs.rialto.xyz/developers/swap-api-overview Use Rialto as an execution venue: request a quote, then submit the transaction it returns. ## What the API does The Quote API turns an order into an executable transaction. You request a quote for a sell token, buy token, and amount, and Rialto returns the best route, the expected output, the fee breakdown, and a ready-to-send transaction for the RialtoRouter contract. The integration boundary is intentionally small: call the quote endpoint, then submit the returned transaction. You never build route calldata, pool calls, fee logic, slippage math, Permit2 witnesses, or settlement actions yourself. Rialto publishes Router Registry contracts so partners can discover the active Rialto router instead of hardcoding router addresses. See [Router Registries](/developers/router-registries). ## Base URL ```text theme={null} https://rialto-trade-api.rialto.xyz ``` Protected endpoints require an API key, passed as a bearer token: ```http theme={null} Authorization: Bearer ``` See [Authentication and API Keys](/developers/authentication) for how to obtain and scope a key. ## Execution flows Rialto supports two execution flows. Each quote tells you which settlement mode applies; choose your handling from the response rather than assuming. * Taker-submitted. The user's wallet submits the onchain transaction and pays gas. Use this for native-token sells and for any flow where the taker broadcasts. * Gasless relayer. The user signs a Permit2 message and Rialto broadcasts the transaction and pays gas. Available for ERC20 sells. ## Quickstart 1. Call the tokens endpoint to discover supported tokens. 2. Call the quote endpoint with the sell token, buy token, amount, taker, and slippage. 3. Inspect the quote's issues for balance and allowance blockers. Ask the user to approve if issues.allowance is present. 4. If the quote includes a Permit2 payload, have the taker sign the returned EIP-712 message and insert the signature into tx.data at tx.signature\_offset. 5. Submit the returned transaction from the taker wallet, or for gasless, submit the signature to /gasless/submit and poll /gasless/status/. The pages that follow detail authentication, the tokens and quote endpoints, settlement modes, executing a quote, the gasless flow, integrator onboarding, fees, and errors. ## Reference Full API reference: [https://github.com/rialto-plds/rialto-api-docs/blob/main/RIALTO\_SWAP\_API.md](https://github.com/rialto-plds/rialto-api-docs/blob/main/RIALTO_SWAP_API.md) # Introduction Source: https://docs.rialto.xyz/index Rialto is an onchain spot exchange to trade crypto, equities, ETFs, and commodities with best-execution routing. ## Overview Rialto is an onchain spot exchange to trade crypto, equities, ETFs, and commodities. Your orders are routed to the best available execution across the sources Rialto supports. Rialto's defining liquidity source are propAMMs: onchain market makers that quote a price from their own pricing logic and inventory, rather than from a passive constant-product pool. Rialto quotes every candidate source onchain at request time, ranks routes by output net of gas, and settles the winning route. propAMMs compete alongside conventional DEX pools on every quote, so you get the best price without choosing a venue yourself. ## Core Functionality * Trade a broad range of assets. Buy and sell crypto, equities, ETFs, and commodities from one place. * Get the best available price automatically. Rialto compares every supported source on each order and routes to the best execution, so you do not have to compare venues yourself. * Trade onchain from your own wallet. Settlement happens onchain and you trade directly from your wallet. Rialto never takes custody of your funds. * Pay for gas your way. Submit a trade yourself, or use the gasless option where you sign the order and the network fee is handled for you. # Architecture at a Glance Source: https://docs.rialto.xyz/overview/architecture The main components of Rialto and how an order flows through them. ## Components **Liquidity sources:** propAMMs and conventional DEX pools that quote and fill orders. Each propAMM is operated independently and prices from its own logic and inventory. **Routing engine:** The layer that quotes every candidate source onchain for a given order, ranks the results by output net of gas, and selects the route. **Settlement contract:** The onchain contract that executes the selected route atomically and verifies that the output meets the order's minimum. **Quote API:** The integration surface that returns firm quotes and ready-to-send transactions to wallets, frontends, and other routers. ## Order flow 1. An order is submitted through the Quote API. 2. The routing engine quotes all supported sources against live onchain state. 3. Quotes are ranked by output net of network costs and a route is selected. 4. The settlement contract executes the route onchain in a single transaction and enforces the minimum output. ## Where Rialto sits Rialto operates between the application a user trades through and the underlying liquidity. Applications integrate the Quote API for execution, including rialto.xyz; liquidity sources integrate as quoting and settlement venues. Routing and settlement remain onchain across both sides. # Best Execution and the Aggregator Source: https://docs.rialto.xyz/overview/best-execution Why propAMMs compete on price, and how aggregators turn fragmented quotes into one best price. ## Competition on price, not access propAMMs compete for flow in close to perfect competition. Aggregators route each order to whoever shows the best price, with no relationship or negotiation to fall back on, so a maker that quotes wide loses the flow instantly. The only thing standing between a market maker and the flow is the quality of their code and the tightness of their price. Nothing like this exists on centralized venues, where the right to provide liquidity is gated and intermediaries extract rent at each step. ## The role of the aggregator A propAMM only competes if its quotes can be discovered. Aggregators turn fragmented propAMM quotes into a single best bid and offer, routing each order to whoever shows the best price and splitting a single order across several propAMMs to hit each one's top-of-book liquidity. The effect mirrors what Reg NMS built for US equities with the National Best Bid and Offer, but achieved through routing rather than mandate. # FAQ Source: https://docs.rialto.xyz/overview/faq Common questions about trading on Rialto. ## What is Rialto? An onchain spot exchange for trading crypto, equities, ETFs, and commodities. Orders are routed to the best available execution across the liquidity sources Rialto supports. ## What can I trade? Crypto, equities, ETFs, and commodities, subject to the assets supported on each chain. To see what is available now, visit app.rialto.xyz/trade. ## Do I need to choose a liquidity source? No. Rialto quotes every supported source for your order and routes to the best result automatically. You do not need to know which source filled your trade. ## How does Rialto get me a good price? Each order is quoted onchain against all sources at request time and routed to the one with the best output net of network costs. propAMM sources update their quotes continuously, which generally produces competitive pricing on liquid markets. ## Does Rialto hold my funds? No. Trades settle onchain and execute directly from your wallet. Rialto does not take custody of your assets. ## Why did my quote change or expire? Quotes reflect live market conditions and are valid only for a short window. If the quote ages, it is requoted before you trade so you always act on current terms. ## What is gasless trading? An execution option where you sign your order and a relayer broadcasts the transaction and covers the network fee, where available. ## Are there fees? Any applicable fees are shown in your quote before you confirm, so you see the expected output and costs up front. # Key Concepts and Glossary Source: https://docs.rialto.xyz/overview/glossary Definitions of the core terms used throughout the Rialto documentation. ## Glossary | Term | Definition | | ----------------- | ------------------------------------------------------------------------------------------------------------------------ | | propAMM | An onchain market maker that prices trades from its own logic and inventory and updates its quotes continuously. | | Active liquidity | Liquidity whose price is refreshed continuously by an operator, independent of trade activity. | | Passive liquidity | Liquidity that prices from a fixed formula and only moves as the pool is traded against, such as a constant-product DEX. | | Liquidity source | Any venue Rialto can quote and settle against, including propAMMs and conventional DEX pools. | | Quote | A live price for a specific order size, returned at request time and valid for a brief window. | | Route | The source or set of sources selected to fill an order. | | Leg | A single source's portion of a route when an order is split across more than one source. | | Best execution | Selecting the route that returns the most output net of network costs. | | Slippage | The difference between the quoted output and the minimum output an order will accept before it reverts. | | Reference price | The external price a propAMM anchors its quotes to. | | Inventory | The reserves a propAMM holds and fills trades from. | | Settlement | The onchain execution of a selected route in a single atomic transaction. | | Taker | The party submitting an order to be filled. | | Gasless execution | An execution option where the user signs the order and a relayer broadcasts the transaction and pays the network fee. | | Integrator | A wallet, frontend, or other application that routes orders through Rialto. | # How propAMMs Quote Source: https://docs.rialto.xyz/overview/how-propamms-quote The pricing logic a propAMM runs through on every swap. ## A single liquidity surface When a user swaps, a propAMM prices the trade from a small set of parameters rather than a stack of resting limit orders. A simplified version of the logic runs through four steps. ## Fair value The latest oracle update gives the contract the current fair value for the pair, from which it prices the best bid and best ask. This refreshes every block, and more than once per block when the price moves enough. ## Inventory-aware skew A maker holds inventory in both the base and quote asset and generally wants the two balanced. The price for a given swap skews based on how far current vault reserves sit from target. If the vault is heavy in the inbound token, the price worsens for the taker, which encourages rebalancing flow. ## Freshness The goal is a new oracle update every block, but transactions occasionally fail to confirm. To limit damage from toxic flow exploiting a stale price, the propAMM penalizes its own quotes as the oracle ages, widening the spread in proportion to how many blocks have passed since the last update. ## Liquidity profile Around the fair value sits a bid and ask spread, with increasing depth as quotes move further from mid, producing a familiar order book depth profile. The entire profile is reconstructed deterministically from a small parameter set, so a single oracle update repositions the whole curve in one transaction. A propAMM can express any depth curve; this is just the most common design. # How Rialto Works Source: https://docs.rialto.xyz/overview/how-rialto-works How Rialto quotes every source onchain and routes each order to best execution. ## Overview Rialto routes each order to the best available execution across its supported liquidity sources. Quoting, routing, and settlement all occur onchain in a single transaction. ## Execution lifecycle 1. **Quote:** Rialto requests a live price for the exact order size from every candidate source, including propAMMs and conventional DEX pools. 2. **Rank:** Quotes are compared by output net of network costs. 3. **Settle:** The selected route executes onchain atomically. The order either fills in full at the agreed terms or reverts. ## Onchain quoting Sources are quoted at request time against live onchain state, not cached prices. Each source is sampled for the specific order, so the comparison reflects executable terms. A single order may be split across multiple sources when doing so improves the net result. ## Pricing and quote validity propAMM sources refresh their quotes continuously from their own reference prices, so routing reflects current market conditions. Quotes are therefore short-lived and represent executable terms only for a brief window, after which an order must be requoted. ## Rialto as a liquidity source Rialto also operates its own propAMM, Rivo Altus, which competes as one of the sources quoted on each order. Rivo Altus quotes Stock Tokens and crypto. Like any other source, it only wins a route when it returns the best execution for that order. # Key Benefits Source: https://docs.rialto.xyz/overview/key-benefits Why trading through Rialto delivers competitive pricing with onchain settlement. ## Best execution by default Every order is quoted against all supported sources and routed to the one with the best output net of costs. Users receive competitive pricing without selecting or comparing venues. ## Competitive pricing from active liquidity propAMM sources update quotes continuously and concentrate liquidity around live reference prices. On liquid markets this generally produces tighter pricing than passive pools. ## Broad asset coverage A single venue for trading crypto, equities, ETFs, and commodities, subject to the assets supported on each chain. ## Onchain settlement and self-custody Trades settle onchain and execute directly from the user's wallet. Rialto does not take custody of funds. Each order either settles in full at the agreed terms or reverts. ## Flexible execution Orders can be submitted directly from the user's wallet or, where available, executed gasless by signing the order while the network fee is handled by the relayer. # Programmable Liquidity Source: https://docs.rialto.xyz/overview/programmable-liquidity How onchain market making logic defends against toxic flow and quotes tighter than an order book. ## Liquidity is a function of adverse selection The more toxic flow a market maker faces from sophisticated takers picking off stale quotes during price moves, the wider their spreads must be and the less size they can show. On a price-time priority order book this becomes a latency race: when the reference price moves, makers must cancel stale quotes and repost before a faster trader snipes them. The industry has spent enormous sums on fiber, microwave networks, FPGAs, and colocation chasing that edge. ## Logic inside the exchange A propAMM places the market making logic onchain, inside the exchange's execution environment itself. The quote is no longer a static object posted in advance; it is a function evaluated at the moment of the trade. Book construction, fees, inventory management, and defensive controls all react within the same transaction as the fill. This makes in-block defense possible. After a fill, the program can deplete the levels just hit, widen its offsets, or withhold depth before the next trade in the same block executes. The book defends itself as flow arrives, rather than waiting for the maker to observe the fill and resubmit from outside. The result is that makers can quote tighter spreads and deeper books than they otherwise safely could. ## Built-in protection from toxic flow Because the maker's logic is the matching logic, a propAMM has defenses no order book can offer: * Venue scoring. The program scores the routing path an order arrives through by the historical quality of its flow, showing clean retail routes the full book and giving adverse paths wider offsets or less depth. * Priority-fee analysis. Since oracle updates and swaps compete in the same fee market, a taker paying aggressively to land ahead of the next update is more likely picking off a stale quote, and can be priced or filtered accordingly. * Known counterparties. Operators can decline to quote for known snipers and toxic addresses. * Freshness. As the oracle ages, the program widens spreads and withholds depth until the next update lands. * Inventory. When reserves drift from target, the program skews quotes to attract rebalancing flow and penalizes trades that push inventory further out of line. By competing on pricing models, inventory management, and defensive logic rather than on latency and infrastructure spend, a small team can outcompete incumbents. # What is a propAMM Source: https://docs.rialto.xyz/overview/what-is-a-propamm PropAMMs provide active, professionally managed liquidity to provide competitive pricing. ## Active liquidity, not passive pools A propAMM is an onchain market maker that prices trades using its own logic and its own inventory. This is a different model from the AMMs most people know. A traditional AMM, such as a constant-product or concentrated-liquidity DEX, holds liquidity that crowdsourced providers deposit, and prices trades with a fixed mathematical formula. That liquidity is passive: the price only moves as the pool is traded against, and it sits where it was last placed until someone consumes it. propAMMs provide active liquidity instead. Their prices are updated continuously, independent of whether anyone is trading, so quotes track the live market rather than lagging it. Because a professional operator manages pricing and inventory directly, propAMMs can quote tighter and use their capital more efficiently than a passive pool. ## Two parts: pricing and execution A propAMM is a two-part system. An offchain pricing engine continuously estimates the pair's fair value, usually from the most liquid venue for that asset, for example a major exchange's order book for crypto or, for Stock Tokens, the primary listing exchange of the underlying equity. An onchain execution program then turns that view into executable liquidity, handling book construction, fees, and inventory management. Common pricing inputs include oracle providers, centralized-exchange order books, and the primary listing exchange for a tokenized equity or fund. The propAMM does not rely on the pool's last trade as its only price signal. ## The oracle update A passive AMM only reprices when a trade shifts its pool balance, so price discovery is outsourced to arbitrageurs. A propAMM instead reprices through a low-latency oracle update that publishes the operator's fair value estimate directly onchain. No user trade is needed for the price to move; it tracks the maker's continuously updated view of the market. Updates are pushed on a fixed cadence, often every 100ms, with an immediate update whenever fair value drifts beyond a configurable threshold. Each update is a compact payload carrying only the new fair value and any strategy parameters. The program rebuilds the full liquidity profile from current vault balances and stored configuration, which keeps updates small and cheap to submit. ## Oracle risk mitigation propAMMs mitigate oracle risk by making quote freshness part of the pricing logic. If an oracle update is delayed, the program can widen spreads, withhold depth, or stop quoting until a fresh update lands. Operators can also compare multiple pricing inputs offchain before publishing a value and push an immediate update when the market moves beyond a configured threshold. ## What this means for you * Tighter pricing. Active, continuously updated quotes generally mean better prices than passive pools, especially on liquid pairs. * Reliable fills on supported assets. propAMMs focus on liquid, well-established markets where they can quote with confidence. * No action required on your part. You do not need to know which propAMM you traded against. Rialto compares them all and routes your order to the best result automatically. ## Where propAMMs fit propAMMs do not replace traditional DEXs, they complement them. Conventional pools still serve the long tail of assets and community-provided liquidity, while propAMMs compete to offer the sharpest pricing on the most liquid markets. Rialto draws on both, so each order takes whichever source gives the best execution. # After the Trade Source: https://docs.rialto.xyz/users/after-the-trade How to confirm a trade settled and where to review the details. ## Confirmation Once the transaction is included onchain, your trade is settled and your wallet balances update to reflect the assets received. A direct trade confirms when the transaction you submitted is mined. A gasless trade confirms once the relayer's transaction is mined. ## Transaction details Each settled trade has an onchain transaction hash. You can use it to review the trade on the chain's block explorer, where you can see the assets exchanged, the amounts, the fees paid, and the final status. ## If a trade does not settle A trade that reverts does not change your balances apart from any network fee already spent on a submitted transaction. This usually means the quote moved outside your slippage tolerance before it settled. Request a fresh quote and try again. The next page covers common issues in more detail. # FAQ Source: https://docs.rialto.xyz/users/faq Common questions about trading on Rialto. ## What do I need to start? An EVM-compatible wallet, the asset you want to sell, and enough of the chain's native token for the network fee. Gasless trading removes the need to hold the native token for gas. ## How do I connect? Go to app.rialto.xyz and connect your wallet. Connecting does not move funds or grant access to your assets; you authorize each trade individually. ## What assets can I trade? Crypto, equities, ETFs, and commodities, subject to the assets supported on each chain. To see what is available now, visit app.rialto.xyz/trade. ## How is slippage set? Slippage defaults to 0.5% and can be changed in Settings at the top right of the order form. It sets the minimum you will receive before a trade reverts. ## What fees do I pay? Rialto's standard fee is 0.05%, plus an integrator fee if the app you trade through adds one, both already included in your quoted output. You also pay the network fee unless you trade gasless, in which case the relayer covers it. ## Why did my trade revert? Usually the price moved outside your slippage tolerance before settling. Request a fresh quote and try again. ## Does Rialto hold my funds? No. Trades settle onchain and execute from your wallet. Rialto does not take custody of your assets. # Fees Source: https://docs.rialto.xyz/users/fees The fees that apply to a Rialto trade and when each one is charged. ## Fees shown before you confirm Every quote reflects the fees that apply to your trade, so the expected output you see is what you receive after fees. You can review them before confirming. ## Types of fee * Trading fee. A fee applied to the swap. Rialto's fee is 0.05%. Where the app you are trading through adds one, an integrator fee may also apply on top. Both are already included in your quoted output. * Network fee. The onchain gas cost to settle the transaction. You pay this when you submit the trade from your wallet. With gasless trading, the relayer covers the network fee instead. ## When fees are charged Fees are taken as part of the swap, in the same onchain transaction that settles your trade. There is no separate billing or claim step. If a trade reverts, it does not complete, so no trading fee is charged, though any gas already spent on a submitted transaction is not recoverable. # Gasless Trading Source: https://docs.rialto.xyz/users/gasless-trading Trade without holding the native gas token by signing your order with Permit2. ## What gasless trading is Gasless trading lets you trade without paying the network fee yourself. Instead of submitting the transaction from your wallet, you sign your order and a relayer broadcasts it and covers the gas. You still authorize the exact trade; only the broadcasting and the fee are handled for you. Enable it under Gasless swap in Settings, at the top right of the order form. ## How it works 1. You request a quote as normal. 2. You sign the order with Permit2 in your wallet. This is a signature, not a transaction, so it costs no gas. 3. The relayer broadcasts the transaction and pays the network fee. 4. The trade settles onchain and your balances update on confirmation. The signature authorizes one specific trade, including the asset, amount, recipient, and minimum output. It cannot be reused for anything else. ## What to know * Token approval may still be required. The first time you trade a given token, you may need a one-time onchain approval before signing. That approval step is not gasless, but the trade itself is. * Available for token sales. Gasless applies to ERC20 token sales. Selling the native token directly is done through a standard wallet transaction. * You keep custody. As with any Rialto trade, funds move only as your signed order specifies, and settlement is onchain. # Getting Started Source: https://docs.rialto.xyz/users/getting-started What you need to begin trading on Rialto and how to connect your wallet. ## Before you start To trade on Rialto you need an EVM-compatible wallet, the asset you want to sell, and enough of the chain's native token to cover the network fee. Gasless execution, where available, removes the need to hold the native token for gas. Rialto trades settle onchain from your own wallet, so you keep custody of your funds throughout. ## Connect your wallet 1. Go to app.rialto.xyz. 2. Connect your wallet and approve the connection request in your wallet. 3. Confirm your wallet is set to a supported network. Connecting a wallet does not move any funds or grant access to your assets. You authorize each trade individually. ## Place your first trade 1. Select the asset you want to sell and the asset you want to buy. 2. Enter the amount. Rialto returns a live quote showing the expected output and any fees. 3. Review the quote, then confirm. Approve the transaction or signature in your wallet. 4. The trade settles onchain and your balances update on confirmation. The next pages cover how quotes and pricing work, how to set slippage, and what to do if a trade does not go through. # How Your Order Is Routed Source: https://docs.rialto.xyz/users/how-your-order-is-routed How Rialto selects the best execution for your order. ## Best execution, automatically When you place an order, Rialto requests a live price for your exact size from every supported liquidity source, compares them by how much you receive after network costs, and routes your order to the best result. This happens on every order. ## You do not choose a source There is no venue to select and no routing setting to configure. Rialto selects the source for you, drawing on its own propAMM, third-party propAMMs, and conventional DEX pools. ## Orders can be split When splitting an order across more than one source produces a better overall result, Rialto does that automatically. You still see a single trade with one outcome. # Making a Swap Source: https://docs.rialto.xyz/users/making-a-swap A step-by-step walkthrough of placing, reviewing, and confirming a trade on Rialto. ## Build your order Select the asset to sell and the asset to buy, then enter the amount. Rialto returns a live quote for that exact size, showing the expected output, the minimum you will receive after slippage, and any fees. ## Review the quote Before confirming, check: * Expected output. The amount you receive at the current quote. * Minimum received. The least you will accept; the trade reverts below this. * Fees. Any applicable fees, already reflected in the quote. Quotes are valid only briefly. If the quote ages before you confirm, it is refreshed so you act on current terms. ## Check your settings Before confirming, open Settings from the button at the top right of the order form and confirm: * Slippage. The maximum price movement you will accept, set to 0.5% by default. You can choose a preset or enter a custom value. This sets the minimum received on your order. * Gasless swap. When enabled, you sign the order with Permit2 and a relayer broadcasts the transaction and pays the network gas. When off, you submit the transaction from your wallet and pay gas yourself. * Show Token Value in USD. Displays the USD value of the assets in your order. ## Approve, then confirm Depending on the asset and execution method, your wallet will prompt you to either sign or approve: * Token approval. The first time you sell a given token, you may need a one-time approval so the trade can move that token. This is a standard onchain step. * Order signature or transaction. You then either sign the order, for gasless execution, or submit the transaction directly from your wallet. Confirm the prompt in your wallet to execute the trade. ## Settlement The selected route settles onchain in a single transaction. The order either fills in full at the agreed terms or reverts, and your balances update on confirmation. If it reverts, your funds stay in your wallet apart from any network fee already spent. # Understanding Quotes and Pricing Source: https://docs.rialto.xyz/users/quotes-and-pricing How Rialto determines your price and how to read the parts of a quote. ## How your price is determined When you enter an order, Rialto requests a live price for that exact size from every supported source and routes to the one that returns the most output after network costs. The quote you see is the result of that comparison, not a single venue's standing price. Because propAMM sources update their quotes continuously, the price reflects current market conditions at the moment you request it. ## Reading the quote A quote shows: * Expected output. The amount you receive if the trade settles at the current quoted price. * Minimum received. The least you will accept, derived from your slippage setting. The trade reverts if it cannot deliver at least this amount. * Rate. The effective exchange rate between the two assets for this order. * Fees. Any applicable fees, already reflected in the expected output. ## Quote validity Quotes are valid only for a short window because the underlying prices move quickly. If a quote ages before you confirm, Rialto refreshes it so you always act on current terms. # Referrals Source: https://docs.rialto.xyz/users/referrals Earn rewards by inviting others and give them a discount on fees. # Referrals Invite new users with your referral code to earn rewards when they pay eligible fees. Referred users also receive a discount on their own fees. ## Overview The referral program has two participants: * **Referrer**: the user who shares a referral code. * **Referee**: the user who signs up or connects through that referral code. Rewards and discounts are tied to the referral relationship between the referrer and referee. ## Unlock referrals This reward is based on the fees paid by referred users after they start using the product. ## Rewards and discounts ### Referrer reward Referrers earn **10% of the eligible fees** generated by their referees. ### Referee discount Referees receive **10% off eligible fees**. The discount applies to fees charged to the referred user. ## Important notes * Referral rewards and discounts only apply to eligible fees. * Rewards and discounts only apply after the referral relationship has been created. # Slippage and Settings Source: https://docs.rialto.xyz/users/slippage-and-settings How to set slippage tolerance and configure your trade settings on Rialto. ## What slippage is Slippage is the maximum price movement you will accept between requesting a quote and the trade settling. It sets the minimum amount you will receive. If the market moves beyond your tolerance and the trade cannot deliver at least that minimum, it reverts rather than filling at a worse price. ## Setting slippage Open Settings from the button at the top right of the order form. Slippage is set to 0.5% by default. You can select a preset or enter a custom value. Choosing a value is a tradeoff: * Lower slippage protects you from unfavorable price movement but makes a trade more likely to revert if the market moves. * Higher slippage makes a trade more likely to fill but allows a wider range between the quoted and received amounts. ## Other settings * Gasless swap. Sign your order with Permit2 and have a relayer broadcast the transaction and pay the network gas. See the next page for how this works. * Show Token Value in USD. Display the USD value of the assets in your order. # Troubleshooting Source: https://docs.rialto.xyz/users/troubleshooting Common issues when trading on Rialto and how to resolve them. ## Trade reverted The most common cause is the price moving outside your slippage tolerance before the trade settled. Request a fresh quote and try again. If it keeps happening in fast-moving conditions, a slightly higher slippage tolerance can help. ## Insufficient balance Your wallet does not hold enough of the asset you are trying to sell. Reduce the order size or top up the balance. ## Approval required The first time you sell a given token, you may need a one-time onchain approval before the trade can proceed. Approve the prompt in your wallet, then continue. ## Not enough gas A direct trade needs enough of the chain's native token to cover the network fee. Add native token to your wallet, or use gasless trading where available so the relayer covers the fee. ## Quote expired Quotes are valid only briefly. If a quote ages before you confirm, it is refreshed automatically. Confirm against the current quote. ## Wrong network Your wallet must be set to a network Rialto supports. Switch your wallet to the correct network and reconnect if needed.