Swapping crypto using Privy and 0x
To enable crypto asset swapping (e.g. convert USDC to ETH), you can integrate with the exchange of your choice. In this case, we use 0x which offers a huge amount of swapping pairs and great rates. This guide will enable a Privy wallet to convert USDC to ETH.
This guide assumes that the Privy wallet has already been created and funded with ETH to pay for transaction fees. Code examples are in Javascript.
Step 1: Register with 0x and retrieve API keys
Go the 0x dashboard and create an account. Save your API keys in your local .env
file.
Step 2: Approve the Permit2 contract to enable asset movement from your wallet
In order to facilitate a sale of USDC, 0x needs to be able to move USDC from your wallet to the buyer based on the trade. To do so, the wallet owner (user) must approve of this via a signature, which is then verified onchain. All of this can be done invisibly for the user.
This is a one time action that won’t have to be done again for any future swapping for this wallet.
Step 3: Get quote from 0x
Next, you want to fetch a quote from 0x to sell your USDC for ETH.
Step 4: Prepare the transaction and execute
Finally, you will prepare the transaction to fulfill the order and execute the swap. The user should see additional ETH in their wallet in exchange for their USDC.