Abyss Crypto

How to Get The Price of Ethereum

Our goal is to get this data in the most decentralized way possible


Decentralized Option #1: Uniswap v3 The Graph Sub Graph

For a more in depth understanding on The Graph, we have a page about it: Uniswap The Graph Basics
To see how this was done in Uniswap v2 (which still works) you can check out our previous version of this page


There is a Playground: https://api.thegraph.com/subgraphs/name/ianlapham/uniswap-v3-subgraph

You Can't Just Query The Direct Price

Uniswap is always trading one crypto for another, so the price of Ethereum 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 Ethereum in something we're familiar with. In the below example, we'll be comparing Ethereum with the USDC stablecoin.

The Query In TheGraph's GraphQL API

    {
        pools(where: { token0: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", token1: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"}) {
            token0Price token1Price
        }
    }

Example Data Returned:

                {
                    "data": {
                      "pools": [
                        {
                          "token0Price": "1860.812885992499892387234042295301",
                          "token1Price": "0.0005373995459337283170692501990343056"
                        },

How to process with PHP:

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://api.thegraph.com/subgraphs/name/ianlapham/uniswap-v3-subgraph');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['query' => "{ pools(where: { token0: \"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48\", token1: \"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2\"}) { 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 "Ethereum Price: " . $data->data->pools[0]->token0Price;


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!