Integrating the 0x API into your contracts
How to automatically get the best prices via 0x
Why you want 0x in your contracts? It's simple:

Okay, but seriously. Let's see why the 0x Swap API is interesting.
What is the 0x Swap API?
Last month the 0x team released the new v1 of the API. First announced in the beginning of the year, it was introduced to provide an easy way to get the best prices for trades without having to worry too much about the trade details. It combines a number of markets which in v1 now include
This video visualizes it pretty well:
What this means for you is getting the best prices available. According to 0x (so take it with a grain of salt) the results outperform any other options out there. If you can believe 0x, the API yields very convincing swaps:

What's new in v1?
With the new API version you now get heavily gas optimized trades. In fact the gas fees can sometimes be cheaper than trading on Uniswap directly. There are also several new liquidity providers added and many more changes, see here.
Alright, you are now interested? Let's take a look on how you could add it in your contracts.
Integrating 0x into your contracts
We are going to add automatic conversion of ETH to DAI to our contracts. It's always best to learn by example, so let's try to do this for a contract. A fully working Remix example can be found at the end.
1. Adding automatic conversions
Assume we have a pay
function that users can call to interact with our contract. We want to give them the option to pay in DAI directly or they can automatically trade ETH to DAI using the 0x API.
First the function might look likt this:
function pay(uint256 amount) public payable {
require(
DAI.transferFrom(
msg.sender,
address(this),
amount
),
"DAI transfer failed"
);
// do something with that DAI
[...]
}
But now we want to add a second option for the user to pay in ETH. You can see this on the right. In the case of users sending 0 ETH (msg.value == 0
), we assume that the user wants to pay in DAI directly. Then we do a transferFrom as before and additionally require all swap related parameters to be empty.
In the case of a user wanting to trade his ETH, we call our convert function _convertEthToDai
with all the swap parameters. Let's take a look how the convert function looks like...
function pay(
uint256 paymentAmountInDai,
address spender,
address payable swapTarget,
bytes calldata swapCallData
) public payable {
if (msg.value > 0) {
_convertEthToDai(
paymentAmountInDai,
spender,
swapTarget,
swapCallData
);
} else {
require(
spender == address(0),
"EMPTY_SPENDER_WITHOUT_SWAP"
);
require(
swapTarget == address(0),
"EMPTY_TARGET_WITHOUT_SWAP"
);
require(
swapCallData.length == 0,
"EMPTY_CALLDATA_WITHOUT_SWAP"
);
require(
DAI.transferFrom(msg.sender, address(this), paymentAmountInDai),
"DAI transfer failed"
);
}
// do something with that DAI
[...]
}
2. Converting the ETH to DAI
Now we get to the heart of the logic. On a high level we do
- wrap ETH into WETH
- approve WETH for target
- execute 0x API swap
- run refunds
How you would get these parameters for the conversion, you can see in step 3. But essentially what they represent is an optimized swap contract call. swapTarget.call(swapCallData)
executes the trade which internally transfers the WETH funds from this contract to the spender address.
Once the swap is finished, we can return any leftover ETH and DAI to the trader. The DAI refund might not be required as the leftover amount in my tests was always almost non existent. But keep it when doing large scale trades to be safe.
function _convertEthToDai(
uint256 paymentAmountInDai,
address spender, // API: "allowanceTarget"
address swapTarget, // API: "to"
bytes calldata swapCallData // API: "data"
) private {
WETH.deposit{value: msg.value}();
uint256 currentDaiBalance = DAI.balanceOf(address(this));
require(
WETH.approve(spender, type(uint256).max),
"approve failed"
);
(bool success, bytes memory res) = swapTarget.call(swapCallData);
require(
success,
string(bytes('SWAP_CALL_FAILED: ').concat(bytes(res.getRevertMsg())))
);
msg.sender.transfer(address(this).balance);
uint256 boughtAmount = DAI.balanceOf(address(this)) - currentDaiBalance;
require(boughtAmount >= paymentAmountInDai, "INVALID_BUY_AMOUNT");
// may not be required?
uint256 daiRefund = boughtAmount - paymentAmountInDai;
DAI.transfer(msg.sender, daiRefund);
}
3. Retrieving the API Request Data
Now we have the swap functionality, but the user still needs to know what to send as the swap parameters. For this we add a view function that returns the 0x API Request URL. We use https://kovan.api.0x.org for our tests, for mainnet you of course would use https://api.0x.org/.
For example given we want to buy one DAI, we would pass "1000000000000000000" (1e18) to the function and we get our request url looking like this: https://kovan.api.0x.org/swap/v1/quote?sellToken=0xd0A1E359811322d97991E03f863a0C30C2cF029C&buyToken=0x1528f3fcc26d13f7079325fb78d9442607781c8c&buyAmount=1000000000000000000. You can directly open this in the browser to get the results. Obviously if you have a frontend, you can automate all of this.
Now once you click the link, all you need are three values:
- "allowanceTarget" →
address spender
- "to" →
address payable swapTarget
- "data" →
bytes calldata swapCallData
string private api0xUrl = 'https://kovan.api.0x.org/swap/v1/quote';
string private wethToDai0xApiRequest = '?sellToken=0xd0A1E359811322d97991E03f863a0C30C2cF029C&buyToken=0x1528f3fcc26d13f7079325fb78d9442607781c8c&buyAmount=';
function get0xApiRequest(uint256 paymentAmountInDai) external view returns(string memory) {
return string(bytes(api0xUrl).concat(bytes(wethToDai0xApiRequest)).concat(paymentAmountInDai.toBytes()));
}
Now once you click the link, all you need are three values:
- "allowanceTarget" →
address spender
- "to" →
address swapTarget
- "data" →
bytes calldata swapCallData
With these variables a user now has all he needs to call myContract.pay(amount, spender, swapTarget, swapCallData)
.
4. Useful Helper Functions

If you wondered about some of the functions in the code above, don't worry. We've implemented and used a few useful helper functions, namingly concat
, toStringBytes
and getRevertMsg
. Those may be quite useful to you in general, so it's worth taking a closer look.
1. Concat String Bytes
With the new abi.encodePacked function since Solidity v5, concatenating strings is particularly easy. You can use this function for strings like this: concat(bytes(myString1), bytes(myString2))
.
function concat(
bytes memory a,
bytes memory b
) internal pure returns (bytes memory) {
return abi.encodePacked(a, b);
}
2. Uint256 to String Bytes
Inspired by the Provable code here, this function computes the string
representation of a uint256
number returned as bytes
array.
Strings in Solidity are UTF-8 encoded. The value 48 implies the character '0'. So to convert a number to the correct string, we essentially compute and store 48 + remainder of modulo 10 for each digit.
function toStringBytes(
uint256 v
) internal pure returns (bytes memory) {
if (v == 0) { return "0"; }
uint256 j = v;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len - 1;
while (v != 0) {
bstr[k--] = byte(uint8(48 + v % 10));
v /= 10;
}
return bstr;
}
3. Get Revert Message for Low-level Call
Lastly we added a function to retrieve the revert message from low-level contract calls. This allows us to give more detailed information about the revert reason. Implementation was taken from Stackexchange, a website you should check out whenever you can.
function getRevertMsg(
bytes memory _returnData
) internal pure returns (string memory) {
if (_returnData.length < 68)
return 'Transaction reverted silently';
assembly {
_returnData := add(_returnData, 0x04)
}
return abi.decode(_returnData, (string));
}
Fully working example for Remix
You can find a fully working example for Remix here. To test it make sure to deploy to Kovan, retrieve the API data and then send along enough ETH for the swap (top left 'value' field).
You can also take a look at the 0x Starter Guide. It further includes a direct swap example in case you don't want to deploy your own contract.
Solidity Developer
More great blog posts from Markus Waas
How to use ChatGPT with Solidity
Using the Solidity Scholar and other GPT tips
How to integrate Uniswap 4 and create custom hooks
Let's dive into Uniswap v4's new features and integration
How to integrate Wormhole in your smart contracts
Entering a New Era of Blockchain Interoperability
Solidity Deep Dive: New Opcode 'Prevrandao'
All you need to know about the latest opcode addition
How Ethereum scales with Arbitrum Nitro and how to use it
A blockchain on a blockchain deep dive
The Ultimate Merkle Tree Guide in Solidity
Everything you need to know about Merkle trees and their future
The New Decentralized The Graph Network
What are the new features and how to use it
zkSync Guide - The future of Ethereum scaling
How the zero-knowledge tech works and how to use it
Exploring the Openzeppelin CrossChain Functionality
What is the new CrossChain support and how can you use it.
Deploying Solidity Contracts in Hedera
What is Hedera and how can you use it.
Writing ERC-20 Tests in Solidity with Foundry
Blazing fast tests, no more BigNumber.js, only Solidity
ERC-4626: Extending ERC-20 for Interest Management
How the newly finalized standard works and can help you with Defi
Advancing the NFT standard: ERC721-Permit
And how to avoid the two step approve + transferFrom with ERC721-Permit (EIP-4494)
Moonbeam: The EVM of Polkadot
Deploying and onboarding users to Moonbeam or Moonriver
Advanced MultiSwap: How to better arbitrage with Solidity
Making multiple swaps across different decentralized exchanges in a single transaction
Deploying Solidity Smart Contracts to Solana
What is Solana and how can you deploy Solidity smart contracts to it?
Smock 2: The powerful mocking tool for Hardhat
Features of smock v2 and how to use them with examples
How to deploy on Evmos: The first EVM chain on Cosmos
Deploying and onboarding users to Evmos
EIP-2535: A standard for organizing and upgrading a modular smart contract system.
Multi-Facet Proxies for full control over your upgrades
MultiSwap: How to arbitrage with Solidity
Making multiple swaps across different decentralized exchanges in a single transaction
The latest tech for scaling your contracts: Optimism
How the blockchain on a blockchain works and how to use it
Ultimate Performance: The Aurora Layer2 Network
Deploying and onboarding users to the Aurora Network powered by NEAR Protocol
What is ecrecover in Solidity?
A dive into the waters of signatures for smart contracts
How to use Binance Smart Chain in your Dapp
Deploying and onboarding users to the Binance Smart Chain (BSC)
Using the new Uniswap v3 in your contracts
What's new in Uniswap v3 and how to integrate Uniswap v3
What's coming in the London Hardfork?
Looking at all the details of the upcoming fork
Welcome to the Matrix of blockchain
How to get alerted *before* getting hacked and prevent it
The Ultimate Ethereum Mainnet Deployment Guide
All you need to know to deploy to the Ethereum mainnet
SushiSwap Explained!
Looking at the implementation details of SushiSwap
Solidity Fast Track 2: Continue Learning Solidity Fast
Continuing to learn Solidity fast with the advanced basics
What's coming in the Berlin Hardfork?
Looking at all the details of the upcoming fork
Using 1inch ChiGas tokens to reduce transaction costs
What are gas tokens and example usage for Uniswap v2
Openzeppelin Contracts v4 in Review
Taking a look at the new Openzeppelin v4 Release
EIP-3156: Creating a standard for Flash Loans
A new standard for flash loans unifying the interface + wrappers for existing ecosystems
Tornado.cash: A story of anonymity and zk-SNARKs
What is Tornado.cash, how to use it and the future
High Stakes Roulette on Ethereum
Learn by Example: Building a secure High Stakes Roulette
How to implement generalized meta transactions
We'll explore a powerful design for meta transactions based on 0x
Utilizing Bitmaps to dramatically save on Gas
A simple pattern which can save you a lot of money
Using the new Uniswap v2 as oracle in your contracts
How does the Uniswap v2 oracle function and how to integrate with it
Smock: The powerful mocking tool for Hardhat
Features of smock and how to use them with examples
How to build and use ERC-721 tokens in 2021
An intro for devs to the uniquely identifying token standard and its future
Trustless token management with Set Protocol
How to integrate token sets in your contracts
Exploring the new Solidity 0.8 Release
And how to upgrade your contracts to Solidity 0.8
How to build and use ERC-1155 tokens
An intro to the new standard for having many tokens in one
Leveraging the power of Bitcoins with RSK
Learn how RSK works and how to deploy your smart contracts to it
Solidity Fast Track: Learn Solidity Fast
'Learn X in Y minutes' this time with X = Solidity 0.7 and Y = 20
Sourcify: The future of a Decentralized Etherscan
Learn how to use the new Sourcify infrastructure today
How to build and use ERC-777 tokens
An intro to the new upgraded standard for ERC-20 tokens
COMP Governance Explained
How Compound's Decentralized Governance is working under the hood
How to prevent stuck tokens in contracts
And other use cases for the popular EIP-165
Understanding the World of Automated Smart Contract Analyzers
What are the best tools today and how can you use them?
A Long Way To Go: On Gasless Tokens and ERC20-Permit
And how to avoid the two step approve + transferFrom with ERC20-Permit (EIP-2612)!
Smart Contract Testing with Waffle 3
What are the features of Waffle and how to use them.
How to use xDai in your Dapp
Deploying and onboarding users to xDai to avoid the high gas costs
Stack Too Deep
Three words of horror
Integrating the new Chainlink contracts
How to use the new price feeder oracles
TheGraph: Fixing the Web3 data querying
Why we need TheGraph and how to use it
Adding Typescript to Truffle and Buidler
How to use TypeChain to utilize the powers of Typescript in your project
Integrating Balancer in your contracts
What is Balancer and how to use it
Navigating the pitfalls of securely interacting with ERC20 tokens
Figuring out how to securely interact might be harder than you think
Why you should automatically generate interests from user funds
How to integrate Aave and similar systems in your contracts
How to use Polygon (Matic) in your Dapp
Deploying and onboarding users to Polygon to avoid the high gas costs
Migrating from Truffle to Buidler
And why you should probably keep both.
Contract factories and clones
How to deploy contracts within contracts as easily and gas-efficient as possible
How to use IPFS in your Dapp?
Using the interplanetary file system in your frontend and contracts
Downsizing contracts to fight the contract size limit
What can you do to prevent your contracts from getting too large?
Using EXTCODEHASH to secure your systems
How to safely integrate anyone's smart contract
Using the new Uniswap v2 in your contracts
What's new in Uniswap v2 and how to integrate Uniswap v2
Solidity and Truffle Continuous Integration Setup
How to setup Travis or Circle CI for Truffle testing along with useful plugins.
Upcoming Devcon 2021 and other events
The Ethereum Foundation just announced the next Devcon in 2021 in Colombia
The Year of the 20: Creating an ERC20 in 2020
How to use the latest and best tools to create an ERC-20 token contract
How to get a Solidity developer job?
There are many ways to get a Solidity job and it might be easier than you think!
Design Pattern Solidity: Mock contracts for testing
Why you should make fun of your contracts
Kickstart your Dapp frontend development with create-eth-app
An overview on how to use the app and its features
The big picture of Solidity and Blockchain development in 2020
Overview of the most important technologies, services and tools that you need to know
Design Pattern Solidity: Free up unused storage
Why you should clean up after yourself
How to setup Solidity Developer Environment on Windows
What you need to know about developing on Windows
Avoiding out of gas for Truffle tests
How you do not have to worry about gas in tests anymore
Design Pattern Solidity: Stages
How you can design stages in your contract
Web3 1.2.5: Revert reason strings
How to use the new feature
Gaining back control of the internet
How Ocelot is decentralizing cloud computing
Devcon 5 - Review
Impressions from the conference
Devcon 5 - Information, Events, Links, Telegram
What you need to know
Design Pattern Solidity: Off-chain beats on-chain
Why you should do as much as possible off-chain
Design Pattern Solidity: Initialize Contract after Deployment
How to use the Initializable pattern
Consensys Blockchain Jobs Report
What the current blockchain job market looks like
Provable — Randomness Oracle
How the Oraclize random number generator works
Solidity Design Patterns: Multiply before Dividing
Why the correct order matters!
Devcon 5 Applications closing in one week
Devcon 5 Applications closing
Randomness and the Blockchain
How to achieve secure randomness for Solidity smart contracts?