0x Documentation
Search…
⌃K
🤔

FAQs & Troubleshooting

Categories

🧰 Troubleshooting

If your 0x quote is reverting, besides the standard revert issues related to ETH transactions, we recommend check the following are set correctly:
  • Are allowances properly set for the user to trade the sellToken?
  • Does the user have enough sellToken balance to execute the swap?
  • Do users have enough to pay the gas?
  • The slippage tolerance may be too low if the liquidity is very shallow for the token the user is trying to swap. Read here for how to handle this.
  • Fee-on-transfer tokens may wreak havoc on our contracts. Read here for how to handle this
For more details on addressing common issues, read Troubleshooting 0x API Swaps.
By passing a takerAddress parameter, 0x API can provide a more bespoke quote and help catch revert issues:
  • 0x API will estimate the gas cost for takerAddress to execute the provided quote.
  • If successfully called, the gas parameter in the quote will be an accurate amount of gas needed to execute the swap.
  • If unsuccessful for revert reasons suggested above, then 0x API will throw a gas cost estimation error, alluding to an issue with the takerAddress executing the quote.
TLDR Pass takerAddress to get the quote validated before provided to you, assuring that a number of revert cases will not occur.
0x API selects the best 0x protocol interface to interact with based on the provided parameters and the smart order routing logic.
There are two main interfaces that 0x API will provide quotes for:
Exchange contract - the main entry-point of the 0x protocol, all swap quotes are settled by the exchange contract.
Forwarder extension contract - a payable interface allowing swaps between native ETH (as a sellToken) and another ERC20 asset.
Find the currently deployed contracts here.
Developers may note when analyzing their transactions that some subset of 0x orders may revert (not filled) but the whole transaction is successful. This is expected behavior as implied earlier, some orders due to timing, and the pricing may be filled or expired before a users attempt to fill the order. This would result in a revert and 0x protocol will utilize fallback orders to compensate for the reverted order. This will result in a successful transaction even though reverts occur within the transactions.

🔄 0x API Swap

📜 About 0x API

No, the 0x API is free to use and is intended for public use. If you are an integrator who needs access higher rate limits, please fill out 0x API Taker Integration Request Form to apply for a custom enterprise API endpoint.
Beyond simply sampling each liquidity source for their respective prices, 0x API adjusts for the gas consumption of each liquidity source with the specified gas price (if none provided 0x API will use ethGasStation's fast amount of gwei) and any associated fees with the specific liquidity source. By sampling through varying compositions of liquidity sources, 0x API selects the best set of orders to give you the best price. 0x API also creates another set of fallback orders to ensure that the quote can be executed by users.
Ex: 0x API will adjust the price potentially received from Curve Finance by gas * gasPrice and its fees. Because of Curve Finance’s costly gas consumption, its nominal price may not be the best price when settled.
Use the API endpoint /swap/v1/sources to get the liquidity sources per chain. You will need to specify the root-endpoint for the chain you are interested in, for example, https://polygon.api.0x.org/swap/v1/sources for the Polygon Network or https://api.0x.org/swap/v1/sources for Ethereum Mainnet. See the 0x API SwapIntroductionfor a full list of endpoints we support.
  • If sellToken is utilized, then any unused sellToken will be refunded to the user.
  • When buyAmount is used, the only guarantee is that at least the amount specified is bought. 0xAPI will not terminate early in the case where one order fills at a better price, so the user can in effect over buy the specified amount. This is somewhat amplified by usage of slippagePercentage which underestimates the on-chain price by a percentage.
Also, some liquidity sources do not enable querying by buyAmount (i.e Kyber), these sources are ignored when quoting for buyAmounts
TLDR Whenever possible, use sellAmount over buyAmount to get more deterministic behavior.
The current 0x API logic for selecting between forwarder or exchange is deterministic and enable developers to easily ensure which interface is used for a quote:
  • If sellToken is not set to ETH (say WETH), 0x API will always provide a quote that interfaces with the main exchange contract.
  • If sellToken is set to ETH, 0x API will always provide a quote that interfaces with forwarder contract.
TLDR sellToken=ETH uses Forwarder, sellToken=WETH uses Exchange.
Slippage Protection is a feature of the 0x API that finds the best routes for decentralized exchange (DEX) trades while avoiding slippage and MEV attacks.
Slippage Protection incorporates slippage forecasts into 0x API’s smart order routing algorithm to deliver the optimal trade route. With Slippage Protection activated, 0x API will enable developers to surface more reliable quotes and consistently deliver the best executed price to users. Slippage Protection is currently supported on Ethereum for the most active trading pairs (ETH-USDC, ETH-DAI, ETH-USDT, ETH-WBTC, WETH-USDC, WETH-DAI, WETH-USDT, WETH-WBTC)
Slippage Protection is an auto-enabled feature of the 0x API, and no additional action is required to enable to implement it in your API request. Read here for the full details of Slippage Protection.
In cases of positive slippage (i.e. when the quoted price is more than the executed price) the 0x protocol returns that difference back to the user.
If you would like to trade a custom token, you will need to create the liquidity either by using 0x limit orders or by creating a Liquidity Pool for your token on one of the various AMM sources that the API sources from, such as Uniswap, SushiSwap, or Curve. Learn more about creating limit order: https://docs.0x.org/protocol/docs/exchange-proxy/features/nativeorders#limit-orders

💻 Parameter Questions

0x API selects the best 0x protocol interface to interact with based on the provided parameters and the smart order routing logic.
There are two main interfaces that 0x API will provide quotes for:
Exchange contract - the main entry-point of the 0x protocol, all swap quotes are settled by the exchange contract.
Forwarder extension contract - a payable interface allowing swaps between native ETH (as a sellToken) and another ERC20 asset.
Find the currently deployed contracts here.
The price field provides developers a sense of what the BEST price they could receive, denominated in sellToken for one buyToken. The gauranteedPrice is the price that developers can expect in a WORST case scenario where all the fallback orders are utilized over the better priced orders.
Say you found a swap for ETH to DAI at 220 DAI while the market price for ETH is 200 DAI. Obviously this is a great price and will not last forever, a “race” of sorts occurs as users compete to settle the swap of ETH for 220 DAI by selecting a competitive gasPrice that would result in their transaction being mined over others.
When such a race happens, only one user gets to receive the swap of ETH for 220 DAI, the other users will see their transactions revert.
To ensure that users will always have their swap executed within a reasonable price, 0x API quoting logic provides a set of fallback orders, created with on-chain sources (kyber, uniswap, PLP, curve) that will be filled at a slightly worse rate if the more aggressively priced orders expires or are filled by somebody else.
TLDR expect the actual settled price of a 0x quote to be somewhere between price and gauranteedPrice.
  • If sellToken is utilized, then any unused sellToken will be refunded to the user.
  • When buyAmount is used, the only guarantee is that at least the amount specified is bought. 0xAPI will not terminate early in the case where one order fills at a better price, so the user can in effect over buy the specified amount. This is somewhat amplified by usage of slippagePercentage which underestimates the on-chain price by a percentage.
Also, some liquidity sources do not enable querying by buyAmount (i.e Kyber), these sources are ignored when quoting for buyAmounts
TLDR Whenever possible, use sellAmount over buyAmount to get more deterministic behavior.
Developers can influence how much “worse” the guaranteedPrice is through the slippagePercentage parameter. With on-chain sources, prices can vary between the quote being made and settlement. The slippagePercentage provides a "upper bound" to how much the price provided by these on-chain sources can slip and remain desirable by the developer.
TLDR slippagePercentage controls how much worse the price can be for the fallback orders provided in a 0x API quote which influences the guaranteedPrice.
  • If sellToken is utilized, then any unused sellToken will be refunded to the user.
  • When buyAmount is used, the only guarantee is that at least the amount specified is bought. 0xAPI will not terminate early in the case where one order fills at a better price, so the user can in effect over buy the specified amount. This is somewhat amplified by usage of slippagePercentage which underestimates the on-chain price by a percentage.
Also, some liquidity sources do not enable querying by buyAmount (i.e Kyber), these sources are ignored when quoting for buyAmounts
TLDR Whenever possible, use sellAmount over buyAmount to get more deterministic behavior.
Read our full blog post on Price Impact Protection and how to use it in the Swap API.
What is price impact? Price impact is the influence that a user’s trade has over the market price of an underlying trading pair. It is directly related to the amount of liquidity in the pool. Price impact can be particularly high for illiquid trading pairs and in certain instances can cause significant losses for traders.
This is different from price slippage, although the terms are often mistakenly used interchangeably. Price slippage refers to the difference between the executed price and the quoted price, caused by external market movements unrelated to your trade. What is our solution? We launched Price Impact Protection to make it easier to protect users from getting rekt by illiquid markets. Despite Swap API enabling access to the deepest liquidity from over 70+ exchanges, there are still some long-tailed token pairs that suffer from suboptimal liquidity on decentralized exchanges.
When we are able to calculate price impact estimates, users leveraging the Swap API will be notified when their trade faces a price impact over a certain threshold. The API will return an error of insufficient liquidity due to the price impact being higher than the defined limit. The threshold is easily customizable by setting PriceImpactProtectionPercentage anywhere from 0-1, so we encourage every Swap API user to customize this parameter based on their needs and tolerance.
Price Impact Protection is an optional feature - the default threshold will be set at 1. Developers and API users who want to take advantage of it will need to opt-in by adjusting this setting.
Developers can also surface this information in their UI so users can see the potential price impact of a trade prior to submitting an order. Developers can simply ping the Swap API [swap/v1/quote] and use the returned estimatedPriceImpact information.

🏆 Best Practices

Our rate limits exists because we want to encourage anyone using our infra to actually swap, not just use our API as a price oracle. If you would like to query for token prices, we would recommend either setting up your own 0x API instance via the repo README instructions or query a 3rd party service like coingecko.
Our rate limits exists because we want to encourage anyone using our infra to actually swap, not just use our API as a price oracle. If you would like to query for token prices, we would recommend either setting up your own 0x API instance via the repo README instructions or query a 3rd party service like coingecko.
TL;DR You have full flexibility on the fees you collect on your trades
Yes, this can be done by setting the feeRecipient and buyTokenPercentageFee parameters in a /swapAPI request. Set a buyTokenPercentageFee on your DEX trades which represents the percentage (between 0 - 1.0) of the buyAmount (tokens being received) that should be attributed to feeRecipient (your wallet) as an affiliate fee. When the transaction has gone through, the fee amount will be sent to the feeRecipient address you've set. The fee is receive in the buyToken (the token that the user will receive). If you would like to receive a specific type of token (e.g. USDC), you will need to convert those on your own. Details about these parameters can be found in GET /swap/v1/quote.
The fee amount is incorporated as part of the quoted price. If you would like to display the fee separately, just display the amount return by buyAmount * buyTokenPercentageFee
Use the API endpoint /swap/v1/sources to get the liquidity sources per chain. You will need to specify the root-endpoint for the chain you are interested in, for example, https://polygon.api.0x.org/swap/v1/sources for the Polygon Network or https://api.0x.org/swap/v1/sources for Ethereum Mainnet. See the 0x API SwapIntroductionfor a full list of endpoints we support.
All ERC20 tokens are supported with the caveat that if the token is fee-on-transfer or has some other special logic there is no way for the API to detect this and their requests may fail/transactions revert/result in some wonky swaps. We recommend referring to tokenlist.org, specifically the CoinGecko tokenlist for a list of all available ERC20 tokens.

🌐 Protocol

The community voted to remove protocol fees in ZEIP-91 which decreased the protocol fee multiplier from the current value (70,000) to zero (0) for v3 onward.
The following is kept for historical reference but no longer applies
A protocol fee was paid by takers and ultimately rebated to market makers when their orders are filled.
Protocol fees were calculated per order using the gas price multiplied by a constant (currently 70,000). 0x API calculated the required protocol fees to be paid and returns this in the value field. Since we recommended using a high gas price, in the event where the taker fills at a lower gas price, the excess was returned.
It was possible for the protocol fees to be paid in WETH rather than sent in the transaction as ETH. This could be achieved by the taker having a WETH balance and setting a WETH allowance to the Protocol fee collector address. This address can be read on the Exchange contract: Exchange.protocolFeeCollector.
TLDR 0x API handled the heavy lifting related to protocol fees and provides a value field.
Yes, 0x protocol’s contracts are open source and extensively tested by 0x core team’s internal protocol team and by external auditors (Consensys dilligence, Trail of Bits).
The Exchange contract, because they are the main entry point of the 0x protocol, is versioned, and governed by ZRX token holders. Because of its critical place in 0x infrastructure, the 0x core team employs a number of external audits to ensure the safe and intended usage of the 0x contract.
The Forwarder contract is internally audited and constantly improved upon by the 0x core team. Forwarder, an optional extension contract that users can opt in/out of using when swapping, has a minimized attack surface because no approval of user funds is needed.
0x protocol returns a FillResults object that returns the result of executing a 0x swap:
struct FillResults {
uint256 makerAssetFilledAmount; // Total amount of buyToken filled.
uint256 takerAssetFilledAmount; // Total amount of sellToken filled.
uint256 protocolFeePaid; // Total amount of protocolFee pair in WETH or ETH
...
}
On-chain, easily decode the result of executing the calldata like so:
import "@0x/contracts-exchange-libs/contracts/src/LibFillResults.sol";
...
(bool success, bytes memory data) = address(exchange).call.value(quote.protocolFee)(quote.calldataHex);
require(success, "Swap not filled");
fillResults = abi.decode(data, (LibFillResults.FillResults));

📬 Contact the 0x Team

We appreciate your interest in consuming liquidity from the 0x API. Please fill out this form for us to to learn more about application and how you use the 0x API. Our team will review and reach out to you.
Thank you for your interest in providing liquidity to the 0x ecosystem via our RFQ suite of products. Please fill out this form to help us learn more about your firm, and determine whether 0x is a good fit for you. Our team will review and reach out to you.