A high-quality ERC20 token API is essential when building dapps. By using the following line of code, you can use Moralis’ enterprise-grade ERC20 token API to fetch the price of any ERC20 token on any EVM-compatible chain:
const response = await Moralis.EvmApi.token.getTokenPrice(options);
If you’ve worked with Moralis before and are JavaScript proficient, you probably know exactly what to do with the above code snippet. However, if you need guidance on incorporating the ultimate ERC20 token API, read on! After all, a tutorial utilizing the above “getTokenPrice” endpoint is waiting for you below. So, if you are eager to get your hands dirty, create your free Moralis account and jump to the “Example of How to Use Moralis’ ERC20 Token API” section. If you are new to Moralis, we recommend you cover the entire article, as it will help you properly grasp the basics behind using the best token API.
Overview
Ethereum was the first programmable blockchain, which granted this network a first-mover advantage. This new public blockchain attracted many believers of the decentralized web, and the Ethereum community rapidly increased in popularity. Despite the birth of many so-called “Ethereum killers” in the last couple of years, Ethereum continues to run the show. After all, it is the home of countless dapps and crypto tokens. Thus, getting acquainted and placing the most powerful ERC20 token API in your development tool suite is a no-brainer. Fortunately, this is exactly what today’s article was designed to help you with.
Moving forward, you’ll first learn what an ERC20 token API is and how it can be useful. With these basics under your belt, we’ll take a closer look at the Moralis enterprise-grade token API. Basically, we’ll do an overview of this neat solution. This is also where we’ll look at the currently included ERC20 token API endpoints. In addition, you’ll learn how to easily test each of them and obtain the right lines of code for any programming language.
Last but not least, we’ll focus on showing you how to utilize the “getTokenPrice” endpoint. After all, there are many types of dapps where fetching ERC20 token prices can be of great value. By completing this tutorial, you will also learn how to get started with Moralis. You’ll then be equipped to use any other ERC20 token API endpoint and the entire set of Moralis’ Web3 APIs – Auth API, NFT API, and Streams API.
ERC20 Token API – What is it?
An ERC20 token API is a specific type of Web3 API tool. As the name suggests, it focuses on data regarding ERC20 tokens. That said, you need to understand what a Web3 API is and what ERC20 tokens are to fully understand what an ERC20 token API entails. So, without further ado, let’s start by looking at what a Web3 API is.
Understanding Web3 APIs
As you may know, API stands for “application programming interface”, and it has been an important part of the legacy development space. After all, various APIs are in charge of facilitating communication between software. They do so by translating instructions for correlative understanding. Furthermore, these tools enable reliable programming in secure and controlled development environments. APIs achieve the latter by supplying functions on request reliably and consistently. Web3 APIs do the same things as legacy APIs; however, they focus on communicating with blockchain nodes on the one hand and dapps’ backends on the other.
If you are unfamiliar with APIs and want to get a solid understanding of them, using the following restaurant analogy helps. Think of the kitchen as the “system” or “software” that handles customers’ orders. However, restaurant customers do not normally communicate directly with the kitchen. Instead, their orders are usually taken by a waitress or waiter, who serves as an intermediary. The waitress/waiter delivers a customer’s order (request) and supplies the customer with a response from the kitchen (system) in the form of food. In this analogy, APIs are the waiters/waitresses. However, instead of facilitating communication between customers and the kitchen, they do so among different pieces of software.
Furthermore, we utilize APIs whenever we browse the internet. As our devices connect to the web and send information to the receiving end, which analyzes the data, performs the required actions, and sends back a response. Our devices then interpret the information and present it in a readable way. Of course, when focusing on Web3 APIs, this sort of communication happens within the blockchain space. Ultimately, Web3 APIs open up the power of Web3 development for developers worldwide!
Understanding ERC20 Tokens
Now that you know what a Web3 API is, we also need to ensure you understand the meaning of ERC20. Only then will you be able to answer the “what is an ERC20 token API?” question confidently.
You don’t have to be a crypto expert to know that many crypto tokens or cryptocurrencies are available. The majority of these tokens live on the Ethereum network. Accordingly, when focusing on fungible tokens, most of them follow the ERC20 standard; hence, we call them ERC20 tokens. Furthermore, ERC20 is short for “Ethereum Request for Comments 20”, which was proposed and accepted at the end of 2015. Ever since Ethereum devs put it in place, all fungible tokens minted on Ethereum have the exact same basic qualities. The latter follows Ethereum’s native coin (ETH) specifics.
Also, note that Web3 devs refer to the ERC20 standard as the “ERC20 contract”. After all, smart contracts (on-chain pieces of software) are used to implement this standard. Accordingly, whenever devs decide to create ERC20 tokens, they need to deploy a smart contract that incorporates the ERC20 standard’s guidelines. You should remember that the smart contract used to mint the token is also in charge of ensuring that all token transfers follow predefined rules. Basically, the ERC20 contract standard imposes proper rules for creating and handling ERC20 tokens.
How an API for ERC20 Tokens Can Be Useful
ERC20 tokens can serve many different purposes. For instance, they can be used as utility tokens, governance tokens, etc. So, when you create a dapp that incorporates either yours or other existing ERC20 tokens, a proper token API makes all the difference. It enables you to fetch on-chain details about the fungible tokens and use the data to trigger a specific dapp functionality. Of course, this also lets you present your dapp users with this token data in a user-friendly manner.
Furthermore, you can also use an ERC20 token API to build a DeFi platform. Or, you can even utilize this excellent tool to incorporate ERC20 tokens in a Web3 game. Ultimately, if you plan on building a dapp that needs to deal with ERC20 tokens, a proper token API can save you a ton of time and resources. Without this tool, you’d need to build your own backend infrastructure to establish the required communication.
Introduction to the Enterprise-Grade ERC20 Token API
We already mentioned that the ultimate ERC20 token API is brought to you by Moralis’ Token API. Unless you’ve been living under a rock, odds are you know that Moralis is an enterprise-grade Web3 API provider. Thanks to its cross-platform interoperability, Moralis bridges the development gap between Web2 and Web3. Hence, you can use your favorite legacy dev platforms and programming languages to join the Web3 revolution. In addition, Moralis is also all about cross-chain interoperability. Hence, it supports all leading programmable blockchains, which future-proofs your work as you never get stuck to any particular chain.
Moralis’ ERC20 token API allows you to integrate real-time token data into your applications. Among other features, this powerful tool gives you full access to token prices, ownership, balances, and transfer data across all major blockchains. In fact, here’s a list of the most prominent out-of-the-box functionalities provided by Moralis’ Token API:
- Fetching ERC20 prices (native and USD)
- Fetching an ERC20 token owned by a given wallet
- Fetching ERC20 balances for a given wallet
- Fetching ERC20 transfers for a given wallet
- Support for all ERC20 tokens
- Real-time ERC20 token price discovery and metadata
Token API Endpoints
All of the above-listed functionalities are possible thanks to the following Token API endpoints:
- “getTokenPrice” – To get the token price denominated in the blockchain’s native token and USD.
- “getWalletTokenBalances” – To get a balance of ERC20 tokens for a specific wallet address.
- “getTokenAllowance” – To get the amount that the spender is allowed to withdraw on behalf of the owner.
- “getWalletTokenTransfers” – To get ERC20 token transactions ordered by block number in descending order for a particular wallet.
- “getTokenTransfers” – To get ERC20 token transactions from a contract ordered by block number in descending order.
- “getTokenMetadata” – To get the metadata for a given token contract address (name, symbol, decimals, and logo).
- “getTokenMetadataBySymbol” – To get the metadata for a list of token symbols (name, symbol, decimals, and logo).
With these endpoints, you can easily support live price feeds, portfolio apps, transaction monitoring, ownership verification, and more.
Moving forward, we’ll take a closer look at the “getTokenPrice” endpoint, which we’ll work with in the upcoming tutorial. However, we encourage you to use the token API documentation to check out the details of other endpoints that you can use with the “Moralis.EvmApi.token” method.
The “getTokenPrice” Endpoint
We’ve mentioned at least a couple of times that the “getTokenPrice” endpoint is the key to getting ERC20 token prices. Since we’ll be using this endpoint in the next section, let’s look at its documentation page:
The above screenshot shows you that the “address” parameter is the only required parameter. After all, the endpoint needs to know which smart contract to focus on. Furthermore, this useful ERC20 token API endpoint also supports the following optional parameters:
- “chain” – The chain to query
- “providerUrl” – The Web3 provider URL to use when using the local dev chain
- “exchange” – Factory name or address of the token exchange
- “to_block” – To fetch the historical token prices (at any specific block)
Nonetheless, in the image above, you can also see that the Moralis documentation pages enable you to test-run all endpoints. In addition, you get to select the programming language you want to use on the top-right side. Then, you can simply copy the code snippet from the “request” section.
Example of How to Use Moralis’ ERC20 Token API
Finally, we get to focus on completing today’s tutorial, where you’ll get to use the above-presented “getTokenPrice” ERC20 token API endpoint. However, before you tackle the three-step procedure outlined below, make sure you have completed the following prerequisites:
- Install Node v.14 or higher.
- Prepare your favorite code editor or IDE. We tend to use Visual Studio Code (VSC).
- Install your preferred package manager (NPM, Yarn, or PNPM).
Step 1: Obtain Your ERC20 Token API Key and Install the Moralis SDK
In case you haven’t created your free Moralis account yet, do so now. You can use the link at the top of the article or the “Start for Free” button on Moralis’ homepage. With your account up and running, you’ll get to access your admin area, where you need to copy your ERC20 token API key, a.k.a. Web3 API key:
We’ll show you where to paste your API key shortly. But for now, hold on to it and focus on installing the Moralis SDK. You get to do that by running one of the following commands (depending on the package manager that you are using):
npm install moralis
yarn add moralis
pnpm add moralis
Step 2: Use an Example Script That Gets ERC20 Token Price
The following lines of code represent our example “index.js” script, which properly incorporates the “getTokenPrice” endpoint:
const Moralis = require("moralis").default; const { EvmChain } = require("@moralisweb3/evm-utils"); const runApp = async () => { await Moralis.start({ apiKey: "YOUR_API_KEY", // ...and any other configuration }); const address = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"; const chain = EvmChain.ETHEREUM; const response = await Moralis.EvmApi.token.getTokenPrice({ address, chain, }); console.log(response); } runApp();
Note: In case you prefer to work with TypeScript instead of JavaScript, visit the documentation page on how to get ERC20 token price. There, you’ll get to copy our example “index.ts” script.
As you can see above, by using “EvmChain.ETHEREUM“, we are focusing on Ethereum. However, you could fetch ERC20 token prices on other supported blockchains by replacing “ETHEREUM” accordingly. Furthermore, “YOUR_API_KEY” instructs you to replace that placeholder with the above-obtained Moralis Web3 API key:
Step 3: Execute the Program and Explore the Results
With the above script in place and your Web3 API key properly inserted, you can execute the program. By doing so, you will get to see the results in your terminal.
Make sure to use the right command:
For JavaScript:
node index.js
For TypeScript:
npx ts-node index.ts
Nonetheless, if you haven’t changed the above example address (“0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2“), you should see this response:
{ "nativePrice": { "value": "1000000000000000000", "decimals": 18, "name": "Ether", "symbol": "ETH" }, "usdPrice": 1202.4880237457774, "exchangeAddress": "0x1f98431c8ad98523631ae4a59f267346ea31f984", "exchangeName": "Uniswap v3" }
Note: Since the above price is live, you will probably get a different value.
We strongly encourage you to test the above script for other contract addresses and other EVM-compatible chains!
Exploring the Ultimate ERC20 Token API – Summary
In today’s article, you had an opportunity to learn about Web3 APIs and ERC20 tokens. This knowledge came in handy when trying to understand what an ERC20 token API is. We also told you how an API for ERC20 tokens could be useful. The latter was clarified when we introduced you to Moralis’ Token API, a.k.a. the ultimate ERC20 token API. This is where you learn about all the current endpoints in this particular Web3 API set and what they can do. Last but not least, you had a chance to follow our tutorial and see one of these endpoints – “getTokenPrice” – in action.
If you are serious about incorporating ERC20 tokens into your dapps, make sure to take other Token API endpoints for a test run. Moreover, you may want to do the same for non-fungible tokens (NFTs), which continue to be one of the most popular blockchain use cases. Nonetheless, if you need some help with building your first dapp, make sure to use the Moralis docs. On the other hand, you may be interested in exploring other blockchain development topics. If so, the Moralis YouTube channel and our crypto blog are excellent outlets. Some of the latest articles focus on AWS Lambda NodeJS, the Optimism network, Polygon webhooks, and much more.
Last but not least, there are countless job opportunities in the blockchain industry, and you can improve your chances of landing your dream crypto job by becoming blockchain-certified. Hence, make sure to consider enrolling in Moralis Academy. Once on the inside, you’ll be able to choose from many different courses. However, given the latest downturn for centralized crypto exchanges, it might be the right time to master DeFi.
Read More: moralis.io