0

I have a simple front end, and when the user inputs an amount , on blur i want to show the amount of token B they will be buying with the input amount.

for that I'm trying to use 0x price api

const handleBlur = async () => {
        /**@DEV on blur will use the 0x api to fetch token price  */
        if(amount1 !== 0 && selectedToken1 !== "" && selectedToken2!== ""){
            
            const params = { 
                chainId:8453,
                buyToken: selectedToken2.address,
                sellToken:selectedToken1.address,
                sellAmount:amount1
            }
            const headers = {'0x-api-key': `${process.env.ZERO_X_API_KEY}`};
            const resp = await fetch(`https://api.0x.org/swap/permit2/price?${qs.stringify(params)}`,{headers});
            console.log(resp.json);
        }
    }

This is the function that handles the fetch request to the 0x API. also here you can find the documentation of the API and its params https://0x.org/docs/api

1 Answer 1

0

Instead of passing params as Object, you've to pass them individually as query parameters, which are part of the URL.

Also, you've to pass '0x-version': 'v2' in the headers.

Here's an example:

const chainId = 1;
const sellToken = '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee';
const buyToken = '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48';
const sellAmount = '1000000000000000000';
const apiKey = process.env.ZERO_X_API_KEY;

const url = `https://api.0x.org/swap/permit2/price?chainId=${chainId}&sellToken=${encodeURIComponent(sellToken)}&buyToken=${encodeURIComponent(buyToken)}&sellAmount=${sellAmount}`;

const options = {
    method: 'GET',
    headers: {
        '0x-api-key': apiKey,
        '0x-version': 'v2'
    }
};

fetch(url, options)
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));
1
  • 1
    I had to modify that version a bit and got it running , thanks for the reply. I also noticed that CORS on Brave browser was blocking the fetch from the front end of the app, so I had to make the call on the client side.
    – yahdielo
    Commented Oct 17 at 21:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.