Abyss Crypto

How to Get The Price of Bitcoin

Lets start with one of the most basic things - the Bitcoin price. Our goal is to get this data in the most decentralized way possible


Decentralized Option #1: Uniswap v2 The Graph Sub Graph

For a more in depth understanding on The Graph, we have a page about it: Uniswap The Graph Basics

There is a Playground: https://thegraph.com/hosted-service/subgraph/uniswap/uniswap-v2

You Can't Just Query The Direct Price

Uniswap is always trading one crypto for another, so the price of Bitcoin is all sorts of different ratios depending on what crypto you are exchanging it with. This is where stable coins make it easier to find the price of Bitcoin in something we're familiar with. In the below example, we'll be comparing Bitcoin with the USDC stablecoin.

Additionally, Bitcoin isn't an Ethereum token. So we'll be using Wrapped Bitcoin, WBTC

The Query In TheGraph's GraphQL API

    {
        pairs(where: { token0: "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599", token1: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"}) {
            token0Price token1Price
        }
    }

Example Data Returned:

    {"data":{"pairs":[{"token0Price":"0.0000331179756294414503158360107460632","token1Price":"30195.08230783928062472426216758919"}]}}

How to process with PHP:

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['query' => "{ pairs(where: { token0: \"0x2260fac5e5542a773aa44fbcfedf7c193bc2c599\", token1: \"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48\"}) { token0Price token1Price } }"]));

    $headers = array();
    $headers[] = 'Content-Type: application/json';
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    }
    curl_close($ch);
    $data = json_decode($result);
    echo "Bitcoin Price: " . $data->data->pairs[0]->token1Price;


Deep Dive Section

How To Get token0 and token1

The values for token0 and token1 are the contract addresses for the tokens we are looking up. There are two basic easy ways to find this data

1. If the pair is popular, you can pretty easily find it Uniswap info page: https://info.uniswap.org/#/ , clicking on the token, and clicking on the (0x....) bit. That will take us to Etherscan, we'll see the full 0x.... contract address, and we can copy it now!

2. For more obscure tokens, you will proabably need to start your journey on Etherscan itself.



If you have information about a better way to access this data, or a way to access this data in a programming language we don't have listed, please let us know!