How to make a buy programatically
A tutorial on how to make a script for buying NFTs on caviar
Last updated
A tutorial on how to make a script for buying NFTs on caviar
Last updated
For this tutorial we will use the library and to programatically buy a few BAYC NFTs on the goerli testnet. To get goerli ETH you can claim some from .
The first step is to create an empty directory and install the dependencies:
Now before we start writing code we also need the required ABI files (caviar.abi.json
and pair.abi.json
) to interact with the contracts. Those can be found on the . Copy and paste caviar.abi.json
and pair.abi.json
into the root of caviar-swap-example/
.
Great, now we can start actually writing the script. Create a file buy.js
and then open it and import the required dependencies along with making an empty entrypoint function called main()
.
Now we need to setup an ethers.js so that we can interact with the chain and send transactions. Inside of the main()
function:
And then create a .env file with the following content:
Now let's fetch the pair contract address for floor BAYC:ETH pair and create a contract instance that we can interact with. We can do this by querying the Caviar factory contract:
Although you can choose any two NFTs, we will just choose the first two that were returned from the response. Now for the final moment! let's actually submit a transaction to buy:
Cool, that's most of the setup out of the way. Now let's query the contract and figure out how much ETH we will have to spend to buy two BAYCs from the pool. To do this we need to query the reserves and implement some logic which is the same as in the pair contract:
So we know how much ETH we will need to spend. All we need to do now is pick some NFTs that we want to buy from the pair. In order to do this we need to find out what NFTs the pair actually holds. This can be done via the :
If all goes well you should have just bought two BAYCs. Here is a link to a transaction I submitted using this script on . Yours should look quite similar except with different token IDs. All of the code for this tutorial is available on . The next step is now to make a sell transaction. The sell tutorial is available .