Web3

How to Get Token Prices with an RPC Node

Are you on the lookout for an straightforward method to get token costs with an RPC node? If that’s the case, you’ve come to the proper place! In right this moment’s tutorial, we’ll introduce you to Moralis’ Prolonged RPC Strategies and our eth_getTokenPrice endpoint. With this endpoint, you simply want a single RPC request to get the worth of any token. Are you keen to learn the way this works? Take a look at the pattern script under: 

import fetch from 'node-fetch';

const choices = {
 methodology: 'POST',
 headers: {
   settle for: 'utility/json',
   'content-type': 'utility/json'
 },
 physique: JSON.stringify({
   "jsonrpc": "2.0",
   "id": 1,
   "method": "eth_getTokenPrice",
   "params": [
     {
       "address": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
       "include": "percent_change"
     }
   ]
 })
};

fetch('YOUR_NODE_URL', choices)
 .then(response => response.json())
 .then(response => console.log(response))
 .catch(err => console.error(err));

Working the code above gives you the worth of the desired token denominated in each the chain’s native foreign money and USD. Right here’s an instance of what the response will seem like: 

{
  jsonrpc: '2.0',
  id: 1,
  end result: {
    tokenName: 'USD Coin',
    tokenSymbol: 'USDC',
    tokenLogo: '
    tokenDecimals: '6',
    nativePrice: {
      worth: '399015837290761',
      decimals: 18,
      title: 'Ether',
      image: 'ETH',
      handle: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2'
    },
    usdPrice: 0.9998033934658264,
    usdPriceFormatted: '0.999803393465826414',
    '24hrPercentChange': '-0.023636130935194257',
    exchangeName: 'Uniswap v3',
    exchangeAddress: '0x1F98431c8aD98523631AE4a59f267346ea31F984',
    tokenAddress: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
    priceLastChangedAtBlock: '20669844',
    possibleSpam: false,
    verifiedContract: true,
    pairAddress: '0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640',
    pairTotalLiquidityUsd: '165658281.27'
  }
}

That’s it; fetching token costs with an RPC node doesn’t have to be more difficult than this. Nonetheless, if you would like a extra in-depth tutorial, be a part of us on this information or take a look at the eth_getTokenPrice documentation web page. 

Prepared to begin utilizing our Prolonged RPC Strategies? Join free with Moralis straightaway! 

Overview

In the event you’re trying to construct cryptocurrency wallets, portfolio trackers, tax platforms, or different comparable tasks, you’ll seemingly want entry to token costs. Nonetheless, fetching token costs utilizing customary RPC strategies requires a number of requests and quite a lot of handbook knowledge aggregations. As such, this can be a time-consuming and resource-intensive course of, which is why we launched Moralis’ Prolonged RPC Strategies. 

With Moralis’ Prolonged RPC Strategies, you now solely want a single RPC request to get the worth of any token. However how does this work? If you need to learn the way to get token costs utilizing an RPC node, be a part of us on this information as we lay all of it out for you. Let’s kick issues off! 

What are RPC Strategies?

RPC, quick for “Remote Procedure Call,” refers to communication protocols that enable one software program system to name and request providers from software program on different units. Within the blockchain area, RPC protocols allow dapps to work together with blockchain networks like Ethereum, Optimism, and Base.

Text: "What are RPC methods?"

There are a number of standardized RPC protocols, with JSON-RPC being a outstanding instance. It options many predefined RPC strategies, similar to eth_getProof, that streamline blockchain interactions. These RPC strategies make it attainable to seamlessly learn and write on-chain knowledge.

Right here’s an inventory of outstanding strategies:

  • eth_getTransactionByHash: Returns knowledge a couple of transaction by hash.
  • eth_getChainId: Returns the present chain ID.
  • eth_gasPrice: Returns the present gasoline worth.
  • eth_getBalance: Returns the stability of an handle.
  • eth_getBlockNumber: Returns the variety of the newest block.

Nonetheless, whereas customary RPC strategies streamline blockchain interactions, they’ve some important limitations it is best to take into account. As an example, they can’t instantly present token costs. To get this knowledge, you want to make a number of requests and even contain third-party suppliers.

To unravel this concern and supply a extra seamless developer expertise, we launched our next-generation RPC nodes!

Introducing Moralis’ Subsequent-Technology RPC Nodes – The Best Manner to Get Token Prices

Moralis is a outstanding RPC node supplier, providing you with next-generation nodes that may streamline your developer expertise. With our intuitive point-and-click interface, you possibly can arrange RPC nodes for all main chains, together with Ethereum, Optimism, Base, Polygon, BNB Sensible Chain (BSC), and plenty of extra with ease. 

Moralis' RPC Nodes.

However what makes our RPC nodes particular? 

  • Pace: We set the {industry} benchmark for velocity, with response instances from 70 ms. 
  • Reliability: Moralis’ nodes boast an spectacular 99.9% uptime, ensuring you get all the information you want with none hassle. 
  • Prolonged RPC Strategies: With our Prolonged RPC Strategies, you possibly can simply question decoded, human-readable knowledge via RPC-style requests. 

Expertise the subsequent technology of RPC nodes with lightning-fast response instances, unmatched reliability, and our highly effective Prolonged RPC Strategies! 

Prolonged RPC Strategies

With Moralis’ Prolonged RPC Strategies, now you can seamlessly get decoded, human-readable knowledge via RPC-style requests. With only one name, you possibly can fetch NFT balances, ERC-20 balances, decoded pockets historical past, metadata, token costs, and rather more. As such, when utilizing Moralis, you possibly can streamline your developer expertise and construct dapps quicker and extra effectively. 

Moralis' Extended RPC Methods.

Listed here are all of the accessible strategies: 

  • eth_getTokenPrice: Get the worth of any ERC-20 token.
  • eth_getNFTBalances: Fetch the NFT stability of a pockets.
  • eth_getNFTCollections: Get all collections held by a pockets.
  • eth_getTransactions: Question the native transactions of a pockets. 
  • eth_getDecodedTransactions: Get a pockets’s full transaction historical past.
  • eth_getTokenBalances: Question the ERC-20 balances of a pockets.
  • eth_getTokenMetadata: Get the metadata of an ERC-20 token.

In abstract, the strategies above offer you seamless entry to decoded, human-readable knowledge by way of RPC-style requests. 

eth_getTokenPrice – Get Token Prices with one RPC Name

With our eth_getTokenPrice methodology, now you can seamlessly get token costs with out breaking a sweat. All you want is a single RPC request, and also you’ll obtain the worth of any token denominated in each the chain’s native cryptocurrency and USD. As such, it has by no means been simpler to get token costs utilizing an RPC node than when working with Moralis. 

Ethereum logo with token price chart.

However how does the eth_getTokenPrice methodology work? And what precisely does a response seem like? In the event you’re on the lookout for the solutions to these questions, learn on, and we’ll information you thru a complete tutorial on how to get token costs utilizing an RPC node in three easy steps! 

3-Step Tutorial: How to Get Token Prices with an RPC Node

We’ll now present you the way to get token costs with an RPC node. Thanks to the accessibility of our Prolonged RPC Strategies, you will get this knowledge in three easy steps:

  1. Signal Up with Moralis & Set Up a Node
  2. Write a Script Calling eth_getTokenPrice
  3. Run the Code

Nonetheless, earlier than you possibly can transfer on, you want to handle a few stipulations! 

Stipulations

In the event you haven’t already, be sure to have the next prepared earlier than persevering with: 

Step 1: Signal Up with Moralis & Set Up a Node

Join a Moralis account by clicking the ”Begin for Free” button on the prime proper: 

Arrow pointing at "Start for Free" at top right.

Log in, navigate to the ”Nodes” tab, and hit ”+ Create Node”: 

Red arrows pointing at "Nodes" tab and "+ Create Node" button

Choose ”Ethereum,” ”Mainnet,” and click on ”Create Node”: 

Node configurations.

Copy and hold considered one of your node URLs, as you’ll want it within the following step: 

Red arrows pointing at copy button for Ethereum node URLs.

Step 2: Write a Script Calling eth_getTokenPrice

Arrange a brand new folder in your most popular IDE and initialize a mission with the terminal command under: 

npm init

Set up the wanted dependencies by operating the instructions under in your terminal: 

npm set up node-fetch --save
npm set up moralis @moralisweb3/common-evm-utils

Add ”sort”: ”module” to your ”bundle.json” file: 

"type": "module" highlighted in code editor.

Create a brand new ”index.js” file and add the code under:

import fetch from 'node-fetch';

const choices = {
 methodology: 'POST',
 headers: {
   settle for: 'utility/json',
   'content-type': 'utility/json'
 },
 physique: JSON.stringify({
   "jsonrpc": "2.0",
   "id": 1,
   "method": "eth_getTokenPrice",
   "params": [
     {
       "address": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
       "include": "percent_change"
     }
   ]
 })
};

fetch('YOUR_NODE_URL', choices)
 .then(response => response.json())
 .then(response => console.log(response))
 .catch(err => console.error(err));

Substitute YOUR_NODE_URL with the URL copied in the course of the preliminary step, and modify the handle parameter in order that it matches your question: 

Code configurations.

Step 3: Run the Code

Run the terminal command under within the root folder of your mission to execute the script: 

node index.js

In return, you’ll get the worth of the desired token denominated in each the chain’s native foreign money and USD. Moreover, the response is enriched with token logos, symbols, worth modifications over time, and rather more. Right here’s an instance of what it would seem like: 

{
  jsonrpc: '2.0',
  id: 1,
  end result: {
    tokenName: 'USD Coin',
    tokenSymbol: 'USDC',
    tokenLogo: '
    tokenDecimals: '6',
    nativePrice: {
      worth: '399015837290761',
      decimals: 18,
      title: 'Ether',
      image: 'ETH',
      handle: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2'
    },
    usdPrice: 0.9998033934658264,
    usdPriceFormatted: '0.999803393465826414',
    '24hrPercentChange': '-0.023636130935194257',
    exchangeName: 'Uniswap v3',
    exchangeAddress: '0x1F98431c8aD98523631AE4a59f267346ea31F984',
    tokenAddress: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
    priceLastChangedAtBlock: '20669844',
    possibleSpam: false,
    verifiedContract: true,
    pairAddress: '0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640',
    pairTotalLiquidityUsd: '165658281.27'
  }
}

That’s it; you now know the way to get token costs with an RPC node! 

Use Circumstances for Token Prices

Token costs are utilized in a variety of dapps. Beneath are three outstanding examples:

  • Web3 Wallets: Web3 wallets sometimes enable customers to purchase and promote cryptocurrencies. As such, to present a seamless expertise, these platforms want to entry and show correct token costs.
  • Portfolio Trackers: Portfolio trackers give customers an overview of their digital holdings. To current an correct view of efficiency, they want to know present cryptocurrency costs.
  • Tax Platforms: Tax platforms require entry to each historic and present token costs to generate correct tax reviews.
Token prices use cases.

These are only a few examples. Token worth knowledge can also be essential for constructing decentralized exchanges (DEXs), token analytics platforms, and extra.

Past How to Get Token Prices with an RPC Node – Diving Into Different Prolonged RPC Strategies

Now that you know the way to get token costs with a node, let’s additionally discover a few of our different Prolonged RPC Strategies. Extra particularly, we’ll take a more in-depth have a look at the next three: 

  1. eth_getTransactions
  2. eth_getTokenBalances
  3. eth_getNFTBalances

eth_getTransactions

With eth_getTransactions, now you can seamlessly get pockets transactions utilizing RPC nodes. In actual fact, you solely want a single RPC request to get the total native transaction historical past of the desired pockets. Right here’s an instance of what it would seem like: 

import fetch from 'node-fetch';

const choices = {
 methodology: 'POST',
 headers: {
   settle for: 'utility/json',
   'content-type': 'utility/json'
 },
 physique: JSON.stringify({
   "jsonrpc": "2.0",
   "id": 1,
   "method": "eth_getTransactions",
   "params": [
     {
       "address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
       "limit": 100,
     }
   ]
 })
};

fetch('YOUR_NODE_URL', choices)
 .then(response => response.json())
 .then(response => console.log(response))
 .catch(err => console.error(err));

In return for operating the code above, you’ll get an inventory of the desired pockets’s previous native transactions. Furthermore, every transaction is totally enriched with handle labels, gasoline costs, and rather more. Right here’s a pattern response: 

{
  //...
    end result: [
      {
        hash: '0xd89b02f289a08ae7b2feead06031fec20777bad8b73fc8d853f9040bc423a6c7',
        nonce: '0',
        transaction_index: '142',
        from_address: '0xda74ac6b69ff4f1b6796cddf61fbdd4a5f68525f',
        from_address_label: '',
        to_address: '0xdac17f958d2ee523a2206206994597c13d831ec7',
        to_address_label: 'Tether USD (USDT)',
        value: '0',
        gas: '207128',
        gas_price: '17020913648',
        input: '0xa9059cbb00000000000000000000000028c6c06298d514db089934071355e5743bf21d6000000000000000000000000000000000000000000000000000000017a1df1700',
        receipt_cumulative_gas_used: '8270587',
        receipt_gas_used: '41309',
        receipt_contract_address: null,
        receipt_root: null,
        receipt_status: '1',
        block_timestamp: '2023-01-22T15:00:11.000Z',
        block_number: '16463098',
        block_hash: '0x2439330d0a282f9a6464b0aceb9f766ac4d7b050c048b4a1322b48544c61e01d',
        transaction_fee: '0.000703116921885232'
      },
      //...
    ]
  }
}

eth_getTokenBalances

With our eth_getTokenBalances endpoint, you possibly can simply get ERC-20 token balances utilizing RPC nodes. All you want is a single name. Right here’s an instance displaying you the way this methodology works in follow: 

import fetch from 'node-fetch';

const choices = {
 methodology: 'POST',
 headers: {
   settle for: 'utility/json',
   'content-type': 'utility/json'
 },
 physique: JSON.stringify({
   "jsonrpc": "2.0",
   "id": 1,
   "method": "eth_getTokenBalances",
   "params": [
     {
       "address": "0xcB1C1FdE09f811B294172696404e88E658659905",
     }
   ]
 })
};

fetch('YOUR_NODE_URL', choices)
 .then(response => response.json())
 .then(response => console.log(response))
 .catch(err => console.error(err));

In return for calling the endpoint above, you’ll get the ERC-20 balances of the desired pockets, enriched with logos, decimals, thumbnails, spam indicators, and extra for every token. Right here’s what it would seem like: 

{
  //...
  end result: [
    {
      token_address: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',
      name: 'Wrapped Ether',
      symbol: 'WETH',
      decimals: 18,
      logo: '
      thumbnail: '
      balance: '10000000000000000',
      possible_spam: false,
      verified_contract: true,
      total_supply: '2746607222348759943423350',
      total_supply_formatted: '2746607.22234875994342335',
      percentage_relative_to_total_supply: 3.64085549569e-7
    },
    //...
  ]
}

eth_getNFTBalances

With the eth_getNFTBalances methodology, you possibly can effortlessly get NFT balances with one RPC name. Fetch and combine NFT balances into your dapps with out breaking a sweat. Right here’s a pattern script displaying the way it works: 

import fetch from 'node-fetch';

const choices = {
 methodology: 'POST',
 headers: {
   settle for: 'utility/json',
   'content-type': 'utility/json'
 },
 physique: JSON.stringify({
   "jsonrpc": "2.0",
   "id": 1,
   "method": "eth_getNFTBalances",
   "params": [
     {
       "address": "0xDc597929101c2DE50c97D43C8EA3A372Bf55fdc0",
       "limit": 10,
     }
   ]
 })
};

fetch('YOUR_NODE_URL', choices)
 .then(response => response.json())
 .then(response => console.log(response))
 .catch(err => console.error(err));

In return for calling the eth_getNFTBalances endpoint, you’ll get the NFT balances of the desired pockets. What’s extra, the response is enriched with addresses, assortment knowledge, metadata, and many others.: 

{
  jsonrpc: '2.0',
  id: 1,
  end result: {
    //...
    end result: [
          {
      amount: '1',
      token_id: '1919',
      token_address: '0xbd3531da5cf5857e7cfaa92426877b022e612cf8',
      contract_type: 'ERC721',
      owner_of: '0xdc597929101c2de50c97d43c8ea3a372bf55fdc0',
      last_metadata_sync: '2024-08-25T23:35:51.384Z',
      last_token_uri_sync: '2024-08-25T23:35:50.893Z',
      metadata: '{"attributes":[{"trait_type":"Background","value":"Mint"},{"trait_type":"Skin","value":"Olive Green"},{"trait_type":"Body","value":"Turtleneck Pink"},{"trait_type":"Face","value":"Eyepatch"},{"trait_type":"Head","value":"Wizard Hat"}],"description":"A collection 8888 Cute Chubby Pudgy Penquins sliding around on the freezing ETH blockchain.","image":"ipfs://QmNf1UsmdGaMbpatQ6toXSkzDpizaGmC9zfunCyoz1enD5/penguin/1919.png","name":"Pudgy Penguin #1919"}',
      block_number: '19754671',
      block_number_minted: null,
      title: 'PudgyPenguins',
      image: 'PPG',
      token_hash: 'cbd8bd0901f422afb88e76615e3d2a1a',
      token_uri: '
      minter_address: null,
      verified_collection: true,
      possible_spam: false,
      collection_logo: '
      collection_banner_image: '
      },
      //...
    ]
  }
}

Take a look at our official Prolonged RPC Strategies documentation web page to discover the remaining strategies! 

Exploring Moralis’ Web3 API Suite

As well as to our Prolonged RPC Strategies, we additionally supply a complete suite of Web3 APIs. Some outstanding examples embrace the Pockets API, Token API, Streams API, NFT API, and plenty of extra. These APIs present much more in-depth and enriched knowledge, making it simpler for you to construct all the pieces from Web3 wallets to video games!

Moralis logo.

However why must you use our APIs?

  • Complete: Our APIs offer you extra knowledge with fewer calls. Get a pockets’s full historical past, token balances with costs, up-to-date NFT metadata, and rather more with only one request.
  • Cross-Chain: Moralis’ APIs are totally cross-chain, providing you with full characteristic parity throughout all main networks. This contains Ethereum, Polygon, Optimism, BSC, Base, and plenty of extra.
  • Safe & Dependable: We’re proud holders of a SOC 2 Sort 2 certification, highlighting our dedication to sustaining enterprise-grade safety and reliability.

Now, let’s get extra particular and discover a few of our APIs in additional element!

Web3 APIs

Our suite of Web3 APIs contains many use case-specific interfaces. Listed here are three outstanding examples: 

  • Pockets API: Fetch any pockets’s full transaction historical past, token balances, web price, profitability, token approvals, and rather more with solely single strains of code. 
  • Token API: Get token costs, metadata, transactions, balances, and extra with simply one request. 
  • NFT API: Question NFT balances, up-to-date metadata, costs, and many others., with only one single API name. 

Take a look at our Web3 API web page to discover all our industry-leading APIs! 

Abstract: How to Get Token Prices with an RPC Node 

Fetching token costs utilizing standard RPC strategies requires a number of requests and intensive handbook knowledge aggregation. As such, it’s a time-consuming and resource-intensive course of. Thankfully, now you can keep away from the related trouble and get token costs utilizing an RPC node in only one name with Moralis’ Prolonged RPC Strategies! 

With our Prolonged RPC Strategies, you possibly can seamlessly fetch decoded, human-readable knowledge utilizing RPC-style requests. Get token balances, costs, NFT balances, and rather more with single calls. 

To spotlight the accessibility of this characteristic, take a look at the pattern script under, displaying you the way to get token costs with an RPC node: 

import fetch from 'node-fetch';

const choices = {
 methodology: 'POST',
 headers: {
   settle for: 'utility/json',
   'content-type': 'utility/json'
 },
 physique: JSON.stringify({
   "jsonrpc": "2.0",
   "id": 1,
   "method": "eth_getTokenPrice",
   "params": [
     {
       "address": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
       "include": "percent_change"
     }
   ]
 })
};

fetch('YOUR_NODE_URL', choices)
 .then(response => response.json())
 .then(response => console.log(response))
 .catch(err => console.error(err));

In return for calling the script, you’ll get the worth of the desired token denominated in each USD and the chain’s native foreign money. Right here’s an instance of what the response would possibly seem like: 

{
  jsonrpc: '2.0',
  id: 1,
  end result: {
    tokenName: 'USD Coin',
    tokenSymbol: 'USDC',
    tokenLogo: '
    tokenDecimals: '6',
    nativePrice: {
      worth: '399015837290761',
      decimals: 18,
      title: 'Ether',
      image: 'ETH',
      handle: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2'
    },
    usdPrice: 0.9998033934658264,
    usdPriceFormatted: '0.999803393465826414',
    '24hrPercentChange': '-0.023636130935194257',
    exchangeName: 'Uniswap v3',
    exchangeAddress: '0x1F98431c8aD98523631AE4a59f267346ea31F984',
    tokenAddress: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
    priceLastChangedAtBlock: '20669844',
    possibleSpam: false,
    verifiedContract: true,
    pairAddress: '0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640',
    pairTotalLiquidityUsd: '165658281.27'
  }
}

Congratulations! You now know the way to get token costs with an RPC node! 

In the event you loved this tutorial, take into account testing another articles right here on the Moralis weblog. As an example, discover the ins and outs of our Blockchain Tackle Labeling API. 

Additionally, if you want to use our Prolonged RPC Strategies your self, don’t neglect to enroll with Moralis. You possibly can create an account freed from cost, and also you’ll get rapid entry to all our industry-leading instruments!

DailyBlockchain.News Admin

Our Mission is to bridge the knowledge gap and foster an informed blockchain community by presenting clear, concise, and reliable information every single day. Join us on this exciting journey into the future of finance, technology, and beyond. Whether you’re a blockchain novice or an enthusiast, DailyBlockchain.news is here for you.
Back to top button