Are you looking for an easy way to get token prices with an RPC node? If so, you’ve come to the right place! In today’s tutorial, we’ll introduce you to Moralis’ Extended RPC Methods and our eth_getTokenPrice
endpoint. With this endpoint, you just need a single RPC request to get the price of any token. Are you eager to learn how this works? Check out the sample script below:
import fetch from 'node-fetch'; const options = { method: 'POST', headers: { accept: 'application/json', 'content-type': 'application/json' }, body: JSON.stringify({ "jsonrpc": "2.0", "id": 1, "method": "eth_getTokenPrice", "params": [ { "address": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "include": "percent_change" } ] }) }; fetch('YOUR_NODE_URL', options) .then(response => response.json()) .then(response => console.log(response)) .catch(err => console.error(err));
Running the code above will give you the price of the specified token denominated in both the chain’s native currency and USD. Here’s an example of what the response will look like:
{ jsonrpc: '2.0', id: 1, result: { tokenName: 'USD Coin', tokenSymbol: 'USDC', tokenLogo: 'https://logo.developers.moralis.com/0x1_0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48_032b6f94fd2bd5af6c065def140109e9', tokenDecimals: '6', nativePrice: { value: '399015837290761', decimals: 18, name: 'Ether', symbol: 'ETH', address: '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 prices with an RPC node doesn’t have to be more challenging than this. However, if you want a more in-depth tutorial, join us in this guide or check out the eth_getTokenPrice
documentation page.
Ready to start using our Extended RPC Methods? Sign up for free with Moralis straightaway!
Overview
If you’re looking to build cryptocurrency wallets, portfolio trackers, tax platforms, or other similar projects, you’ll likely need access to token prices. However, fetching token prices using standard RPC methods requires multiple requests and a lot of manual data aggregations. As such, this is a time-consuming and resource-intensive process, which is why we introduced Moralis’ Extended RPC Methods.
With Moralis’ Extended RPC Methods, you now only need a single RPC request to get the price of any token. But how does this work? If you want to learn how to get token prices using an RPC node, join us in this guide as we lay it all out for you. Let’s kick things off!
What are RPC Methods?
RPC, short for “Remote Procedure Call,” refers to communication protocols that allow one software system to call and request services from software on other devices. In the blockchain space, RPC protocols enable dapps to interact with blockchain networks like Ethereum, Optimism, and Base.
There are multiple standardized RPC protocols, with JSON-RPC being a prominent example. It features many predefined RPC methods, such as eth_getProof
, that streamline blockchain interactions. These RPC methods make it possible to seamlessly read and write on-chain data.
Here’s a list of prominent methods:
eth_getTransactionByHash
: Returns data about a transaction by hash.eth_getChainId
: Returns the current chain ID.eth_gasPrice
: Returns the current gas price.eth_getBalance
: Returns the balance of an address.eth_getBlockNumber
: Returns the number of the most recent block.
However, while standard RPC methods streamline blockchain interactions, they have some significant limitations you should consider. For instance, they cannot directly provide token prices. To get this data, you need to make multiple requests and even involve third-party providers.
To solve this issue and provide a more seamless developer experience, we introduced our next-generation RPC nodes!
Introducing Moralis’ Next-Generation RPC Nodes – The Easiest Way to Get Token Prices
Moralis is a prominent RPC node provider, giving you next-generation nodes that will streamline your developer experience. With our intuitive point-and-click interface, you can set up RPC nodes for all major chains, including Ethereum, Optimism, Base, Polygon, BNB Smart Chain (BSC), and many more with ease.
But what makes our RPC nodes special?
- Speed: We set the industry benchmark for speed, with response times from 70 ms.
- Reliability: Moralis’ nodes boast an impressive 99.9% uptime, making sure you get all the data you need without any trouble.
- Extended RPC Methods: With our Extended RPC Methods, you can easily query decoded, human-readable data through RPC-style requests.
Experience the next generation of RPC nodes with lightning-fast response times, unmatched reliability, and our powerful Extended RPC Methods!
Extended RPC Methods
With Moralis’ Extended RPC Methods, you can now seamlessly get decoded, human-readable data through RPC-style requests. With just one call, you can fetch NFT balances, ERC-20 balances, decoded wallet history, metadata, token prices, and much more. As such, when using Moralis, you can streamline your developer experience and build dapps faster and more efficiently.
Here are all the available methods:
eth_getTokenPrice
: Get the price of any ERC-20 token.eth_getNFTBalances
: Fetch the NFT balance of a wallet.eth_getNFTCollections
: Get all collections held by a wallet.eth_getTransactions
: Query the native transactions of a wallet.eth_getDecodedTransactions
: Get a wallet’s full transaction history.eth_getTokenBalances
: Query the ERC-20 balances of a wallet.eth_getTokenMetadata
: Get the metadata of an ERC-20 token.
In summary, the methods above give you seamless access to decoded, human-readable data via RPC-style requests.
eth_getTokenPrice
– Get Token Prices with one RPC Call
With our eth_getTokenPrice
method, you can now seamlessly get token prices without breaking a sweat. All you need is a single RPC request, and you’ll receive the price of any token denominated in both the chain’s native cryptocurrency and USD. As such, it has never been easier to get token prices using an RPC node than when working with Moralis.
But how does the eth_getTokenPrice
method work? And what exactly does a response look like? If you’re looking for the answers to these questions, read on, and we’ll guide you through a comprehensive tutorial on how to get token prices using an RPC node in three simple steps!
3-Step Tutorial: How to Get Token Prices with an RPC Node
We’ll now show you how to get token prices with an RPC node. Thanks to the accessibility of our Extended RPC Methods, you can get this data in three simple steps:
- Sign Up with Moralis & Set Up a Node
- Write a Script Calling
eth_getTokenPrice
- Run the Code
However, before you can move on, you need to take care of a couple of prerequisites!
Prerequisites
If you haven’t already, make sure you have the following ready before continuing:
Step 1: Sign Up with Moralis & Set Up a Node
Sign up for a Moralis account by clicking the ”Start for Free” button at the top right:
Log in, navigate to the ”Nodes” tab, and hit ”+ Create Node”:
Select ”Ethereum,” ”Mainnet,” and click ”Create Node”:
Copy and keep one of your node URLs, as you’ll need it in the following step:
Step 2: Write a Script Calling eth_getTokenPrice
Set up a new folder in your preferred IDE and initialize a project with the terminal command below:
npm init
Install the needed dependencies by running the commands below in your terminal:
npm install node-fetch --save npm install moralis @moralisweb3/common-evm-utils
Add ”type”: ”module”
to your ”package.json” file:
Create a new ”index.js” file and add the code below:
import fetch from 'node-fetch'; const options = { method: 'POST', headers: { accept: 'application/json', 'content-type': 'application/json' }, body: JSON.stringify({ "jsonrpc": "2.0", "id": 1, "method": "eth_getTokenPrice", "params": [ { "address": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "include": "percent_change" } ] }) }; fetch('YOUR_NODE_URL', options) .then(response => response.json()) .then(response => console.log(response)) .catch(err => console.error(err));
Replace YOUR_NODE_URL
with the URL copied during the initial step, and adjust the address
parameter so that it fits your query:
Step 3: Run the Code
Run the terminal command below in the root folder of your project to execute the script:
node index.js
In return, you’ll get the price of the specified token denominated in both the chain’s native currency and USD. Furthermore, the response is enriched with token logos, symbols, price changes over time, and much more. Here’s an example of what it might look like:
{ jsonrpc: '2.0', id: 1, result: { tokenName: 'USD Coin', tokenSymbol: 'USDC', tokenLogo: 'https://logo.developers.moralis.com/0x1_0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48_032b6f94fd2bd5af6c065def140109e9', tokenDecimals: '6', nativePrice: { value: '399015837290761', decimals: 18, name: 'Ether', symbol: 'ETH', address: '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 how to get token prices with an RPC node!
Use Cases for Token Prices
Token prices are used in a wide range of dapps. Below are three prominent examples:
- Web3 Wallets: Web3 wallets typically allow users to buy and sell cryptocurrencies. As such, to provide a seamless experience, these platforms need to access and display accurate token prices.
- Portfolio Trackers: Portfolio trackers give users an overview of their digital holdings. To present an accurate view of performance, they need to know current cryptocurrency prices.
- Tax Platforms: Tax platforms require access to both historical and current token prices to generate accurate tax reports.
These are just a few examples. Token price data is also crucial for building decentralized exchanges (DEXs), token analytics platforms, and more.
Beyond How to Get Token Prices with an RPC Node – Diving Into Other Extended RPC Methods
Now that you know how to get token prices with a node, let’s also explore some of our other Extended RPC Methods. More specifically, we’ll take a closer look at the following three:
eth_getTransactions
eth_getTokenBalances
eth_getNFTBalances
eth_getTransactions
With eth_getTransactions
, you can now seamlessly get wallet transactions using RPC nodes. In fact, you only need a single RPC request to get the full native transaction history of the specified wallet. Here’s an example of what it might look like:
import fetch from 'node-fetch'; const options = { method: 'POST', headers: { accept: 'application/json', 'content-type': 'application/json' }, body: JSON.stringify({ "jsonrpc": "2.0", "id": 1, "method": "eth_getTransactions", "params": [ { "address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "limit": 100, } ] }) }; fetch('YOUR_NODE_URL', options) .then(response => response.json()) .then(response => console.log(response)) .catch(err => console.error(err));
In return for running the code above, you’ll get a list of the specified wallet’s past native transactions. Moreover, each transaction is fully enriched with address labels, gas prices, and much more. Here’s a sample response:
{ //... 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 can easily get ERC-20 token balances using RPC nodes. All you need is a single call. Here’s an example showing you how this method works in practice:
import fetch from 'node-fetch'; const options = { method: 'POST', headers: { accept: 'application/json', 'content-type': 'application/json' }, body: JSON.stringify({ "jsonrpc": "2.0", "id": 1, "method": "eth_getTokenBalances", "params": [ { "address": "0xcB1C1FdE09f811B294172696404e88E658659905", } ] }) }; fetch('YOUR_NODE_URL', options) .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 specified wallet, enriched with logos, decimals, thumbnails, spam indicators, and more for each token. Here’s what it might look like:
{ //... result: [ { token_address: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', name: 'Wrapped Ether', symbol: 'WETH', decimals: 18, logo: 'https://logo.developers.moralis.com/0x1_0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2_a578c5277503e547a072ae32517254ca', thumbnail: 'https://logo.developers.moralis.com/0x1_0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2_a578c5277503e547a072ae32517254ca', 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
method, you can effortlessly get NFT balances with one RPC call. Fetch and integrate NFT balances into your dapps without breaking a sweat. Here’s a sample script showing how it works:
import fetch from 'node-fetch'; const options = { method: 'POST', headers: { accept: 'application/json', 'content-type': 'application/json' }, body: JSON.stringify({ "jsonrpc": "2.0", "id": 1, "method": "eth_getNFTBalances", "params": [ { "address": "0xDc597929101c2DE50c97D43C8EA3A372Bf55fdc0", "limit": 10, } ] }) }; fetch('YOUR_NODE_URL', options) .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 specified wallet. What’s more, the response is enriched with addresses, collection data, metadata, etc.:
{ jsonrpc: '2.0', id: 1, result: { //... 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, name: 'PudgyPenguins', symbol: 'PPG', token_hash: 'cbd8bd0901f422afb88e76615e3d2a1a', token_uri: 'https://ipfs.developers.moralis.com:2053/ipfs/bafybeibc5sgo2plmjkq2tzmhrn54bk3crhnc23zd2msg4ea7a4pxrkgfna/1919', minter_address: null, verified_collection: true, possible_spam: false, collection_logo: 'https://i.seadn.io/gae/yNi-XdGxsgQCPpqSio4o31ygAV6wURdIdInWRcFIl46UjUQ1eV7BEndGe8L661OoG-clRi7EgInLX4LPu9Jfw4fq0bnVYHqg7RFi?w=500&auto=format', collection_banner_image: 'https://i.seadn.io/gcs/files/8a26e3de0f309089cbb1e5ab969fc0bc.png?w=500&auto=format' }, //... ] } }
Check out our official Extended RPC Methods documentation page to explore the remaining methods!
Exploring Moralis’ Web3 API Suite
In addition to our Extended RPC Methods, we also offer a comprehensive suite of Web3 APIs. Some prominent examples include the Wallet API, Token API, Streams API, NFT API, and many more. These APIs provide even more in-depth and enriched data, making it easier for you to build everything from Web3 wallets to games!
But why should you use our APIs?
- Comprehensive: Our APIs give you more data with fewer calls. Get a wallet’s full history, token balances with prices, up-to-date NFT metadata, and much more with just one request.
- Cross-Chain: Moralis’ APIs are fully cross-chain, giving you full feature parity across all major networks. This includes Ethereum, Polygon, Optimism, BSC, Base, and many more.
- Secure & Reliable: We are proud holders of a SOC 2 Type 2 certification, highlighting our dedication to maintaining enterprise-grade security and reliability.
Now, let’s get more specific and explore some of our APIs in further detail!
Web3 APIs
Our suite of Web3 APIs comprises many use case-specific interfaces. Here are three prominent examples:
- Wallet API: Fetch any wallet’s full transaction history, token balances, net worth, profitability, token approvals, and much more with only single lines of code.
- Token API: Get token prices, metadata, transactions, balances, and more with just one request.
- NFT API: Query NFT balances, up-to-date metadata, prices, etc., with just one single API call.
Check out our Web3 API page to explore all our industry-leading APIs!
Summary: How to Get Token Prices with an RPC Node
Fetching token prices using conventional RPC methods requires multiple requests and extensive manual data aggregation. As such, it’s a time-consuming and resource-intensive process. Fortunately, you can now avoid the associated hassle and get token prices using an RPC node in just one call with Moralis’ Extended RPC Methods!
With our Extended RPC Methods, you can seamlessly fetch decoded, human-readable data using RPC-style requests. Get token balances, prices, NFT balances, and much more with single calls.
To highlight the accessibility of this feature, check out the sample script below, showing you how to get token prices with an RPC node:
import fetch from 'node-fetch'; const options = { method: 'POST', headers: { accept: 'application/json', 'content-type': 'application/json' }, body: JSON.stringify({ "jsonrpc": "2.0", "id": 1, "method": "eth_getTokenPrice", "params": [ { "address": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "include": "percent_change" } ] }) }; fetch('YOUR_NODE_URL', options) .then(response => response.json()) .then(response => console.log(response)) .catch(err => console.error(err));
In return for calling the script, you’ll get the price of the specified token denominated in both USD and the chain’s native currency. Here’s an example of what the response might look like:
{ jsonrpc: '2.0', id: 1, result: { tokenName: 'USD Coin', tokenSymbol: 'USDC', tokenLogo: 'https://logo.developers.moralis.com/0x1_0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48_032b6f94fd2bd5af6c065def140109e9', tokenDecimals: '6', nativePrice: { value: '399015837290761', decimals: 18, name: 'Ether', symbol: 'ETH', address: '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 how to get token prices with an RPC node!
If you enjoyed this tutorial, consider checking out some other articles here on the Moralis blog. For instance, explore the ins and outs of our Blockchain Address Labeling API.
Also, if you wish to use our Extended RPC Methods yourself, don’t forget to sign up with Moralis. You can create an account free of charge, and you’ll get immediate access to all our industry-leading tools!