# Request bind between profile of two addresses
Source: https://docs.moralis.com/api-reference/bind/request-bind-between-profile-of-two-addresses
/openapi-files/auth-api/auth.json post /bind/request
Request for message to bind profile that is belong to the two addresses
All profiles under the addresses will be bound and new profile will be generated.
# Request to remove bind of an address from a profile
Source: https://docs.moralis.com/api-reference/bind/request-to-remove-bind-of-an-address-from-a-profile
/openapi-files/auth-api/auth.json post /bind/remove
# Verify bind request
Source: https://docs.moralis.com/api-reference/bind/verify-bind-request
/openapi-files/auth-api/auth.json post /bind/request/verify
# Verify remove bind request
Source: https://docs.moralis.com/api-reference/bind/verify-remove-bind-request
/openapi-files/auth-api/auth.json post /bind/remove/verify
# Request Aptos challenge
Source: https://docs.moralis.com/api-reference/challenge/request-aptos-challenge
/openapi-files/auth-api/auth.json post /challenge/request/aptos
# Request EVM challenge
Source: https://docs.moralis.com/api-reference/challenge/request-evm-challenge
/openapi-files/auth-api/auth.json post /challenge/request/evm
# Request Solana challenge
Source: https://docs.moralis.com/api-reference/challenge/request-solana-challenge
/openapi-files/auth-api/auth.json post /challenge/request/solana
# Verify Aptos challenge
Source: https://docs.moralis.com/api-reference/challenge/verify-aptos-challenge
/openapi-files/auth-api/auth.json post /challenge/verify/aptos
# Verify EVM challenge
Source: https://docs.moralis.com/api-reference/challenge/verify-evm-challenge
/openapi-files/auth-api/auth.json post /challenge/verify/evm
# Verify Solana challenge
Source: https://docs.moralis.com/api-reference/challenge/verify-solana-challenge
/openapi-files/auth-api/auth.json post /challenge/verify/solana
# Get addresses that are bound to the specific profileId
Source: https://docs.moralis.com/api-reference/profile/get-addresses-that-are-bound-to-the-specific-profileid
/openapi-files/auth-api/auth.json get /profile/{profileId}/addresses
# Auth API
Source: https://docs.moralis.com/auth-api/overview
Web3 authentication using wallet signature, built on the EIP-4361 standard for secure off-chain identity verification.
## Overview
Moralis **Auth API** enables secure **Web3 authentication** by letting users prove wallet ownership through message signing.
Instead of managing passwords or OAuth flows, Auth API uses cryptographic signatures to verify that users control their wallets - the native identity primitive of Web3.
***
## What Is Auth API?
Auth API provides a complete **wallet-based authentication flow** that:
* Generates secure challenge messages for users to sign
* Verifies wallet signatures cryptographically
* Returns a unique user identifier (`profileId`) across sessions
* Works with both EVM chains and Solana
The authentication follows the **EIP-4361** standard (Sign-In with Ethereum), ensuring compatibility with wallet apps and established security practices.
***
## How It Works
The authentication flow consists of three steps:
1. **Request Challenge** - Your backend requests a challenge message from Moralis
2. **User Signs** - The user signs the challenge message with their wallet
3. **Verify Signature** - Your backend sends the signature to Moralis for verification
Upon successful verification, you receive a `profileId` that uniquely identifies the user - regardless of which wallet or chain they used to authenticate.
***
## Key Features
Auth API includes:
* **EIP-4361 Standard** - Built on Sign-In with Ethereum for broad wallet compatibility
* **Unified Profile ID** - Single identifier per user across wallets and chains
* **Multi-Wallet Support** - Users can link multiple wallets to one profile
* **Cross-Chain** - Works with EVM chains and Solana
* **Stateless Verification** - No session management required on Moralis side
***
## Supported Networks
Auth API supports wallet authentication across:
* **EVM Chains** - Ethereum, Polygon, BNB Chain, Arbitrum, Optimism, Base, Avalanche, and more
* **Solana** - Full support for Solana wallet signatures
***
## Wallet Integrations
Auth API works with popular wallet connection libraries:
* MetaMask
* WalletConnect
* RainbowKit
* Coinbase Wallet
* Web3Auth
* Magic.Link
* Particle Network
***
## Common Use Cases
Auth API is commonly used for:
* **dApp Authentication**\
(secure login without passwords)
* **Gated Content**\
(verify wallet ownership before granting access)
* **NFT Verification**\
(prove ownership for holder-only features)
* **Multi-Wallet Accounts**\
(link multiple wallets to a single user profile)
* **Cross-Chain Identity**\
(unified identity across EVM and Solana)
***
## Limitations
Auth API currently does **not** support:
* **EIP-1271 Signatures** - Smart contract wallet signatures (e.g., Safe, Argent) are not supported. Only EOA (Externally Owned Account) wallets can authenticate.
***
## Get Started
* [How to Authenticate Users with MetaMask](/get-started/tutorials/auth-api/authenticate-users-with-meta-mask)
* [How to Authenticate Users with RainbowKit](/get-started/tutorials/auth-api/authenticate-users-with-rainbow-kit)
* [How to Authenticate Users with WalletConnect](/get-started/tutorials/auth-api/authenticate-users-with-wallet-connect)
* [How to Authenticate Users with Coinbase Wallet](/get-started/tutorials/auth-api/authenticate-users-with-coinbase-wallet)
* [How to Authenticate Users with Web3Auth](/get-started/tutorials/auth-api/authenticate-users-with-web3-auth)
* [How to Authenticate Users with Magic.Link](/get-started/tutorials/auth-api/authenticate-users-with-magic-link)
# Product updates
Source: https://docs.moralis.com/changelog
New releases and improvements
**October 21, 2026**
## Tempo is now supported
Tempo mainnet is now supported across the Moralis Data API, Streams, Datashare and Data Feeds.
| Detail | Value |
| - | - |
| Chain ID | `0x1079` (4217) |
| Chain values | `tempo`, `0x1079` |
| Native token | None. Tempo has no native gas token, so balances and transfers are TIP-20 tokens |
**Data API**
Tempo supports every Data API feature except DeFi positions and NFT trades, sale prices and floor prices:
* **Wallets:** token balances, transaction history, net worth and profitability
* **Tokens:** metadata, transfers, owners and prices
* **NFTs:** NFTs by wallet, collection metadata and transfers
* **Blockchain:** blocks, transactions and [internal transactions](/data-api/data-features/data-enrichment/internal-transactions)
* **Entities:** labelled addresses and entities
Use `tempo` or `0x1079` as the `chain` or `chainAlias` value, or pass it through the `chains` query parameter on multi-chain endpoints.
**Streams**
Create Tempo streams with chain ID `0x1079` for token and NFT activity, contract events, internal transactions and transaction data. Streams requires the hex chain ID; the `tempo` alias is not accepted. See [Streams supported chains](/streams/supported-chains).
**Data Feeds**
[Data Feeds](/data-feeds/overview) index Tempo into your own infrastructure, from raw blocks through to decoded, USD-valued events, with no indexing layer to build or run.
* **Full history and live data:** backfill from genesis, tail the chain head in realtime, or do both in [hybrid mode](/data-feeds/concepts/modes). Reorgs near the tip are [corrected automatically](/data-feeds/concepts/reorgs).
* **Raw chain data:** block headers, transactions, receipts and every event log through the [`block` array](/data-feeds/concepts/the-block-array), for indexing any contract or event signature.
* **Decoded activity:** token transfers with post-transfer balances, NFT transfers, swaps, token prices and token metadata, in the same unified schema as every other chain.
* **Ready-made [templates](/data-feeds/templates/overview):** wallet history, token balances (current and historical), token holders, approvals, token transfers, prices and stats, swaps by wallet, token or pair, pair OHLCV and reserves, NFTs by wallet, NFT owners, NFT transfers and collection metadata, and contract logs.
* **Use-case bundles:** [accounting](/data-feeds/use-cases/accounting), [portfolio tracking](/data-feeds/use-cases/portfolio-tracking), [token analytics](/data-feeds/use-cases/token-analytics), [compliance and AML](/data-feeds/use-cases/compliance-aml) and [event indexing](/data-feeds/use-cases/event-indexing).
* **Your choice of destination:** land tables in [ClickHouse, Postgres or MySQL](/data-feeds/concepts/destinations), consume through [Kafka, RabbitMQ or SQS](/data-feeds/access-methods/streaming)-compatible clients, or pull with [REST or Arrow Flight](/data-feeds/access-methods/direct-reads).
Tempo has no native gas token, so native balance templates don't apply, and the NFT Trades template stays empty because no NFT marketplace trades have happened on Tempo.
**Datashare**
Tempo token transfers, NFT transfers and swaps are available as bulk historical exports through [Datashare](/datashare/supported-chains).
[View all supported chains →](/data-api/supported-chains)
**September 30, 2026**
## Robinhood Chain is now supported
Robinhood Chain mainnet is now supported across Moralis Data APIs and Streams.
You can query Robinhood Chain for blocks, transactions, token prices, OHLCV data, DEX swaps, wallet token balances, and wallet transaction history, or use Streams to subscribe to realtime onchain events.
Moralis indexing covers the chain from its genesis block on 30 April 2026.
| Detail | Value |
| - | - |
| Chain ID | `0x1237` (4663) |
| Chain values | `robinhood`, `0x1237` |
| Native token | ETH |
**Supported Data API capabilities**
* **Blockchain:** blocks and transactions
* **Token prices:** current price, [price sparkline](/data-api/universal/token/price/token-price-sparkline), [price timeseries](/data-api/universal/token/price/token-price-timeseries)
* **Market data:** OHLCV candlesticks, swaps by pair, swaps by token
* **Wallets:** token balances and transaction history
For chain-specific endpoints, use `robinhood` or `0x1237` as the `chainAlias`.
For wallet token balances and wallet transaction history, pass Robinhood Chain through the `chains` query parameter.
**Streams**
Robinhood Chain is also supported in [Moralis Streams](/streams/supported-chains). Use chain ID `0x1237` to create Robinhood Chain streams for native transfers, ERC-20 and NFT activity, contract events, and transaction data. Streams requires the hex chain ID; the `robinhood` alias is not accepted.
**Internal transactions**
Internal transactions are not supported on Robinhood Chain.
Internal native transfers and trace-level contract deployments created through `CREATE` or `CREATE2` are therefore not included. Top-level contract creation is still reported through `contractAddress`.
See [Internal Transactions](/data-api/data-features/data-enrichment/internal-transactions).
[View all supported chains →](/data-api/supported-chains)
**September 28, 2026**
## Sei Testnet Support Ends October 2, 2026
Moralis is removing support for **Sei Testnet** (`sei-testnet` / `0x530`) on **Friday, October 2, 2026**, across Data API, Streams, and Datashare. After that date, requests targeting Sei Testnet will return an unsupported-chain error.
**Sei mainnet is not affected.** Sei (`sei` / `0x531`) remains fully supported across Data API, Streams, and Datashare, and no action is needed for mainnet integrations.
If you use Sei Testnet for development or testing, switch to one of our other [supported testnets](/data-api/supported-chains) (such as Ethereum Sepolia, Base Sepolia, or Arbitrum Sepolia) before October 2, 2026, and update or delete any Streams configured for `0x530`.
[Reach out to the team](https://admin.moralis.com/) (via chat widget) if you need help migrating.
**September 28, 2026**
## Moralis Data Feeds
[Moralis Data Feeds](/data-feeds/overview) is now available: the blockchain data your application needs, delivered straight into your own database. Backfill history, stay in sync block by block, and query the data directly in your own stack.
**What you can do:**
* **Start from a template or build from scratch**: use [pre-built templates](/data-feeds/templates/overview) for wallet history, token balances, swaps, NFT activity, contract logs, and more.
* **Choose your chain and datasets**: work across supported EVM networks, Solana, and Bitcoin, then select the blockchain data relevant to your application.
* **Transform data with SQL**: filter rows, select fields, and shape the output before it reaches your destination.
* **Real-time + historical**: stream new blockchain data as new blocks arrive, or start from an earlier block or date to replay history. See [Modes](/data-feeds/concepts/modes) and [History and Backfill](/data-feeds/concepts/history-and-backfill).
* **Connect your own stack**: send data to PostgreSQL, MySQL, ClickHouse, Kafka, AMQP, SQS, REST API, or Arrow Flight [destinations](/data-feeds/concepts/destinations).
* **Build with Alpha**: use the AI co-pilot to configure and build Data Feeds from natural-language instructions.
**Who it’s for:** wallets, trading platforms, analytics products, exchanges, accounting and compliance tools, and teams that need persistent blockchain datasets inside their own infrastructure. Browse [use cases](/data-feeds/use-cases/portfolio-tracking) for complete workflows.
**Pricing:** All paid Moralis plans include real-time Data Feeds usage, with a monthly budget based on your plan. Historical backfill is billed separately, with cost based on the amount of historical data processed.
**APIs give you ready-made answers. Data Feeds gives you the dataset to build on.**
[Get started with the quickstart →](/data-feeds/migration/quickstart)
[Compare Data Feeds and the REST API →](/data-feeds/concepts/data-feeds-vs-the-rest-api)
**August 26, 2026**
## Moonbeam, Moonriver and Lisk Support Ends September 25, 2026
Moralis is removing support for **Moonbeam** (`0x504`), **Moonriver** (`0x505`), and **Lisk** (`0x46f`) on **September 25, 2026**, across all products: Data API, Streams, RPC Nodes, and Datashare.
GLMR and MOVR have already migrated to Base ([Moonbeam](https://moonbeam.network/news/moonbeam-strategic-update-moonbeam-network-relaunches-on-base/), [Moonriver](https://moonbeam.network/news/moonriver-strategic-update-movr-is-migrating-to-base/)), and both original networks stopped producing new blocks on August 1, 2026. Lisk is winding down the Lisk Chain as part of [the next chapter for Lisk](https://lisk.com/blog/posts/introducing-the-new-lisk/). In both cases the activity has moved to chains Moralis already supports in full.
**Timeline**
| Date | State |
| - | - |
| August 1, 2026 | Moonbeam and Moonriver stopped producing new blocks |
| September 25, 2026 | Moralis removes all three chains. Requests targeting them return an unsupported-chain error |
| October 31, 2026 | Lisk's deadline to bridge assets from the Lisk Chain to Ethereum. Bridging takes at least 7 days |
| November 30, 2026 | Final shutdown of the Lisk Chain and its related infrastructure |
**Where to point your integration**
| Removed chain | Migrate to |
| - | - |
| Moonbeam (`moonbeam` / `0x504`) | Base (`base` / `0x2105`) |
| Moonriver (`moonriver` / `0x505`) | Base (`base` / `0x2105`) |
| Lisk (`lisk` / `0x46f`) | Ethereum (`eth` / `0x1`) or Base (`base` / `0x2105`) |
For RPC Nodes, swap the path segment, for example `https://site1.moralis-nodes.com/base/`. Your API key, authentication, request shapes, and response formats do not change. Only the target chain does.
GLMR and MOVR use new contracts on Base. LSK is unchanged on Ethereum, so if you hold it there or on an exchange, no action is needed.
| Token | Contract address on Base |
| - | - |
| GLMR | `0xb3846fd356c2149ee8d30b0449088dc74e265459` |
| MOVR | `0x43fEB74608334DDa8c1a6500D185cFC3Ea962B83` |
**What changes on September 25, 2026**
* **Data API:** wallet, token, NFT, DeFi, and price endpoints reject `moonbeam`, `0x504`, `moonriver`, `0x505`, `lisk`, and `0x46f`. This applies to the `chain` query parameter on Deep Index endpoints and to the `chains` array on Universal API endpoints, so remove these values from your chain lists rather than relying on the rest of a multi-chain request still resolving.
* **RPC Nodes:** the `moonbeam`, `moonriver`, and `lisk` paths on `site1.moralis-nodes.com` and `site2.moralis-nodes.com` stop resolving, including archive reads at historical block heights (`eth_getBlockByNumber`, `eth_getLogs`, `eth_getBalance` with a past block tag).
* **Streams:** any stream that still lists `0x504`, `0x505`, or `0x46f` in `chainIds` is invalid. List your streams with [Get streams](/streams/api-reference/streams/get-streams), then either [update the stream](/streams/api-reference/streams/update-stream) to a supported chain or [delete it](/streams/api-reference/streams/delete-stream).
* **Datashare:** all three chains are removed from the available datasets.
* **Docs:** the Moonbeam and Lisk RPC reference pages and their rows in the supported-chains tables are removed from the navigation.
Lisk Sepolia (`0x106a` / 4202) was already removed in the [June 15, 2026 testnet wind-down](#testnets-removed).
**Export your history before September 25, 2026**
Historical data stays queryable until then. Paginate each call with `cursor` until the response returns an empty `result` and no `cursor`.
| Data | Endpoint |
| - | - |
| Full wallet history, decoded | [Wallet History](/data-api/evm/wallet/wallet-history) |
| ERC-20 transfers | [Wallet Token Transfers](/data-api/evm/wallet/token-transfers) |
| NFT transfers | [Wallet NFT Transfers](/data-api/evm/wallet/nft-transfers) |
| Closing token balances | [Wallet Token Balances](/data-api/evm/wallet/token-balances) |
**The Lisk Chain runs past our removal date**
Moralis removes Lisk ahead of Lisk's own timeline. The Lisk Chain keeps producing blocks and its infrastructure keeps running as normal until November 30, 2026, so if you need chain access after September 25, 2026, point your integration at Lisk's own endpoints. Lisk's [documentation](https://docs.lisk.com/) stays available and user-facing support has moved to [support.lisk.com](https://support.lisk.com/).
For a walkthrough of the Moonbeam and Moonriver migration, watch [Moonbeam and Moonriver Migration to Base](https://www.youtube.com/watch?v=63UJ4EaqfUM).
If this change affects your integration or you need additional time, [reach out to the team](https://admin.moralis.com/) (via chat widget).
**August 11, 2026**
## Moonbeam and Moonriver API Deprecation: Migrate to Base
> [!NOTE]
>
> **Updated August 26, 2026.** Both chains stopped producing new blocks on August 1, 2026, so there has been no real-time data to serve since then. Historical data stayed available and is now scheduled for removal on **September 25, 2026**. See [Moonbeam, Moonriver and Lisk Support Ends September 25, 2026](#moonbeam-moonriver-and-lisk-support-ends-september-25-2026) for the current timeline.
Moralis API support for **Moonbeam** (`0x504`) and **Moonriver** (`0x505`) is being removed. Both chains stopped producing new blocks on **August 1, 2026**, and historical support for both is removed on **September 25, 2026**.
Following [Moonbeam's network relaunch on Base](https://moonbeam.network/news/moonbeam-strategic-update-moonbeam-network-relaunches-on-base/), GLMR has fully migrated from the Moonbeam Polkadot parachain to Base as a 1:1 ERC-20 token, and [MOVR has migrated to Base](https://moonbeam.network/news/moonriver-strategic-update-movr-is-migrating-to-base/) on the same terms. Holder bridging closed on July 31, 2026, both original networks stopped producing new blocks on August 1, 2026, and both have wound down.
**What's changing:**
* **Data API:** wallet, token, NFT, DeFi, and price endpoints no longer return new Moonbeam or Moonriver data, since neither chain has produced a block since August 1, 2026. Historical records up to the final block are still returned until September 25, 2026.
* **RPC Nodes:** the Moonbeam and Moonriver RPC endpoints (`https://site1.moralis-nodes.com/moonbeam/` and `.../moonriver/`) still resolve and serve the final state of each chain. They are removed on September 25, 2026, along with their documentation.
* **Streams:** existing Moonbeam and Moonriver streams no longer emit webhook notifications, since there are no new blocks, and should be deleted from your workspace.
**What you need to do:** migrate your integration to Moralis Base endpoints. GLMR, MOVR, and all associated activity are now tracked on Base.
* Update your `chain` parameter to `base` (`0x2105`). For RPC Nodes, switch the path segment to `https://site1.moralis-nodes.com/base/`.
* Use the new token contracts on Base:
| Token | Contract address on Base |
| - | - |
| GLMR | `0xb3846fd356c2149ee8d30b0449088dc74e265459` |
| MOVR | `0x43fEB74608334DDa8c1a6500D185cFC3Ea962B83` |
**Not affected:** your API key, authentication, request shapes, and response formats. Base is already fully supported across the Data API, RPC Nodes, and Streams. Only the target chain changes.
Export anything you still need from Moonbeam or Moonriver before September 25, 2026 to avoid errored responses. Questions? [Reach out to the team](https://admin.moralis.com/) (via chat widget).
**July 31, 2026**
## Token Holders and Solana Token Discovery Endpoints Removed
As [announced on June 30](#token-holders-and-solana-token-discovery-endpoints-sunsetting), the following endpoints have now been **removed** as of July 31, 2026. Requests to these endpoints return a 404. If you are still calling any of them, migrate to the replacements below.
**Solana token holders:**
* `GET /token/{network}/holders/{address}` — migrate to [Token Holders](/data-feeds/templates/token/token-holders)
* `GET /token/{network}/{address}/top-holders` — migrate to [Token Holders](/data-feeds/templates/token/token-holders)
* `GET /token/{network}/holders/{address}/historical` — migrate to [Historical Balances](/data-feeds/templates/token/historical-balances)
**EVM token holders (historical only):**
* `GET /erc20/{tokenAddress}/holders/historical` — migrate to [Historical Balances](/data-feeds/templates/token/historical-balances)
The other two EVM token holder endpoints, [`GET /erc20/{tokenAddress}/holders`](/data-api/evm/token/holders/token-holder-stats) (holder stats) and [`GET /erc20/{token_address}/owners`](/data-api/evm/token/holders/token-holders) (token holders), **remain fully supported**.
**Solana token discovery (`/token/{network}/exchange/*`):**
* `GET /token/{network}/exchange/{exchange}/new`
* `GET /token/{network}/exchange/{exchange}/bonding`
* `GET /token/{network}/exchange/{exchange}/graduated`
* `GET /token/{network}/{address}/bonding-status`
All four are served by [Token Bonding Status](/data-feeds/templates/token/token-bonding-status).
The API reference pages for these endpoints have been removed from the navigation, and their entries are gone from the OpenAPI sources so generated docs and API clients no longer advertise them.
If you need help identifying the right replacement, [reach out to the team](https://admin.moralis.com/) (via chat widget).
**July 21, 2026**
## Cross-Chain Token Balances
One of our most popular Deep Index endpoints, **Token Balances**, is now available on the Universal API as **Cross-Chain Token Balances**. A single request returns a wallet's token balances across multiple chains - no more one-request-per-chain plus client-side stitching.
**What changed vs. the legacy endpoint:**
| | Legacy ([getWalletTokenBalancesPrice](https://deep-index.moralis.io/api-docs-2.2/#/Wallets/getWalletTokenBalancesPrice)) | New ([getTokenBalances](https://api.moralis.com/api#/Wallets/getTokenBalances)) |
| - | - | - |
| Scope | Single chain per request | Multi-chain in one request |
| Chain coverage | EVM | EVM + Bitcoin (Solana coming) |
| Filters | Spam exclusion, unverified contracts, liquidity thresholds, etc. | All preserved |
| Pricing data | Included | Included, plus optional `includeSparklines` and `includePnl` enrichment per token |
Everything customers already rely on - spam filtering, unverified contract exclusion, liquidity thresholds, USD pricing - works exactly the same. The only difference is you can now ask for multiple chains in a single call.
**Who it's for:** wallets, exchanges, portfolio dashboards, tax tools, and AI agents that need a wallet's full multi-chain holdings without firing one request per chain.
**Why it matters:**
* **Fewer requests, simpler integration** - one call instead of N (where N = chains your users hold assets on)
* **Faster portfolio views** - no client-side stitching across responses
* **Same trusted filters** - spam, unverified, and low-liquidity controls carry over unchanged, so existing implementations port cleanly
**Roadmap:** covers EVM and Bitcoin (address or xpub) today. Coming next:
* **Solana** - Solana token balances brought into the Universal API (we already offer Solana token balances as a dedicated API; this unifies them into the same multi-chain request structure)
The end state: one endpoint, one request shape, balances across EVM, Bitcoin, and Solana wallets.
[Try the new endpoint →](https://api.moralis.com/api#/Wallets/getTokenBalances)
**July 20, 2026**
## Data Feeds Early Access
Data Feeds is now available in **early access**. Instead of calling APIs per request, Data Feeds continuously syncs Moralis data (wallet history, balances, prices, swaps, holders, and more) directly into your own ClickHouse, Postgres, or MySQL database.
**What's included:**
* [Overview and concepts](/data-feeds/overview): how Data Feeds works, modes, destinations, history and backfill, and reorg handling.
* [Quickstart](/data-feeds/migration/quickstart): run your first sink with the starter pack and see data land in minutes.
* [Data Feed Templates](/data-feeds/templates/overview): 26 pre-built blueprints that reconstruct our most popular endpoints across Wallet, Token, Price, DeFi, NFT, and Blockchain APIs.
* [Migration guides](/data-feeds/migration/overview): field-by-field mappings from the Moralis REST API to templates, including an [endpoint lookup](/data-feeds/migration/endpoints).
* [Use cases](/data-feeds/use-cases/portfolio-tracking): portfolio tracking, accounting, token analytics, trading and charting, NFT marketplaces, compliance, and event indexing.
Early access is limited. [Request access](https://admin.moralis.com/data-feeds) to get started.
**July 18, 2026**
## Token Price Timeseries & Sparkline
Two chart-ready price endpoints are now available on the Universal API, covering native coins and tokens across EVM (Ethereum, Base, BNB, Polygon, Arbitrum, Linea, and more), Solana, and Bitcoin - through a single request shape.
* **[Token Price Timeseries](/data-api/universal/token/price/token-price-timeseries)** ([getTokenPriceTimeSeries](https://api.moralis.com/api#/Tokens/getTokenPriceTimeSeries)) - historical price points for a token at your chosen `interval` (`5m` up to `monthly`), with optional forward-fill for gap-free line charts.
* **[Token Price Sparkline](/data-api/universal/token/price/token-price-sparkline)** ([getTokenPriceSparkline](https://api.moralis.com/api#/Tokens/getTokenPriceSparkline)) - a fixed number of price points for a selected `range` (`24h` to `1y`) - drop the response directly into a sparkline widget in token lists, watchlists, or portfolio rows, no resampling needed.
**Who it's for:** wallets, portfolio dashboards, token screeners, and trading UIs that need price charts without building candle-aggregation pipelines.
[Try the new endpoints →](https://api.moralis.com/api#/Tokens)
**July 15, 2026**
## Multi-Chain PnL Endpoints
Wallet profitability is now available on the Universal API as a dedicated **[PnL API](/data-api/universal/pnl/overview)** - three new endpoints that replace the legacy single-chain Deep Index profitability endpoints with **multi-chain requests**:
| New (Universal) | Replaces (Deep Index) |
| - | - |
| [Wallet PnL](/data-api/universal/pnl/wallet-pnl) - per-token realized/unrealized PnL, ROI, volumes, and trade counts across multiple chains | [Wallet PnL Breakdown](/data-api/evm/wallet/wallet-pnl) |
| [Wallet PnL Summary](/data-api/universal/pnl/wallet-pnl-summary) - aggregated wallet-level totals including win rate | [Wallet PnL Summary](/data-api/evm/wallet/wallet-pnl-summary) |
| [Top Traders by Token](/data-api/universal/pnl/top-traders) - top-trader leaderboard for a token, ranked by a selectable PnL metric | [Top Traders by Token](/data-api/evm/token/signals/top-traders) |
**What's new vs. the legacy endpoints:**
* **Multi-chain in one call** - pass a list of `chains` (or `mainnets`) instead of one request per chain
* **Broader chain coverage** - Ethereum, Base, BNB, Polygon, Optimism, Avalanche, and Pulse
* **Quality filters** - `excludeLowLiquidity`, `minVolumeUsd`, and `minTradeCount` cut noise from the results
* **Flexible time ranges** - a `period` shorthand (`7d`, `30d`, `all`) or explicit `fromTimestamp`/`toTimestamp`
* **Selectable ranking** - sort top traders by realized, unrealized, or total PnL, volume, or trade count
**Who it's for:** portfolio trackers, trading platforms, copy-trading products, and token analytics surfacing smart-money activity.
[Try the new endpoints →](https://api.moralis.com/api#/PnL)
**June 30, 2026**
## Token Holders and Solana Token Discovery Endpoints Sunsetting
> [!NOTE]
>
> **These endpoints were removed on July 31, 2026.** See [Token Holders and Solana Token Discovery Endpoints Removed](#token-holders-and-solana-token-discovery-endpoints-removed) for the replacements.
The following endpoints are now deprecated and will be removed on **July 31, 2026**. If you rely on any of them, please migrate before that date. [Reach out to the team](https://admin.moralis.com/) (via chat widget) if you need help identifying replacements.
**Solana token holders (all sunset):**
* `GET /token/{network}/holders/{address}` — Token holder metrics
* `GET /token/{network}/{address}/top-holders` — Top token holders
* `GET /token/{network}/holders/{address}/historical` — Historical token holders
**EVM token holders (historical only):**
* `GET /erc20/{tokenAddress}/holders/historical` — Historical token holders
The other two EVM token holder endpoints — [`GET /erc20/{tokenAddress}/holders`](/data-api/evm/token/holders/token-holder-stats) (holder stats) and [`GET /erc20/{token_address}/owners`](/data-api/evm/token/holders/token-holders) (token holders) — **remain fully supported**.
**Solana token discovery (`/token/{network}/exchange/*`):**
* `GET /token/{network}/exchange/{exchange}/new` — New tokens by exchange
* `GET /token/{network}/exchange/{exchange}/bonding` — Bonding tokens by exchange
* `GET /token/{network}/exchange/{exchange}/graduated` — Graduated tokens by exchange
* `GET /token/{network}/{address}/bonding-status` — Token bonding status
**June 30, 2026**
## Token Score Becoming EVM-Only (Solana Support Sunsetting)
Token Score is becoming an **EVM-only** feature. Solana support for Token Score is now deprecated and will be removed on **July 31, 2026**. Token Score remains fully supported on all EVM chains — nothing changes there.
**What's changing on Solana:**
* The Token Score and Historical Token Score endpoints — [`GET /tokens/{tokenAddress}/score`](/data-api/universal/token/score/token-score) and [`GET /tokens/{tokenAddress}/score/historical`](/data-api/universal/token/score/token-score-timeseries) — will no longer return data for Solana tokens. They remain available for EVM.
* The embedded `score` field is being removed from Solana token responses: Solana token price, token metadata, and wallet token balances.
The Solana `score` field is now marked deprecated in the API reference and will stop being returned on July 31, 2026. Remove any code that reads it before then. EVM Token Score — including the `securityScore` field on EVM token price — is unaffected.
[Reach out to the team](https://admin.moralis.com/) (via chat widget) if you need help.
**June 15, 2026**
## Testnets Removed
As of June 15, 2026, the following testnets are no longer supported across Moralis products (Data API, Streams, RPC Nodes, and Datashare). Requests targeting these chains will no longer return data.
* Chiliz Testnet (`0x15b32` / 88882)
* Gnosis Chiado (`0x27d8` / 10200)
* Linea Sepolia (`0xe705` / 59141)
* Moonbase (`0x507` / 1287)
* Lisk Sepolia (`0x106a` / 4202)
The corresponding mainnets (Chiliz, Gnosis, Linea, Moonbeam, and Lisk) remain fully supported.
API reference sources have been refreshed so generated endpoint docs no longer advertise these retired testnets.
If you're impacted, we recommend switching to one of our other [supported testnets](/streams/supported-chains) (such as Ethereum Sepolia, Base Sepolia, or Arbitrum Sepolia) for your testing needs.
**June 4, 2026**
## Cortex API and legacy Data API Endpoints Removed
As [announced on May 5](#cortex-api-and-legacy-data-api-endpoints-sunsetting), the following endpoints and APIs have now been **removed** as of June 4, 2026. Requests to these endpoints will return an error. If you are still calling any of them, migrate to the replacements below.
**Cortex API:**
* `POST /chat` — migrate to [Onchain Skills](/data-api/onchain-skills/overview), which replaces Cortex as our AI interface for Moralis data.
**Discovery endpoints (`/discovery/*`):**
* `POST /discovery/tokens`
* `GET /discovery/token` — migrate to the [Token Search API](/data-api/universal/token/search/token-search).
* `GET /discovery/tokens/rising-liquidity`
* `GET /discovery/tokens/buying-pressure`
* `GET /discovery/tokens/solid-performers`
* `GET /discovery/tokens/experienced-buyers`
* `GET /discovery/tokens/risky-bets`
* `GET /discovery/tokens/blue-chip`
* `GET /discovery/tokens/top-gainers`
* `GET /discovery/tokens/top-losers`
* `GET /discovery/tokens/trending`
**Volume endpoints (`/volume/*`):**
* `GET /volume/chains`
* `GET /volume/categories`
* `GET /volume/timeseries`
* `GET /volume/timeseries/{categoryId}`
**Sniper endpoints (EVM and Solana):**
* `GET /pairs/{address}/snipers` (EVM)
* `GET /token/{network}/pairs/{pairAddress}/snipers` (Solana)
**ERC20 endpoints (EVM):**
* `GET /erc20/exchange/{exchangeName}/new`
* `GET /erc20/exchange/{exchangeName}/bonding`
* `GET /erc20/exchange/{exchangeName}/graduated`
* `GET /erc20/{tokenAddress}/bondingStatus`
* `GET /erc20/{address}/stats`
* `GET /erc20/{token_address}/pairs/stats` — migrate to [`GET /tokens/{tokenAddress}/analytics`](/data-api/universal/token/analytics/token-analytics)
* `GET /erc20/metadata/symbols` — migrate to [`GET /tokens/search`](/data-api/universal/token/search/token-search)
**Market data endpoints (`/market-data/*`):**
* `GET /market-data/erc20s/top-tokens`
* `GET /market-data/erc20s/top-movers`
* `GET /market-data/nfts/top-collections`
* `GET /market-data/nfts/hottest-collections`
* `GET /market-data/global/market-cap`
* `GET /market-data/global/volume`
If you need help identifying the right replacement for a removed endpoint, [reach out to the team](https://admin.moralis.com/) (via chat widget).
**June 1, 2026**
## 11 New Solana DEXes
We've expanded Solana DEX coverage with **11 newly indexed DEX programs**, powering token pairs, swaps, prices, OHLC, and other DEX-derived features across the Data API.
**Newly supported:**
* **BisonFi**
* **HumidiFi**
* **Phoenix**
* **Manifest**
* **Tessera V**
* **SolFi**
* **ZeroFi**
* **GoonFi V1** (dormant) and **GoonFi V2** (active)
* **Saber**
* **PancakeSwap**
For these protocols, swap data (and therefore prices) is available from **June 1, 2026** onwards. Full historical coverage is coming soon. All other Solana DEXes have full history.
See the full list of program IDs on the [Supported DEXes](/data-api/data-features/integrations/supported-dexs#solana-dex-support) page.
**June 1, 2026**
## Sunsetting Zeta Chain RPC
As of June 1, 2026, Moralis is sunsetting RPC node support for Zeta Chain. The Zetachain and Zetachain Testnet RPC endpoints are no longer available, and their documentation has been removed.
If you rely on Zeta Chain RPC, please migrate to an alternative provider. All other supported chains are unaffected.
**May 29, 2026**
## Fantom Chain Sunsetting
Fantom mainnet support is being removed across all Moralis APIs on **May 29, 2026**. Fantom Opera testnet has already been removed. The Fantom Opera network is winding down as a legacy chain, and we're retiring our integration in line with the broader ecosystem shift.
**What's changing:**
* **Data API** — wallet, token, NFT, DeFi, and price endpoints no longer return Fantom (`0xfa`) data. Requests passing `fantom` or chain id `0xfa` will return an error.
* **RPC Nodes** — Fantom RPC node endpoints are no longer available, and their documentation has been removed.
* **Streams** — existing Fantom streams will stop emitting webhook notifications and should be deleted from your workspace.
* **Testnet** — Fantom Opera testnet was removed ahead of mainnet as part of this wind-down.
**Why:** Fantom Opera has transitioned into a legacy chain with declining activity following the broader migration to Sonic. Maintaining a dedicated integration is no longer justified by usage, so we're consolidating support onto actively maintained networks.
**What to do:**
* Remove any `fantom` / `0xfa` references from your API requests, SDK calls, and stream configurations before May 29 to avoid errored responses.
* If you still rely on Fantom data, migrate to an alternative provider, or move your workloads to one of the [supported chains](/data-api/supported-chains).
All other supported chains are unaffected.
**May 27, 2026**
## Bitcoin Data API
Full Bitcoin coverage now lands on the Moralis Universal API — raw blocks and transactions, market prices with sparklines, address history and balances, plus native xpub tooling. Every endpoint is the same Universal endpoint EVM and Solana developers already use; just pass `bitcoin` as the chain.
**What's new:**
* **Raw data** — raw blocks and raw transactions for teams working directly with onchain data
* **Market data** — current BTC price, full historical time series, and chart-ready price sparklines for chart UIs
* **Address-level data** — transaction history and token balances for any Bitcoin address
* [**Xpub tooling**](/data-api/bitcoin/utility/overview) — pass a Bitcoin address **or** an xpub to the wallet endpoints, plus a new [utility endpoint](/data-api/bitcoin/utility/addresses-from-xpub) to enumerate every derived address from a given xpub
**Address or xpub inputs:** the wallet endpoints accept either a Bitcoin address or an xpub directly, so the API slots into whatever shape your wallet or backend already uses.
```bash theme={null}
# Address input
GET /v1/wallets/bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq/tokens?chains=bitcoin
# Xpub input — same endpoint, derives addresses server-side
GET /v1/wallets/{xpub}/tokens?chains=bitcoin
```
This brings the full Bitcoin data lifecycle under one consistent surface — replacing the block explorer, price feed, custom indexer, xpub derivation library, and chart caching layer teams used to stitch together — with the same auth, SDKs, pricing, and rate limits as the rest of Moralis.
**Use cases:** Bitcoin wallets, custody platforms, block explorers, BTC analytics, and multi-chain platforms extending their Bitcoin coverage.
See the [Bitcoin Data API overview](/data-api/bitcoin/overview) for the full endpoint list and schemas, or start with the [Bitcoin Quickstart](/get-started/tutorials/data-api/bitcoin/bitcoin-quickstart).
[Explore the Bitcoin Data API →](/data-api/bitcoin/overview)
**May 26, 2026**
## Three New Solana DeFi Protocols
Three top-tier Solana DeFi protocols are now supported through our existing DeFi endpoints, taking total Solana DeFi coverage to **10 protocols** - roughly 90% of Solana DeFi TVL, including all of the top protocols by TVL (Jupiter, Kamino, Sanctum, and Raydium).
**Newly supported:**
* **Jupiter Perpetual Exchange** - derivatives on the dominant Solana DEX aggregator (Jupiter Lend was already supported)
* **Kamino Lend** - the second-largest protocol on Solana by TVL
* **Sanctum** - validator liquid staking; the third-largest protocol on Solana by TVL
These plug into the existing [Solana DeFi endpoints](/data-api/solana/defi/overview), so anyone already pulling Solana DeFi data picks them up automatically - no code changes required.
**New utility endpoint:** `GET /v1/defi/protocols` returns the full list of supported DeFi protocols for a given chain, so you can query coverage programmatically and keep your integration in sync. See [DeFi Protocols](/data-api/data-features/integrations/defi-protocols).
[Explore the Solana DeFi API →](/data-api/solana/defi/overview)
**May 14, 2026**
## Mempool Notifications for Bitcoin Streams
Bitcoin Streams now emit webhook notifications for **unconfirmed transactions** as soon as they hit the mempool — no need to wait for block inclusion.
**What's new:**
* **Pre-confirmation delivery** — matching transactions fire a webhook the moment they are broadcast to the mempool
* **Same payload shape** as a confirmed-block webhook, with sentinel fields on the `block` object marking the delivery as mempool:
* `block.height` → `"0"`
* `block.hash` → `"mempool"`
* `confirmed` → `false`
* **`vin` and `vout` addresses both populated** in mempool payloads, so a watched address triggers a match whether it is sending or receiving
* **Xpub-derived addresses fully supported**
**Behavior to plan around:**
* Each mempool transaction is delivered **at most once per stream**
* The mempool delivery has **no follow-up** — the regular confirmed-block stream (`confirmed: false` then `confirmed: true`) handles in-block and reorg-safe deliveries for the same `txid`
* Mempool transactions are **not guaranteed to confirm** — they can be replaced (RBF), evicted, or expire on low fee. Treat them as pending, not settled
**Use cases:** show users a pending balance the instant a tx is broadcast, trigger UX flows on payment broadcast instead of confirmation, mempool monitoring, RBF detection, fee analytics, and MEV / arbitrage signals.
No new endpoint, parameter, or schema. Existing Bitcoin streams pick this up automatically — branch on `block.hash === "mempool"` in your webhook handler to separate mempool events from confirmed-block events. See the [Mempool Notifications](/streams/bitcoin-streams#mempool-notifications) section for the full payload and handler patterns.
[Explore Bitcoin Streams →](/streams/bitcoin-streams)
**May 7, 2026**
## Bitcoin Streams
Moralis Streams now extends to Bitcoin mainnet. Define a stream, attach the addresses or xpubs you want to watch, and receive real-time webhook deliveries within seconds of a block being mined - no node, no polling, no missed blocks.
**What's new:**
* **Bitcoin mainnet support** on the same Streams developer model used for EVM and Solana
* **Dual-phase notifications** - matched transactions fire a webhook in the mempool (unconfirmed) and again on block confirmation, so you can mark deposits `pending` then `confirmed` from the same stream
* **All address formats supported** - P2PKH (legacy `1...`), P2SH (SegWit-wrapped `3...`), and Bech32 native SegWit (`bc1q...`)
* **Xpub support** - attach an extended public key and Moralis derives and monitors its addresses automatically, ideal for HD wallets
* **Automatic retries** until your endpoint returns HTTP 200
**Monitoring modes available at launch:**
* `addresses` — watch specific Bitcoin addresses
* `xpub` — derive and monitor addresses from an extended public key
* `allAddresses` — firehose mode: receive every Bitcoin transaction
**Use cases:** exchange deposit detection (mempool → confirmed lifecycle), cold wallet surveillance, mining pool payout tracking, and real-time treasury monitoring for corporate or DAO-held BTC.
A few Bitcoin-specific behaviors to plan around: input `address` and `value` fields are not populated (inbound detection only), output values are BTC decimals rather than satoshis, and `isCoinbase` should be detected via heuristic. See the [Bitcoin Streams docs](/streams/bitcoin-streams) for the full payload structure and processing patterns.
[Explore Bitcoin Streams →](/streams/bitcoin-streams)
**May 5, 2026**
## Solana Streams
Moralis Streams now extends to Solana mainnet. Define a stream, set filters, and receive real-time webhook deliveries the moment matching transactions land in a slot - no node, no polling, no missed slots.
**What's new:**
* **Solana mainnet support** on the same Streams developer model used for EVM
* **Pre / post token balances** included in every payload, so you can compute exact SPL token deltas without replaying instructions
* **Inner instructions included**, so you can trace nested behavior across Cross-Program Invocations (CPIs) directly from the payload
* **Automatic retries** until your endpoint returns HTTP 200
**Filters available at launch:**
* `addresses` — match transactions where any `accountKey` in the transaction matches a watched address
* `programIds` — filter to transactions invoking specific Solana programs (e.g., the SPL Token Program)
* `mintAddresses` — filter to transactions involving specific SPL tokens, matched via `pre` / `postTokenBalances`
* `allAddresses` — firehose mode: receive every Solana transaction
**Use cases:** wallet activity notifications, DEX / DeFi position monitoring by `programId`, SPL token transfer tracking, bot and MEV monitoring, and AI agents reacting to on-chain events as they happen.
If you've used Streams on EVM, the developer model is identical — only the filters differ.
[Explore Solana Streams →](/streams/solana-streams)
**May 5, 2026**
## Cortex API and legacy Data API Endpoints Sunsetting
The following endpoints and APIs are now deprecated and will be removed on **June 4, 2026**:
**Cortex API:**
* `POST /chat` — migrate to [Onchain Skills](/data-api/onchain-skills/overview), which replaces Cortex as our AI interface for Moralis data.
**Discovery endpoints (`/discovery/*`):**
* `POST /discovery/tokens`
* `GET /discovery/token` — migrate to the [Token Search API](/data-api/universal/token/search/token-search).
* `GET /discovery/tokens/rising-liquidity`
* `GET /discovery/tokens/buying-pressure`
* `GET /discovery/tokens/solid-performers`
* `GET /discovery/tokens/experienced-buyers`
* `GET /discovery/tokens/risky-bets`
* `GET /discovery/tokens/blue-chip`
* `GET /discovery/tokens/top-gainers`
* `GET /discovery/tokens/top-losers`
* `GET /discovery/tokens/trending`
**Volume endpoints (`/volume/*`):**
* `GET /volume/chains`
* `GET /volume/categories`
* `GET /volume/timeseries`
* `GET /volume/timeseries/{categoryId}`
**Sniper endpoints (EVM and Solana):**
* `GET /pairs/{address}/snipers` (EVM)
* `GET /token/{network}/pairs/{pairAddress}/snipers` (Solana)
**ERC20 endpoints (EVM):**
* `GET /erc20/exchange/{exchangeName}/new`
* `GET /erc20/exchange/{exchangeName}/bonding`
* `GET /erc20/exchange/{exchangeName}/graduated`
* `GET /erc20/{tokenAddress}/bondingStatus`
* `GET /erc20/{address}/stats`
* `GET /erc20/{token_address}/pairs/stats` — migrate to [`GET /tokens/{tokenAddress}/analytics`](/data-api/universal/token/analytics/token-analytics)
* `GET /erc20/metadata/symbols` — migrate to [`GET /tokens/search`](/data-api/universal/token/search/token-search)
**Market data endpoints (`/market-data/*`):**
* `GET /market-data/erc20s/top-tokens`
* `GET /market-data/erc20s/top-movers`
* `GET /market-data/nfts/top-collections`
* `GET /market-data/nfts/hottest-collections`
* `GET /market-data/global/market-cap`
* `GET /market-data/global/volume`
If you rely on any of these endpoints, please migrate before June 4, 2026. [Reach out to the team](https://admin.moralis.com/) (via chat widget) if you need help identifying replacements.
**Apr 30, 2026**
## Fantom Chain Sunsetting
Fantom mainnet support will be removed across all Moralis APIs on **May 29, 2026**. Fantom Opera testnet has already been removed as of today. The Fantom Opera network is winding down as a legacy chain, and we're retiring our integration in line with the broader ecosystem shift.
**April 29, 2026**
## DeFi API: Now on Solana
The same three Universal DeFi API endpoints that returned EVM positions last week now return Solana positions too. No new endpoints, no schema changes - the existing calls now cover the most-used Solana protocols alongside EVM.
**What's new:**
* **Solana support** on the same Universal DeFi endpoints used for EVM
* **7 of the most-used Solana protocols** supported at launch:
* Jito
* Save (formerly Solend)
* Jupiter Lending
* Raydium
* Orca
* Drift
* Marinade
* **Unified schema:** identical response shape across EVM and Solana - no client-side stitching
* **Single call:** query EVM and Solana wallets through the same endpoints with the same filters
**Main endpoints:**
* [`getDefiSummary`](/data-api/solana/defi/wallet-protocols) — every protocol a wallet holds positions in, total USD value, and unclaimed rewards
* [`getDefiPositionsSummary`](/data-api/solana/defi/wallet-positions) — all positions with token types, values, and reward tokens
* [`getDefiPositionsByProtocol`](/data-api/solana/defi/wallet-positions-detailed) — detailed per-protocol breakdown with position-level detail
**Usecases:** portfolio trackers, exchanges, tax tools, DeFi dashboards, and AI agents that need a unified DeFi position view across EVM and Solana in a single, consistent response.
More Solana protocols are being added on a rolling basis. If you need a specific Solana protocol prioritized, [reach out to the team](https://moralis.com/enterprise/).
[Explore the Solana DeFi API →](/data-api/solana/defi/overview)
**April 22, 2026**
## DeFi API: 5,000+ Protocols, Now Multichain
We've significantly expanded the DeFi API (EVM) with broader protocol coverage and simpler multichain queries in a single call.
**What's new:**
* **5,000+ DeFi protocols** supported, covering 96% of the entire EVM DeFi market
* **Multichain queries:** fetch positions from a single chain, multiple chains, or all EVM chains in one API call
* **Protocols include:** Uniswap V2/V3, Aave V2/V3, Lido, Curve, Compound, MakerDAO, Pendle, Convex, Yearn, GMX, Aerodrome, Velodrome, SushiSwap, PancakeSwap, Eigenlayer, Etherfi, Rocket Pool, Spark, Morpho, and thousands more
**Main endpoints:**
* [`getDefiSummary`](/data-api/evm/defi/wallet-protocols) — every protocol a wallet holds positions in, total USD value, and unclaimed rewards
* [`getDefiPositionsSummary`](/data-api/evm/defi/wallet-positions) — all positions with token types, values, and reward tokens
* [`getDefiPositionsByProtocol`](/data-api/evm/defi/wallet-positions-detailed) — detailed per-protocol breakdown with position-level detail
**Usecases:** portfolio trackers, DeFi dashboards, tax and accounting tools, and risk monitoring. Anywhere you need a unified view of a wallet's DeFi exposure without wiring each protocol in manually.
Solana DeFi support is coming soon.
[Explore the DeFi API →](/data-api/evm/defi/overview)
[Moralis DeFi API Overview](https://www.youtube.com/embed/yc-THd5xH5s)
**April 2, 2026**
## Wallet Insights
We've launched the Wallet Insights endpoint - a single API call that returns a comprehensive behavioral profile for any EVM wallet address.
Get wallet age, activity timelines, transaction counts, transfer breakdowns (native, ERC-20, NFT), swap volume, gas spend, net flow, unique counterparties, contracts created, and more - all in one response. Each metric is also available per-chain via the `includeChainBreakdown` array, so you can see exactly how a wallet behaves across different networks.
[Explore Wallet Insights →](/data-api/evm/wallet/wallet-insights)
**Feburary 4, 2026**
## Historical Token Scores
We've added the ability to track Token Scores over time with a new Historical Token Score endpoint.
The Historical Token Score endpoint lets you retrieve a token's score history across different timeframes, so you can see how a token's onchain quality has changed over time.
[Explore Historical Token Scores →](/data-api/universal/token/score/token-score-timeseries)
**December 16, 2025**
## Token Scores
We've launched the Moralis Token Score - a unified 0–100 rating that summarizes a token's onchain quality in a single, easy-to-use metric.
[Explore Token Scores →](/data-api/universal/token/score/token-score)
**November 24, 2025**
## Monad EVM Live
We've added Monad EVM support to both the Data APIs and the Streams API, giving you access to this next-generation, EVM-compatible Layer-1 that delivers 10,000 TPS, 0.4-second block times, 800 ms finality, and near-zero gas fees.
**October 16, 2025**
## Sei EVM Live
We’ve added Sei EVM support to both the Data APIs and the Streams API, expanding your access to this high-performance Layer 1 chain built for speed and scalability.
**September 30, 2025**
## HyperEVM Live
We've added HyperEVM mainnet to the Moralis Streams API. You can now listen to real-time blockchain activity on HyperEVM - perfect for notifications, indexing, and on-chain automation.
# Data API Tutorials
Source: https://docs.moralis.com/data-api-tutorials
Step-by-step tutorials for building with the Moralis Data API — wallets, tokens, NFTs, prices, and blockchain data.
## Overview
These tutorials walk you through common use cases with the Moralis Data API, with complete code examples you can run locally.
***
### Wallets & Accounts
> [card] [Get Internal Transactions](/get-started/tutorials/data-api/wallets-and-accounts/get-internal-transactions-for-a-wallet-address)
>
> Fetch internal transactions for any wallet address.
> [card] [Get Native Token Balances](/get-started/tutorials/data-api/wallets-and-accounts/get-native-token-balances-for-eoas-and-smart-accounts)
>
> Retrieve native balances for EOAs and smart accounts.
> [card] [Get Multi-Chain Activity](/get-started/tutorials/data-api/wallets-and-accounts/get-multi-chain-activity-for-a-wallet-address)
>
> Track wallet activity across multiple chains.
> [card] [Get Full Wallet History](/get-started/tutorials/data-api/wallets-and-accounts/get-full-wallet-transaction-history-eoa-and-smart-accounts)
>
> Fetch complete transaction history for any wallet.
> [card] [Build a Revoke Dashboard](/get-started/tutorials/data-api/wallets-and-accounts/build-a-token-approval-and-revoke-dashboard-revoke-cash-style)
>
> Build a token approval and revoke dashboard.
***
### Tokens & Markets
> [card] [Top ERC-20 by Market Cap](/get-started/tutorials/data-api/tokens-and-markets/get-top-erc-20-tokens-by-market-cap)
>
> Get the top ERC-20 tokens ranked by market cap.
> [card] [Build a DEX Screener Clone](/get-started/tutorials/data-api/tokens-and-markets/build-a-dex-screener-clone)
>
> Build a DEX screener-style token dashboard.
> [card] [ERC-20 Transfer History](/get-started/tutorials/data-api/tokens-and-markets/get-erc-20-transfer-history-by-wallet-or-token)
>
> Fetch ERC-20 transfer history by wallet or token.
> [card] [Token Metadata](/get-started/tutorials/data-api/tokens-and-markets/get-erc-20-token-metadata-by-address-or-symbol)
>
> Get ERC-20 token metadata by address or symbol.
> [card] [Token Pairs & Liquidity](/get-started/tutorials/data-api/tokens-and-markets/get-token-pairs-and-liquidity-data)
>
> Fetch token pairs and liquidity data.
> [card] [DEX Pair Addresses](/get-started/tutorials/data-api/tokens-and-markets/get-dex-pair-addresses-uniswap-pancake-swap-sushi-swap)
>
> Get DEX pair addresses from Uniswap, PancakeSwap, and more.
> [card] [Pump.fun Tokens & Swaps](/get-started/tutorials/data-api/tokens-and-markets/get-pump-fun-tokens-swaps-and-prices)
>
> Fetch Pump.fun token swaps and prices.
> [card] [Pump.fun Bonding & Graduated](/get-started/tutorials/data-api/tokens-and-markets/get-pump-fun-new-bonding-and-graduated-tokens)
>
> Track new bonding and graduated Pump.fun tokens.
***
### NFTs
> [card] [Get All NFTs by Wallet](/get-started/tutorials/data-api/nfts/get-all-nfts-owned-by-a-wallet-address)
>
> Fetch all NFTs owned by a wallet address.
> [card] [NFT Collections by Wallet](/get-started/tutorials/data-api/nfts/get-nft-collections-owned-by-a-wallet)
>
> Get NFT collections owned by a wallet.
> [card] [NFT Metadata](/get-started/tutorials/data-api/nfts/get-nft-metadata-by-contract-and-token-id)
>
> Fetch NFT metadata by contract and token ID.
> [card] [NFT Owners & Ownership](/get-started/tutorials/data-api/nfts/get-nft-owners-and-ownership-details)
>
> Get NFT owners and ownership details.
> [card] [NFT Floor Prices](/get-started/tutorials/data-api/nfts/get-nft-floor-prices)
>
> Fetch NFT floor prices for collections.
***
### Prices & Charts
> [card] [Get ERC-20 Token Price](/get-started/tutorials/data-api/prices-and-charts/get-the-price-of-an-erc-20-token)
>
> Fetch the current price of any ERC-20 token.
> [card] [Historical OHLC Data](/get-started/tutorials/data-api/prices-and-charts/get-historical-erc-20-token-prices-ohlc-data)
>
> Get historical OHLC price data for tokens.
> [card] [Build Price Charts](/get-started/tutorials/data-api/prices-and-charts/build-crypto-price-charts-using-ohlc-data)
>
> Build crypto price charts using OHLC data.
***
### Blocks & Transactions
> [card] [Get Transaction by Hash](/get-started/tutorials/data-api/blocks-and-transactions/get-a-blockchain-transaction-by-hash)
>
> Fetch a blockchain transaction by its hash.
> [card] [Find Block by Timestamp](/get-started/tutorials/data-api/blocks-and-transactions/find-the-closest-block-by-unix-timestamp)
>
> Find the closest block to a Unix timestamp.
***
## Data API Overview Video
[Moralis Data API Overview – Fetch Onchain Data at Scale](https://www.youtube.com/embed/O8PXFkN71oo)
# Get Block
Source: https://docs.moralis.com/data-api/bitcoin/blockchain/block
openapi-files/data-api/bitcoin-api-v1.json GET /v1/chains/{chainAlias}/blocks/{blockIdentifier}
Returns full Bitcoin block data including transactions, inputs, outputs, and UTXO-level detail.
> [!NOTE]
>
> For Bitcoin, pass `bitcoin` (or `bitcoin-mainnet`) as `chainAlias`. The `blockIdentifier` accepts either a Bitcoin block height (all-digit values are treated as heights) or a block hash (any other value is forwarded as a hash).
# Bitcoin Blockchain API
Source: https://docs.moralis.com/data-api/bitcoin/blockchain/overview
Raw Bitcoin blocks and transactions — block headers, full transaction payloads, inputs, outputs, and UTXO-level detail.
## Overview
The **Bitcoin Blockchain API** provides direct access to raw Bitcoin blocks and transactions through Moralis's Universal API. Pass `bitcoin` as the chain alias on the standard block and transaction endpoints.
Query block headers, full transaction payloads, inputs, outputs, and UTXO-level detail without running your own Bitcoin node.
***
## Endpoints
| Endpoint | Universal path |
| - | - |
| [Get Block](/data-api/bitcoin/blockchain/block) | `GET /v1/chains/bitcoin/blocks/{blockIdentifier}` |
| [Get Transaction](/data-api/bitcoin/blockchain/transaction) | `GET /v1/chains/bitcoin/transactions/{txHash}` |
***
## Common Use Cases
* **Block explorers** — display block and transaction detail
* **Analytics pipelines** — ingest raw onchain data for custom indexing
* **Compliance and tracing** — follow UTXO flows across transactions
* **Wallet backends** — verify transaction inclusion and confirmation depth
# Get Transaction
Source: https://docs.moralis.com/data-api/bitcoin/blockchain/transaction
openapi-files/data-api/bitcoin-api-v1.json GET /v1/chains/{chainAlias}/transactions/{txHash}
Returns full Bitcoin transaction data including inputs, outputs, and UTXO-level detail.
> [!NOTE]
>
> For Bitcoin, pass `bitcoin` (or `bitcoin-mainnet`) as `chainAlias` and the Bitcoin txid as `txHash`.
# Bitcoin Data API
Source: https://docs.moralis.com/data-api/bitcoin/overview
Complete Bitcoin data coverage — raw blocks and transactions, market prices with sparklines, address history and balances, plus native xpub-key tooling.
### Overview
The **Bitcoin Data API** brings full Bitcoin coverage to the Moralis Universal API. Every endpoint is the same Universal endpoint EVM and Solana developers already use — just pass `bitcoin` as the chain.
Historically, shipping a serious Bitcoin app meant stitching together five different services: a block explorer for raw data, a price feed, a custom indexer for address activity, a derivation library for xpubs, and your own caching layer for chart UIs. The Bitcoin API replaces all of that under one consistent surface with the same auth, SDKs, pricing, and rate limits as the rest of Moralis.
***
### Explore the Bitcoin API
> [card] [Blockchain API](/data-api/bitcoin/blockchain/overview)
>
> Raw blocks and raw transactions — work directly with onchain data.
> [card] [Price API](/data-api/bitcoin/price/overview)
>
> Current BTC price, full historical time series, and chart-ready sparklines.
> [card] [Wallet API](/data-api/bitcoin/wallet/overview)
>
> Transaction history and token balances for any Bitcoin address or xpub.
> [card] [Xpub Utility](/data-api/bitcoin/utility/overview)
>
> Derive every address associated with a Bitcoin xpub.
***
### How It Works
The Bitcoin API is delivered through Moralis's Universal API endpoints:
| Capability | Universal endpoint | Bitcoin parameters |
| - | - | - |
| Raw blocks | `GET /v1/chains/{chainAlias}/blocks/{blockIdentifier}` | `chainAlias=bitcoin` |
| Raw transactions | `GET /v1/chains/{chainAlias}/transactions/{txHash}` | `chainAlias=bitcoin` |
| BTC current price | `GET /v1/chains/{chainAlias}/tokens/{tokenAliasOrTokenAddress}/price` | `chainAlias=bitcoin`, `tokenAlias=native` |
| BTC historical price | `GET /v1/chains/{chainAlias}/tokens/{tokenAliasOrTokenAddress}/price/timeseries` | `chainAlias=bitcoin`, `tokenAlias=native` |
| BTC sparkline | `GET /v1/chains/{chainAlias}/tokens/{tokenAliasOrTokenAddress}/price/sparkline` | `chainAlias=bitcoin`, `tokenAlias=native` |
| Wallet BTC balances | `GET /v1/wallets/{walletAddressOrPublicKey}/tokens` | `chains=bitcoin`, `walletAddress=address OR xpub` |
| Wallet transaction history | `GET /v1/wallets/{walletAddressOrPublicKey}/history` | `chains=bitcoin`, `walletAddress=address OR xpub` |
| Addresses from xpub | `GET /v1/chains/{chainAlias}/wallets/{publicKey}/addresses` | `chainAlias=bitcoin`, `publicKey=xpub` |
***
### Key Capabilities
* **Full Bitcoin data lifecycle in one API** — raw blocks and transactions, market data, address activity, and balances. No stitching required.
* **Native xpub support** — every wallet endpoint accepts a Bitcoin address **or** an xpub, plus a utility endpoint to enumerate every derived address from an xpub.
* **Chart-ready price data** — sparklines bundled alongside historical time series, no second integration needed.
* **Address OR xpub inputs** — slot the API into whatever your wallet or backend already uses.
* **Same Moralis developer experience** — consistent auth, SDKs, pricing, and rate limits with the rest of Moralis coverage.
***
### Address or Xpub Inputs
The wallet endpoints accept either a Bitcoin address or an xpub directly:
```bash theme={null}
# Address input
GET /v1/wallets/bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq/tokens?chains=bitcoin
# Xpub input — same endpoint, derives addresses server-side
GET /v1/wallets/xpub6CUGRUonZSQ4TWtTMmzXdrXDtypWKiKrhko4egpiMZbpiaQL2jkwSB1icqYh2cfDfVxdx4df189oLKnC5fSwqPfgyP3hooxujYzAu3fDVmz/tokens?chains=bitcoin
```
To **enumerate** every derived address from an xpub (rather than just query against it), use the [xpub utility endpoint](/data-api/bitcoin/utility/addresses-from-xpub).
***
### Get Started
* [**Blockchain API**](/data-api/bitcoin/blockchain/overview) — raw blocks and transactions
* [**Price API**](/data-api/bitcoin/price/overview) — current price, history, and sparklines
* [**Wallet API**](/data-api/bitcoin/wallet/overview) — address history and balances
* [**Xpub Utility**](/data-api/bitcoin/utility/overview) — derive addresses from an xpub
* [**Bitcoin Quickstart**](/get-started/tutorials/data-api/bitcoin/bitcoin-quickstart) — first request, address-or-xpub flow
***
### Watch: Bitcoin Data API
[Moralis Bitcoin Data API](https://www.youtube.com/embed/us4CIqGre0A)
# Current Price
Source: https://docs.moralis.com/data-api/bitcoin/price/current-price
openapi-files/data-api/bitcoin-api-v1.json GET /v1/chains/{chainAlias}/tokens/{tokenAliasOrTokenAddress}/price
Get the current BTC price and additional market metadata.
> [!NOTE]
>
> For BTC, pass `bitcoin` as `chainAlias` and `native` as `tokenAliasOrTokenAddress`.
# Historical Price
Source: https://docs.moralis.com/data-api/bitcoin/price/historical-price
openapi-files/data-api/bitcoin-api-v1.json GET /v1/chains/{chainAlias}/tokens/{tokenAliasOrTokenAddress}/price/timeseries
Get historical BTC price data points suitable for rendering line charts. Supports time intervals from 5 minutes to monthly.
> [!NOTE]
>
> For BTC, pass `bitcoin` as `chainAlias` and `native` as `tokenAliasOrTokenAddress`.
# Bitcoin Price API
Source: https://docs.moralis.com/data-api/bitcoin/price/overview
Current BTC price, full historical time series, and chart-ready sparklines through the Universal Token Price endpoints.
## Overview
The **Bitcoin Price API** delivers BTC market data through the Moralis Universal Token Price endpoints. Pass `bitcoin` as the chain alias and `native` as the token alias to target BTC itself.
Sparklines ship alongside historical data, so building a price chart UI doesn't require a second integration or your own caching layer.
***
## Endpoints
| Endpoint | Universal path |
| - | - |
| [Current Price](/data-api/bitcoin/price/current-price) | `GET /v1/chains/bitcoin/tokens/native/price` |
| [Historical Price](/data-api/bitcoin/price/historical-price) | `GET /v1/chains/bitcoin/tokens/native/price/timeseries` |
| [Sparkline](/data-api/bitcoin/price/sparkline) | `GET /v1/chains/bitcoin/tokens/native/price/sparkline` |
***
## Common Use Cases
* **Portfolio dashboards** — BTC price, change, and a sparkline next to balances
* **Trading apps** — full historical charts with configurable granularity
* **Notifications** — fire on price thresholds without polling a third-party feed
* **Reporting** — pull historical price for accounting and tax flows
# Sparkline
Source: https://docs.moralis.com/data-api/bitcoin/price/sparkline
openapi-files/data-api/bitcoin-api-v1.json GET /v1/chains/{chainAlias}/tokens/{tokenAliasOrTokenAddress}/price/sparkline
Get a small set of recent BTC price points suitable for sparkline charts. Returns a fixed number of points based on the selected range.
> [!NOTE]
>
> For BTC, pass `bitcoin` as `chainAlias` and `native` as `tokenAliasOrTokenAddress`. The response is a compact, chart-ready price array — drop it directly into a sparkline widget without resampling.
# Addresses From Xpub
Source: https://docs.moralis.com/data-api/bitcoin/utility/addresses-from-xpub
openapi-files/data-api/bitcoin-api-v1.json GET /v1/chains/{chainAlias}/wallets/{publicKey}/addresses
Returns every derived address along with its transfer count for a given Bitcoin xpub key.
> [!NOTE]
>
> Pass `bitcoin` (or `bitcoin-mainnet`) as `chainAlias` and your Bitcoin extended public key as `publicKey`. The response lists every derived address along with its transfer count, so you can show only the addresses that have actually been used.
# Xpub Utility
Source: https://docs.moralis.com/data-api/bitcoin/utility/overview
Native Bitcoin xpub tooling — derive every address from a Bitcoin extended public key (xpub) along with its transfer count.
## Overview
Bitcoin developers regularly need to map an xpub to **every address it derives** — and to know which of those addresses have actually been used. The xpub utility solves that natively.
Pass a Bitcoin extended public key (xpub), and the API returns every derived address with its transfer count. No client-side derivation library required.
***
## Endpoint
| Endpoint | Universal path |
| - | - |
| [Addresses From Xpub](/data-api/bitcoin/utility/addresses-from-xpub) | `GET /v1/chains/bitcoin/wallets/{publicKey}/addresses` |
***
## Pairing With the Wallet API
The Wallet API endpoints accept either an address or an xpub directly. For most flows you don't need to call the utility endpoint first — the API derives the addresses server-side.
Use the utility endpoint when you need to **enumerate and display** the derived addresses themselves — for example a wallet UI that surfaces "this xpub controls the following addresses," or an analytics pipeline that wants to track each derived address independently.
# BTC Balances
Source: https://docs.moralis.com/data-api/bitcoin/wallet/address-balances
openapi-files/data-api/bitcoin-api-v1.json GET /v1/wallets/{walletAddressOrPublicKey}/tokens
Get native BTC balances for a Bitcoin address or xpub. When an xpub is supplied, balances are aggregated across all derived addresses server-side.
> [!NOTE]
>
> The `walletAddressOrPublicKey` path parameter accepts either a Bitcoin address or an **xpub** — when an xpub is supplied, balances are aggregated across all derived addresses server-side.
> [!NOTE]
>
> **Address auto-detection:** for a Bitcoin address or xpub, the `chains` parameter is optional — Moralis detects the chain family from the address format. Passing `chains=bitcoin` explicitly still works.
# Wallet History
Source: https://docs.moralis.com/data-api/bitcoin/wallet/address-transactions
openapi-files/data-api/bitcoin-api-v1.json GET /v1/wallets/{walletAddressOrPublicKey}/history
Get Bitcoin transaction history for a wallet. The wallet identifier accepts either a Bitcoin address or an xpub - when an xpub is supplied, history is aggregated across all derived addresses server-side.
**Supported chain family:** Bitcoin (native BTC transfers).
> [!NOTE]
>
> The `walletAddressOrPublicKey` path parameter accepts either a Bitcoin address or an **xpub** — when an xpub is supplied, history is aggregated across all derived addresses server-side.
> [!NOTE]
>
> **Address auto-detection:** for a Bitcoin address or xpub, the `chains` parameter is optional — Moralis detects the chain family from the address format. Passing `chains=bitcoin` explicitly still works.
# Bitcoin Wallet API
Source: https://docs.moralis.com/data-api/bitcoin/wallet/overview
Transaction history and token balances for any Bitcoin address — or xpub. Slots into whatever shape your wallet or backend already uses.
## Overview
The **Bitcoin Wallet API** provides address-level activity and balances through the Moralis Universal Wallet endpoints. Pass `bitcoin` as the chain and either a Bitcoin address **or** an xpub as the wallet identifier.
For workflows that need to enumerate every address derived from an xpub, pair the Wallet API with the [xpub utility](/data-api/bitcoin/utility/addresses-from-xpub).
***
## Endpoints
| Endpoint | Universal path |
| - | - |
| [BTC Balances](/data-api/bitcoin/wallet/address-balances) | `GET /v1/wallets/{addressOrXpub}/tokens?chains=bitcoin` |
| [Wallet History](/data-api/bitcoin/wallet/address-transactions) | `GET /v1/wallets/{addressOrXpub}/history?chains=bitcoin` |
***
## Key Features
* **Address OR xpub input** — pass either; the API derives addresses server-side for xpubs
* **Paginated history** — cursor-based pagination tuned for high-activity addresses
* **No node required** — managed indexer handles UTXO accounting and reorgs
***
## Common Use Cases
* **Bitcoin wallets** — show balances and history without operating a node
* **Custody platforms** — surface activity for managed addresses
* **Block explorers** — render address pages with full history and holdings
* **Analytics** — aggregate flows across every address derived from a single xpub
# Address & Entity Labeling
Source: https://docs.moralis.com/data-api/data-features/data-enrichment/address-labelling
Moralis enriches blockchain data with human-readable labels and entities, helping you understand who is behind on-chain activity.
Moralis enriches blockchain data with **human-readable labels and entities**, helping you understand *who* is behind on-chain activity.
This includes both:
* **Address labels** (e.g. “Coinbase Hot Wallet”)
* **Entities** (e.g. Coinbase, Uniswap, BlackRock)
Together, they provide identity, context, and discoverability across wallets, transactions, and protocols.
***
## What Are Entities?
**Entities** represent real-world organizations, projects, protocols, or individuals that control one or more blockchain addresses.
Examples include:
* Companies and institutions (e.g. exchanges, funds, TradFi firms)
* DeFi protocols and DAOs
* NFT marketplaces and collections
* Public individuals
Entities build on top of address labels by grouping **multiple related addresses** under a single, identifiable actor.
***
## Why Entities Matter
Historically, blockchain data exposed only raw addresses or simple labels.\
This made it difficult to answer higher-level questions like:
* Who is interacting with this wallet?
* Which addresses belong to the same organization?
* How does an entity operate across chains?
With Entities, Moralis provides:
* **In-depth context**\
Entities include metadata such as name, logo, description, and website.
* **Cross-address visibility**\
Multiple addresses can be linked to a single entity, giving a more complete picture of activity.
* **Better discovery and analysis**\
You can search for entities and analyze their on-chain behavior, rather than dealing with individual addresses in isolation.
***
## Entity-Enriched Responses
When supported, Moralis APIs enrich address fields with both **labels** and **entity information**.
Example:
```json theme={null}
{
"hash": "0x70c30285a9a4cc1c147cc94e5d0cefebe693fffd5fd5cbf727e2f86b6829d71b",
"nonce": "6810858",
"transaction_index": "72",
"from_address": "Oxa9d1e08c7793af67e9d92fe308d5697fb81d3e43",
"from_address_label": "Coinbase: Hot Wallet",
"from_address_entity": "Coinbase",
"from_address_entity_logo": "https://entities-logos.s3.us-east-1.amazonaws.com/coinbase.png",
"to_address": "Oxa9d1e08c7793af67e9d92fe308d5697fb81d3e43",
"to_address_label": "Blackrock Wallet",
"to_address_entity": "Blackrock, Inc",
"to_address_entity_logo": "https://entities-logos.s3.us-east-1.amazonaws.com/blackrock.png",
"value": "0",
"gas": "207128",
"gas_price": "32393720336",
"input": "0xa9059cbb000000000000000000000000c476723407b737c173bdfd87c7abc80f6856e6320000000000000000000000000000000000000000000000008533e3870aec3000",
"receipt_cumulative_gas_used": "8535588",
"receipt_gas_used": "52089",
"receipt_contract_address": null,
"receipt_root": null,
"receipt_status": "1",
"block_timestamp": "2023-06-26T16:48:23.000Z",
"block_number": "17564884",
"block_hash": "0x4e61fbb792a84c419a22ffcc590cbcb2f5a1b88d8e864d608e3544a3594c0e69",
"transfer_index": [17564884, 72]
}
```
This allows you to display transactions as **entity-to-entity interactions**, rather than raw address transfers.
***
## Where Entity & Address Labeling Is Available
Entity and address labeling is supported on:
* Any endpoint that includes `from_address` and `to_address`
* Dedicated **Entity API** endpoints for discovery and lookup
This means labeling is automatically available across:
* Transactions
* Wallet activity
* Transfers
* DeFi interactions
***
## Entity Coverage
Moralis currently supports:
* **500+ entities**
* **10,000+ labeled addresses**
Coverage is strongest across:
* Ethereum
* Polygon
* BNB Chain
* Optimism
* Base
* Arbitrum
### Supported Entity Categories
Entities span a wide range of categories, including:
* Centralized Exchange
* Decentralized Exchange
* NFT Marketplace
* DeFi
* TradFi
* Fund
* DAO
* Bridge
* Stablecoin
* Lending / Borrowing
* Liquid Staking / Restaking
* NFT Collection
* Gaming
* Wallet
* MEV
* Real World Assets
* Privacy
* Cross-chain Infrastructure
* Individual
* Misc
Coverage and categorisation are continuously expanding.
***
## Common Use Cases
Address & Entity Labeling enables you to:
* Build readable transaction feeds
* Detect interactions with known exchanges, protocols, or institutions
* Power compliance, monitoring, and analytics workflows
* Aggregate activity at the entity level instead of per address
***
## Notes & Limitations
* Labeling and entity assignment is **best-effort**
* Not all addresses belong to known entities
* New entities and labels are added continuously as coverage expands
# Internal Transactions
Source: https://docs.moralis.com/data-api/data-features/data-enrichment/internal-transactions
Understand and access internal transactions to get a complete view of wallet activity, contract execution, and native value transfers on EVM chains.
## Overview
Internal transactions are a critical part of many EVM-based interactions - and without them, **your data is incomplete**.
Moralis provides **full historical and real-time support for internal transactions**, allowing you to capture value transfers and contract interactions that do **not** appear as standalone blockchain transactions.
This is a key differentiator versus many APIs that only index external (user-initiated) transactions.
Related pages:
* [Wallet History](/data-api/evm/wallet/wallet-history)
* [Raw Transactions](/data-api/evm/wallet/wallet-transactions)
* [Transaction Decoding](/data-api/data-features/data-enrichment/transaction-decoding)
***
## What are internal transactions?
Internal transactions are **value transfers and contract calls that occur during the execution of a transaction**, rather than being initiated directly by an externally owned account (EOA).
They typically occur when:
* A smart contract calls another contract
* A contract transfers native currency (ETH, BNB, etc.)
* A single transaction triggers multiple downstream actions
> Internal transactions are **not separate blockchain transactions** - they are derived from EVM execution traces.
***
## Why internal transactions matter
Without internal transactions, you miss:
* Native transfers triggered by smart contracts
* Airdrops distributed within a single transaction
* Protocol rewards, fees, and payouts
* Full wallet balance movements
* Complete contract execution paths
### Example
A user interacts with a DeFi protocol:
1. User sends **one** transaction
2. Contract distributes ETH to multiple addresses internally
3. Only internal transactions show where value actually moved
Without internal transactions:
* Wallet history is incomplete
* Net worth calculations are wrong
* Important events appear to be missing
***
## What Moralis provides
Moralis indexes **full EVM execution traces**, enabling:
* Historical internal transactions
* Real-time internal transaction detection
* Native value transfers inside contract calls
* Consistent internal transaction data across APIs
This ensures:
* Complete wallet activity
* Accurate portfolio and PnL calculations
* Better protocol analytics
***
## Supported chains
Internal transactions are supported across all major EVM **mainnet** networks, with **full historical coverage**. Testnets are not supported. Robinhood Chain does not support internal transactions; top-level contract creation is still reported, but trace-level `CREATE` / `CREATE2` deployments are not.
| Chain | Real-time | Historical |
| :- | :- | :- |
| Ethereum Mainnet | ✅ | ✅ |
| Polygon Mainnet | ✅ | ✅ |
| BNB Chain | ✅ | ✅ |
| Arbitrum | ✅ | ✅ |
| Avalanche | ✅ | ✅ |
| Base | ✅ | ✅ |
| Optimism | ✅ | ✅ |
| Linea | ✅ | ✅ |
| Chiliz | ✅ | ✅ |
| Monad Mainnet | ✅ | ✅ |
| Tempo | ✅ | ✅ |
***
## Internal transactions vs external transactions
| Feature | External | Internal |
| :- | :- | :- |
| Initiated by user | ✅ | ❌ |
| Has its own tx hash | ✅ | ❌ |
| Appears on block explorers by default | ✅ | ❌ |
| Transfers native value | ✅ | ✅ |
| Required for full wallet history | ✅ | ✅ |
***
## Streams support
Internal transactions are also available in **Streams**, enabling:
* Real-time detection of internal value transfers
* Monitoring protocol payouts and rewards
* Capturing native transfers triggered by contracts
See:
* [Streams Overview](/streams/overview)
* [Webhook Payload](/streams/webhooks/webhook-payloads)
***
## Summary
Internal transactions are essential for **accurate, production-grade blockchain data**.
Moralis provides:
* Full historical and real-time internal transactions
* Broad EVM chain coverage
* Simple access via existing and dedicated endpoints
If you care about **completeness**, internal transactions are not optional.
# NFT Metadata
Source: https://docs.moralis.com/data-api/data-features/data-enrichment/nft-metadata
Fetch and normalize NFT metadata into a clean, predictable format across ERC721 and ERC1155 collections.
## Overview
NFT metadata is notoriously inconsistent.
Different collections use different schemas, naming conventions, attribute formats, and storage locations - making it difficult to work with at scale.
Moralis solves this by **normalizing NFT metadata into a clean, predictable structure**, while still allowing access to the original source data when needed.
Related pages:
* [NFT API Overview](/data-api/evm/nft/overview)
* [NFT Traits & Rarity](/data-api/data-features/data-enrichment/nft-rarity)
* [NFT Image Previews](/data-api/data-features/data-enrichment/nft-metadata/image-previews-cdn)
* [Supported NFT Marketplaces](/data-api/data-features/integrations/nft-marketplaces)
***
## What is NFT metadata normalization?
When enabled, Moralis transforms raw NFT metadata into a **standardized JSON structure** that works consistently across:
* ERC721
* ERC1155
* OpenSea-style metadata
* Collection-specific formats (e.g. CryptoPunks, ENS)
This removes the need for custom parsing logic per collection.
### Why this matters
Without normalization:
* Attributes are inconsistently named
* Values change type across collections
* Metadata is often returned as a raw JSON string
* Frontends and analytics break easily
With normalization:
* Predictable fields
* Consistent attribute structure
* Easier UI rendering
* Easier indexing and analytics
***
## How to enable normalized metadata
Several NFT endpoints support metadata normalization via the `normalizeMetadata` query parameter.
When enabled:
* Raw metadata is preserved
* A new `normalized_metadata` object is added to the response
***
## Normalized metadata structure
The normalized metadata object provides a **stable schema** across collections.
### Core fields
```javascript theme={null}
{
"name": "Moralis Mug",
"description": "Moralis Coffee mug 3D asset",
"image": "https://...",
"external_link": "https://...",
"animation_url": "https://...",
"attributes": []
}
```
***
### Normalized attributes
Each attribute follows a consistent structure:
```javascript theme={null}
{
"trait_type": "Eye Color",
"value": "Hazel",
"display_type": "string",
"max_value": 100,
"trait_count": 7,
"order": 1
}
```
This makes it easy to:
* Render traits
* Sort attributes
* Calculate rarity
* Compare NFTs across collections
See also:
* [NFT Traits & Rarity](/data-api/data-features/data-enrichment/nft-rarity)
***
## Raw vs normalized metadata
Moralis always preserves the original metadata source.
### Normalized metadata
* Returned as structured JSON
* Easy to consume
* Consistent across collections
### Raw metadata
* Returned as a string
* Mirrors the original token URI response
* Useful for debugging or edge cases
Example (raw metadata string):
```text theme={null}
"{ \"name\": \"Dave Starbelly\", \"attributes\": [...] }"
```
***
## Collection-specific normalization
Moralis includes **custom normalization logic** for well-known collections and standards, including:
* CryptoPunks
* CryptoKitties
* ENS
* OpenSea-style metadata
If a collection does not match a known format:
* A default transformation is applied
* Based on ERC721 or ERC1155 conventions
* Most fields are still normalized successfully
This ensures broad compatibility without manual handling.
***
## Automatic metadata refresh
NFT metadata can change over time - especially when hosted on IPFS.
To keep data fresh, Moralis automatically refreshes metadata when NFTs are requested.
### How it works
* When an NFT is requested, it is queued for refresh
* If the metadata URI points to IPFS:
* The token is eligible for periodic refresh
* Refreshing happens transparently in the background
### Cool-off period
Metadata refresh is resource-intensive, so a cool-off period applies:
* **IPFS-based metadata:**\
Refresh allowed once every **10 minutes per token**
This balances freshness with performance.
***
## Collection offchain metadata
In addition to token-level metadata, Moralis also enriches NFT collections with **offchain metadata** sourced from trusted marketplaces such as **OpenSea**.
This includes collection-level information that is often **not available on-chain**, such as:
* Collection name
* Collection description
* Collection image and banner image
* External links (website, Twitter, Discord, etc.)
* Marketplace identifiers
This enrichment allows you to:
* Display richer collection pages
* Avoid making separate marketplace API calls
* Work with consistent collection metadata across chains
Collection offchain metadata is returned alongside on-chain data on supported NFT endpoints.
***
## Common use cases
* **NFT galleries**\
Render attributes consistently across collections
* **Marketplaces**\
Normalize metadata for search, filtering, and ranking
* **Analytics & rarity tools**\
Work with structured traits at scale
* **Wallet & portfolio views**\
Display NFTs reliably without custom parsing logic
***
## Supported chains
NFT metadata normalization is available on all supported **mainnet** networks only. Testnets are not supported.
***
## Summary
Moralis NFT Metadata normalization provides:
* Clean, predictable metadata
* Broad collection support
* Automatic refresh handling
* Reduced frontend and backend complexity
If you’re working with NFTs at scale, normalization isn’t optional — it’s foundational.
# NFT Image Previews (CDN)
Source: https://docs.moralis.com/data-api/data-features/data-enrichment/nft-metadata/image-previews-cdn
Generate and serve optimized NFT image previews via Moralis CDN for faster loading and better user experiences.
## Overview
Moralis provides optimized **NFT image previews** for both **EVM and Solana NFTs**, generated on demand and delivered via a global CDN.
Instead of loading large, slow, and inconsistent original NFT images directly from IPFS or third-party hosts, you can rely on Moralis to serve **low, medium, and high-resolution thumbnails** that are fast, cacheable, and reliable - ideal for wallets, marketplaces, dashboards, and feeds.
This removes the need to build and operate your own NFT media pipeline while significantly improving frontend performance and UX.
Related pages:
* [NFT Metadata](/data-api/data-features/data-enrichment/nft-metadata)
* [NFT API Overview](/data-api/evm/nft/overview)
***
## What are NFT image previews?
NFT image previews are **pre-generated thumbnails** of the original NFT media, optimized for common UI use cases such as:
* Wallet views
* Galleries
* Marketplaces
* Search results
* Collection pages
Moralis generates and caches these previews once, then serves them via CDN for subsequent requests.
***
## Supported image formats
Moralis currently supports common static image formats, including:
* JPG / JPEG
* PNG
* GIF
* TIFF
* WEBP
* SVG
### Not yet supported
* Video (planned)
***
## How to enable image previews
Image previews are returned when the `media_items` query parameter is set to `true`.
Once enabled, preview URLs are included directly in the API response.
***
## Does this cost extra?
No. Enabling `media_items=true` does **not consume additional compute units (CUs)**.
***
## Preview generation lifecycle
Image previews are generated **on demand**.
### What happens on first request?
* If previews don’t yet exist:
* Generation starts automatically
* The original media URL is still returned
* Once generated:
* Previews are cached
* Subsequent requests return previews instantly
***
## Preview generation statuses
Each NFT media item includes a generation status:
| Status | Description |
| :- | :- |
| `success` | Preview generated and returned |
| `processing` | Preview is being generated |
| `unsupported_media` | Media type not supported |
| `invalid_url` | Metadata image URL is invalid |
| `retry` | Generation failed and will retry |
| `host_unavailable` | Media host is unavailable |
| `temporarily_unavailable` | Temporary failure (e.g. rate limits) |
Regardless of status, the API **always returns the original media URL** as a fallback.
***
## Retry behavior
If preview generation fails, Moralis automatically retries with **exponential backoff**.
* Up to **8 retry attempts**
* Increasing delay between attempts
### Retry schedule
| Attempt | Delay |
| :- | :- |
| 1 | 1 minute |
| 2 | 5 minutes |
| 3 | 10 minutes |
| 4 | 15 minutes |
| 5 | 30 minutes |
| 6 | 40 minutes |
| 7 | 50 minutes |
| 8 | 60 minutes |
This ensures resilience against:
* Temporary host issues
* Rate-limited IPFS gateways
* Intermittent CDN failures
***
## Why this matters
Without image previews:
* Large images slow down UIs
* IPFS gateways can be unreliable
* Frontends must handle resizing and caching manually
With Moralis image previews:
* Faster load times
* Predictable image sizes
* CDN-backed delivery
* No custom infrastructure required
***
## Common use cases
* **Wallet dashboards**\
Fast-loading NFT grids
* **Marketplaces**\
Consistent thumbnails for listings
* **Search & discovery**\
Lightweight previews for large result sets
* **Mobile apps**\
Reduced bandwidth and faster rendering
***
## Supported chains
NFT image previews are supported across both major NFT ecosystems:
* **EVM chains**\
Ethereum, Polygon, Base, Arbitrum, Optimism, BNB Chain, and more
* **Solana**\
Including SPL NFTs and Metaplex-based collections
Image previews behave consistently across supported chains, with the same:
* Generation logic
* Retry behavior
* CDN delivery
* API response structure
***
## Summary
Moralis NFT Image Previews provide:
* On-demand thumbnail generation
* CDN-backed delivery
* Multi-resolution previews
* Zero additional CU cost
* Automatic retries and fallbacks
This allows you to ship fast, reliable NFT experiences without worrying about media hosting or processing.
# NFT Rarity
Source: https://docs.moralis.com/data-api/data-features/data-enrichment/nft-rarity
Understand how Moralis calculates NFT rarity across collections using trait frequency analysis, rarity scores, rankings, and refreshable on-demand processing for ERC721 and ERC1155 NFTs.
## Overview
NFT rarity measures how **unique an NFT is within its collection**, based on how common or uncommon its attributes are compared to other NFTs in the same collection.
In most NFT collections, traits such as background, color, accessories, or attributes appear at different frequencies. NFTs with **less common trait combinations** are considered rarer and are often perceived as more valuable by collectors, marketplaces, and analytics platforms.
Moralis provides **deterministic, collection-wide rarity scores and rankings**, calculated directly from indexed NFT metadata.
Related pages:
* [NFT Metadata](/data-api/data-features/data-enrichment/nft-metadata)
* [NFT Image Previews (CDN)](/data-api/data-features/data-enrichment/nft-metadata/image-previews-cdn)
* [NFT API Overview](/data-api/evm/nft/overview)
***
## How rarity is calculated
Moralis computes rarity **per collection**, not globally.
The rarity calculation process consists of two layers:
### 1. Trait-level analysis
For every trait across the collection, we compute:
* `count`\
Number of NFTs that contain this trait
* `percentage`\
Percentage of the collection that contains this trait
* `rarity_label`\
Human-readable label based on trait frequency\
*(e.g. “Top 1% trait”, “Top 10% trait”)*
This makes rarity explainable, not just numeric.
***
### 2. NFT-level rarity scoring
For each NFT, we compute:
* `rarity_score`\
Numerical score derived from the combined rarity of all its traits
* `rarity_rank`\
Rank of the NFT within the collection (1 = rarest)
* `rarity_percentage`\
Relative rarity compared to the entire collection
* `rarity_label`\
Human-readable summary (e.g. “Top 1% rarity”)
These fields are returned directly in supported NFT endpoints.
***
## Supported collections
Rarity calculations are supported for:
* **ERC-721 collections**
* **ERC-1155 collections**
With the following constraints:
* Maximum collection size: **50,000 NFTs**
* All NFTs must be discoverable and indexed
* Metadata and traits must be available for the full collection
If these conditions are not met, rarity will not be calculated.
***
## Supported chains
NFT rarity is supported on **all EVM chains** where Moralis NFT metadata is available, including:
* Ethereum
* Polygon
* Base
* Arbitrum
* Optimism
* BNB Chain
* Other supported EVM chains
Rarity logic is chain-agnostic and applied consistently.
***
## Trait syncing & rarity processing
Rarity is computed **on demand**, per collection.
### Initial sync flow
1. A collection is queried using `getNFTTraitsByCollection`
2. The collection is added to a processing queue
3. Traits are synced for all NFTs
4. Rarity scores and rankings are calculated
While processing is in progress, trait endpoints return:
```
202 – Contract is being resynced at the moment. Please try again later.
```
***
### Processing times
Typical processing times:
* Small collections: **5–15 seconds**
* Medium collections: **15–60 seconds**
* Large collections (20,000+ NFTs): may take longer
If processing exceeds **5 minutes**, contact support.
Once queued, a collection **cannot be reprocessed again for 30 minutes**.
***
## Refreshing rarity scores
Rarity scores **can be refreshed** after:
* NFT reveals
* New mints
* Metadata or trait updates
Refreshing rarity is triggered by re-syncing traits, which automatically recalculates all rarity data.
See:
* [Metadata Resyncing](/data-api/evm/nft/utilities/resync-nft-metadata)
* [Rarity Resyncing](/data-api/evm/nft/utilities/resync-nft-traits)
***
## Why rarity matters
NFT rarity enables:
* Collection ranking & discovery
* Trait-based filtering
* Floor price and valuation analysis
* Wallet and portfolio insights
* Marketplace and analytics UIs
Without indexing internal trait distributions, rarity cannot be computed accurately - which is why many platforms approximate or omit this entirely.
***
## Best practices
* Don’t assume rarity exists until processing completes
* Handle `202` responses gracefully
* Cache rarity results when possible
* Re-sync after major collection events (e.g. reveals)
***
## Summary
Moralis NFT Rarity provides:
* Deterministic rarity scores
* Trait-level transparency
* Collection-wide rankings
* Multichain support (EVM)
* Refreshable, on-demand computation
This allows you to build **analytics, discovery, and marketplace experiences** without maintaining your own rarity infrastructure.
# Profitability (PnL)
Source: https://docs.moralis.com/data-api/data-features/data-enrichment/profitability-pnl
Analyze realized wallet and token profitability using Moralis PnL endpoints. Learn how realized PnL is calculated, supported swaps, pricing logic, chain coverage, and known limitations.
## Overview
Moralis provides **realized profit and loss (PnL)** analytics for wallets and tokens, calculated directly from **on-chain swap activity**.
PnL data is designed for:
* Wallet analytics
* Trading performance dashboards
* Portfolio tools
* Token-level profitability analysis
* Leaderboards and rankings
***
## Supported PnL endpoints
PnL data is exposed through the following endpoints:
* [Wallet PnL Summary](/data-api/evm/wallet/wallet-pnl-summary)\
High-level profitability metrics for a wallet
* [Wallet PnL Breakdown](/data-api/evm/wallet/wallet-pnl)\
Token-by-token profitability details
* [Top Traders by Token](/data-api/evm/token/signals/top-traders)\
Rankings of wallets by realized profit for a given token
***
## What type of PnL is supported?
Moralis currently supports **realized PnL only**.
* **Realized PnL** is calculated from completed on-chain swaps (buys and sells).
* **Unrealized PnL** (open positions based on current market prices) is **not calculated directly** by the PnL endpoints.
#### Calculating Unrealized PnL
You can calculate unrealized PnL yourself by combining:
* **Cost basis / realized trade data** from the [PnL endpoints](/data-api/evm/wallet/wallet-pnl)
* **Real-time token balances + real-time prices** from the [Token Balances](/data-api/evm/wallet/token-balances) endpoint
A common approach is:
```
(currentPrice − averageCost) × currentTokenBalance
```
This approach gives you full flexibility to build portfolio views that include:
* Realized PnL
* Unrealized PnL
* Total PnL (realized + unrealized)
***
## How PnL is calculated
Moralis uses a method closely aligned with a **weighted average cost basis**.
### Core formula
```
(avgSellPriceUsd − avgCostOfQuantitySold) × totalTokensSold
```
Where:
* **avgSellPriceUsd**\
Continuously updated average sell price in USD
* **avgCostOfQuantitySold**\
Calculated as:\
`totalUsdInvested / totalTokensBought`
This ensures profits are calculated based on **actual cost basis**, not FIFO or speculative pricing.
***
## How trades are matched
PnL is calculated **per trading pair**, not per token globally.
Examples:
* Buy `UNI` with `WETH` → tracked as `UNI/WETH`
* Sell `UNI` for `WETH` → updates the same trade
* Sell `UNI` for `PEPE` → tracked as a **new trade** (`UNI/PEPE`)
This avoids mixing unrelated price contexts.
***
## Token pricing & trade history
Moralis determines token prices by:
1. Indexing on-chain **DEX swap events**
2. Extracting price directly from swap logs
3. Converting swap prices to USD
4. Applying those prices to PnL calculations
No off-chain price feeds are used for PnL.
***
## Supported swap events
Currently supported swap topics:
* **Uniswap V2**
```
0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822
```
* **Uniswap V3**
```
0xc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67
```
Only swaps emitting these events are included in PnL.
***
## Transaction fees
**Gas fees and transaction fees are not included** in PnL calculations.
PnL strictly reflects **token-level trading performance**, not net wallet balance changes.
***
## Update latency
PnL data updates in **near real-time**.
* Average update time: **\~10 seconds**
* Triggered after swap settlement on-chain
This makes PnL suitable for:
* Live dashboards
* Trading analytics
* Near real-time alerts
***
## Token Support
### ERC20 Tokens
PnL is supported for **all ERC20 tokens** that:
* Have participated in a **supported DEX swap**
* Emit **supported swap events**
* Are **paired with either**:
* a **stablecoin** (e.g. USDC, USDT, DAI), or
* a **native or wrapped native token** (e.g. ETH, WETH)
This covers the vast majority of actively traded ERC20 tokens.
***
### Native Tokens (e.g. ETH)
* ***Native tokens are supported for PnL***, **but only when traded against stablecoins**.
* Trades between native tokens and stablecoins are used to establish realized PnL.
Examples:
* ✅ ETH ↔ USDC → ETH PnL supported
* ❌ ETH ↔ WETH → not tracked (native ↔ wrapped native)
Native tokens are treated similarly to ERC20s **only when a stablecoin price anchor exists**.
***
### Wrapped Native Tokens (e.g. WETH)
* **Wrapped native tokens are supported**, **but only when traded against stablecoins**.
* They are **not tracked when traded against native tokens or other wrapped natives**.
Examples:
* ✅ WETH ↔ USDC → WETH PnL supported
* ❌ WETH ↔ ETH → not tracked
* ❌ WETH ↔ WBTC → not tracked unless a stablecoin leg exists
***
### Stablecoins
* **Wallet PnL is not calculated for stablecoins themselves** (e.g. USDC, USDT, DAI).
* However, **ERC20, native, and wrapped native tokens that are paired with stablecoins are fully supported**.
Examples:
* ✅ UNI ↔ USDC → UNI PnL supported
* ✅ ETH ↔ USDT → ETH PnL supported
* ❌ USDC ↔ DAI → no wallet PnL (stablecoin-only trade)
Stablecoins act as **pricing anchors**, not PnL assets.
***
### Summary
| Asset | PnL tracked? | Conditions |
| :- | :- | :- |
| ERC20 tokens | ✅ Yes | Paired with stable or native/wrapped native |
| Native tokens (ETH, etc.) | ✅ Yes | **Only when paired with stablecoins** |
| Wrapped native tokens (WETH, etc.) | ✅ Yes | **Only when paired with stablecoins** |
| Stablecoins | ❌ No | Used for pricing only |
| ERC20 ↔ Stablecoin | ✅ Yes | Fully supported |
| ERC20 ↔ WETH | ✅ Yes | Fully supported |
| ETH ↔ USDC | ✅ Yes | Supported |
| ETH ↔ WETH | ❌ No | Not supported |
***
## Supported chains
Profitability is currently live on:
* **Ethereum Mainnet**
* **Polygon Mainnet**
* **Base Mainnet**
More chains are planned.
***
## Known limitations
* Unrealized gains are not included
* Gas costs are excluded
* Only supported DEX events are tracked
* PnL is per trading pair, not global per token
These trade-offs are intentional to ensure **accuracy and determinism**.
***
## Summary
Moralis Profitability (PnL) provides:
* Realized, on-chain PnL
* Weighted average cost basis
* Near real-time updates
* Token- and wallet-level views
* Deterministic, explainable calculations
It’s built for **analytics accuracy**, not speculative valuation.
# Solana Token Standards
Source: https://docs.moralis.com/data-api/data-features/data-enrichment/solana-token-standards
Understand the Solana token standards supported by Moralis, including the SPL Token Program and Metaplex metadata standard.
Solana uses a different token model than EVM chains. Instead of each token deploying its own smart contract, all tokens are managed by shared **token programs**. Moralis supports the major Solana token standards and enriches API responses with decoded metadata.
***
## Token Programs
### SPL Token Program
The original **SPL Token Program** is the standard for fungible and non-fungible tokens on Solana. Most tokens on Solana — including SOL-wrapped tokens, stablecoins, and meme coins — use this program.
Key characteristics:
* Tokens are identified by their **mint address**
* Each holder has an **associated token account** (ATA) linked to their wallet
* Token metadata (name, symbol, logo) is stored offchain via the **Metaplex** standard
## Metaplex Metadata Standard
Most Solana tokens and NFTs use the **Metaplex** metadata standard to store human-readable information (name, symbol, image, attributes) offchain. The `standard` field in Moralis API responses indicates when a token follows this standard.
When Moralis returns `"standard": "metaplex"`, the response includes a `metaplex` object:
```json theme={null}
{
"mint": "9BB6NFEcjBCtnNLFko2FqVQBq8HHM13kCyYcdQbgpump",
"standard": "metaplex",
"name": "Fartcoin",
"symbol": "Fartcoin",
"metaplex": {
"metadataUri": "https://ipfs.io/ipfs/QmYfe8zVGHA1heej47AkBX3Nnetg2h2kqj5yymz1xyKeHb",
"masterEdition": false,
"isMutable": false,
"sellerFeeBasisPoints": 0,
"updateAuthority": "TSLvdd1pWpHVjahSpsvCXUbgwsL3JAcvokwaKt1eokM",
"primarySaleHappened": 0
}
}
```
### Metaplex fields explained
| Field | Description |
| - | - |
| `metadataUri` | URI pointing to the full metadata JSON (often IPFS or Arweave) |
| `updateAuthority` | The address that can modify the token's metadata |
| `sellerFeeBasisPoints` | Creator royalty on secondary sales (100 = 1%) |
| `primarySaleHappened` | Whether the initial sale has occurred |
| `isMutable` | Whether the metadata can still be updated |
| `masterEdition` | Whether this is a master edition NFT |
***
## NFTs on Solana
Unlike EVM chains where NFTs are grouped under a single contract, each Solana NFT is represented by a **unique mint address**. Moralis returns rich NFT metadata including:
* **Collection data** — `collectionAddress`, collection name, description, and verification status
* **Attributes** — Trait types and values (e.g., `"traitType": "Gender", "value": "Male"`)
* **Creator information** — Addresses, share percentages, and verification status
* **Media previews** — Low, medium, and high resolution image URLs via Moralis CDN
Example NFT metadata:
```json theme={null}
{
"address": "FVzM6rUA1SigPxh6e3iQ8dAPjQNf2guap3Xcdj8Q6R2H",
"standard": "metaplex",
"name": "Mad Lads #7256",
"symbol": "MAD",
"metaplex": {
"metadataUri": "https://madlads.s3.us-west-2.amazonaws.com/json/7256.json",
"updateAuthority": "2RtGg6fsFiiF1EQzHqbd66AhW7R5bWeQGpTbv2UMkCdW",
"sellerFeeBasisPoints": 420,
"primarySaleHappened": 1,
"isMutable": true,
"masterEdition": false
},
"collection": {
"collectionAddress": "J1S9H3QjnRtBbbuD4HjPV6RpRhwuk4zKbxsnCHuTgh9w",
"name": "Mad Lads",
"description": "Fock it.",
"metaplexMint": "J1S9H3QjnRtBbbuD4HjPV6RpRhwuk4zKbxsnCHuTgh9w",
"sellerFeeBasisPoints": 500
},
"creators": [
{
"address": "5XvhfmRjwXkGp3jHGmaKpqeerNYjkuZZBYLVQYdeVcRv",
"share": 0,
"verified": true
},
{
"address": "2RtGg6fsFiiF1EQzHqbd66AhW7R5bWeQGpTbv2UMkCdW",
"share": 100,
"verified": true
}
]
}
```
> [!NOTE]
>
> Some NFTs may lack a `collectionAddress` or other metadata fields. You can identify Metaplex-standard NFTs by the presence of a `metaplexMint` value.
***
## How Moralis Uses These Standards
Moralis automatically detects the token standard and enriches responses accordingly:
* **Fungible tokens** — Returns mint address, name, symbol, decimals, supply, logo, and market data (price, FDV)
* **NFTs** — Returns full Metaplex metadata, collection info, creator details, attributes, and media previews
* **Token balances** — Includes associated token account addresses and formatted amounts
The `standard` field in API responses tells you which metadata standard a token uses (currently `"metaplex"` for most Solana tokens).
***
## Related Pages
* [Token Metadata](/data-api/data-features/data-enrichment/token-metadata) — EVM token metadata enrichment
* [NFT Metadata](/data-api/data-features/data-enrichment/nft-metadata) — NFT metadata across chains
# Token Metadata
Source: https://docs.moralis.com/data-api/data-features/data-enrichment/token-metadata
Understand how Moralis combines onchain and offchain token metadata - names, supply, logos, categories, links, safety signals, and cross-chain implementations into a single developer-friendly response.
Moralis token metadata combines **onchain facts** (what the contract reports) with **offchain enrichment** (logos, categories, descriptions, links, verification, and market fields) to give you a clean, consistent token object across chains.
This page explains what data comes from where, how to interpret key fields, and how to use related data features like token scores and spam filtering.
Related pages:
* [Token API Overview](/data-api/evm/token/overview)
* [Token Scores](/data-api/data-features/token-scores)
* [Verified Contracts](/data-api/data-features/safety-and-trust/verified-contracts)
* [Spam Filtering](/data-api/resources/spam-filtering)
* [Token Search](/data-api/data-features/search-and-discovery/token-search)
***
## Onchain vs Offchain metadata
### Onchain metadata (from the token contract)
These values are sourced directly from chain data and are generally deterministic:
* `address`
* `name`
* `symbol`
* `decimals`
* `total_supply`
* `block_number` (block created)
* `created_at` (when Moralis first observed/indexed the contract)
***
### Offchain metadata (curated/enriched)
These values are enriched using trusted external sources and Moralis internal systems:
* `logo`
* `description`
* `categories`
* `links` (website, twitter, telegram, etc.)
* `security_score`
* `possible_spam`
* `verified_contract`
* `circulating_supply` (sourced from CoinGecko where available)
* `market_cap`, `fully_diluted_valuation`
* `address_label` (human-readable label)
Offchain enrichment improves UX and trust signals, and is especially useful for:
* Wallet UIs
* Token discovery experiences
* Safety filtering
* Market analytics
See:
* [Token Scores](/data-api/data-features/token-scores)
* [Spam Filtering](/data-api/resources/spam-filtering)
* [Verified Contracts](/data-api/data-features/safety-and-trust/verified-contracts)
***
## Example response
```
[
{
"address": "0x6982508145454ce325ddbe47a25d4ec3d2311933",
"address_label": "Pepe (PEPE)",
"name": "Pepe",
"symbol": "PEPE",
"decimals": "18",
"logo": "https://logo.moralis.io/0x1_0x6982508145454ce325ddbe47a25d4ec3d2311933_5c5ee6fce6d19f71c224cba025989229.jpeg",
"total_supply": "420689899653542539491331875576506",
"total_supply_formatted": "420689899653542.539491331875576506",
"fully_diluted_valuation": "2095999648.29",
"block_number": "17046105",
"validated": 1,
"created_at": "2023-04-14T14:51:35.000Z",
"possible_spam": false,
"verified_contract": true,
"categories": ["Meme"],
"links": {
"reddit": "https://www.reddit.com",
"telegram": "https://t.me/pepecoineth",
"twitter": "https://twitter.com/pepecoineth",
"website": "https://www.pepe.vip/"
},
"security_score": 96,
"description": "Pepe ($PEPE) is a meme coin aiming to bring back the glory days of memecoins...",
"circulating_supply": "420690000000000",
"market_cap": "2096000148.24",
"implementations": [
{
"chainId": "0xa86a",
"chain": "avalanche",
"chainName": "Avalanche",
"address": "0xa659d083b677d6bffe1cb704e1473b896727be6d"
},
{
"chainId": "0x38",
"chain": "bsc",
"chainName": "BNB Smart Chain",
"address": "0x25d887ce7a35172c62febfd67a1856f20faebb00"
},
{
"chainId": "0xa4b1",
"chain": "arbitrum",
"chainName": "Arbitrum One",
"address": "0x25d887ce7a35172c62febfd67a1856f20faebb00"
}
]
}
]
```
***
## Key fields explained
### Identity
* `address_label`: Human-readable label (useful for UI)
* `name`, `symbol`, `decimals`: Standard ERC-20 fields
* `logo`: Offchain logo URL (may be missing for new/unknown tokens)
Related:
* [Token Search](/data-api/data-features/search-and-discovery/token-search)
***
### Supply & valuation
* `total_supply`/ `total_supply_formatted`: Onchain total supply
* `circulating_supply`: Offchain circulating supply (CoinGecko where available)
* `market_cap`: Typically `price × circulating_supply`
* `fully_diluted_valuation`**(FDV)** : Typically `price × total_supply`
#### Circulating supply fallback
If `circulating_supply` is not available, Moralis falls back to `total_supply`.\
In that case, **market cap effectively becomes FDV**.
This is important when building:
* token rankings
* market cap charts
* “top tokens” discovery feeds
Related:
* [Token Prices](/data-api/data-features/data-enrichment/token-prices)
***
### Safety & trust signals
* `possible_spam`: Flag for suspicious/spam tokens
* `verified_contract`: Verified by CoinGecko (not Etherscan)
* `security_score`: Moralis safety score (0-100)
Related:
* [Spam Filtering](/data-api/resources/spam-filtering)
* [Verified Contracts](/data-api/data-features/safety-and-trust/verified-contracts)
* [Token Scores](/data-api/data-features/token-scores)
***
### Classification & links
* `categories`: Token categories (e.g. Meme, DeFi)
* `links`: Offchain links (twitter, website, telegram, etc.)
* `description`: Offchain token description
***
### Cross-chain implementations
* `implementations` lists known linked deployments of the “same” token across multiple chains (e.g. bridged or multi-chain versions).
> [!NOTE]
>
> `implementations` only lists the **other** chains the token is deployed on. The chain you queried is never repeated in the array — that deployment is the token object itself (`address` at the top level). In the example above the token was requested on Ethereum, so the array contains Avalanche, BNB Smart Chain, and Arbitrum, but not Ethereum. If you need the full multi-chain set, combine the queried chain and address with the entries in `implementations`.
This enables:
* consistent UI labels/logos across chains
* unified token discovery experiences
* cross-chain token analytics
***
## Summary
Moralis Token Metadata provides a unified token object that combines:
* **Onchain** ERC-20 data (name, symbol, decimals, supply)
* **Offchain** enrichment (logos, links, categories, descriptions)
* **Trust signals** (spam flags, verification, security score)
* **Market fields** (circulating supply, market cap, FDV)
* **Cross-chain implementations** for linked tokens
# Token Prices
Source: https://docs.moralis.com/data-api/data-features/data-enrichment/token-prices
Learn how Moralis token prices are derived from onchain DEX activity, including pool selection, pair-based pricing, liquidity filtering, inactivity rules, and mainnet-only behavior.
## Token Prices
Moralis token prices are derived directly from **onchain DEX activity**, not from aggregated offchain price feeds.
Prices are based on real swaps, making them:
* Trust-minimized (no centralized oracle dependency)
* Chain-specific
* Deterministic and reproducible
Prices can be fetched:
* **By token address** (Moralis selects the best pool automatically), or
* **Directly by pair address**, when you want full control over which pool is used
Related concepts:
* [Supported DEXes](/data-api/data-features/integrations/supported-dexs)
* [Liquidity Filtering](/data-api/data-features/safety-and-trust/liquidity-filtering)
***
## How Token Prices Work
Moralis calculates token prices using the **last traded price** observed on supported decentralized exchanges.
Key characteristics:
* Prices come from real onchain swap events
* No volume-weighted averaging across exchanges
* Prices are returned in USD
* Pricing can be **pool-selected automatically** or **explicitly defined by pair**
This makes token prices safe to use in downstream features such as [Token Balances](/data-api/evm/wallet/token-balances), [Wallet Net Worth](/data-api/evm/wallet/net-worth), [PnL](/data-api/evm/wallet/wallet-pnl) and many more.
***
## Fetching Prices by Token vs Pair
Moralis supports two pricing models:
### Token-Based Pricing (Default)
When querying by token address:
* Moralis automatically selects the most appropriate pool
* Pool selection follows liquidity and activity rules
* Best suited for portfolio, net worth, and analytics use cases
This is the recommended approach for most applications.
Related pages:
* [Token price by token address](/data-api/evm/token/prices/token-price)
* [Token price by pair address](/data-api/evm/token/swaps/pair-stats)
***
### Pair-Based Pricing (Explicit Pool)
You can also fetch prices **directly by pair address**.
When querying by pair:
* The specified pool is always used
* No pool ranking or substitution occurs
* The price reflects swaps in that exact pair
This is useful when:
* You need deterministic pricing from a known pool
* You want to inspect or monitor a specific market
* You are building trading, monitoring, or analytics tools around a single pair
Liquidity and inactivity checks still apply to ensure price safety.
***
## Supported Pair Types
Moralis supports **all DEX pair types**, including:
* **Stablecoin pairs** (e.g. USDC / USDT / DAI)
* **Wrapped native token pairs** (e.g. WETH, WBNB, SOL)
* **Token / Token pairs** (e.g. REPPO / VIRTUAL)
This applies to both **token-based** and **pair-based** price queries, as long as sufficient onchain liquidity exists.
***
## Mainnet-Only Support
Token prices are **mainnet-only**.
Why:
* Prices depend on active onchain DEX liquidity
* Testnets generally lack sustained or meaningful trading activity
Any feature that depends on token prices is therefore also mainnet-only, including:
* Token price
* Wallet net worth
* Portfolio percentages
* PnL calculations
***
## What “Price” Means
A token’s price represents:
* The most recent swap price
* Extracted from the DEX swap log
* Converted to USD
For Token / Token pairs, the price is resolved from the selected pair and converted to USD using the best available onchain reference.
When querying by pair address, this conversion is based strictly on that pool’s swap activity.
***
### Multiple Swaps in the Same Block
If multiple swaps occur within a single block:
* The **final swap price in that block** is used
* Intra-block price movements are not tracked
This keeps pricing deterministic and avoids block-level noise.
***
## Pool Selection Logic (Token-Based Pricing)
When querying prices by token address:
### Real-Time Prices
1. Pools that fail [liquidity filtering](/data-api/data-features/safety-and-trust/liquidity-filtering) are excluded
2. Remaining pools are ranked by swap activity over the last 24 hours
3. The most active pool is selected
### Historical Prices
1. The top two pools by lifetime usage are selected
2. The most recent record from each pool is compared
3. The pool with higher liquidity is chosen
Pair-based queries bypass this logic and always use the specified pool.
***
## Liquidity Thresholds
Moralis enforces minimum liquidity requirements per chain.
Default thresholds:
* **EVM chains:** \$50 minimum liquidity per side (each token in the pair)
* **Solana:** no enforced liquidity threshold
This threshold applies at the pool level and is evaluated for both assets in the pair. The pool is considered eligible only if **both sides** meet the minimum threshold.
Read more about [Liquidity Thresholds](/data-api/data-features/safety-and-trust/liquidity-filtering).
***
## Inactivity Handling
Tokens or pairs with no recent trading activity can be excluded.
Use the `max_token_inactivity` query parameter to filter out inactive markets.
This applies to:
* Token-based pricing
* Pair-based pricing
* Token balances
***
## Common Error Scenarios
You may encounter the following:
* **No liquidity pool found**\
No qualifying pool exists for the token or pair
* **Insufficient liquidity**\
Pool fails liquidity filtering
* **Inactive market**\
Token or pair fails inactivity filtering
* **Testnet request**\
Token prices are not supported on testnets
***
## When to Use Token Prices (and When Not To)
Token prices are well-suited for:
* Wallet net worth calculations
* Portfolio tracking
* PnL and trading analytics
* Token discovery and filtering
Pair-based pricing is best suited for:
* Market monitoring
* Trading analytics
* Pool-specific dashboards
They are not intended to replace:
* High-frequency trading price feeds
* Offchain oracle systems
* Tick-level or order-book pricing data
# Transaction Decoding
Source: https://docs.moralis.com/data-api/data-features/data-enrichment/transaction-decoding
Moralis enriches raw blockchain transactions with human-readable meaning, making it easier to understand what actually happened onchain.
Instead of working with low-level logs and method calls, you get **decoded actions, labels, and categories** that describe wallet activity in a clear, consistent way.
***
## What This Includes
Transaction decoding and enrichment combines two core capabilities:
* **Wallet activity categorisation** (what type of action occurred)
* **ABI-based decoding and labelling** (what the transaction did at a contract level)
Together, these form Moralis’ **semantic transaction layer**.
***
## Wallet Activity Decoding
Moralis can return a **single, chronological view of a wallet’s onchain activity**, covering all major transaction types.
This includes:
* Native transfers
* ERC20 swaps and token transfers
* NFT transfers and sales
* DeFi interactions
* Smart contract interactions
All activity is normalized into a consistent timeline, removing the need to aggregate multiple endpoints or data sources.
### Key Benefits
* **Single API request**\
Fetch a complete wallet history in one call.
* **Automatic categorisation**\
Each transaction is classified into a clear, human-readable category.
* **Reduced complexity**\
No need to manually decode logs, traces, or contract calls.
* **Consistent ordering**\
Transactions are returned in a clean, chronological format.
***
## Transaction Categories
Each transaction is assigned a category based on its onchain behavior.
Currently supported categories include:
* Send
* Receive
* Token Send
* Token Receive
* NFT Send
* NFT Receive
* Deposit
* Withdraw
* Token Swap
* Airdrop
* Mint
* Burn
* NFT Purchase
* NFT Sale
* Borrow
* Approve
* Revoke
* Contract Interaction
> [!NOTE]
>
> Category support is continuously expanding as new transaction patterns and protocols are added.
***
## ABI Decoding & Transaction Labelling
Beyond high-level categories, Moralis also decodes transactions at the **contract interaction level**.
Using verified ABIs and internal decoding logic, Moralis:
* Decodes method calls
* Interprets parameters
* Assigns meaningful **labels** to transactions
This allows you to distinguish between different contract interactions even when they fall under the same high-level category.
***
## Why This Matters
Transaction decoding and enrichment enables you to:
* Build readable wallet activity feeds
* Show users *what they actually did* onchain
* Power analytics, notifications, and alerts
* Avoid custom ABI decoding and protocol-specific logic
* Deliver consistent UX across chains and protocols
This is especially valuable for:
* Wallets and portfolio trackers
* Analytics dashboards
* Tax and accounting tools
* Compliance and monitoring systems
***
## Important Notes
* Decoding and categorisation are **best-effort** and based on available onchain data and ABIs
* Unknown or unverified contracts may fall back to generic labels (e.g. `Contract Interaction`)
* New transactions occurring during pagination will not affect already-decoded results (see Pagination)
# Data Features Overview
Source: https://docs.moralis.com/data-api/data-features/data-features-overview
An overview of Moralis Data Features, including enrichment, safety signals, discovery tools, and protocol coverage that turn raw blockchain data into usable insights.
Moralis transforms raw blockchain data into **structured, enriched, and trustworthy insights** that are easy to build on.
Instead of dealing with low-level transactions, logs, and metadata inconsistencies, you get **interpreted data** - with context, labels, scores, and normalization applied consistently across chains and APIs.
These features fall into four broad areas:
> [card] [Data Enrichment](/data-api/data-features/data-enrichment/address-labelling)
>
> Logic and normalization that add **meaning and context** to onchain data.
> [card] [Safety & Trust](/data-api/data-features/safety-and-trust/verified-contracts)
>
> Signals that help identify legitimate assets and reduce exposure to scams.
> [card] [Search & Discovery](/data-api/data-features/search-and-discovery/token-search)
>
> Tools that help users **find relevant tokens and assets** across chains.
> [card] [Prices](/data-api/data-features/data-enrichment/token-prices)
>
> Understand how Moralis **decodes and normalizes** token and NFT prices.
> [card] [Integrations](/data-api/data-features/integrations/supported-dexs)
>
> Clear visibility into **what Moralis supports** across chains and protocols.
# DeFi Protocols
Source: https://docs.moralis.com/data-api/data-features/integrations/defi-protocols
DeFi protocol coverage across EVM and Solana, how protocol decoding works, and how to fetch the full, always-current list of supported protocols from the API.
Moralis decodes DeFi activity - lending, borrowing, staking, liquid staking, and liquidity pools - across **thousands of protocols on EVM chains** and the **top protocols on Solana**, returning enriched, protocol-aware positions through the [DeFi API](/data-api/universal/defi/overview).
Coverage expands continuously, so the API itself is the source of truth for what is supported at any given moment.
> [!NOTE]
>
> This page covers **protocol availability**. To fetch a wallet's actual DeFi **balances and positions**, use the DeFi API endpoints — [Wallet Protocols](/data-api/universal/defi/wallet-protocols), [Wallet Positions](/data-api/universal/defi/wallet-positions), and [Detailed Positions](/data-api/universal/defi/wallet-positions-detailed) — each accepts the `chain` parameter for EVM or Solana.
## Fetch the Full List of Supported Protocols
Use the [**Get Supported DeFi Protocols**](/data-api/universal/defi/supported-protocols) endpoint to retrieve the complete, current list of supported protocols with their chain coverage - ideal for keeping your own UI or coverage checks in sync:
```bash theme={null}
curl "https://api.moralis.com/v1/defi/protocols?chains=eth" \
-H "X-Api-Key: YOUR_API_KEY"
```
Pass the optional `chains` filter (for example `eth`, `base`, `polygon`, or `solana`) to narrow results to specific chains.
> [!NOTE]
>
> By default, we track all forked Uniswap v2 protocols. If a particular protocol has not yet been decoded, it appears as `unknown` in API responses - [reach out to support](https://moralis.com/enterprise/) and we will prioritize decoding it.
## EVM Coverage
DeFi protocol decoding is available across these EVM chains:
* Arbitrum
* Avalanche
* Base
* Binance
* Ethereum
* Linea
* Monad
* Optimism
* Polygon
* Sei
> [!NOTE]
>
> **Coverage is not uniform across chains.** Protocol availability depends on where each protocol is deployed and its adoption per chain. Query the endpoint above for exact per-chain support.
We support thousands of EVM protocols, including all forked Uniswap v2 protocols. A few of the most widely used, with their query parameters:
| Protocol | Query Parameter | Example Chains |
| - | - | - |
| Aave v3 | `aave-v3` | Base, Ethereum, Polygon |
| Uniswap v3 | `uniswap-v3` | Arbitrum, Avalanche, Base, Binance, Ethereum, Optimism, Polygon |
| Pancakeswap v3 | `pancakeswap-v3` | Arbitrum, Base, Binance, Ethereum, Linea, Monad |
| Lido | `lido` | Ethereum |
| Rocket Pool | `rocketpool` | Arbitrum, Base, Ethereum, Optimism, Polygon |
| Eigenlayer | `eigenlayer` | Ethereum |
| MakerDAO | `makerdao` | Ethereum |
| Pendle | `pendle` | Ethereum |
This is a curated highlight, not the full list - call the endpoint above for complete, up-to-date coverage.
## Solana Coverage
The Solana DeFi API supports **10 protocols**, together covering roughly **90% of Solana DeFi TVL** - including the top protocols by TVL (Jupiter, Kamino, Sanctum, and Raydium):
| Protocol | Category |
| - | - |
| Jupiter Lend | Lending |
| Jupiter Perpetual Exchange | Perpetuals |
| Kamino Lend | Lending |
| Sanctum | Liquid staking |
| Save (formerly Solend) | Lending |
| Raydium | DEX / AMM |
| Orca | DEX / AMM |
| Drift | Perpetuals |
| Jito | Liquid staking |
| Marinade | Liquid staking |
See the [DeFi API](/data-api/universal/defi/overview) for endpoints and examples — the same cross-chain endpoints return Solana and EVM positions.
More protocols are added on a rolling basis. To request prioritization of a specific protocol, [reach out to the team](https://moralis.com/enterprise/).
# NFT Marketplaces
Source: https://docs.moralis.com/data-api/data-features/integrations/nft-marketplaces
See which NFT marketplaces Moralis supports across chains, powering NFT trades, sale prices, and marketplace analytics.
## Supported NFT Marketplaces
Moralis indexes onchain NFT trades from a growing set of **NFT marketplaces** across multiple chains. This coverage powers features such as:
* NFT trades
* NFT sale prices
* Collection and token-level trading analytics
* Wallet NFT activity
This page lists **marketplace coverage only**. Endpoint behavior and response structure are documented on the relevant NFT feature pages.
***
## Marketplace Support by Chain
### OpenSea
Supported chains:
* Ethereum
* Polygon
* Binance
* Arbitrum
* Avalanche
* Optimism
* Base
* Monad
OpenSea is the primary source of NFT trade activity across multiple EVM chains and provides broad, high-liquidity marketplace coverage.
***
### Blur
Supported chains:
* Ethereum
Blur trades are included for high-frequency and professional NFT trading activity on Ethereum.
***
### LooksRare
Supported chains:
* Ethereum
LooksRare trades are indexed for Ethereum-based NFT collections.
***
### X2Y2
Supported chains:
* Ethereum
X2Y2 marketplace trades are supported for Ethereum NFTs.
***
### 0x Protocol
Supported chains:
* Ethereum
0x Protocol trades are indexed where NFTs are bought and sold through the protocol's onchain execution layer.
***
## Notes and Expectations
* Marketplace coverage is **chain-specific**.
* Only **executed marketplace trades** are indexed - listings alone are not considered trades.
* NFT transfers that are not marketplace sales (e.g. gifts or direct transfers) are excluded.
* New marketplaces and chains are added continuously based on:
* Trading volume
* Ecosystem relevance
* Customer demand
# Supported DEXes
Source: https://docs.moralis.com/data-api/data-features/integrations/supported-dexs
See which decentralized exchanges (DEXes) Moralis indexes per chain across EVM and Solana, powering token pairs, swaps, pricing, and related DEX-derived features.
## Supported DEXes
Moralis indexes onchain liquidity and swaps from a curated set of decentralized exchanges (DEXes) across **EVM chains and Solana**. This coverage powers token pairs, swaps, token prices, OHLC, and other DEX-derived features.
If you don’t specify a DEX, Moralis automatically searches across supported DEXes on the target chain and selects eligible markets using safety rules such as [Liquidity Filtering](/data-api/data-features/safety-and-trust/liquidity-filtering).
Related pages:
* [Token Prices](/data-api/data-features/data-enrichment/token-prices)
* [Liquidity Filtering](/data-api/data-features/safety-and-trust/liquidity-filtering)
***
## EVM DEX support by chain
### Ethereum (0x1)
* Uniswap v4
* Uniswap v3
* Uniswap v2
* Sushiswap v2
* Fraxswap (v2)
### Polygon (0x89)
* Uniswap v4
* Quickswap v2
* Uniswap v3
* Uniswap v2
* MM Finance
### Binance Smart Chain / BSC (0x38)
* Uniswap v4
* PancakeSwap v3
* PancakeSwap v2
* PancakeSwap v1
* Uniswap v3
* Uniswap v2
### Avalanche (0xa86a)
* Uniswap v4
* Trader Joe
* Pangolin
### Cronos (0x19)
* VVS Finance
* MM Finance
* Crodex
### Arbitrum (0xa4b1)
* Uniswap v4
* Uniswap v3
* Camelot v2
* Sparta Dex
### Optimism (0xa)
* Uniswap v4
* Sushiswap v2
* Uniswap v2
### Base (0x2105)
* Uniswap v4
* Uniswap v3
* Uniswap v2
* Sushiswap v2
* Sushiswap v3
* PancakeSwap v2
* PancakeSwap v3
* Aerodrome
* BaseSwap
* Sharkswap
### Linea (0xe708)
* PancakeSwap v3
* Nile
### Moonbeam (0x504)
* Beamswap v3
* StellaSwap
### Ronin (0x7e4)
* Katana
### PulseChain (0x171)
* PulseX
* 9inch
### Monad (0x8f)
* Uniswap v4
* Uniswap v3
* Uniswap v2
* PancakeSwap v3
* PancakeSwap v2
***
## Solana DEX support
Moralis indexes multiple DEX programs on Solana to support token pairs, swaps, pricing, and other DEX-derived features.
### Solana
* **Raydium v4**\
Program: `675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8`
* **Raydium CLMM (concentrated liquidity)**\
Program: `CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK`
* **Raydium CPMM (constant product)**\
Program: `CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C`
* **Meteora Dynamic AMM**\
Program: `Eo7WjKq67rjJQSZxS6z3YkapzY3eMj6Xy8X5EQVn5UaB`
* **Meteora Dynamic AMM v2**\
Program: `cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG`
* **Meteora DLMM (dynamic liquidity)**\
Program: `LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo`
* **Meteora Dynamic Bonding Curve (DBC)**\
Program: `dbcij3LWUppWqq96dh6gJWwBifmcGfLSB5D4DuSMaqN`
* **Orca / Whirlpool**\
Program: `whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc`
* **PumpFun**\
Program: `6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P`
* **PumpSwap**\
Program: `pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA`
* **LaunchLab**\
Program: `LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj`
* **BisonFi**\
Program: `BiSoNHVpsVZW2F7rx2eQ59yQwKxzU5NvBcmKshCSUypi`
* **HumidiFi**\
Program: `9H6tua7jkLhdm3w8BvgpTn5LZNU7g4ZynDmCiNN3q6Rp`
* **Phoenix**\
Program: `2rds7kS9FcvUqaz3dXtgxfGC1otD3vyf3PkKByWRT7Bmm9T9aWuJ1DTaj2KUJC7FP22qyawnivUsNfBqTxo7SkG`
* **Manifest**\
Program: `MNFSTqtC93rEfYHB6hF82sKdZpUDFWkViLByLd1k1Ms`
* **Tessera V**\
Program: `TessVdML9pBGgG9yGks7o4HewRaXVAMuoVj4x83GLQH`
* **SolFi**\
Program: `SoLFiHG9TfgtdUXUjWAxi3LtvYuFyDLVhBWxdMZxyCe`
* **ZeroFi**\
Program: `ZERor4xhbUycZ6gb9ntrhqscUcZmAbQDjEAtCf4hbZY`
* **GoonFi V1 (dormant)**\
Program: `goonERTdGsjnkZqWuVjs73BZ3Pb9qoCUdBUL17BnS5j`
* **GoonFi V2 (active)**\
Program: `goonuddtQRrWqqn5nFyczVKaie28f3kDkHWkHtURSLE`
* **Saber**\
Program: `SSwpkEEcbUqx4vtoEByFjSkhKdCT862DNVb52nZg1UZ`
* **PancakeSwap**\
Program: `HpNfyc2Saw7RKkQd8nEL4khUcuPhQ7WwY1B2qjx8jxFq`
> [!NOTE]
>
> For the following protocols, swap data (and therefore prices) is available from **June 1, 2026** onwards. Full historical coverage for these protocols is coming soon. All other Solana DEXes listed above have full history.
>
> * BisonFi
> * HumidiFi
> * Phoenix
> * Manifest
> * Tessera V
> * SolFi
> * ZeroFi
> * GoonFi V1 (dormant)
> * GoonFi V2 (active)
> * Saber
> * PancakeSwap
***
## Notes and expectations
* DEX coverage is chain-specific: a DEX brand may not exist (or be indexed) on every chain.
* Inclusion does not guarantee every pool is eligible - [Liquidity Filtering](/data-api/data-features/safety-and-trust/liquidity-filtering) still applies.
* This page is intentionally coverage-only. Endpoint-specific behavior belongs on the relevant feature pages.
# NFT Floor Prices
Source: https://docs.moralis.com/data-api/data-features/prices/floor-prices
Learn how Moralis provides NFT floor prices, including what a floor price represents, supported chains, data sources, refresh cadence, inactivity rules, and historical availability.
NFT Floor Prices provide a **collection-level snapshot** of the lowest-priced NFT currently listed for sale. This gives a fast, comparable baseline for what it would cost to acquire the cheapest item in a collection *right now*.
Floor prices are best suited for:
* Market overviews and dashboards
* Collection comparisons
* Entry-price signals and alerts
They are intentionally different from [NFT Sale Prices](/data-api/data-features/prices/sale-prices), which are based on completed onchain trades.
***
## What a Floor Price Represents
The floor price is the **lowest active listing price** for an NFT in a given collection.
Important characteristics:
* Based on **active listings**, not completed sales
* Represents seller intent, not executed market price
* Calculated at the **collection level**, not per token
Because listings can be added or removed at any time, floor prices are inherently volatile and should be treated as **indicative**, not authoritative trade prices.
***
## Supported Chains
NFT floor prices are currently supported on:
* Ethereum
* Base
* Monad
* Arbitrum
* Ronin
* Flow
* Sei
Coverage may expand over time. For trade-based pricing with broader chain support, see NFT Sale Prices.
***
## Data Sources
Floor prices are sourced from a combination of marketplace and aggregation APIs:
* **OpenSea API** (primary source)
* **Magic Eden API**\
Magic Eden aggregates floor prices across multiple marketplaces, including OpenSea, Blur, X2Y2, and Magic Eden itself
* **CoinGecko** (fallback / enrichment)
These sources provide listing-level market data that cannot be derived purely from onchain events.
Important distinction:
* **NFT Sale Prices** → derived from onchain marketplace trades
* **NFT Floor Prices** → derived from offchain marketplace listing data
Related pages:
* [NFT Marketplaces](/data-api/data-features/integrations/nft-marketplaces)
* [NFT Sale Prices](/data-api/data-features/prices/sale-prices)
***
## Refresh Frequency
Floor prices are refreshed **every 60 minutes**.
This cadence balances:
* Marketplace rate limits
* Data freshness
* Platform-wide performance and stability
Floor prices are not real-time and should not be treated as tick-level market data.
***
## First-Time Requests (Warm-Up Behavior)
If a collection’s floor price has **never been requested before**, the first request will return:
* HTTP status: **202**
* Message:
```javascript theme={null}
{
"message": "This contract is currently being processed. Floor price data will be available shortly. Please try again later."
}
```
During this warm-up period:
* The collection is registered for tracking
* Floor price data begins syncing
Once processing completes, subsequent requests return floor price data normally.
***
## Inactivity Handling
If a collection has **no trading activity for 7 days**:
* Floor price updates are paused
* No new floor price snapshots are recorded
Once trading activity resumes:
* Floor price updates automatically resume
* No manual action is required
This prevents stale or misleading prices from being continuously refreshed for inactive markets.
***
## Historical Floor Price Data
### Backfilling
Historical floor prices are **not backfilled**.
Reason:
* Marketplace APIs do not currently expose historical listing data
* Historical tracking can only begin after the first request
Moralis starts saving floor prices in **60-minute intervals** from the moment a collection is first requested.
***
### Supported Historical Intervals
When requesting time-series floor price data, the interval determines the data resolution:
* **1 day**\
Data points every 60 minutes
* **7 days**\
Hourly data points
* **30 days**\
Hourly data points
* **Greater than 30 days**\
Daily data points
This adaptive resolution keeps queries efficient while preserving meaningful trends.
***
## Inactive Collections and Historical Access
If a collection becomes inactive:
* Floor prices stop updating
* **Previously saved historical data remains accessible**
This allows you to:
* Analyze past market conditions
* Build long-term charts
* Compare historical floors even for dormant collections
***
## When to Use Floor Prices (and When Not To)
Use NFT Floor Prices when you need:
* A quick market baseline
* Collection-to-collection comparisons
* Entry price signals
Do not rely on floor prices for:
* Valuation of a specific NFT
* Profitability or realized value calculations
* Historical execution accuracy
For executed market prices and provenance, use [NFT Sale Prices](/data-api/data-features/prices/sale-prices).
# NFT Sale Prices
Source: https://docs.moralis.com/data-api/data-features/prices/sale-prices
Understand how Moralis computes NFT sale prices from onchain marketplace trades, including last/lowest/highest/average sale, lookback windows, marketplace + chain coverage, and enriched trade metadata.
Moralis NFT Sale Prices summarize **real onchain sale and trade activity** for NFTs and collections, based on buys/sells from supported NFT marketplaces.
This feature is built on top of Moralis **NFT Trades** data and is designed for production use cases like:
* Sale price tracking and alerts
* Wallet and token-level trade analysis
* Portfolio valuation and historical provenance
***
## What “Sale Price” Means
A sale is recorded when an NFT is bought/sold on a supported marketplace. Moralis extracts and normalizes:
* The **payment token** used (native or ERC20)
* The **raw price** paid (base units) and **formatted price**
* The **USD price at time of sale**
* The **current USD value** using today’s token price
Important: these are **marketplace sales**, not arbitrary transfers. Simple NFT transfers (gift/send) are not considered sales.
***
## What You Get Back
Sale price summaries typically include:
### Last sale
The most recent recorded sale within the available trade history, including:
* `transaction_hash`
* `block_timestamp`
* `buyer_address` / `seller_address`
* `token_id`
* `price` (raw base units)
* `price_formatted` (decimal-adjusted)
* `usd_price_at_sale`
* `current_usd_value`
* `payment_token` metadata (name, symbol, decimals, address, logo)
### Lowest sale (within a lookback window)
The lowest recorded sale price within the specified lookback period (see “Lookback window” below).
### Highest sale
The highest recorded sale price (typically within the same scope as the response; depends on endpoint).
### Average sale
An average price across trades included in the response scope:
* `price` / `price_formatted`
* `current_usd_value`
### Total trades
A count of sales/trades included for that scope:
* `total_trades`
Notes on price fields:
* `price` is the raw integer amount in the payment token’s base units.
* `price_formatted` is the human-readable value using `token_decimals`.
* `usd_price_at_sale` is the USD valuation at the time the sale happened.
* `current_usd_value` is recalculated using the current price of the payment token (useful for mark-to-market comparisons).
***
## Lookback Window (`days`)
Some sale price summaries (notably **lowest sale**) support an optional `days` query parameter:
* Default: **7 days**
* Maximum: **365 days**
If you set `days=30`, “lowest sale” will be the lowest sale price found in the last 30 days. If you omit it, the system uses 7 days.
Practical guidance:
* Use smaller windows (7–30) for “recent floor” style features.
* Use larger windows (90–365) for long-term volatility and range analysis.
***
## Marketplace Coverage
Sale prices are derived from trades on supported marketplaces. Current coverage includes:
* OpenSea
* Blur
* LooksRare
* X2Y2
* 0xProtocol
Coverage can vary by chain and marketplace. For the authoritative matrix, use the [Marketplaces](/data-api/data-features/integrations/nft-marketplaces) page.
Related pages:
* [NFT Marketplaces](/data-api/data-features/integrations/nft-marketplaces)
***
## Chain Coverage
NFT Trades (and therefore NFT Sale Prices) are available on:
* Ethereum
* Polygon
* Binance
* Arbitrum
* Avalanche
* Optimism
* Base
* Monad
***
## Enriched Trade Metadata
All NFT Trade endpoints (including those powering sale price summaries) can include enriched metadata such as:
* Marketplace metadata (name + logo)
* Collection metadata (collection name + logo)
* Payment token metadata (name, symbol, logo, decimals, address)
* Current USD value for each trade (mark-to-market)
* Optional NFT metadata via `nft_metadata=true`
Use `nft_metadata=true` when you need token attributes/media in the same response. Leave it off for performance when you only need pricing and trade facts.
Related pages:
* [NFT Metadata](/data-api/data-features/data-enrichment/nft-metadata)
* [NFT Image Previews](/data-api/data-features/data-enrichment/nft-metadata/image-previews-cdn)
***
## Related Endpoints (Trade Feeds)
Sale price summaries are most useful when paired with raw trade feeds:
* [NFT Trades by Collection](/data-api/evm/nft/trades/collection-trades)\
Fetch the full trade history for a collection (sales feed)
* [NFT Trades by Wallet](/data-api/evm/wallet/nft-trades-by-wallet)\
Fetch all NFT trades associated with a wallet address
* [NFT Trades by Token ID](/data-api/evm/nft/trades/trades-by-token-id)\
Fetch the trade history for a specific NFT (collection + token id)
# Accurate Net Worth & Token Balances
Source: https://docs.moralis.com/data-api/data-features/safety-and-trust/accurate-net-worth-and-balances
Keep spam tokens and unreliable prices out of wallet balances and net worth. Which filters to use, recommended values for each use case, and checks to run on the response.
Wallets collect tokens they never asked for. Airdropped spam, dead tokens and tokens that trade in tiny pools can all carry a USD price, and one bad price is enough to inflate a portfolio total.
You control how strict Moralis is when it values a wallet. This page explains the filters, recommends values for common use cases, and lists the extra checks worth running on the response.
It applies to:
* [Token Balances](/data-api/evm/wallet/token-balances) (`/wallets/{address}/tokens`)
* [Wallet Net Worth](/data-api/evm/wallet/net-worth) (`/wallets/{address}/net-worth`)
* [Cross-Chain Token Balances](/data-api/universal/wallet/cross-chain-token-balances) (`/v1/wallets/{address}/tokens`)
* [Token Price](/data-api/evm/token/prices/token-price) and [Token Prices (Batch)](/data-api/evm/token/prices/token-prices-batch), which take the price filters
> [!WARNING]
>
> On these endpoints every filter is **off by default**. If you show balances or net worth to end users, set them explicitly.
***
## Why values look wrong
Moralis prices tokens from onchain DEX swaps: a token's price is the last price it traded at in its selected pool (see [Token Prices](/data-api/data-features/data-enrichment/token-prices)). This is accurate for actively traded tokens. It goes wrong in three cases:
| Cause | What you see | Filter that fixes it |
| - | - | - |
| **Spam tokens.** Airdropped tokens with fake names, often copying a real token, sometimes with a pool set up to give them a price. | Unknown tokens with large balances and large USD values. | `exclude_spam` |
| **Thin pools.** A token's only pool holds a few hundred dollars. One small swap moves the price by orders of magnitude. | A token's value spikes, then corrects on a later call once the pool trades again. | `min_pair_side_liquidity_usd` |
| **Dead tokens.** Trading stopped weeks or months ago, so the last price is stale. | Tokens nobody can sell still add to net worth. | `max_token_inactivity` |
If the inflated value goes away on the next call, the cause is almost always a thin pool. The price really was traded onchain, but in a pool too small to trust. A liquidity threshold stops those prices being used at all.
***
## The filters
### `exclude_spam`
Removes tokens that Moralis flags as `possible_spam`. Detection uses contract metadata, known spam and phishing patterns, and onchain behaviour, and is updated as new patterns appear. See [Spam Filtering](/data-api/resources/spam-filtering).
**Recommendation: always set `exclude_spam=true`** for anything shown to users. Hardly any real holdings are flagged, and spam is the most common source of inflated totals.
### `min_pair_side_liquidity_usd`
Sets the minimum USD liquidity a pool must hold on **each side** before Moralis uses it to price a token. With `1000`, a TOKEN/USDC pool counts only if both the TOKEN side and the USDC side hold at least \$1,000. Tokens with no qualifying pool are excluded. The default on EVM chains is \$50 per side. See [Liquidity Filtering](/data-api/data-features/safety-and-trust/liquidity-filtering).
This is the most effective filter against prices that jump and then correct. Pushing a price up with a single swap costs a lot more in a \$1,000-a-side pool than in a \$50-a-side pool.
**Recommendation: `1000` for consumer wallets and portfolio apps.** Use `250` to keep more small-cap tokens, or `10000` or more for reporting, accounting or anything that moves money based on the value. Above \$1,000 a side you start losing real but small tokens, so raise it only when a false value costs more than a missing one.
### `max_token_inactivity`
Excludes tokens that have not traded for more than the given number of days.
**Recommendation: `7`.** A price more than a week old isn't a fair current value for a portfolio. Raise it to `30` if your users hold long-tail tokens that trade rarely and you would rather show a stale price than none.
### `exclude_unverified_contracts`
Keeps only ERC20 tokens verified by CoinGecko (`verified_contract: true`). See [Verified Contracts](/data-api/data-features/safety-and-trust/verified-contracts).
This is the strictest filter. It removes almost all spam and manipulated tokens, along with real tokens that are new or too small to be listed on CoinGecko.
**Recommendation: use it for headline numbers that must be defensible**, such as a total balance shown on an exchange, a figure used in reporting, or an eligibility check. For a wallet that lists everything the user holds, leave it off and use the `verified_contract` field instead (see [Checks to run on the response](#checks-to-run-on-the-response)).
***
## Recommended settings
| Use case | `exclude_spam` | `min_pair_side_liquidity_usd` | `max_token_inactivity` | `exclude_unverified_contracts` |
| - | - | - | - | - |
| **Wallet or portfolio app.** Show everything real, value it sensibly. | `true` | `1000` | `7` | `false` |
| **Strict valuation.** Exchanges, reporting, rewards, risk and eligibility checks. | `true` | `10000` | `3` | `true` |
| **Discovery or trading tools.** Users want the long tail and accept more noise. | `true` | `250` | `30` | `false` |
Start with the first row. Move to a stricter row if users still report inflated values, and to a looser one if they report missing tokens.
```bash Wallet or portfolio app theme={null}
curl "https://deep-index.moralis.io/api/v2.2/wallets/0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045/net-worth?chains=eth&chains=base&exclude_spam=true&exclude_unverified_contracts=false&min_pair_side_liquidity_usd=1000&max_token_inactivity=7" \
-H "X-API-Key: YOUR_API_KEY"
```
Use **the same values** on Token Balances and Net Worth. Then the tokens in the list add up to the total, and users don't see a figure they can't reconcile.
***
## Checks to run on the response
The filters cover most cases. For a portfolio that real users rely on, also check these Token Balances fields before showing a value:
* **`verified_contract`**: when unverified tokens are left in, show them in the list but leave them out of the headline total, or label them "unverified". You get the stricter total without hiding anything.
* **`possible_spam`**: if you don't use `exclude_spam`, for example to show spam in a separate "hidden" tab, never count these tokens towards value.
* **`percentage_relative_to_total_supply`**: an ordinary wallet that holds a large share (say more than 1%) of an unverified token's supply has usually been airdropped it. Real holdings of that size are rare outside the team that issued the token.
* **`usd_price_24hr_percent_change`**: a price that is up several thousand percent in a day, on an unverified token, is more likely a bad print than a real move. Hold it back until it repeats on the next call.
* **`portfolio_percentage`**: if one unverified token suddenly makes up most of a wallet's value, check it before you show the total.
If you store snapshots, compare each token's value with the previous snapshot. A low-liquidity token that jumps more than about 10x between two calls can safely wait one refresh cycle before you show the new value.
***
## Endpoint reference
| Endpoint | Spam | Liquidity | Inactivity | Verified only |
| - | - | - | - | - |
| [Token Balances](/data-api/evm/wallet/token-balances) | `exclude_spam` | `min_pair_side_liquidity_usd` | `max_token_inactivity` | `exclude_unverified_contracts` |
| [Wallet Net Worth](/data-api/evm/wallet/net-worth) | `exclude_spam` | `min_pair_side_liquidity_usd` | `max_token_inactivity` | `exclude_unverified_contracts` |
| [Cross-Chain Token Balances](/data-api/universal/wallet/cross-chain-token-balances) | `excludeSpam` | `liquidityThreshold` | `maxTokenInactivity` | `excludeUnverifiedContracts` |
| [Token Price](/data-api/evm/token/prices/token-price), [Token Prices (Batch)](/data-api/evm/token/prices/token-prices-batch) | n/a | `min_pair_side_liquidity_usd` | `max_token_inactivity` | n/a |
| [Solana Token Balances](/data-api/solana/wallet/token-balances), [Solana Portfolio](/data-api/solana/wallet/portfolio) | `excludeSpam` | n/a | n/a | n/a |
Cross-Chain Token Balances also returns `securityScore` on each token, the token's [Token Score](/data-api/data-features/token-scores). Filtering out low scores is a good extra check on top of the filters above.
On Solana, the wallet endpoints don't return USD values, and there is no default liquidity threshold. Set `excludeSpam=true`, use `isVerifiedContract` the way you would use `verified_contract`, and apply your own checks to any prices you fetch.
> [!NOTE]
>
> The [legacy Token Balances](/data-api/evm/wallet/token-balances-legacy) endpoint (`/{address}/erc20`) excludes spam by default, but it doesn't take the price filters. Use [Token Balances](/data-api/evm/wallet/token-balances) for anything that shows USD values.
# Liquidity Filtering
Source: https://docs.moralis.com/data-api/data-features/safety-and-trust/liquidity-filtering
Understand how Moralis uses liquidity filtering to protect price accuracy, including default thresholds, how pair-side liquidity is evaluated for both tokens in a pool, endpoint behavior, and custom liquidity controls.
## Liquidity Filtering
Liquidity Filtering is a safety mechanism used across Moralis price-dependent features to avoid returning unreliable or easily manipulated prices.
It ensures that prices are only derived from pools with sufficient onchain liquidity, making downstream data (net worth, PnL, analytics) safer and more predictable.
Liquidity filtering is applied across:
* [Token Prices](/data-api/evm/token/prices/token-prices-batch)
* [Wallet Token Balances](/data-api/evm/wallet/token-balances) (with prices)
* [Wallet Net Worth](/data-api/evm/wallet/net-worth)
* Other price-dependent features
***
## Why Liquidity Filtering Exists
Onchain markets often include:
* Thin or inactive pools
* Short-lived pools created for manipulation
* Pools where one side has meaningful liquidity but the other side is effectively empty
Without liquidity filtering, these pools can:
* Produce unstable or misleading prices
* Inflate portfolio values
* Distort rankings and analytics
Liquidity filtering acts as a minimum quality bar for any price Moralis returns.
***
## Default Liquidity Thresholds
Moralis enforces minimum liquidity requirements per chain.
Default thresholds:
* **EVM chains:** \$50 minimum liquidity per side (each token in the pair)
* **Solana:** no enforced liquidity threshold
This threshold applies at the pool level and is evaluated for both assets in the pair.
***
## What “pair-side liquidity” means
“Pair-side liquidity” means the USD liquidity of **each token in the pool**, evaluated independently.
For a TOKEN / USDC pool, Moralis checks:
* TOKEN-side liquidity (in USD)
* USDC-side liquidity (in USD)
The pool is considered eligible only if **both sides** meet the minimum threshold.
### Why this approach
This prevents pools where one side is effectively illiquid, even if the other side looks healthy.
Example:
* TOKEN liquidity: \$100,000
* USDC liquidity: \$10
Even though the TOKEN side is deep, the USDC side is too small for the pool to be a reliable pricing venue, so Moralis excludes it.
This is especially important for:
* Long-tail tokens
* Manipulation-resistant pricing
* Stable portfolio and net worth calculations
***
## Liquidity Skew
Get Token Pairs ([EVM](/data-api/evm/token/swaps/token-pairs), [Solana](/data-api/solana/token/pairs/token-pairs)) exposes a property that measures how balanced a pair's reserves are across both sides of the pool. It is named `liquidity_skew` on EVM and `liquiditySkew` on Solana.
* `1` = perfectly balanced reserves
* `0` = fully imbalanced (liquidity concentrated on one side)
When this value is below `0.005`, the pair's liquidity is treated as `0`. This prevents heavily one-sided pools, where one side is effectively empty, from being used as a reliable pricing venue.
***
## Low Liquidity Behavior
When a pool fails liquidity filtering, behavior depends on the endpoint.
* [Get Token Price](/data-api/evm/token/prices/token-price)\
Returns a `404` error indicating insufficient liquidity
* [Get Multiple Token Prices](/data-api/evm/token/prices/token-prices-batch)\
The token is omitted from the response
* [Wallet Token Balances](/data-api/evm/wallet/token-balances) (with prices)\
Token price is returned as `null`
* [Wallet Net Worth](/data-api/evm/wallet/net-worth)\
Token is excluded from the net worth calculation
This behavior is intentional and consistent across price-dependent features.
***
## Consistency Across Features
Liquidity filtering is applied uniformly so that:
* A pool excluded from Token Prices\
will not silently be used to value assets in Wallet Net Worth
* A token with `null` price in balances\
will not inflate portfolio values unexpectedly
This consistency is critical for building reliable dashboards, analytics, and valuation logic.
***
## Custom Liquidity Thresholds
You can override the default threshold using the `min_pair_side_liquidity_usd` query parameter.
Example:\
`min_pair_side_liquidity_usd=5000`
This ensures that only pools where **both sides** have at least \$5,000 USD liquidity are considered.
For recommended thresholds by use case, see [Accurate Net Worth & Token Balances](/data-api/data-features/safety-and-trust/accurate-net-worth-and-balances).
***
### Common Use Cases for Custom Thresholds
* Risk-averse or institutional reporting
* Cleaner portfolio and net worth calculations
* Excluding long-tail or thinly traded tokens
* Reducing exposure to short-lived or manipulated pools
***
## What Liquidity Filtering Does Not Do
Liquidity filtering:
* Does not guarantee market fairness
* Does not detect scams by itself
* Does not replace deeper risk analysis
It is one component of Moralis’ broader Safety & Trust model and should be used alongside:
* [Token Scores](/data-api/data-features/token-scores)
* [Spam Filtering](/data-api/resources/spam-filtering)
* [Verified Contracts](/data-api/data-features/safety-and-trust/verified-contracts)
# Verified Contracts
Source: https://docs.moralis.com/data-api/data-features/safety-and-trust/verified-contracts
Moralis surfaces verification signals for ERC20 tokens and NFT collections to help you distinguish legitimate projects from impersonators, clones, or scams.
These signals are based on trusted third-party verification sources and are exposed directly in API responses.
## Verified Contracts (ERC20)
The `verified_contract` flag indicates that an **ERC20 token contract has been verified by CoinGecko**.
> [!NOTE]
>
> This verification is **not** based on Etherscan contract verification.
### What CoinGecko Verification Means
When a contract is marked as verified:
* The token has been reviewed by the **CoinGecko team**
* It has passed CoinGecko’s internal criteria for legitimacy
* It is considered a **trusted, recognised token** within the ecosystem
This helps developers:
* Filter out scam or impersonator tokens
* Prioritise legitimate assets in search and UI
* Build safer default experiences for users
***
## Verified NFT Collections
The `verified_collection` flag applies to **NFT collections** that have been verified by **OpenSea**.
When a collection is verified:
* OpenSea has reviewed and validated the collection
* The collection is recognised as authentic
* Users can more easily distinguish real projects from fakes
This is the same verification signal users see as a **verified badge on OpenSea**.
***
## Why Verification Matters
Verification signals are especially useful for:
* Wallets and portfolio trackers
* Token and NFT discovery
* Search and filtering experiences
* Reducing exposure to scams and copycat projects
They are often used alongside:
* [Spam Filtering](/data-api/resources/spam-filtering)
* [Token Scores](/data-api/data-features/token-scores)
* [Token Search](/data-api/data-features/search-and-discovery/token-search)
to build a layered safety model.
***
## Notes & Limitations
* Verification is **source-dependent**:
* ERC20 tokens → CoinGecko
* NFT collections → OpenSea
* Not all legitimate projects are verified
* Verification status may change over time as source data updates
Always treat verification as a **signal**, not a guarantee.
# Token Search
Source: https://docs.moralis.com/data-api/data-features/search-and-discovery/token-search
Token Search lets you discover tokens across multiple blockchains using names, symbols, token address or DEX pair addresses, with built-in ranking and verification signals to surface high-quality results.
Token Search indexes tokens across supported chains and returns ranked results based on relevance, activity, and verification signals.
It’s designed for building fast, reliable token discovery experiences in wallets, dashboards, and trading applications.
You can search by:
* Token name (e.g. `Pepe`)
* Token symbol (e.g. `PEPE`)
* Token address
* DEX pair address
* Partial matches (e.g. `PEP` → `PEPE`)
Search is:
* Case-insensitive
* Resilient to partial input
* Optimized to prioritize legitimate tokens
***
## Search Controls & Ranking
Token Search exposes several controls that affect how results are ranked and filtered.
### Verification Controls
* `isVerifiedContract`\
When `true`, only [verified tokens](/data-api/data-features/safety-and-trust/verified-contracts) are returned.\
Default: `false`
* `boostVerifiedContracts`\
When `true`, [verified tokens](/data-api/data-features/safety-and-trust/verified-contracts) are ranked higher.\
Default: `true`
***
### Sorting Options
You can sort results using:
* `volume1hDesc` *(default)*
* `volume24hDesc`
* `liquidityDesc`
* `marketCapDesc`
This allows you to tune search results for:
* Trading UIs
* Analytics dashboards
* Discovery vs relevance
***
## Multi-Chain Search
Token Search supports querying across multiple chains in a single request.
Blockchains currently supported:
* Ethereum
* Polygon
* BNB Chain
* Arbitrum
* Optimism
* Base
* Avalanche
* Linea
* Ronin
* PulseChain
* Solana
Support is continuously expanding.
***
## Verified Token Prioritisation
Token Search applies additional weighting to [verified tokens](/data-api/data-features/safety-and-trust/verified-contracts) to improve result quality.
### How verification affects results
* Tokens listed on **CoinGecko** are treated as verified
* Verified tokens are:
* Ranked higher by default
* Preferred over similarly named unverified tokens
* This reduces exposure to spam, clones, and misleading symbols
You can:
* **Boost** verified tokens (default behavior)
* **Filter** results to only verified tokens
***
## Response Data
Each search result may include:
```json theme={null}
{
"tokenAddress": "0x6982508145454ce325ddbe47a25d4ec3d2311933",
"chainId": "0x1",
"name": "Pepe",
"symbol": "PEPE",
"blockNumber": 17046105,
"blockTimestamp": 1681483895,
"usdPrice": 0.00000660795798374201,
"marketCap": 2779901844.180426,
"experiencedNetBuyers": {
"oneHour": -4,
"oneDay": -6,
"oneWeek": 50
},
"netVolumeUsd": {
"oneHour": -109135.83610023865,
"oneDay": 409602.78393524094
},
"liquidityChangeUSD": {
"oneHour": -102512.48357243836,
"oneDay": -334000.64153755084
},
"usdPricePercentChange": {
"oneHour": -1.0458516076000621,
"oneDay": 0.021417598614723917
},
"volumeUsd": {
"oneHour": 190965.87173599334,
"oneDay": 5241212.457093451
},
"securityScore": 96,
"logo": "https://adds-token-info-29a861f.s3.eu-central-1.amazonaws.com/marketing/evm/0x6982508145454ce325ddbe47a25d4ec3d2311933_icon.png",
"isVerifiedContract": true,
"fullyDilutedValuation": 2779901181.0952516,
"totalHolders": 503992,
"totalLiquidityUsd": 24553340.56545042,
"implementations": []
}
```
***
## Limits & Constraints
Current limitations to be aware of:
* Default limit: **10 results**
* Maximum limit: **1000 results**
* No pagination support
* Chain identifiers must be valid and correctly formatted
***
## Usage Guidelines
To get the best results:
* Use precise search queries where possible
* Limit searches to relevant chains
* Use verification filters for safer UX
* Choose appropriate sorting for your use case
***
## Availability & Access
Token Search is a **premium feature** and requires a **Pro plan** or higher.
Trial access can be activated to evaluate the feature before upgrading.
# Token Scores
Source: https://docs.moralis.com/data-api/data-features/token-scores
The Moralis Token Score is a unified 0-100 rating that evaluates the onchain quality of a token using six weighted metrics, supported across all EVM chains.
> [!NOTE]
>
> **Token Score is becoming an EVM-only feature.** Solana support is deprecated and will be removed on **July 31, 2026** — after that date, Token Score and the embedded Solana `score` field are no longer available for Solana tokens. Token Score remains fully supported on all EVM chains. See the [changelog](/changelog) for details.
## What is the Token Score?
The Token Score summarizes a token's onchain fundamentals into a single value between 0 and 100, where:
* Higher scores indicate stronger onchain quality
* Lower scores indicate weaker liquidity, activity, distribution, or unrealistic valuations
It is designed to be:
* Simple to display
* Easy to filter and sort
* Transparent and easy to explain
***
## How is the Token Score calculated?
Each of the six metrics produces a sub-score from 0 to 100, and the final score is a weighted average. The metrics are:
1. Age - token activity across multiple timeframes
2. Liquidity - liquidity depth
3. FDV - fully diluted valuation reasonableness
4. Holder Supply - distribution of supply among top holders
5. Volume - trading volume
6. Activity - transaction counts
***
## Metrics Overview
### 1. Token Age & Maturity
* Evaluates activity across timeframes (10m → 30d).
* Tokens that sustain or grow activity over longer periods receive higher scores.
### 2. Liquidity Depth
* Measures liquidity across all pools belonging to a token.
* Higher liquidity generally indicates healthier and more resilient markets.
### 3. Fully Diluted Valuation (FDV)
* Penalizes extreme or unrealistic valuations.
* Reasonably valued tokens receive higher FDV scores.
### 4. Holder Distribution
* Assesses how much of the supply is concentrated in the top holders.
* More decentralization = higher score.
### 5. Trading Volume
* Measures trading volume across all time windows.
* High volume in any timeframe positively impacts the score.
### 6. Transaction Activity
* Measures frequency of swaps and transfers.
* High transaction counts indicate stronger adoption and usage.
***
## Dynamic Scoring
The Token Score is **dynamic**, meaning it updates automatically as new onchain data becomes available. Because the model incorporates multiple rolling timeframes (10 minutes up to 1 month), a token’s score may change due to:
* Increased or decreased transaction activity
* Shifts in liquidity
* Changes in trading volume
* Supply distribution evolving
* Market valuation moving significantly
Scores naturally **decay over time** if a token becomes inactive, as older datapoints fall out of the model. This ensures the score always reflects **current** onchain conditions.
***
## Early & New Tokens
Scores for very new tokens can sometimes be **volatile or appear inconsistent** in the earliest stages of trading. This is expected, as the scoring model is still collecting activity patterns across its time horizons.
**Key points about new-token scoring:**
* Early activity is often spiky and unstable
* Short-term timeframes dominate the score until longer periods accumulate
* As data builds up, the score stabilizes and becomes more representative
* Tokens with genuine early adoption will quickly rise into their appropriate score range
> [!NOTE]
>
> The model adapts rapidly to real onchain traction - tokens with strong fundamentals will see their scores normalize within a short timeframe.
***
## Score Updates
* Scores are recalculated whenever a token has activity
* As long as trading continues, the score stays up to date
* If activity stops, older data decays out of the model and the score may decline
***
## How can the Token Score be used?
The Token Score is an informational onchain quality signal suitable for:
#### Wallets & Explorers
* Displaying token quality at a glance
* Highlighting high-quality tokens
* Warning users about low-scoring assets
### DEXs & Trading Interfaces
* Supporting safer trading experiences
* Powering token discovery and ranking flows
### Analytics & Discovery Tools
* Filtering tokens by score (e.g., score ≥ 70)
* Sorting tokens by onchain quality
* Highlighting trending or improving tokens
### Risk & Monitoring Systems
* Triggering alerts for sharp score drops
* Flagging potentially risky assets for review
> [!NOTE]
>
> Note: The Token Score is not investment advice. It is an onchain quality indicator.
***
## Historical Token Scores
In addition to the latest score, Moralis provides [historical Token Scores](/data-api/universal/token/score/token-score-timeseries), allowing you to track how a token’s onchain quality evolves over time.
Historical scores return a **time-series of Token Scores**, making it possible to:
* Visualize long-term trends
* Detect momentum shifts
* Identify improving or deteriorating tokens
* Backtest filters and ranking strategies
This is especially powerful when combined with discovery, alerts, or trading analytics.
***
### Supported Timeframes
Historical Token Scores support the following lookback windows and resolutions:
* **1 day** → hourly resolution
* **7 days** → hourly resolution
* **30 days** → daily resolution
Each data point represents the Token Score at the start of the aggregation window.
***
### Historical Token Score Endpoint
Developers can fetch the historical scoring breakdown using the [Timeseries Token Score](/data-api/universal/token/score/token-score-timeseries) endpoint:
```
GET /tokens/{tokenAddress}/score/historical
```
Example response:
```javascript theme={null}
{
"chainId": "0x1",
"tokenAddress": "0xdac17f958d2ee523a2206206994597c13d831ec7",
"timeseries": [
{
"timestamp": "2026-01-22T00:00:00Z",
"score": 85
},
{
"timestamp": "2026-01-21T00:00:00Z",
"score": 84
},
{
"timestamp": "2026-01-20T00:00:00Z",
"score": 82
},
{},
{},
{}
]
}
```
> [!NOTE]
>
> Note: This endpoint is available on **Pro plans and above**.
***
## Accessing Detailed Score Data
Developers can fetch the full scoring breakdown using the [Token Score](/data-api/universal/token/score/token-score) endpoint:
```
GET /tokens/{address}/score
```
This endpoint returns:
* Final score (0–100)
* Sub-scores for all six metrics
* Raw onchain metrics used in the calculation
* Timestamp of last update
Example response:
```json theme={null}
{
"tokenAddress": "0x6982508145454ce325ddbe47a25d4ec3d2311933",
"chainId": "0x1",
"score": 94,
"updatedAt": "2025-12-17T13:13:16.000Z",
"metrics": {
"usdPrice": 0.00000402842434389702,
"liquidityUsd": 17796503.766060613,
"volumeUsd": {
"10m": 450.2313257520407,
"30m": 1698.933789208249,
"1h": 12046.524987589466,
"4h": 258302.39298010131,
"12h": 364831.1304703939,
"1d": 775582.3422029199,
"7d": 6831957.3632850265,
"30d": 40129952.32714323
},
"transactions": {
"10m": 4,
"30m": 27,
"1h": 47,
"4h": 106,
"12h": 389,
"1d": 1393,
"7d": 9614,
"30d": 87370
},
"supply": {
"total": 420689899653542.56,
"top10Percent": 41.53
}
}
}
```
> [!NOTE]
>
> Note: This endpoint is available on **Pro plans and above**.
***
## Supported Chains
The Token Score is available on all **EVM mainnet chains**, giving you a unified metric to **compare token quality across EVM chains**.
> [!NOTE]
>
> Solana support for Token Score is deprecated and will be removed on **July 31, 2026**. After that date, Token Score is an EVM-only feature. See the [changelog](/changelog) for details.
# Address Transactions
Source: https://docs.moralis.com/data-api/evm/blockchain/address-transactions
openapi-files/data-api/api.json GET /{address}
Get raw native transactions ordered by block number in descending order.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/wallet-native-txns) — the same decoded
onchain dataset, in real time, with no per-call limits.
# Address Transactions (Decoded)
Source: https://docs.moralis.com/data-api/evm/blockchain/address-transactions-decoded
openapi-files/data-api/api.json GET /{address}/verbose
Get ABI-decoded native transactions ordered by block number in descending order.
# Block by Date
Source: https://docs.moralis.com/data-api/evm/blockchain/block-by-date
openapi-files/data-api/api.json GET /dateToBlock
Find the closest block to a specific date on a blockchain.
# Block by Hash or Number
Source: https://docs.moralis.com/data-api/evm/blockchain/block-by-hash
openapi-files/data-api/api.json GET /block/{block_number_or_hash}
Get the contents of a block given the block hash.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/block) — the same decoded
onchain dataset, in real time, with no per-call limits.
# Latest Block
Source: https://docs.moralis.com/data-api/evm/blockchain/latest-block
openapi-files/data-api/api.json GET /latestBlockNumber/{chain}
Get the most recent block number for a specified blockchain.
# Blockchain API
Source: https://docs.moralis.com/data-api/evm/blockchain/overview
Low-level blockchain access made simple - query raw blocks, transactions, logs, and events with consistent, multi-chain APIs.
## Overview
The **Blockchain API** provides low-level access to raw blockchain data including blocks, transactions, and logs.
Query the blockchain directly without running your own nodes - get block data, transaction details, and decoded contract interactions across all supported EVM chains.
***
## What Is the Blockchain API?
The Blockchain API lets you query:
* **Blocks** - Block data by hash, number, or timestamp
* **Transactions** - Raw and decoded transaction details
* **Address Activity** - All transactions for a specific address
* **Logs** - Event logs and contract emissions
* **Internal Transactions** - Contract-to-contract calls
***
## Key Features
The Blockchain API includes:
* **Block Lookups** - Query blocks by hash or find blocks by timestamp
* **Transaction Details** - Full transaction data including gas and status
* **Decoded Transactions** - Human-readable interpretation of contract calls
* **Address History** - Complete transaction history for any address
* **Multi-Chain** - Consistent interface across all EVM chains
* **Latest Block** - Get the current block number for any chain
***
## Common Use Cases
The Blockchain API is commonly used for:
* **Block Explorers**\
(display block and transaction data)
* **Address Monitoring**\
(track transactions for specific wallets)
* **Historical Analysis**\
(query blockchain state at specific times)
* **Transaction Verification**\
(confirm transaction status and details)
* **Data Indexing**\
(build custom indexes from raw data)
* **Debugging**\
(inspect failed transactions and logs)
***
## Popular Endpoints
| Endpoint | Description |
| - | - |
| [Get Block by Hash](/data-api/evm/blockchain/block-by-hash) | Retrieve block data by hash |
| [Get Block by Date](/data-api/evm/blockchain/block-by-date) | Find block closest to a timestamp |
| [Get Transaction](/data-api/evm/blockchain/transaction-by-hash) | Get transaction details by hash |
| [Decoded Transaction](/data-api/evm/blockchain/transaction-by-hash-decoded) | Get decoded transaction data |
| [Address Transactions](/data-api/evm/blockchain/address-transactions) | Get all transactions for an address |
***
## Get Started
Explore some of the popular Blockchain API endpoints:
* [Get Block by Hash](/data-api/evm/blockchain/block-by-hash)
* [Get Block by Date](/data-api/evm/blockchain/block-by-date)
* [Get Transaction](/data-api/evm/blockchain/transaction-by-hash)
* [Get Address Transactions](/data-api/evm/blockchain/address-transactions)
# Get Transaction
Source: https://docs.moralis.com/data-api/evm/blockchain/transaction-by-hash
openapi-files/data-api/api.json GET /transaction/{transaction_hash}
Get the contents of a transaction by the given transaction hash.
# Get Transaction (Decoded)
Source: https://docs.moralis.com/data-api/evm/blockchain/transaction-by-hash-decoded
openapi-files/data-api/api.json GET /transaction/{transaction_hash}/verbose
Get the ABI-decoded contents of a transaction by the given transaction hash.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/transaction-verbose) — the same decoded
onchain dataset, in real time, with no per-call limits.
# Wallet Positions
Source: https://docs.moralis.com/data-api/evm/defi/legacy/wallet-positions
openapi-files/data-api/api.json GET /wallets/{address}/defi/positions
Get a concise overview of a wallet’s DeFi positions across all protocols.
# Detailed Positions
Source: https://docs.moralis.com/data-api/evm/defi/legacy/wallet-positions-detailed
openapi-files/data-api/api.json GET /wallets/{address}/defi/{protocol}/positions
Fetch detailed DeFi positions for a given wallet and protocol.
# Wallet Protocols
Source: https://docs.moralis.com/data-api/evm/defi/legacy/wallet-protocols
openapi-files/data-api/api.json GET /wallets/{address}/defi/summary
Summarize a wallet’s DeFi activity, including total USD value, unclaimed rewards and active protocols.
# DeFi API
Source: https://docs.moralis.com/data-api/evm/defi/overview
Track DeFi positions, balances, rewards, and protocol interactions with enriched, protocol-aware data across supported chains.
## Overview
The **DeFi API** provides detailed insights into wallet positions across DeFi protocols including lending, borrowing, staking, and liquidity pools.
Query a wallet's DeFi exposure without manually integrating with each protocol - get a unified view of positions, balances, and rewards across supported protocols.
***
## What Is the DeFi API?
The DeFi API lets you query:
* **Protocol Summary** - Overview of all DeFi protocols a wallet uses
* **Positions** - Detailed position data per protocol
* **Position Details** - Enhanced breakdown with underlying assets
* **Multi-Protocol** - Support for major DeFi protocols
***
## Key Features
The DeFi API includes:
* **Protocol Detection** - Automatically identifies which protocols a wallet uses
* **Position Breakdown** - Detailed view of deposits, borrows, and rewards
* **USD Valuations** - Position values calculated in USD
* **Multi-Chain** - Track positions across supported EVM chains
* **Unified Format** - Consistent data structure across protocols
***
## Supported Protocols
The DeFi API supports major protocols including:
* Aave
* Compound
* Uniswap
* Lido
* Rocket Pool
* Eigenlayer
* And more
***
## Common Use Cases
The DeFi API is commonly used for:
* **Portfolio Trackers**\
(show DeFi positions alongside tokens and NFTs)
* **DeFi Dashboards**\
(aggregate positions across protocols)
* **Risk Monitoring**\
(track lending health factors and exposure)
* **Yield Tracking**\
(monitor staking rewards and LP positions)
* **Tax Reporting**\
(calculate DeFi gains and income)
***
## Popular Endpoints
| Endpoint | Description |
| - | - |
| [Wallet Protocols](/data-api/evm/defi/wallet-protocols) | Summary of protocols used by a wallet |
| [Wallet Positions](/data-api/evm/defi/wallet-positions) | Detailed positions per protocol |
| [Detailed Positions](/data-api/evm/defi/wallet-positions-detailed) | Enhanced position breakdown |
***
## Get Started
* [Get Wallet Protocols](/data-api/evm/defi/wallet-protocols)
* [Get Wallet Positions](/data-api/evm/defi/wallet-positions)
* [Get Detailed Positions](/data-api/evm/defi/wallet-positions-detailed)
***
## DeFi API Overview Video
[Moralis DeFi API Overview](https://www.youtube.com/embed/dLcoB3vFf38)
# Wallet Positions
Source: https://docs.moralis.com/data-api/evm/defi/wallet-positions
openapi-files/data-api/api-v1.json GET /v1/wallets/{walletAddress}/defi/positions
Returns all DeFi positions (lending, liquidity, staking) for a wallet address across specified chains in a unified schema.
# Detailed Positions
Source: https://docs.moralis.com/data-api/evm/defi/wallet-positions-detailed
openapi-files/data-api/api-v1.json GET /v1/wallets/{walletAddress}/defi/{protocol}/positions
Returns DeFi positions for a wallet address filtered by a specific protocol across specified chains.
# Wallet Protocols
Source: https://docs.moralis.com/data-api/evm/defi/wallet-protocols
openapi-files/data-api/api-v1.json GET /v1/wallets/{walletAddress}/defi/summary
Returns a summary of all DeFi positions for a wallet address across specified chains.
# NFT Collections by Wallet
Source: https://docs.moralis.com/data-api/evm/nft/collections/nft-collections-by-wallet
openapi-files/data-api/api.json GET /{address}/nft/collections
Fetch all NFT Collections held by a specified wallet address. Each Collection returned includes on-chain metadata as well as off-chain metadata, floor prices and more where available.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/wallet-nft-collections) — the same decoded
onchain dataset, in real time, with no per-call limits.
# NFTs by Collection
Source: https://docs.moralis.com/data-api/evm/nft/collections/nfts-by-collection
openapi-files/data-api/api.json GET /nft/{address}
Fetch all NFTs for a given collection. Each NFT returned includes on-chain metadata as well as off-chain metadata, floor prices, rarity and more where available.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/nfts-by-contract) — the same decoded
onchain dataset, in real time, with no per-call limits.
# NFTs by Wallet
Source: https://docs.moralis.com/data-api/evm/nft/collections/nfts-by-wallet
openapi-files/data-api/api.json GET /{address}/nft
Fetch all NFTs held by a specified wallet address. Use `token_addresses` to filter by one or many specific contract(s). Each NFT returned includes on-chain metadata as well as off-chain metadata, floor prices, rarity and more where available.
# Collection Metadata
Source: https://docs.moralis.com/data-api/evm/nft/metadata/collection-metadata
openapi-files/data-api/api.json GET /nft/{address}/metadata
Fetch on-chain metadata like name, symbol, and base token URI for an NFT contract. Also returns off-chain metadata, floor prices and more where available.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/nft-collection-metadata) — the same decoded
onchain dataset, in real time, with no per-call limits.
# Collection Metadata (Batch)
Source: https://docs.moralis.com/data-api/evm/nft/metadata/collection-metadata-batch
openapi-files/data-api/api.json POST /nft/metadata
Retrieve metadata (name, symbol) for up to 25 NFT contracts in one call. Also returns off-chain metadata, floor prices and more where available.
# Collection Stats
Source: https://docs.moralis.com/data-api/evm/nft/metadata/collection-stats
openapi-files/data-api/api.json GET /nft/{address}/stats
Get summary stats by NFT collection including total NFT transfers, total tokens and total owners.
# NFT Metadata
Source: https://docs.moralis.com/data-api/evm/nft/metadata/nft-metadata
openapi-files/data-api/api.json GET /nft/{address}/{token_id}
Fetch metadata for a specific NFT. Includes on-chain metadata as well as off-chain metadata, floor prices, rarity and more where available.
# NFT Metadata (Batch)
Source: https://docs.moralis.com/data-api/evm/nft/metadata/nft-metadata-batch
openapi-files/data-api/api.json POST /nft/getMultipleNFTs
Get NFT metadata for one or many NFTs. Accepts an array of up to 25 `tokens`, each requiring `token_address` and `token_id`. Each NFT returned includes on-chain metadata as well as off-chain metadata, floor prices, rarity and more where available.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/nft-multiple) — the same decoded
onchain dataset, in real time, with no per-call limits.
# NFT API
Source: https://docs.moralis.com/data-api/evm/nft/overview
Everything you need to build NFT experiences - metadata, ownership, transfers, sales, rarity, floor prices, and marketplace activity across major chains.
## Overview
The **NFT API** provides complete NFT data including metadata, ownership, trading history, pricing, and collection analytics.
Whether you're building a marketplace, portfolio tracker, or analytics platform, the NFT API gives you everything you need to work with NFTs across all EVM chains.
***
## What Is the NFT API?
The NFT API lets you query:
* **Metadata** - Token and collection metadata with media URLs
* **Ownership** - Current owners and ownership history
* **Transfers** - Transfer history by collection or token ID
* **Pricing** - Floor prices, sale history, and price trends
* **Traits** - Attribute data and rarity analysis
* **Discovery** - Top collections by volume or market cap
***
## Key Features
The NFT API includes:
* **Rich Metadata** - Fully resolved metadata with IPFS gateway support
* **Floor Price Tracking** - Current and historical floor prices
* **Sales Data** - Trade history with prices and marketplaces
* **Trait Analysis** - Collection traits with rarity percentages
* **Ownership Queries** - Find all owners of a collection or token
* **Market Discovery** - Discover trending collections
* **Batch Queries** - Fetch metadata for multiple NFTs at once
***
## Common Use Cases
The NFT API is commonly used for:
* **NFT Marketplaces**\
(listings, metadata, ownership verification)
* **Portfolio Trackers**\
(display NFT holdings with valuations)
* **Analytics Platforms**\
(collection stats, volume, floor trends)
* **Rarity Tools**\
(trait analysis and rarity rankings)
* **Verification Systems**\
(prove NFT ownership for gating)
* **Collection Dashboards**\
(monitor collection performance)
***
## Popular Endpoints
| Endpoint | Description |
| - | - |
| [NFT Metadata](/data-api/evm/nft/metadata/nft-metadata) | Get metadata for a specific NFT |
| [Collection Metadata](/data-api/evm/nft/metadata/collection-metadata) | Get collection-level metadata |
| [Floor Price](/data-api/evm/nft/prices/collection-floor-price) | Current floor price for a collection |
| [NFT Owners](/data-api/evm/nft/ownership/owners-by-contract) | List all owners of a collection |
| [NFT Transfers](/data-api/evm/nft/transfers/collection-transfers) | Transfer history for a collection |
| [Collection Trades](/data-api/evm/nft/trades/collection-trades) | Recent sales for a collection |
***
## Get Started
Explore some of the popular NFT API endpoints:
* [Get NFT Metadata](/data-api/evm/nft/metadata/nft-metadata)
* [Get Collection Floor Price](/data-api/evm/nft/prices/collection-floor-price)
* [Get NFT Owners](/data-api/evm/nft/ownership/owners-by-contract)
* [Get NFT Transfers](/data-api/evm/wallet/nft-transfers)
# Owners by Collection
Source: https://docs.moralis.com/data-api/evm/nft/ownership/owners-by-contract
openapi-files/data-api/api.json GET /nft/{address}/unique-owners
Get unique wallet addresses owning NFTs from a contract.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/nft-owners) — the same decoded
onchain dataset, in real time, with no per-call limits.
# Owners by Token ID
Source: https://docs.moralis.com/data-api/evm/nft/ownership/owners-by-token-id
openapi-files/data-api/api.json GET /nft/{address}/{token_id}/owners
List wallets owning a specific NFT, defined by its contract and token ID.
# Floor Price by Collection
Source: https://docs.moralis.com/data-api/evm/nft/prices/collection-floor-price
openapi-files/data-api/api.json GET /nft/{address}/floor-price
Get floor price for a given collection. Refreshes every 30 minutes.
# Floor Price by Token ID
Source: https://docs.moralis.com/data-api/evm/nft/prices/floor
openapi-files/data-api/api.json GET /nft/{address}/{token_id}/floor-price
Get the floor price for a specific NFT, defined by its contract and token ID. Refreshes every 30 minutes.
# Timeseries Floor Price by Contract
Source: https://docs.moralis.com/data-api/evm/nft/prices/historical-floor-price
openapi-files/data-api/api.json GET /nft/{address}/floor-price/historical
Get timeseries historical floor prices for a given NFT collection. Refreshes every 30 minutes.
# Sale Price by Collection
Source: https://docs.moralis.com/data-api/evm/nft/prices/sale-price-by-contract
openapi-files/data-api/api.json GET /nft/{address}/price
Fetch sale prices for NFTs in a contract over a specified number of days. Returns the last sale, lowest sale, highest sale, average sale and total trades within the specified period.
# Sale Price by Token ID
Source: https://docs.moralis.com/data-api/evm/nft/prices/sale-price-by-token-id
openapi-files/data-api/api.json GET /nft/{address}/{token_id}/price
Fetch sale prices for a specific NFT over a specified number of days. Returns the last sale, lowest sale, highest sale, average sale and total trades within the specified period.
# NFT Trades by Collection
Source: https://docs.moralis.com/data-api/evm/nft/trades/collection-trades
openapi-files/data-api/api.json GET /nft/{address}/trades
Get NFT trades for a given contract with the ability to filter by marketplace.
# NFT Trades by Token ID
Source: https://docs.moralis.com/data-api/evm/nft/trades/trades-by-token-id
openapi-files/data-api/api.json GET /nft/{address}/{token_id}/trades
Get NFT trades for a specific NFT by specifying a contract addres and token ID.
# NFTs by Traits
Source: https://docs.moralis.com/data-api/evm/nft/traits/nfts-by-traits
openapi-files/data-api/api.json POST /nft/{address}/nfts-by-traits
Find NFTs in a contract matching specific traits, perfect for attribute-based searches.
# NFT Traits by Collection
Source: https://docs.moralis.com/data-api/evm/nft/traits/traits-by-collection
openapi-files/data-api/api.json GET /nft/{address}/traits
Explore the distinct traits of NFTs in a contract, showcasing their unique attributes.
# Traits by Collection (Paginated)
Source: https://docs.moralis.com/data-api/evm/nft/traits/traits-by-collection-paginated
openapi-files/data-api/api.json GET /nft/{address}/traits/paginate
Fetch NFT traits for a contract with pagination for efficient navigation of large collections.
# NFT Transfers by Contract
Source: https://docs.moralis.com/data-api/evm/nft/transfers/collection-transfers
openapi-files/data-api/api.json GET /nft/{address}/transfers
Get NFT transfers for a contract, with options to filter by date, token, or other parameters.
# NFT Transfers by Token ID
Source: https://docs.moralis.com/data-api/evm/nft/transfers/token-id-transfers
openapi-files/data-api/api.json GET /nft/{address}/{token_id}/transfers
Get transfers of a specific NFT given a contract address and token ID.
# Resync NFT Metadata
Source: https://docs.moralis.com/data-api/evm/nft/utilities/resync-nft-metadata
openapi-files/data-api/api.json GET /nft/{address}/{token_id}/metadata/resync
Update an NFT’s metadata, either from its current token URI or a new one. Choose sync for immediate results or async for background processing.
# Resync NFT Traits
Source: https://docs.moralis.com/data-api/evm/nft/utilities/resync-nft-traits
openapi-files/data-api/api.json GET /nft/{address}/traits/resync
Refresh trait and rarity data for NFTs in a contract to ensure accuracy.
# EVM Data API
Source: https://docs.moralis.com/data-api/evm/overview
The EVM Data API provides a single, consistent interface for accessing blockchain data across 30+ supported chains, including Ethereum, Base, Binance Smart Chain, and more. It standardizes complex on-chain data into clean, developer-friendly formats.
### Overview
The **EVM API** provides **deep, EVM-native access** to blockchain data across **30+ EVM-compatible networks**, including Ethereum, Base, Binance Smart Chain, Polygon, Arbitrum, Optimism, and more.
It exposes rich EVM-specific concepts while still delivering data in clean, structured, developer-friendly formats.
***
### Explore Data APIs:
> [card] [Wallet API](/data-api/evm/wallet/overview)
>
> Wallet history, transfers balances, tokens and PnL.
> [card] [Token API](/data-api/evm/token/overview)
>
> Token search, balances, transfers, holders and swaps.
> [card] [NFT API](/data-api/evm/nft/overview)
>
> Metadata, floor prices, transfers and ownership.
> [card] [Price API](/data-api/evm/price/overview)
>
> Real-time crypto prices, OHLC, trading volume.
> [card] [DeFi API](/data-api/evm/defi/overview)
>
> DeFi positions, liquidity, reserves and token pairs.
> [card] [Blockchain API](/data-api/evm/blockchain/overview)
>
> Raw blocks, transactions, internal transactions and logs.
***
### What the EVM API Is For
The EVM API is designed for:
* Applications focused primarily on **EVM ecosystems**
* Advanced use cases that rely on **EVM-specific behavior**
* Teams that need **maximum depth and flexibility** when working with EVM data
Some EVM-specific endpoints and data models are **not available** in the Universal API.
***
### Relationship to the Universal API
* The Universal API covers **shared functionality** across EVM and Solana
* The EVM API provides **deeper, more specialized EVM support**
* Not all EVM endpoints are candidates for universal consolidation
Think of the EVM API as the **expert-level interface** for EVM chains.
***
# Floor Price by Collection
Source: https://docs.moralis.com/data-api/evm/price/collection-floor-price
openapi-files/data-api/api.json GET /nft/{address}/floor-price
Get floor price for a given collection. Refreshes every 30 minutes.
# OHLC by Pair Address
Source: https://docs.moralis.com/data-api/evm/price/ohlc
openapi-files/data-api/api.json GET /pairs/{address}/ohlcv
Retrieve OHLCV (Open, High, Low, Close, Volume) candlestick data for a token pair.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/pair-ohlcv) — the same decoded
onchain dataset, in real time, with no per-call limits.
> [!WARNING]
>
> This endpoint requires a **pair address**, not a token address. To find the pair addresses for a token, use the [Token Pairs endpoint](/data-api/evm/token/swaps/token-pairs).
# Price API
Source: https://docs.moralis.com/data-api/evm/price/overview
Real-time crypto prices, OHLC, trading volume.
## Overview
The **Price API** provides real-time and historical pricing data for tokens and NFTs across all supported EVM chains.
Get current prices, OHLC candlestick data, floor prices, and trading volume without managing your own price feeds or aggregation infrastructure.
***
## What Is the Price API?
The Price API lets you query:
* **Token Prices** - Current USD prices for any ERC-20 token
* **OHLC Data** - Candlestick data for charting and technical analysis
* **NFT Floor Prices** - Current and historical floor prices by collection
* **Sale Prices** - Recent NFT sales with transaction details
* **Batch Queries** - Fetch prices for multiple tokens in one request
***
## Key Features
The Price API includes:
* **Real-Time Prices** - Current token prices with USD values
* **Historical Data** - Price history for trend analysis
* **OHLC Candles** - Open, high, low, close data for charting
* **Floor Price History** - Track NFT collection floor over time
* **Batch Support** - Query multiple tokens efficiently
* **Multi-Chain** - Consistent pricing across all EVM chains
***
## Common Use Cases
The Price API is commonly used for:
* **Price Feeds**\
(display current token prices in apps)
* **Trading Charts**\
(OHLC data for candlestick visualizations)
* **Portfolio Valuation**\
(calculate holdings value in USD)
* **NFT Analytics**\
(track floor price trends)
* **Alerts & Notifications**\
(trigger on price thresholds)
* **Market Data Dashboards**\
(aggregate pricing across tokens)
***
## Popular Endpoints
| Endpoint | Description |
| - | - |
| [Token Price](/data-api/evm/token/prices/token-price) | Get current price for a token |
| [Token Prices (Batch)](/data-api/evm/token/prices/token-prices-batch) | Get prices for multiple tokens |
| [OHLC](/data-api/evm/price/ohlc) | Candlestick data for charting |
| [Collection Floor Price](/data-api/evm/price/collection-floor-price) | Current NFT floor price |
| [Historical Floor Price](/data-api/evm/price/timeseries-floor-price) | Floor price over time |
# Sale Price by Token ID
Source: https://docs.moralis.com/data-api/evm/price/sale-price-by-token-id
openapi-files/data-api/api.json GET /nft/{address}/{token_id}/price
Fetch sale prices for a specific NFT over a specified number of days. Returns the last sale, lowest sale, highest sale, average sale and total trades within the specified period.
# Sale Price by Collection
Source: https://docs.moralis.com/data-api/evm/price/sale-prices-by-collection
openapi-files/data-api/api.json GET /nft/{address}/price
Fetch sale prices for NFTs in a contract over a specified number of days. Returns the last sale, lowest sale, highest sale, average sale and total trades within the specified period.
# Timeseries Floor Price by Contract
Source: https://docs.moralis.com/data-api/evm/price/timeseries-floor-price
openapi-files/data-api/api.json GET /nft/{address}/floor-price/historical
Get timeseries historical floor prices for a given NFT collection. Refreshes every 30 minutes.
# Floor Price by Token ID
Source: https://docs.moralis.com/data-api/evm/price/token-id-floor-price
openapi-files/data-api/api.json GET /nft/{address}/{token_id}/floor-price
Get the floor price for a specific NFT, defined by its contract and token ID. Refreshes every 30 minutes.
# Token Price
Source: https://docs.moralis.com/data-api/evm/price/token-price
openapi-files/data-api/api.json GET /erc20/{address}/price
Retrieve the current or historical price of an ERC20 token in the blockchain’s native currency and USD. Each token returned includes on-chain metadata, as well as off-chain metadata, logos, spam status and more. Additional options to exclude low-liquidity tokens and inactive tokens.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/erc20-price) — the same decoded
onchain dataset, in real time, with no per-call limits.
# Token Prices (Batch)
Source: https://docs.moralis.com/data-api/evm/price/token-prices-batch
openapi-files/data-api/api.json POST /erc20/prices
Retrieve the current or historical prices for multiple ERC20 tokens in the blockchain’s native currency and USD. Accepts an array of up to 100 `tokens`, each requiring `token_address` and optional fields such as `to_block` or `exchange`. Each token returned includes on-chain metadata, as well as off-chain metadata, logos, spam status and more. Additional options to exclude low-liquidity tokens and inactive tokens.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/erc20-prices) — the same decoded
onchain dataset, in real time, with no per-call limits.
# Token Categories
Source: https://docs.moralis.com/data-api/evm/token/discovery/token-categories
openapi-files/data-api/api.json GET /tokens/categories
List all supported token categories, which can then be used for filtering on endpoints such as getFilteredTokens.
# Token Holder Metrics
Source: https://docs.moralis.com/data-api/evm/token/holders/token-holder-stats
openapi-files/data-api/api.json GET /erc20/{tokenAddress}/holders
Returns total holders for a given token, as well as aggregated stats holder supply, holder trends, holder distribution and holder acquisition metrics.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/erc20-holders) — the same decoded
onchain dataset, in real time, with no per-call limits.
# Top Token Holders
Source: https://docs.moralis.com/data-api/evm/token/holders/token-holders
openapi-files/data-api/api.json GET /erc20/{token_address}/owners
Identify the major holders of an ERC20 token and understand their ownership percentages. Includes known entities, exchanges and wallet labels.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/erc20-owners) — the same decoded
onchain dataset, in real time, with no per-call limits.
# Token Metadata
Source: https://docs.moralis.com/data-api/evm/token/metadata/token-metadata
openapi-files/data-api/api.json GET /erc20/metadata
Retrieve metadata (name, symbol, decimals, logo) for an ERC20 token contract, as well as off-chain metadata, total supply, categories, logos, spam status and more.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/erc20-metadata) — the same decoded
onchain dataset, in real time, with no per-call limits.
# Token Score
Source: https://docs.moralis.com/data-api/evm/token/metadata/token-score
openapi-files/data-api/api.json GET /tokens/{tokenAddress}/score
Retrieve a score for a specific token along with detailed metrics including price, volume, liquidity, transaction counts, and supply information.
# Token Score - Timeseries
Source: https://docs.moralis.com/data-api/evm/token/metadata/token-score-timeseries
openapi-files/data-api/api.json GET /tokens/{tokenAddress}/score/historical
Retrieve historical score data for a specific token over time.
# Token API Overview
Source: https://docs.moralis.com/data-api/evm/token/overview
The most powerful Token API in Web3 - fetch, analyse, and monitor ERC20 tokens across multiple chains, covering prices, balances, transfers, liquidity, holders, volume, profitability, and advanced safety signals through a single unified interface.
## Overview
The **Token API** provides comprehensive ERC-20 token data including prices, balances, transfers, holders, liquidity, swaps, and advanced analytics across all supported EVM chains.
From simple balance queries to complex token analytics, the Token API delivers the data you need to build trading platforms, portfolio trackers, and token analysis tools.
***
## What Is the Token API?
The Token API lets you query:
* **Balances** - Token holdings for any wallet address
* **Transfers** - Transfer history by wallet or token contract
* **Prices** - Real-time and historical token prices
* **Holders** - Token holder lists and distribution analytics
* **Swaps** - DEX trading activity and swap history
* **Liquidity** - Trading pairs, reserves, and liquidity data
* **Metadata** - Token details including name, symbol, decimals, and logo
***
## Key Features
* **Real-Time Prices** - Current token prices with USD values
* **Historical Data** - Price history and OHLC candlestick data
* **Holder Analytics** - Top holders, holder counts, and distribution
* **Swap Tracking** - DEX trades with token pairs and values
* **Pair Discovery** - Find trading pairs across DEXs
* **Token Search** - Search tokens by name or symbol
* **Safety Signals** - Token security analysis and risk indicators
* **Multi-Chain** - Consistent data across all EVM chains
***
## Common Use Cases
* **Trading Platforms**\
(real-time prices, charts, swap history)
* **Portfolio Trackers**\
(token balances with USD valuations)
* **Token Analytics**\
(holder distribution, volume, liquidity)
* **DEX Aggregators**\
(pair discovery, liquidity analysis)
* **Wallet Apps**\
(display token holdings and transfers)
* **Research Tools**\
(token metrics and safety analysis)
***
## Get Started
Explore some of the popular Token API endpoints:
* [Token Balances](/data-api/evm/wallet/token-balances) - Get token holdings for a wallet
* [Token Search](/data-api/data-features/search-and-discovery/token-search) - Search for tokens
* [Token Price](/data-api/evm/price/token-price) - Get current token price
* [Token Transfers](/data-api/evm/wallet/token-transfers) - Get transfer history
* [Token Metadata](/data-api/evm/token/metadata/token-metadata) - Get token details
* [Token Pairs](/data-api/evm/token/swaps/token-pairs) - Get trading pairs
# OHLC by Pair Address
Source: https://docs.moralis.com/data-api/evm/token/prices/ohlc
openapi-files/data-api/api.json GET /pairs/{address}/ohlcv
Retrieve OHLCV (Open, High, Low, Close, Volume) candlestick data for a token pair.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/pair-ohlcv) — the same decoded
onchain dataset, in real time, with no per-call limits.
> [!WARNING]
>
> This endpoint requires a **pair address**, not a token address. To find the pair addresses for a token, use the [Token Pairs endpoint](/data-api/evm/token/swaps/token-pairs).
# Token Price
Source: https://docs.moralis.com/data-api/evm/token/prices/token-price
openapi-files/data-api/api.json GET /erc20/{address}/price
Retrieve the current or historical price of an ERC20 token in the blockchain’s native currency and USD. Each token returned includes on-chain metadata, as well as off-chain metadata, logos, spam status and more. Additional options to exclude low-liquidity tokens and inactive tokens.
> [!TIP]
>
> To avoid prices from thin or stale pools, set `min_pair_side_liquidity_usd` and `max_token_inactivity`. See [Accurate Net Worth & Token Balances](/data-api/data-features/safety-and-trust/accurate-net-worth-and-balances).
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/erc20-price) — the same decoded
onchain dataset, in real time, with no per-call limits.
# Token Prices (Batch)
Source: https://docs.moralis.com/data-api/evm/token/prices/token-prices-batch
openapi-files/data-api/api.json POST /erc20/prices
Retrieve the current or historical prices for multiple ERC20 tokens in the blockchain’s native currency and USD. Accepts an array of up to 100 `tokens`, each requiring `token_address` and optional fields such as `to_block` or `exchange`. Each token returned includes on-chain metadata, as well as off-chain metadata, logos, spam status and more. Additional options to exclude low-liquidity tokens and inactive tokens.
> [!TIP]
>
> To avoid prices from thin or stale pools, set `min_pair_side_liquidity_usd` and `max_token_inactivity`. See [Accurate Net Worth & Token Balances](/data-api/data-features/safety-and-trust/accurate-net-worth-and-balances).
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/erc20-prices) — the same decoded
onchain dataset, in real time, with no per-call limits.
# Top Traders by Token
Source: https://docs.moralis.com/data-api/evm/token/signals/top-traders
openapi-files/data-api/api.json GET /erc20/{address}/top-gainers
List the most profitable wallets that have traded a specific ERC20 token.
\> [accordion] Supported Chains (Beta)
\>
\> This endpoint currently supports
\> chain:
\>
\>
\>
Chain
\>
Query Params
\>
> [!WARNING]
>
> We recommend using the new [Top Traders by Token](/data-api/universal/pnl/top-traders) endpoint on the Universal API - broader chain coverage, a selectable ranking metric, and low-liquidity filters.
# Pair Stats
Source: https://docs.moralis.com/data-api/evm/token/swaps/pair-stats
openapi-files/data-api/api.json GET /pairs/{address}/stats
Access key statistics for a token pair, such as price, buyers, sellers, liquidity, volume and more.
# Pair Swaps
Source: https://docs.moralis.com/data-api/evm/token/swaps/pair-swaps
openapi-files/data-api/api.json GET /pairs/{address}/swaps
Fetch swap transactions (buy, sell, add/remove liquidity) for a specific token pair.
# Token Pairs
Source: https://docs.moralis.com/data-api/evm/token/swaps/token-pairs
openapi-files/data-api/api.json GET /erc20/{token_address}/pairs
List supported trading pairs for a specific ERC20 token. Each pair returned includes price, liquidity, volume and more.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/token-pairs) — the same decoded
onchain dataset, in real time, with no per-call limits.
# Token Swaps
Source: https://docs.moralis.com/data-api/evm/token/swaps/token-swaps
openapi-files/data-api/api.json GET /erc20/{address}/swaps
Get all swap transactions (buy/sell) for a specific ERC20 token.
# Wallet Swaps
Source: https://docs.moralis.com/data-api/evm/token/swaps/wallet-swaps
openapi-files/data-api/api.json GET /wallets/{address}/swaps
List all swap transactions (buy/sell) for a specific wallet. Optionally filter by `tokenAddress` for specific token swaps.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/wallet-swaps) — the same decoded
onchain dataset, in real time, with no per-call limits.
# Token Transfers by Contract
Source: https://docs.moralis.com/data-api/evm/token/transfers/token-transfers
openapi-files/data-api/api.json GET /erc20/{address}/transfers
Get all ERC20 token transfers for a contract, ordered by block number (newest first).
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/token-transfers) — the same decoded
onchain dataset, in real time, with no per-call limits.
# Token Approvals
Source: https://docs.moralis.com/data-api/evm/wallet/approvals
openapi-files/data-api/api.json GET /wallets/{address}/approvals
List active ERC20 token approvals for a wallet, showing which contracts have access.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/wallet-approvals) — the same decoded
onchain dataset, in real time, with no per-call limits.
# Wallet Chain Activity
Source: https://docs.moralis.com/data-api/evm/wallet/chain-activity
openapi-files/data-api/api.json GET /wallets/{address}/chains
List the blockchain networks a wallet is active on, including their first and last seen timestamps. Options to query cross-chain using the `chains` parameter.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/wallet-chains) — the same decoded
onchain dataset, in real time, with no per-call limits.
# Wallet Transactions (Decoded)
Source: https://docs.moralis.com/data-api/evm/wallet/decoded-transactions
openapi-files/data-api/api.json GET /{address}/verbose
Get ABI-decoded native transactions ordered by block number in descending order.
# Detailed Positions
Source: https://docs.moralis.com/data-api/evm/wallet/detailed-positions
openapi-files/data-api/api-v1.json GET /v1/wallets/{walletAddress}/defi/{protocol}/positions
Returns DeFi positions for a wallet address filtered by a specific protocol across specified chains.
# Resolve ENS Domain from Address
Source: https://docs.moralis.com/data-api/evm/wallet/ens-lookup
openapi-files/data-api/api.json GET /resolve/{address}/reverse
Convert an Ethereum address to its associated ENS domain, if registered.
# Detailed Positions
Source: https://docs.moralis.com/data-api/evm/wallet/legacy/detailed-positions
openapi-files/data-api/api.json GET /wallets/{address}/defi/{protocol}/positions
Fetch detailed DeFi positions for a given wallet and protocol.
# Wallet Positions
Source: https://docs.moralis.com/data-api/evm/wallet/legacy/wallet-positions
openapi-files/data-api/api.json GET /wallets/{address}/defi/positions
Get a concise overview of a wallet’s DeFi positions across all protocols.
# Wallet Protocols
Source: https://docs.moralis.com/data-api/evm/wallet/legacy/wallet-protocols
openapi-files/data-api/api.json GET /wallets/{address}/defi/summary
Summarize a wallet’s DeFi activity, including total USD value, unclaimed rewards and active protocols.
# Native Balance
Source: https://docs.moralis.com/data-api/evm/wallet/native-balance
openapi-files/data-api/api.json GET /{address}/balance
Check the native token balance (e.g. ETH) for a specific wallet.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/native-balance) — the same decoded
onchain dataset, in real time, with no per-call limits.
# Native Balance (Batch)
Source: https://docs.moralis.com/data-api/evm/wallet/native-balances-batch
openapi-files/data-api/api.json GET /wallets/balances
Retrieve native token balances (e.g. ETH) for one or many wallet addresses in single request.
> [!NOTE]
>
> **Endpoint cost:** 10 CUs per wallet. [Learn more about compute units](/data-api/pricing).
# Wallet Net Worth
Source: https://docs.moralis.com/data-api/evm/wallet/net-worth
openapi-files/data-api/api.json GET /wallets/{address}/net-worth
Calculate the total net worth of a wallet in USD, with options to exclude spam tokens for accuracy. Options to query cross-chain using the `chains` parameter, as well as additional options to exclude spam tokens, low-liquidity tokens and inactive tokens.
> [!TIP]
>
> Net worth inflated by spam or mispriced tokens? Set `exclude_spam`, `min_pair_side_liquidity_usd` and `max_token_inactivity`. They're all off by default. See [Accurate Net Worth & Token Balances](/data-api/data-features/safety-and-trust/accurate-net-worth-and-balances) for recommended values.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/wallet-networth) — the same decoded
onchain dataset, in real time, with no per-call limits.
# NFT Balances
Source: https://docs.moralis.com/data-api/evm/wallet/nft-balances
openapi-files/data-api/api.json GET /{address}/nft
Fetch all NFTs held by a specified wallet address. Use `token_addresses` to filter by one or many specific contract(s). Each NFT returned includes on-chain metadata as well as off-chain metadata, floor prices, rarity and more where available.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/wallet-nfts) — the same decoded
onchain dataset, in real time, with no per-call limits.
# NFT Collections
Source: https://docs.moralis.com/data-api/evm/wallet/nft-collections
openapi-files/data-api/api.json GET /{address}/nft/collections
Fetch all NFT Collections held by a specified wallet address. Each Collection returned includes on-chain metadata as well as off-chain metadata, floor prices and more where available.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/wallet-nft-collections) — the same decoded
onchain dataset, in real time, with no per-call limits.
# NFT Trades
Source: https://docs.moralis.com/data-api/evm/wallet/nft-trades-by-wallet
openapi-files/data-api/api.json GET /wallets/{address}/nfts/trades
Get NFT trades for a specific wallet address.
# NFT Transfers
Source: https://docs.moralis.com/data-api/evm/wallet/nft-transfers
openapi-files/data-api/api.json GET /{address}/nft/transfers
Get NFT transfers for a wallet, with filters like `contract_addresses` and other parameters. Supports ERC-721, ERC-1155 as well as custom contracts such as CryptoPunks and CryptoKitties.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/wallet-nft-transfers) — the same decoded
onchain dataset, in real time, with no per-call limits.
# Wallet API
Source: https://docs.moralis.com/data-api/evm/wallet/overview
A unified Wallet API to fetch balances, transfers, DeFi positions, PnL, NFTs, and fully decoded wallet activity across multiple chains.
## Overview
The **Wallet API** provides complete wallet intelligence across all activity types - tokens, NFTs, DeFi positions, swaps, and P\&L tracking.
Instead of querying multiple endpoints and aggregating data yourself, the Wallet API gives you a unified view of any wallet's holdings, history, and financial performance across chains.
***
## What Is the Wallet API?
The Wallet API lets you query everything about a wallet address:
* **Asset Holdings** - Token balances, NFT collections, and ownership data
* **Transaction History** - Raw and decoded transactions with human-readable labels
* **DeFi Positions** - Protocol exposure across lending, staking, and liquidity pools
* **Financial Metrics** - Net worth calculations and profit/loss tracking
* **Identity** - ENS name resolution and address labels
* **Approvals** - Token allowances granted to contracts
***
## Key Features
The Wallet API includes:
* **Decoded Transactions** - Human-readable transaction labels and summaries
* **Multi-Chain Support** - Query across all supported EVM chains
* **Net Worth Calculation** - Aggregate USD value of all holdings
* **P\&L Tracking** - Realized and unrealized profit/loss per token
* **Swap History** - DEX trading activity with token pairs and values
* **NFT Trades** - Marketplace activity including buys, sells, and listings
* **Chain Activity** - Identify which chains a wallet is active on
***
## Common Use Cases
The Wallet API is commonly used for:
* **Portfolio Trackers**\
(display holdings, value, and performance)
* **Wallet Explorers**\
(transaction history and activity feeds)
* **DeFi Dashboards**\
(show positions across protocols)
* **Tax Tools**\
(calculate gains/losses from trading)
* **Security Apps**\
(monitor approvals and revoke permissions)
* **Identity Resolution**\
(resolve ENS names and wallet labels)
***
## Popular Endpoints
| Endpoint | Description |
| - | - |
| [Wallet History](/data-api/evm/wallet/wallet-history) | Complete decoded activity feed |
| [Token Balances](/data-api/evm/wallet/token-balances) | Current ERC-20 holdings |
| [NFT Balances](/data-api/evm/wallet/nft-balances) | Current NFT holdings |
| [Net Worth](/data-api/evm/wallet/net-worth) | Total wallet value in USD |
| [Wallet P\&L](/data-api/evm/wallet/wallet-pnl) | Profit/loss per token |
| [Decoded Transactions](/data-api/evm/wallet/decoded-transactions) | Human-readable transaction data |
***
## Get Started
Explore some of the popular Wallet API endpoints:
* [Token Balances](/data-api/evm/wallet/token-balances)
* [NFT Balances](/data-api/evm/wallet/nft-balances)
* [Wallet History](/data-api/evm/wallet/wallet-history)
* [Net Worth](/data-api/evm/wallet/net-worth)
# Resolve Address from ENS Domain
Source: https://docs.moralis.com/data-api/evm/wallet/resolve-address
openapi-files/data-api/api.json GET /resolve/ens/{domain}
Resolve an ENS domain to its associated Ethereum address.
# Token Balances
Source: https://docs.moralis.com/data-api/evm/wallet/token-balances
openapi-files/data-api/api.json GET /wallets/{address}/tokens
Fetch ERC20 and native token balances for a given wallet address, including their USD prices. Each token returned includes on-chain metadata, as well as off-chain metadata, logos, spam status and more. Additional options to exclude spam tokens, low-liquidity tokens and inactive tokens.
> [!TIP]
>
> Seeing spam tokens or inflated USD values? Set `exclude_spam`, `min_pair_side_liquidity_usd` and `max_token_inactivity`. They're all off by default. See [Accurate Net Worth & Token Balances](/data-api/data-features/safety-and-trust/accurate-net-worth-and-balances) for recommended values.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/wallet-tokens) — the same decoded
onchain dataset, in real time, with no per-call limits.
# Token Balances (Legacy)
Source: https://docs.moralis.com/data-api/evm/wallet/token-balances-legacy
openapi-files/data-api/api.json GET /{address}/erc20
Get an unpaginated list of token balances, without token prices, for a specific wallet address. Maximum of 2,000 tokens. Each token returned includes on-chain metadata, as well as off-chain metadata, logos, spam status and more.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/wallet-erc20) — the same decoded
onchain dataset, in real time, with no per-call limits.
> [!WARNING]
>
> We recommended using the latest [Token Balances](/data-api/evm/wallet/token-balances) endpoint.
# Token Transfers
Source: https://docs.moralis.com/data-api/evm/wallet/token-transfers
openapi-files/data-api/api.json GET /{address}/erc20/transfers
Get all ERC20 token transfers for a given wallet address, sorted by block number (newest first).
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/wallet-erc20-transfers) — the same decoded
onchain dataset, in real time, with no per-call limits.
# Wallet History
Source: https://docs.moralis.com/data-api/evm/wallet/wallet-history
openapi-files/data-api/api.json GET /wallets/{address}/history
Get the complete decoded transaction history for a given wallet. All transactions are parsed, decoded, categorized and summarized into human-readable records.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/wallet-history) — the same decoded
onchain dataset, in real time, with no per-call limits.
# Wallet Insights
Source: https://docs.moralis.com/data-api/evm/wallet/wallet-insights
openapi-files/data-api/api.json GET /wallets/{address}/insight
Retrieve comprehensive wallet insight metrics including activity age, transfer counts, counterparties, and swap volume.
\> [accordion] Supported Chains (Beta)
\>
\> This endpoint currently supports
\> chain:
\>
\>
\>
Chain
\>
Query Params
\>
# Wallet PnL Breakdown
Source: https://docs.moralis.com/data-api/evm/wallet/wallet-pnl
openapi-files/data-api/api.json GET /wallets/{address}/profitability
Get a detailed profit and loss breakdown by token for a given wallet, over a specified timeframe (`days`). Optionally filter by `token_addresses` for specific tokens.
\> [accordion] Supported Chains (Beta)
\>
\> This endpoint currently supports
\> chain:
\>
\>
\>
Chain
\>
Query Params
\>
> [!WARNING]
>
> We recommend using the new multi-chain [Wallet PnL](/data-api/universal/pnl/wallet-pnl) endpoint on the Universal API - same profitability data, multiple chains in a single request.
# Wallet PnL Summary
Source: https://docs.moralis.com/data-api/evm/wallet/wallet-pnl-summary
openapi-files/data-api/api.json GET /wallets/{address}/profitability/summary
Get a profit and loss summary for a given wallet, over a specified timeframe (`days`).
\> [accordion] Supported Chains (Beta)
\>
\> This endpoint currently supports
\> chain:
\>
\>
\>
Chain
\>
Query Params
\>
> [!WARNING]
>
> We recommend using the new multi-chain [Wallet PnL Summary](/data-api/universal/pnl/wallet-pnl-summary) endpoint on the Universal API - same summary data, multiple chains in a single request.
# Wallet Positions
Source: https://docs.moralis.com/data-api/evm/wallet/wallet-positions
openapi-files/data-api/api-v1.json GET /v1/wallets/{walletAddress}/defi/positions
Returns all DeFi positions (lending, liquidity, staking) for a wallet address across specified chains in a unified schema.
# Wallet Protocols
Source: https://docs.moralis.com/data-api/evm/wallet/wallet-protocols
openapi-files/data-api/api-v1.json GET /v1/wallets/{walletAddress}/defi/summary
Returns a summary of all DeFi positions for a wallet address across specified chains.
# Wallet Stats
Source: https://docs.moralis.com/data-api/evm/wallet/wallet-stats
openapi-files/data-api/api.json GET /wallets/{address}/stats
Retrieve key statistics for a wallet, such as total transaction count and activity.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/wallet-stats) — the same decoded
onchain dataset, in real time, with no per-call limits.
# Wallet Swaps
Source: https://docs.moralis.com/data-api/evm/wallet/wallet-swaps
openapi-files/data-api/api.json GET /wallets/{address}/swaps
List all swap transactions (buy/sell) for a specific wallet. Optionally filter by `tokenAddress` for specific token swaps.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/wallet-swaps) — the same decoded
onchain dataset, in real time, with no per-call limits.
# Wallet Transactions (Raw)
Source: https://docs.moralis.com/data-api/evm/wallet/wallet-transactions
openapi-files/data-api/api.json GET /{address}
Get raw native transactions ordered by block number in descending order.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/wallet-native-txns) — the same decoded
onchain dataset, in real time, with no per-call limits.
# Make Your First Request
Source: https://docs.moralis.com/data-api/first-request
Learn how to get started with the Moralis Data API.
### Your first request
Let's make your first request using the [Wallet API](/data-api/evm/wallet/overview).\
In this example, we'll retrieve **token balances** for a wallet on Ethereum - including **formatted balances, USD values, prices, and metadata** - with a single API call using [Token Balances](/data-api/evm/wallet/token-balances).
### What we'll fetch
* All ERC-20 and native token balances for a wallet
* Enriched data such as token metadata, prices, and USD values
* Normalized output you can use directly in apps or dashboards
### Make the request
```bash cURL theme={null}
curl --request GET \
--url 'https://deep-index.moralis.io/api/v2.2/wallets/0xcB1C1FdE09f811B294172696404e88E658659905/tokens?chain=eth' \
--header 'X-API-Key: YOUR_API_KEY'
```
> [!NOTE]
>
> Replace `YOUR_API_KEY` with the API key from your [Moralis dashboard](/data-api/get-your-api-key).
### Response
The API returns a JSON object containing the wallet's token balances. Each entry includes balances, prices, USD values, and security metadata.
```json Response (JSON) expandable theme={null}
{
"cursor": null,
"page": 0,
"page_size": 100,
"block_number": 23998783,
"result": [
{
"token_address": "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
"symbol": "ETH",
"name": "Ether",
"logo": "https://cdn.moralis.io/eth/0x.png",
"thumbnail": "https://cdn.moralis.io/eth/0x_thumb.png",
"decimals": 18,
"balance": "1709495362615127",
"possible_spam": false,
"verified_contract": true,
"total_supply": null,
"total_supply_formatted": null,
"percentage_relative_to_total_supply": null,
"security_score": 99,
"balance_formatted": "0.001709495362615127",
"usd_price": 3074.275584969874,
"usd_price_24hr_percent_change": -4.046936070446101,
"usd_price_24hr_usd_change": -129.54660056550028,
"usd_value": 5.255459855906907,
"usd_value_24hr_usd_change": -0.22145931290927692,
"native_token": true,
"portfolio_percentage": 57.264259068625606
},
{
"token_address": "0x4fabb145d64652a948d72533023f6e7a623c7c53",
"symbol": "BUSD",
"name": "BUSD",
"logo": "https://logo.moralis.io/0x1_0x4fabb145d64652a948d72533023f6e7a623c7c53_05b49a8d713a42d99fc194279df539e7.png",
"thumbnail": "https://logo.moralis.io/0x1_0x4fabb145d64652a948d72533023f6e7a623c7c53_05b49a8d713a42d99fc194279df539e7.png",
"decimals": 18,
"balance": "2102143890000000000",
"possible_spam": false,
"verified_contract": true,
"total_supply": "55026240205945520000000000",
"total_supply_formatted": "55026240.20594552",
"percentage_relative_to_total_supply": 0.000003820257175726,
"security_score": 76,
"balance_formatted": "2.10214389",
"usd_price": 0.9966474180866458,
"usd_price_24hr_percent_change": -0.33116797769114314,
"usd_price_24hr_usd_change": -0.0033115438720600077,
"usd_value": 2.0950962804151176,
"usd_value_24hr_usd_change": -0.006961341717117886,
"native_token": false,
"portfolio_percentage": 22.82847542647662
},
{},
{}
]
}
```
### What you get
With a single request, Moralis provides:
* **Low-latency access** to onchain wallet data
* **Normalized balances** across tokens
* **Enriched pricing and USD values**
* **Token metadata and security signals**
* Production-ready responses for apps and analytics
No RPC calls, no custom indexing, no manual price joins.
### Next steps
* Explore more endpoints in the **Wallet API**
* Fetch **NFT balances** or **transaction history**
* Combine with **Streams** to react to wallet activity in real time
* Use **Data Feeds** for large-scale analytics
# Get Your API Key
Source: https://docs.moralis.com/data-api/get-your-api-key
Learn how to get your Moralis API Key
To start using Moralis products, you’ll need an API key to authenticate your requests.
Follow this quick guide to create your account and retrieve your API key- then you'll be ready to make your [first request](/data-api/first-request).
## 1. Create Your Account
Create your **Moralis account** by visiting the [Moralis Dashboard](https://admin.moralis.com/register).

## 2. Navigate to Data APIs
Once registered, navigate to the [Data APIs section](https://admin.moralis.com/data-api) in the dashboard.

## 3. Copy Your API Key
Click the **copy** icon next to your API key to add it to your clipboard.

## 4. Manage API keys (optional)
You can also manage your keys from the **API Keys** section - including creating new keys or rotating existing ones.

That's it - you're now ready to make your [first API request](/data-api/first-request)
# Performance
Source: https://docs.moralis.com/data-api/introduction/resources/performance-and-reliability
Performance characteristics of Moralis APIs, including latency percentiles, supported request rates, data freshness, uptime, and enterprise SLAs.
This page outlines the **real-world performance characteristics** of Moralis APIs, including **latency**, **request throughput**, **data freshness**, and **availability**.
The figures below reflect typical production behavior under normal load and are intended to help teams design and operate reliable systems.
***
## API Latency
Moralis APIs are optimized for **low-latency, high-throughput** access to blockchain data.
Typical response times across core read endpoints:
| Percentile | Latency |
| :- | :- |
| **p50** | **\< 50 ms** |
| **p90** | **\< 500 ms** |
| **p95** | **\< 1 s** |
Latency may vary based on:
* Endpoint complexity
* Chain and network conditions
* Result size and pagination
* Applied enrichment (decoding, pricing, analytics)
***
## Throughput & Request Rates
Moralis supports **high sustained request volumes** for production workloads.
* **1,000+ requests per second (RPS)** is supported on appropriate plans
* Throughput is governed by **Compute Units (CUs)** and plan-level limits
* Short bursts are supported within rolling rate-limit windows
* Enterprise customers can request **custom throughput limits** and dedicated capacity
For plan-specific limits, see:
* [**Rate Limits**](/data-api/resources/rate-limits)
* [**Pricing**](/data-api/pricing)
***
## Data Freshness
Data freshness reflects how quickly new on-chain activity becomes available via the API.
Typical freshness for indexed on-chain data:
| Percentile | Freshness |
| :- | :- |
| **p50** | **\< 4 s** |
| **p90** | **\< 8 s** |
Notes:
* Blocks, transactions, and transfers are indexed near real time
* Price and market data update continuously
* Derived metrics (holders, analytics, PnL) may lag slightly during periods of high activity
***
## Availability & Uptime
Moralis operates production infrastructure **24/7/365**.
* **Enterprise customers** are supported with a **24/7/365 SLA**
* Platform uptime and incident history are publicly available at:\
[**status.moralis.io**](https://status.moralis.io)
# Premium Endpoints
Source: https://docs.moralis.com/data-api/introduction/resources/premium-endpoints
Endpoints that require a paid plan to access.
## Overview
Premium endpoints provide access to advanced analytics, market metrics, token discovery, and DeFi features. These endpoints require an API key on the plan listed for each endpoint or above.
***
## DeFi API
| Endpoint | Method | Path | Required Plan | CUs |
| - | - | - | - | - |
| Wallet Protocols ([EVM](/data-api/evm/defi/wallet-protocols), [Solana](/data-api/solana/defi/wallet-protocols)) | GET | `/v1/wallets/{walletAddress}/defi/summary` | Starter | 5000 |
| Wallet Positions ([EVM](/data-api/evm/defi/wallet-positions), [Solana](/data-api/solana/defi/wallet-positions)) | GET | `/v1/wallets/{walletAddress}/defi/positions` | Starter | 5000 |
| Detailed Positions ([EVM](/data-api/evm/defi/wallet-positions-detailed), [Solana](/data-api/solana/defi/wallet-positions-detailed)) | GET | `/v1/wallets/{walletAddress}/defi/{protocol}/positions` | Starter | 5000 |
***
## Wallet
| Endpoint | Method | Path | Required Plan | CUs |
| - | - | - | - | - |
| [Wallet Insights](/data-api/evm/wallet/wallet-insights) | GET | `/wallets/{address}/insight` | Pro | 100 |
***
## Entity API
| Endpoint | Method | Path | Required Plan | CUs |
| - | - | - | - | - |
| [Entity Search](/data-api/universal/entity/endpoints/entity-search) | GET | `/entities/search` | Pro | 50 |
| [Get Entity](/data-api/universal/entity/endpoints/entity-by-id) | GET | `/entities/{entityId}` | Pro | 50 |
| [Get Entities by Category](/data-api/universal/entity/endpoints/entity-by-category) | GET | `/entities/categories/{categoryId}` | Pro | 50 |
| [Get Entity Categories](/data-api/universal/entity/endpoints/entity-categories) | GET | `/entities/categories` | Pro | 10 |
***
## Token Analytics
| Endpoint | Method | Path | Required Plan | CUs |
| - | - | - | - | - |
| [Token Score](/data-api/evm/token/metadata/token-score) | GET | `/tokens/{tokenAddress}/score` | Pro | 100 |
| [Token Score - Timeseries](/data-api/evm/token/metadata/token-score-timeseries) | GET | `/tokens/{tokenAddress}/score/historical` | Pro | 150 |
| [Token Analytics (Batch)](/data-api/universal/token/analytics/token-analytics-multi) | POST | `/tokens/analytics` | Pro | 150 |
| [Token Analytics - Timeseries](/data-api/universal/token/analytics/token-analytics-timeseries) | POST | `/tokens/analytics/timeseries` | Pro | 200 |
***
## Token Discovery
| Endpoint | Method | Path | Required Plan | CUs |
| - | - | - | - | - |
| [Token Search](/data-api/universal/token/search/token-search) | GET | `/tokens/search` | Pro | 150 |
| [Token Categories](/data-api/evm/token/discovery/token-categories) | GET | `/tokens/categories` | Pro | 10 |
| [Trending Tokens](/data-api/universal/token/trending-tokens) | GET | `/tokens/trending` | Pro | 150 |
***
## Upgrade Your Plan
To access premium endpoints, upgrade your plan at [admin.moralis.com](https://admin.moralis.com).
# Onchain Skills
Source: https://docs.moralis.com/data-api/onchain-skills/overview
Give your AI agent the ability to query blockchain data using Moralis APIs. Works with Claude Code, Cursor, Windsurf, GitHub Copilot, Cline, Codex, Gemini, and more.

## What are Onchain Skills?
Onchain Skills is an open-source package that lets AI agents call the [Moralis API](https://admin.moralis.com/register) directly — giving them the ability to query blockchain data from 40+ EVM chains and Solana in real time.
It works with any agent that supports the [Agent Skills](https://skills.sh/) standard, including **Claude Code, Cursor, Windsurf, GitHub Copilot, Cline, Codex, Gemini**, and 18+ others.
[Build Web3 Apps With AI Using Real Onchain Data | Moralis Onchain Skills](https://www.youtube.com/embed/hq-SlxYji4w)
***
## Quick Start
### 1. Install the Skills
```bash theme={null}
npx skills add novnski/onchain-skills
```
### 2. Set Your API Key
Get your key from [admin.moralis.com](https://admin.moralis.com/register), then add it to a `.env` file in your project root:
```bash theme={null}
echo "MORALIS_API_KEY=your_key_here" >> .env
```
That's it — your AI agent can now query blockchain data through Moralis.
***
## Skills Overview
Onchain Skills includes three skills:
| Skill | Description | Endpoints |
| - | - | - |
| **moralis-data-api** | EVM + Solana blockchain data | 136 |
| **moralis-streams-api** | Real-time event monitoring with webhooks | 20 |
| **learn-moralis** | Routing, FAQ, pricing, and capability guidance | — |
### moralis-data-api
Unified skill for all blockchain data queries. Auto-detects EVM vs Solana from address format. For EVM addresses without a specified chain, defaults to Ethereum.
**136 endpoints** (102 EVM + 34 Solana) across these categories:
* **Wallet** (17) — balances, tokens, NFTs, history, profitability, net worth
* **Token** (22) — prices, metadata, pairs, DEX swaps, analytics, security scores
* **NFT** (22) — metadata, transfers, traits, rarity, floor prices, trades
* **DeFi** (3) — protocol positions, liquidity, exposure
* **Entity** (2) — labeled addresses (exchanges, funds, whales)
* **Price** (4) — OHLCV, token prices, pair prices
* **Blockchain** (5) — blocks, transactions, date-to-block
* **Discovery** (13) — trending tokens
* **Other** (14) — address resolution, token search, candlesticks
* **Solana** (34) — native Solana endpoints + EVM endpoints with Solana support
**Example prompts:**
```
/moralis-data-api Get the balance of 0x1234...
/moralis-data-api Get the balance of 0x1234... on Polygon
/moralis-data-api Get the balance of Solana wallet ABC123...
```
### moralis-streams-api
Real-time blockchain event monitoring with webhooks. **20 endpoints** for creating, managing, and monitoring streams.
**Stream types:** `tx`, `log`, `erc20transfer`, `erc20approval`, `nfttransfer`, `internalTx`
**Example prompts:**
```
/moralis-streams-api Create a stream to monitor all ERC20 transfers on Ethereum
/moralis-streams-api Pause the stream with ID abc123
```
### learn-moralis
Knowledge-only skill for answering general questions about Moralis. Routes you to the correct technical skill after answering.
**Example prompts:**
```
/learn-moralis What is Moralis?
/learn-moralis Which Moralis API should I use for tracking wallet activity?
```
***
## Supported Chains
**EVM (40+):** Ethereum, Polygon, BNB Smart Chain, Arbitrum, Optimism, Avalanche, Base, Sei, Monad, and more.
**Solana:** Mainnet and Devnet.
For the full list of supported chains, see [Supported Chains](/get-started/supported-chains).
***
## Architecture
* **Zero dependencies** — all API calls use curl
* **Works with 18+ agents** — any agent supporting the Agent Skills standard
* **Auto-detects chain** — determines EVM vs Solana from address format
***
## Resources
* [GitHub Repository](https://github.com/novnski/onchain-skills)
* [Get an API Key](https://admin.moralis.com/register)
* [Agent Skills Standard](https://skills.sh/)
* [Video Tutorial: Build Web3 Apps With AI Using Real Onchain Data](https://www.youtube.com/watch?v=hq-SlxYji4w)
# Tutorial
Source: https://docs.moralis.com/data-api/onchain-skills/tutorial
Step-by-step guide to installing and using Moralis Onchain Skills with your AI agent.
## Video Tutorial
Watch the full walkthrough on setting up and using Onchain Skills to build Web3 apps with AI:
[Build Web3 Apps With AI Using Real Onchain Data | Moralis Onchain Skills](https://www.youtube.com/embed/hq-SlxYji4w)
***
## Prerequisites
* **Node.js** installed on your machine
* A **Moralis API key** — get one at [admin.moralis.com](https://admin.moralis.com/register)
* An AI agent that supports the [Agent Skills](https://skills.sh/) standard (e.g., Claude Code, Cursor, Windsurf, GitHub Copilot, Cline, Codex, Gemini)
***
## Step 1: Install Onchain Skills
Run the following command in your project directory:
```bash theme={null}
npx skills add novnski/onchain-skills
```

This installs three skills into your project:
* **moralis-data-api** — query blockchain data (136 endpoints)
* **moralis-streams-api** — real-time event monitoring (20 endpoints)
* **learn-moralis** — general Moralis knowledge and routing
### Alternative Installation Methods
**Via [ClawHub](https://clawhub.ai/):**
```bash theme={null}
clawhub install moralis-data-api
clawhub install moralis-streams-api
clawhub install learn-moralis
```
**Via OpenClaw agent:** If you have an [OpenClaw](https://openclaw.ai/) agent running, ask it to search for and install the Moralis API skills from ClawHub.
***
## Step 2: Configure Your API Key
Add your Moralis API key to a `.env` file in your project root:
```bash theme={null}
echo "MORALIS_API_KEY=your_key_here" >> .env
```
Replace `your_key_here` with your actual API key from [admin.moralis.com](https://admin.moralis.com/register).
> [!NOTE]
>
> Without the API key, the skills cannot call the Moralis API on your behalf.
**For OpenClaw users**, add the key to the `env` section in `~/.openclaw/openclaw.json` instead:
```json theme={null}
{
"env": {
"MORALIS_API_KEY": "your_key_here"
}
}
```
***
## Step 3: Start Using Skills
Once installed and configured, you can prompt your AI agent with skill-specific commands. Prefix your prompt with the skill name to load it directly.
### Query Blockchain Data
```
/moralis-data-api Get the token balances of 0x1234...
```
```
/moralis-data-api What are the top trending tokens on Ethereum?
```
```
/moralis-data-api Get the NFT collections owned by 0x1234...
```
### Monitor Real-Time Events
```
/moralis-streams-api Create a stream to monitor all ERC20 transfers on Ethereum
```
```
/moralis-streams-api List all my active streams
```
### Ask General Questions
```
/learn-moralis What chains does Moralis support?
```
```
/learn-moralis Which API should I use for tracking wallet activity?
```
***
## What's Next?
* Explore the full list of available endpoints in the [Onchain Skills Overview](/data-api/onchain-skills/overview)
* Browse the [EVM API](/data-api/evm) and [Solana API](/data-api/solana) documentation for detailed endpoint references
* Check out the [GitHub repository](https://github.com/novnski/onchain-skills) for source code and contributions
# Data API
Source: https://docs.moralis.com/data-api/overview
The universal multichain Data API provides a single, consistent interface for accessing blockchain data across 30+ supported chains, including Ethereum, Solana, Bitcoin, Base, Binance Smart Chain, and more. It standardizes complex on-chain data into clean, developer-friendly formats.
### How it's structured
The Data API is made up of **four core components**, designed to balance **cross-chain consistency** with **chain-specific depth**:
#### Universal API
Our [Universal API](/data-api/universal/overview) supports cross-chain endpoints that work across **EVM, Solana, and Bitcoin**, using unified schemas wherever possible. Ideal for applications that need to support multiple chains without maintaining separate integrations.
#### EVM API
The [EVM API](/data-api/evm/overview) offers deep, EVM-specific APIs covering Ethereum and EVM-compatible chains, exposing rich transaction, token, NFT, DeFi, and contract-level data.
#### Solana API
Our [Solana API](/data-api/solana/overview) provides parsed, high-performance access to Solana transactions, programs, token accounts, and NFTs, designed around Solana’s unique architecture.
#### Bitcoin API
The [Bitcoin API](/data-api/bitcoin/overview) brings full Bitcoin coverage — raw blocks and transactions, BTC market data, address activity, and balances — through the same Universal endpoints used for EVM and Solana. Pass `bitcoin` as the chain, with native xpub support across every wallet endpoint.
### Explore Data APIs
> [card] [Wallet API](/data-api/evm/wallet/overview)
>
> Wallet history, transfers balances, tokens and PnL.
> [card] [Token API](/data-api/evm/token/overview)
>
> Token search, balances, transfers, holders and swaps.
> [card] [NFT API](/data-api/evm/nft/overview)
>
> Metadata, floor prices, transfers and ownership.
> [card] [Price API](/data-api/evm/price/overview)
>
> Real-time crypto prices, OHLC, trading volume.
> [card] [DeFi API](/data-api/evm/defi/overview)
>
> DeFi positions, liquidity, reserves and token pairs.
> [card] [Blockchain API](/data-api/evm/blockchain/overview)
>
> Raw blocks, transactions, internal transactions and logs.
### Types of use cases
* Building wallets and portfolio trackers
* Powering Web3 dashboards and analytics tools
* Supporting multi-chain dApps from a single backend
* Tracking wallet activity, balances, and history
* Token discovery, monitoring, and market analysis
* NFT marketplaces and NFT analytics platforms
* DeFi apps showing positions, liquidity, and protocol data
* Backend services that need low-latency blockchain reads
### Key features
* **Low-latency APIs** optimized for production workloads
* **Unified schemas** across EVM, Solana, and Bitcoin where possible
* **Decoded and enriched data** (tokens, NFTs, prices, metadata)
* **Multi-chain support** across 30+ blockchains
* **High throughput & reliability** at scale
* **Consistent developer experience** across chains
* **Enterprise-grade infrastructure**, SLAs, and security
* No RPC management or custom indexer maintenance
### For which teams
* **Product teams** building wallets, dashboards, and user-facing apps
* **Backend engineers** who need reliable blockchain data without infra overhead
* **Frontend teams** consuming clean, predictable APIs
* **Analytics teams** accessing structured on-chain data
* **Startups and enterprises** scaling multi-chain applications
***
## Data API Overview Video
[Moralis Data API Overview – Fetch Onchain Data at Scale](https://www.youtube.com/embed/O8PXFkN71oo)
# Data API Pricing
Source: https://docs.moralis.com/data-api/pricing
Detailed pricing information for our Data API.
For a detailed explanation of Compute Units (CUs) and how they work, check out our [Compute Units section](/get-started/pricing).
## Free Trial
Moralis doesn't have a self-serve free plan. To try it before you subscribe, request a free trial and the team will reach out.
Request a free trial
***
## Universal API Compute Units
These endpoints support both EVM and Solana chains.
### Token Discovery & Analytics
| Method | CU Cost |
| - | - |
| [searchTokens](/data-api/universal/token/search/token-search) | 150 |
| [getTokenScore](/data-api/universal/token/score/token-score) | 100 |
| [getHistoricalTokenScore](/data-api/universal/token/score/token-score-timeseries) | 150 |
| [getTokenAnalytics](/data-api/universal/token/analytics/token-analytics) | 80 |
| [getMultipleTokenAnalytics](/data-api/universal/token/analytics/token-analytics-multi) | 150 |
| [getTimeSeriesTokenAnalytics](/data-api/universal/token/analytics/token-analytics-timeseries) | 200 |
| [getTrendingTokens](/data-api/universal/token/trending-tokens) | 150 |
### PnL API
| Method | CU Cost |
| - | - |
| [getWalletProfitability](/data-api/universal/pnl/wallet-pnl) | 50 per requested chain |
| [getWalletProfitabilitySummary](/data-api/universal/pnl/wallet-pnl-summary) | 30 per requested chain |
| [getTopTradersByToken](/data-api/universal/pnl/top-traders) | 50 |
### Token Prices
| Method | CU Cost |
| - | - |
| [getTokenPriceTimeSeries](/data-api/universal/token/price/token-price-timeseries) | 50 |
| [getTokenPriceSparkline](/data-api/universal/token/price/token-price-sparkline) | 50 |
### Entity API
| Method | CU Cost |
| - | - |
| [searchEntities](/data-api/universal/entity/endpoints/entity-search) | 50 |
| [getEntity](/data-api/universal/entity/endpoints/entity-by-id) | 50 |
| [getEntitiesByCategory](/data-api/universal/entity/endpoints/entity-by-category) | 50 |
| [getEntityCategories](/data-api/universal/entity/endpoints/entity-categories) | 10 |
***
## Bitcoin API Compute Units
Bitcoin endpoint costs mirror the closest Web3 API endpoint where applicable. Per-chain wallet endpoints are billed once for each requested chain.
### Bitcoin Blockchain API
| Method | CU Cost |
| - | - |
| [getBlockByNumberOrHash](/data-api/bitcoin/blockchain/block) | 100 |
| [getTransactionByHash](/data-api/bitcoin/blockchain/transaction) | 10 |
### Bitcoin Price API
| Method | CU Cost |
| - | - |
| [getTokenPrice](/data-api/bitcoin/price/current-price) | 50 |
| [getTokenPriceTimeSeries](/data-api/bitcoin/price/historical-price) | 50 |
| [getTokenPriceSparkline](/data-api/bitcoin/price/sparkline) | 50 |
### Bitcoin Wallet API
| Method | CU Cost |
| - | - |
| [getWalletHistory](/data-api/bitcoin/wallet/address-transactions) | 150 per chain |
| [getTokenBalances](/data-api/bitcoin/wallet/address-balances) | 50 per chain |
### Bitcoin Xpub Utility
| Method | CU Cost |
| - | - |
| [getAddressesByXpub](/data-api/bitcoin/utility/addresses-from-xpub) | 50 |
***
## EVM API Compute Units
### EVM Wallet API
| Method | CU Cost |
| - | - |
| [getWalletHistory](/data-api/evm/wallet/wallet-history) | 150 |
| [getWalletStats](/data-api/evm/wallet/wallet-stats) | 50 |
| [getWalletActiveChains](/data-api/evm/wallet/chain-activity) | 50 per chain |
| [getWalletTokenBalancesPrice](/data-api/evm/wallet/token-balances) | 100 |
| [getWalletTokenBalances](/data-api/evm/wallet/token-balances-legacy) | 100 |
| [getNativeBalance](/data-api/evm/wallet/native-balance) | 10 |
| [getNativeBalancesForAddresses](/data-api/evm/wallet/native-balances-batch) | 10 per wallet |
| [getWalletNFTs](/data-api/evm/wallet/nft-balances) | 50 |
| [getWalletNFTCollections](/data-api/evm/wallet/nft-collections) | 50 |
| [getWalletNFTTransfers](/data-api/evm/wallet/nft-transfers) | 50 |
| [getNFTTradesByWallet](/data-api/evm/wallet/nft-trades-by-wallet) | 40 |
| [getWalletTokenTransfers](/data-api/evm/wallet/token-transfers) | 50 |
| [getWalletTransactions](/data-api/evm/wallet/wallet-transactions) | 30 |
| [getWalletTransactionsVerbose](/data-api/evm/wallet/decoded-transactions) | 50 |
| [getWalletApprovals](/data-api/evm/wallet/approvals) | 100 |
| [getWalletNetWorth](/data-api/evm/wallet/net-worth) | 250 per chain |
| [getWalletProfitability](/data-api/evm/wallet/wallet-pnl) | 50 |
| [getWalletProfitabilitySummary](/data-api/evm/wallet/wallet-pnl-summary) | 30 |
| [getDefiSummary](/data-api/evm/wallet/wallet-protocols) | 5000 |
| [getDefiPositionsSummary](/data-api/evm/wallet/wallet-positions) | 5000 |
| [getDefiPositionsByProtocol](/data-api/evm/wallet/detailed-positions) | 5000 |
| [getSwapsByWalletAddress](/data-api/evm/wallet/wallet-swaps) | 50 |
| [resolveENSDomain](/data-api/evm/wallet/ens-lookup) | 10 |
| [resolveAddress](/data-api/evm/wallet/resolve-address) | 10 |
| [getWalletInsight](/data-api/evm/wallet/wallet-insights) | 100 per chain |
### EVM Token API
| Method | CU Cost |
| - | - |
| [getTokenMetadata](/data-api/evm/token/metadata/token-metadata) | 10 |
| [getTokenPrice](/data-api/evm/token/prices/token-price) | 50 |
| [getMultipleTokenPrices](/data-api/evm/token/prices/token-prices-batch) | 100 |
| [getPairCandlesticks](/data-api/evm/token/prices/ohlc) | 150 |
| [getTokenScore](/data-api/evm/token/metadata/token-score) | 100 |
| [getHistoricalTokenScore](/data-api/evm/token/metadata/token-score-timeseries) | 150 |
| [getTokenHolders](/data-api/evm/token/holders/token-holders) | 50 |
| [getTokenStats](/data-api/evm/token/holders/token-holder-stats) | 50 |
| [getTokenTransfers](/data-api/evm/token/transfers/token-transfers) | 50 |
| [getTokenPairs](/data-api/evm/token/swaps/token-pairs) | 50 |
| [getSwapsByTokenAddress](/data-api/evm/token/swaps/token-swaps) | 50 |
| [getSwapsByPairAddress](/data-api/evm/token/swaps/pair-swaps) | 50 |
| [getPairStats](/data-api/evm/token/swaps/pair-stats) | 100 |
| [getTopProfitableWalletPerToken](/data-api/evm/token/signals/top-traders) | 50 |
| [getTokenCategories](/data-api/evm/token/discovery/token-categories) | 10 |
### EVM NFT API
| Method | CU Cost |
| - | - |
| [getNFTMetadata](/data-api/evm/nft/metadata/nft-metadata) | 20 |
| [getMultipleNFTs](/data-api/evm/nft/metadata/nft-metadata-batch) | 150 |
| [getNFTContractMetadata](/data-api/evm/nft/metadata/collection-metadata) | 50 |
| [getNFTBulkContractMetadata](/data-api/evm/nft/metadata/collection-metadata-batch) | 5 |
| [getNFTCollectionStats](/data-api/evm/nft/metadata/collection-stats) | 50 |
| [getNFTFloorPriceByToken](/data-api/evm/nft/prices/floor) | 30 |
| [getNFTFloorPriceByContract](/data-api/evm/nft/prices/collection-floor-price) | 30 |
| [getNFTHistoricalFloorPriceByContract](/data-api/evm/nft/prices/historical-floor-price) | 50 |
| [getNFTSalePrices](/data-api/evm/nft/prices/sale-price-by-token-id) | 30 |
| [getNFTContractSalePrices](/data-api/evm/nft/prices/sale-price-by-contract) | 1 |
| [getNFTTrades](/data-api/evm/nft/trades/collection-trades) | 40 |
| [getNFTTradesByToken](/data-api/evm/nft/trades/trades-by-token-id) | 40 |
| [getNFTOwners](/data-api/evm/nft/ownership/owners-by-contract) | 50 |
| [getNFTTokenIdOwners](/data-api/evm/nft/ownership/owners-by-token-id) | 50 |
| [getNFTContractTransfers](/data-api/evm/nft/transfers/collection-transfers) | 50 |
| [getNFTTransfers](/data-api/evm/nft/transfers/token-id-transfers) | 20 |
| [getNFTTraitsByCollection](/data-api/evm/nft/traits/traits-by-collection) | 50 |
| [getNFTTraitsByCollectionPaginate](/data-api/evm/nft/traits/traits-by-collection-paginated) | 10 |
| [getNFTByContractTraits](/data-api/evm/nft/traits/nfts-by-traits) | 50 |
| [reSyncMetadata](/data-api/evm/nft/utilities/resync-nft-metadata) | 50 |
| [resyncNFTRarity](/data-api/evm/nft/utilities/resync-nft-traits) | 10 |
### EVM Price API
| Method | CU Cost |
| - | - |
| [getTokenPrice](/data-api/evm/price/token-price) | 50 |
| [getMultipleTokenPrices](/data-api/evm/price/token-prices-batch) | 100 |
| [getPairCandlesticks](/data-api/evm/price/ohlc) | 150 |
| [getNFTFloorPriceByToken](/data-api/evm/price/token-id-floor-price) | 30 |
| [getNFTFloorPriceByContract](/data-api/evm/price/collection-floor-price) | 30 |
| [getNFTHistoricalFloorPriceByContract](/data-api/evm/price/timeseries-floor-price) | 50 |
| [getNFTSalePrices](/data-api/evm/price/sale-price-by-token-id) | 30 |
| [getNFTContractSalePrices](/data-api/evm/price/sale-prices-by-collection) | 1 |
### EVM DeFi API
| Method | CU Cost |
| - | - |
| [getDefiSummary](/data-api/evm/defi/wallet-protocols) | 5000 |
| [getDefiPositionsSummary](/data-api/evm/defi/wallet-positions) | 5000 |
| [getDefiPositionsByProtocol](/data-api/evm/defi/wallet-positions-detailed) | 5000 |
### EVM Blockchain API
| Method | CU Cost |
| - | - |
| [getWalletTransactions](/data-api/evm/blockchain/address-transactions) | 30 |
| [getWalletTransactionsVerbose](/data-api/evm/blockchain/address-transactions-decoded) | 50 |
| [getDateToBlock](/data-api/evm/blockchain/block-by-date) | 1 |
| [getBlock](/data-api/evm/blockchain/block-by-hash) | 100 |
| [getLatestBlockNumber](/data-api/evm/blockchain/latest-block) | 10 |
| [getTransaction](/data-api/evm/blockchain/transaction-by-hash) | 10 |
| [getTransactionVerbose](/data-api/evm/blockchain/transaction-by-hash-decoded) | 20 |
***
## Solana API Compute Units
### Solana Wallet API
| Method | CU Cost |
| - | - |
| [balance](/data-api/solana/wallet/native-balance) | 10 |
| [getSPL](/data-api/solana/wallet/token-balances) | 10 |
| [getNFTs](/data-api/solana/wallet/nft-balances) | 10 |
| [getPortfolio](/data-api/solana/wallet/portfolio) | 10 |
| [getSwapsByWalletAddress](/data-api/solana/wallet/wallet-swaps) | 50 |
### Solana Token API
| Method | CU Cost |
| - | - |
| [getTokenMetadata](/data-api/solana/token/token-metadata) | 10 |
| [getMultipleTokenMetadata](/data-api/solana/token/token-metadata-batch) | 100 |
| [getTokenScore](/data-api/solana/token/token-score) | 100 |
| [getHistoricalTokenScore](/data-api/solana/token/token-score-timeseries) | 150 |
| [getTokenPrice](/data-api/solana/token/prices/token-price) | 10 |
| [getMultipleTokenPrices](/data-api/solana/token/prices/token-prices-batch) | 100 |
| [getCandleSticks](/data-api/solana/token/prices/ohlc) | 150 |
| [getTokenPairs](/data-api/solana/token/pairs/token-pairs) | 50 |
| [getSwapsByTokenAddress](/data-api/solana/token/swaps/token-swaps) | 50 |
| [getSwapsByPairAddress](/data-api/solana/token/pairs/pair-swaps) | 50 |
| [getPairStats](/data-api/solana/token/pairs/pair-stats) | 100 |
| [getAggregatedTokenPairStats](/data-api/solana/token/market-metrics/token-analytics) | 80 |
### Solana NFT API
| Method | CU Cost |
| - | - |
| [getNFTMetadata](/data-api/solana/nft/nft-metadata) | 10 |
### Solana Price API
| Method | CU Cost |
| - | - |
| [getTokenPrice](/data-api/solana/price/token-price) | 10 |
| [getMultipleTokenPrices](/data-api/solana/price/token-prices-batch) | 100 |
| [getCandleSticks](/data-api/solana/price/ohlc) | 150 |
# Pagination
Source: https://docs.moralis.com/data-api/resources/pagination
Moralis uses cursor-based pagination for endpoints that return lists (e.g. transactions, transfers, logs, NFTs, etc.).
Pagination lets an API return large result sets in smaller “pages” so responses stay fast and predictable.
Moralis uses **cursor-based pagination** for endpoints that return lists (e.g. transactions, transfers, logs, NFTs, etc.).
## Cursor Pagination
Cursor pagination works by returning a **cursor token** with each response. You pass that cursor into the next request to fetch the next page.
* **First request:** returns `result` + `cursor`
* **Next request:** send the returned `cursor` to get the next page
* When there are no more results, the cursor will be `null`
Cursor pagination is ideal for long lists because performance stays consistent even at large offsets.
## Cursor Pagination in Moralis
Moralis returns a cursor with list endpoints. Keep calling the endpoint with the latest cursor until no cursor is returned.
**Important notes**
* `limit` can only be set on the **initial request**. You can’t change the limit mid-pagination (because the cursor is tied to the original query settings).
* A cursor represents a **stable snapshot of the dataset at the time your first request was made** (a “point in time”).
## Snapshot Behavior (No Duplicates Across Pages)
When you paginate using a cursor, Moralis keeps the ordering consistent across pages for that pagination session.
Example: if you’re fetching “latest wallet transactions” and **new transactions occur while you’re paging**, those new transactions:
* **will not** reshuffle the pages you’re currently fetching
* **will not** cause items from page 1 to appear again on page 2
* **will not** be included in the current cursor run
If you want **new / delta results**, you should **start a new request** (i.e., re-call the endpoint without the old cursor) after you finish paging, or periodically re-poll from the top depending on your use case.
## Example: Cursor Pagination
Below is a simple Node.js example showing how to page through all results using a cursor.
This example:
* Makes an initial request with a `limit`
* Reuses the returned `cursor` to fetch the next page
* Stops when no cursor is returned
* Uses plain `fetch`
```typescript theme={null}
const fetch = require("node-fetch");
const API_KEY = "YOUR_API_KEY";
const BASE_URL = "https://deep-index.moralis.io/api/v2.2";
const address = "0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB";
const chain = "eth";
const limit = 100;
async function fetchAllPages() {
let cursor = null;
let allResults = [];
do {
const url = new URL(`${BASE_URL}/nft/${address}/owners`);
url.searchParams.set("chain", chain);
url.searchParams.set("limit", limit);
if (cursor) {
url.searchParams.set("cursor", cursor);
}
const res = await fetch(url.toString(), {
headers: {
"X-API-Key": API_KEY,
},
});
const data = await res.json();
allResults.push(...data.result);
cursor = data.cursor; // null / empty when no more pages
} while (cursor);
return allResults;
}
fetchAllPages().then((results) => {
console.log("Total records:", results.length);
});
```
# Rate Limits
Source: https://docs.moralis.com/data-api/resources/rate-limits
Moralis APIs use a throughput-based rate-limiting system, measured in requests per second.
Each plan defines how many requests you can send per second. If you exceed this, requests will be rate-limited.
## Throughput & Rolling Window
Throughput limits are evaluated over a **rolling 4-second window**, not per exact second.
This allows short request bursts, as long as your total request count stays within your plan's limits over that window.
## Maximum requests per second
| Plan | Throughput |
| :- | :- |
| Starter | 40 reqs/s |
| Pro | 80 reqs/s |
| Business | 200 reqs/s |
| Enterprise | Custom |
## Avoiding Rate Limits
To avoid rate limiting:
* Keep your request rate within your plan's throughput
* Avoid sustained spikes that exceed the rolling 4-second limit
* Upgrade your plan if you consistently hit limits
If you exceed your throughput, the API will return a **429 Too Many Requests** response.
# Response Codes
Source: https://docs.moralis.com/data-api/resources/response-codes
Moralis uses conventional HTTP response codes to indicate success or failure of an API request.
| Status Code | Message | Description |
| - | - | - |
| 200 | OK | Everything worked as expected. |
| 201 | Created | Resource has been successfully created or added to a queue. |
| 202 | Accepted | Resource has been successfully created or added to a queue. |
| 400 | Bad Request | Bad request, often due to missing or malformed parameter(s). |
| 401 | Unauthorized | Missing or invalid API key. |
| 404 | Not Found | Resource not found (for example pair or token not found for a specific chain). |
| 429 | Rate Limited | Too many requests. Consider upgrading your plan. |
| 500 | Internal Server Error | Something went wrong on Moralis' end. |
# Spam Filtering
Source: https://docs.moralis.com/data-api/resources/spam-filtering
Spam detection helps you identify and handle potentially harmful contracts in the Web3 ecosystem, in real time.
Our spam filtering is designed to protect applications and end users from interacting with spam, phishing, or low-quality token and NFT contracts.
## How It Works
Moralis automatically evaluates contracts as they are processed onchain.
For both **ERC20 tokens** and **NFT contracts**, Moralis adds a boolean field:
```
"possible_spam": true | false
```
This field indicates whether a contract is **likely to be spam or malicious**.
Spam detection is applied **in real time** as part of contract metadata processing (e.g. name, symbol, decimals, NFT metadata).
## Detection Logic
Spam detection is based on multiple internal signals, including:
* Keyword-based matching across contract metadata
* Known spam and phishing patterns
* Heuristic analysis from historical onchain behavior
Detection rules are continuously updated as new spam patterns emerge.
## Using Spam Detection
You can use the `possible_spam` field to:
* Hide suspicious tokens or NFTs from your UI
* Warn users before interacting with risky contracts
* Filter out spam from analytics, balances, or portfolios
Many Moralis endpoints (such as [Token Balances](/data-api/evm/wallet/token-balances)) support **excluding spam contracts** directly at query time. For which filters to combine when calculating balances and net worth, see [Accurate Net Worth & Token Balances](/data-api/data-features/safety-and-trust/accurate-net-worth-and-balances).
## ERC20 Tokens & Token Scores
For ERC20 tokens, spam detection works well alongside [**Token Scores**](/data-api/data-features/token-scores).
While `possible_spam` focuses on **known and likely spam signals**, Token Scores provide a broader **token quality and safety assessment**, considering factors such as:
* Liquidity
* Trading volume
* Holder distribution
* Transaction activity
* Token age
Using both together gives a more complete picture of token risk and quality.
***
## Notes
* `possible_spam` is a **best-effort signal**, not a guarantee
* Always apply additional validation for high-value or security-critical workflows
# Solana DeFi API
Source: https://docs.moralis.com/data-api/solana/defi/overview
Track DeFi positions, balances, and rewards across the most-used Solana protocols using the same Universal API endpoints as EVM.
## Overview
The **Solana DeFi API** provides a unified view of a wallet's DeFi positions across the most-used Solana protocols - lending, borrowing, staking, liquid staking, and liquidity pools.
The same three Universal API endpoints used for EVM DeFi positions now return Solana data, with no schema changes and no separate integration.
***
## What Is the Solana DeFi API?
The Solana DeFi API lets you query:
* **Protocol Summary** - Overview of all Solana DeFi protocols a wallet uses
* **Positions** - Detailed position data per protocol
* **Position Details** - Enhanced breakdown with underlying assets
* **Multi-Chain in One Call** - Query EVM and Solana wallets through the same endpoints
***
## Key Features
* **Protocol Detection** - Automatically identifies which Solana protocols a wallet uses
* **Position Breakdown** - Detailed view of deposits, borrows, staking, and rewards
* **USD Valuations** - Position values calculated in USD
* **Unified Schema** - Identical response shape across EVM and Solana
* **Single Integration** - Same filters and parameters as the EVM DeFi API
***
## Supported Protocols
The Solana DeFi API supports 10 of the most-used protocols on Solana - together covering roughly 90% of Solana DeFi TVL, including the top protocols by TVL (Jupiter, Kamino, Sanctum, and Raydium):
* Jito
* Save (formerly Solend)
* Jupiter Lend
* Jupiter Perpetual Exchange
* Kamino Lend
* Sanctum
* Raydium
* Orca
* Drift
* Marinade
More Solana protocols are being added on a rolling basis. If you need a specific protocol prioritized, [reach out to the team](https://moralis.com/enterprise/).
***
## Common Use Cases
The Solana DeFi API is commonly used for:
* **Portfolio Trackers**\
(show Solana DeFi positions alongside SPL tokens and NFTs)
* **DeFi Dashboards**\
(aggregate positions across Solana protocols)
* **Cross-Ecosystem Wallets**\
(display EVM and Solana DeFi positions side by side)
* **Yield Tracking**\
(monitor staking rewards and LP positions on Solana)
* **Tax Reporting**\
(calculate DeFi gains and income across Solana)
***
## Popular Endpoints
| Endpoint | Description |
| - | - |
| [Wallet Protocols](/data-api/solana/defi/wallet-protocols) | Summary of Solana protocols used by a wallet |
| [Wallet Positions](/data-api/solana/defi/wallet-positions) | Detailed Solana positions per protocol |
| [Detailed Positions](/data-api/solana/defi/wallet-positions-detailed) | Enhanced Solana position breakdown |
***
## Get Started
* [Get Wallet Protocols](/data-api/solana/defi/wallet-protocols)
* [Get Wallet Positions](/data-api/solana/defi/wallet-positions)
* [Get Detailed Positions](/data-api/solana/defi/wallet-positions-detailed)
***
## Get Solana DeFi Data in 1 API Call
[Get Solana DeFi Data in 1 API Call](https://www.youtube.com/embed/Q3W3RFj42bE)
# Wallet Positions
Source: https://docs.moralis.com/data-api/solana/defi/wallet-positions
openapi-files/data-api/api-v1.json GET /v1/wallets/{walletAddress}/defi/positions
Returns all DeFi positions (lending, liquidity, staking) for a wallet address across specified chains in a unified schema.
# Detailed Positions
Source: https://docs.moralis.com/data-api/solana/defi/wallet-positions-detailed
openapi-files/data-api/api-v1.json GET /v1/wallets/{walletAddress}/defi/{protocol}/positions
Returns DeFi positions for a wallet address filtered by a specific protocol across specified chains.
# Wallet Protocols
Source: https://docs.moralis.com/data-api/solana/defi/wallet-protocols
openapi-files/data-api/api-v1.json GET /v1/wallets/{walletAddress}/defi/summary
Returns a summary of all DeFi positions for a wallet address across specified chains.
# NFT Metadata
Source: https://docs.moralis.com/data-api/solana/nft/nft-metadata
openapi-files/data-api/solana-api.json GET /nft/{network}/{address}/metadata
Gets the contract level metadata (mint, standard, name, symbol, metaplex) for the given contract
# Solana NFT API Overview
Source: https://docs.moralis.com/data-api/solana/nft/overview
Query Solana NFT metadata including token details, attributes, and media URLs.
## Overview
The **Solana NFT API** provides NFT metadata for tokens on the Solana blockchain, including attributes, media URLs, and collection information.
Built for Solana's unique NFT standards, the API delivers the data you need to display and work with Solana NFTs.
***
## What Is the Solana NFT API?
The Solana NFT API lets you query:
* **NFT Metadata** - Token metadata including name, symbol, and description
* **Attributes** - NFT traits and properties
* **Media** - Image and media URLs
* **Collection Info** - Collection-level metadata
***
## Key Features
* **Complete Metadata** - Full NFT metadata with all attributes
* **Media Resolution** - Resolved media URLs for display
* **Solana Standards** - Support for Metaplex and other Solana NFT standards
* **Fast Queries** - Optimized for quick metadata retrieval
***
## Common Use Cases
* **NFT Galleries**\
(display Solana NFT collections)
* **Wallet Apps**\
(show NFT holdings with metadata)
* **Marketplaces**\
(NFT listings with full details)
* **Portfolio Trackers**\
(include NFTs in portfolio views)
***
## Get Started
Explore the Solana NFT API endpoints:
* [**NFT Metadata**](/data-api/solana/nft/nft-metadata) - Get metadata for a Solana NFT
# Solana Data API
Source: https://docs.moralis.com/data-api/solana/overview
A dedicated API for accessing Solana blockchain data with Solana-native semantics and structures.
### Overview
The **Solana Data API** provides **deep, Solana-native access** to Solana blockchain data, standardizing complex on-chain structures into clean, developer-friendly formats.
It is designed specifically around **Solana’s account model, programs, and transaction semantics**, rather than forcing Solana data into an EVM-style abstraction.
***
### What the Solana Data API Is For
The Solana Data API is built for:
* Applications focused exclusively on **Solana**
* Use cases that require **Solana-specific data models**
* Developers who need precise control over Solana program and account data
***
### Relationship to the Universal API
* The Universal API includes **shared EVM + Solana functionality**
* The Solana Data API provides **deeper Solana-specific coverage**
* Some Solana-specific endpoints are not available in the Universal API
As with EVM, not all Solana features are suitable for a fully universal abstraction.
***
### When to Use the Solana Data API
Use the Solana Data API if you:
* Are building a Solana-only application
* Need Solana-specific transaction or account details
* Want the most accurate representation of Solana on-chain behavior
# OHLC by Pair Address
Source: https://docs.moralis.com/data-api/solana/price/ohlc
openapi-files/data-api/solana-api.json GET /token/{network}/pairs/{address}/ohlcv
Gets the candlesticks for a specific pair address
> [!WARNING]
>
> This endpoint requires a **pair address**, not a token address. To find the pair addresses for a token, use the [Token Pairs endpoint](/data-api/solana/token/pairs/token-pairs).
# Solana Price API Overview
Source: https://docs.moralis.com/data-api/solana/price/overview
Real-time and historical price data for Solana SPL tokens including current prices, batch queries, and OHLC candlestick data.
## Overview
The **Solana Price API** provides real-time and historical pricing data for SPL tokens on Solana, including current prices, batch queries, and OHLC candlestick data for charting.
Get accurate token prices without managing your own price feeds or aggregation infrastructure.
***
## What Is the Solana Price API?
The Solana Price API lets you query:
* **Token Prices** - Current USD prices for any SPL token
* **Batch Prices** - Fetch prices for multiple tokens in one request
* **OHLC Data** - Candlestick data for charting and technical analysis
***
## Key Features
* **Real-Time Prices** - Current token prices with USD values
* **Batch Support** - Query multiple tokens efficiently
* **OHLC Candles** - Open, high, low, close data for charts
* **Historical Data** - Price history for trend analysis
* **Fast Response** - Optimized for low-latency queries
***
## Common Use Cases
* **Price Feeds**\
(display current token prices)
* **Trading Charts**\
(OHLC data for candlestick visualizations)
* **Portfolio Valuation**\
(calculate holdings value in USD)
* **Price Alerts**\
(trigger notifications on price changes)
* **Market Dashboards**\
(aggregate pricing across tokens)
***
## Get Started
Explore the Solana Price API endpoints:
* [**Token Price**](/data-api/solana/price/token-price) - Get current price for a token
* [**Token Prices (Batch)**](/data-api/solana/price/token-prices-batch) - Get prices for multiple tokens
* [**OHLC**](/data-api/solana/price/ohlc) - Get candlestick data for charting
# Token Price
Source: https://docs.moralis.com/data-api/solana/price/token-price
openapi-files/data-api/solana-api.json GET /token/{network}/{address}/price
Gets the token price (usd and native) for a given contract address and network.
# Token Analytics
Source: https://docs.moralis.com/data-api/solana/token/market-metrics/token-analytics
openapi-files/data-api/api.json GET /tokens/{tokenAddress}/analytics
Retrieve detailed trading analytics for a specific token, including buy volume, sell volume, buyers, sellers, transactions, liquidity and FDV trends over time.
# Token Analytics (Batch)
Source: https://docs.moralis.com/data-api/solana/token/market-metrics/token-analytics-batch
openapi-files/data-api/api.json POST /tokens/analytics
Fetch analytics for multiple tokens, including buy volume, sell volume, buyers, sellers, transactions, liquidity and FDV trends over time. Accepts an array of up to 200 tokens, each requiring chain and tokenAddress.
# Token Analytics - Timeseries
Source: https://docs.moralis.com/data-api/solana/token/market-metrics/token-analytics-timeseries
openapi-files/data-api/api.json POST /tokens/analytics/timeseries
Fetch timeseries swap buy volume, sell volume, liquidity and FDV for multiple tokens. Accepts an array of up to 200 tokens, each requiring chain and tokenAddress.
# Solana Token API Overview
Source: https://docs.moralis.com/data-api/solana/token/overview
Comprehensive Solana token data including metadata, prices, swaps, pairs, and advanced analytics for SPL tokens.
## Overview
The **Solana Token API** provides complete SPL token data including metadata, real-time prices, swap history, trading pairs, and advanced market metrics.
From basic token lookups to complex analytics, the Token API delivers everything you need to build trading platforms and token analysis tools on Solana.
***
## What Is the Solana Token API?
The Solana Token API lets you query:
* **Metadata** - Token details including name, symbol, and logo
* **Prices** - Real-time and historical token prices with OHLC data
* **Swaps** - DEX trading activity and swap history
* **Pairs** - Trading pairs with liquidity and stats
* **Discovery** - Search tokens by name, symbol, or address
***
## Key Features
* **Real-Time Prices** - Current token prices with USD values
* **OHLC Data** - Candlestick data for charting
* **Swap Tracking** - DEX trades on Raydium, Orca, and more
* **Pair Stats** - Liquidity, volume, and trading metrics
* **Token Search** - Find tokens by name or address
* **Pump.fun Integration** - Track new and graduated tokens
* **Top Movers** - Discover top gainers and losers
* **Token Score** - Quality and safety metrics
***
## Common Use Cases
* **Trading Platforms**\
(prices, charts, swap execution)
* **Token Analytics**\
(volume, pair, and market metrics)
* **DEX Interfaces**\
(pair discovery, liquidity data)
* **Token Screeners**\
(filter and discover tokens)
* **New Token Tracking**\
(monitor Pump.fun launches)
* **Research Tools**\
(token metrics and analysis)
***
## Get Started
Explore the Solana Token API endpoints:
* [**Token Metadata**](/data-api/solana/token/token-metadata) - Get token details
* [**Token Price**](/data-api/solana/token/prices/token-price) - Get current price
* [**OHLC**](/data-api/solana/token/prices/ohlc) - Get candlestick data
* [**Token Swaps**](/data-api/solana/token/swaps/token-swaps) - Get swap history
* [**Token Pairs**](/data-api/solana/token/pairs/token-pairs) - Get trading pairs
* [**Token Search**](/data-api/solana/token/search-and-discovery/token-search) - Search tokens
# Pair Stats
Source: https://docs.moralis.com/data-api/solana/token/pairs/pair-stats
openapi-files/data-api/solana-api.json GET /token/{network}/pairs/{pairAddress}/stats
Gets the stats for a specific pair address
# Pair Swaps
Source: https://docs.moralis.com/data-api/solana/token/pairs/pair-swaps
openapi-files/data-api/solana-api.json GET /token/{network}/pairs/{pairAddress}/swaps
Get all swap related transactions (buy, sell, add liquidity & remove liquidity) for a specific pair address.
# Token Pairs
Source: https://docs.moralis.com/data-api/solana/token/pairs/token-pairs
openapi-files/data-api/solana-api.json GET /token/{network}/{address}/pairs
Get the supported pairs for a specific token address.
# OHLC by Pair Address
Source: https://docs.moralis.com/data-api/solana/token/prices/ohlc
openapi-files/data-api/solana-api.json GET /token/{network}/pairs/{address}/ohlcv
Gets the candlesticks for a specific pair address
> [!WARNING]
>
> This endpoint requires a **pair address**, not a token address. To find the pair addresses for a token, use the [Token Pairs endpoint](/data-api/solana/token/pairs/token-pairs).
# Token Price
Source: https://docs.moralis.com/data-api/solana/token/prices/token-price
openapi-files/data-api/solana-api.json GET /token/{network}/{address}/price
Gets the token price (usd and native) for a given contract address and network.
# Token Price (Batch)
Source: https://docs.moralis.com/data-api/solana/token/prices/token-prices-batch
openapi-files/data-api/solana-api.json POST /token/{network}/prices
Gets the token price (usd and native) for a given contract address and network.
# Token Search
Source: https://docs.moralis.com/data-api/solana/token/search-and-discovery/token-search
openapi-files/data-api/api.json GET /tokens/search
Search for tokens using their contract address, pair address, name, or symbol. Cross-chain by default with support to filter by chains. Additional options to sortBy various metrics, such as market cap, liquidity or volume.
# Token Swaps
Source: https://docs.moralis.com/data-api/solana/token/swaps/token-swaps
openapi-files/data-api/solana-api.json GET /token/{network}/{address}/swaps
Get all swap related transactions (buy, sell) for a specific token address.
# Wallet Swaps
Source: https://docs.moralis.com/data-api/solana/token/swaps/wallet-swaps
openapi-files/data-api/solana-api.json GET /account/{network}/{address}/swaps
Get all swap related transactions (buy, sell) for a specific wallet address.
# Token Metadata
Source: https://docs.moralis.com/data-api/solana/token/token-metadata
openapi-files/data-api/solana-api.json GET /token/{network}/{address}/metadata
Get the global token metadata for a given network and contract (mint, standard, name, symbol, metaplex).
# Token Metadata (Batch)
Source: https://docs.moralis.com/data-api/solana/token/token-metadata-batch
openapi-files/data-api/solana-api.json POST /token/{network}/metadata
Get multiple global token metadata for a given network and contract (mint, standard, name, symbol, metaplex). Supports up to 100 tokens per request.
# Token Score
Source: https://docs.moralis.com/data-api/solana/token/token-score
openapi-files/data-api/api.json GET /tokens/{tokenAddress}/score
Retrieve a score for a specific token along with detailed metrics including price, volume, liquidity, transaction counts, and supply information.
> [!WARNING]
>
> **Deprecated — scheduled for removal on July 31, 2026.** See the [changelog](/changelog) for details and migration guidance.
# Native Balance
Source: https://docs.moralis.com/data-api/solana/wallet/native-balance
openapi-files/data-api/solana-api.json GET /account/{network}/{address}/balance
Gets native balance owned by the given address
# NFT Balances
Source: https://docs.moralis.com/data-api/solana/wallet/nft-balances
openapi-files/data-api/solana-api.json GET /account/{network}/{address}/nft
Gets NFTs owned by the given address
# Solana Wallet API Overview
Source: https://docs.moralis.com/data-api/solana/wallet/overview
Query Solana wallet data including native SOL balance, SPL token holdings, NFT balances, portfolio overview, and swap history.
## Overview
The **Solana Wallet API** provides complete wallet data for Solana addresses including native SOL balance, SPL token holdings, NFT balances, and trading activity.
Built specifically for Solana's account model, the Wallet API delivers the data you need to build wallets, portfolio trackers, and Solana-native applications.
***
## What Is the Solana Wallet API?
The Solana Wallet API lets you query:
* **Native Balance** - SOL balance for any wallet address
* **Token Balances** - SPL token holdings with metadata and prices
* **NFT Balances** - NFT holdings on Solana
* **Portfolio** - Complete portfolio overview with valuations
* **Swaps** - DEX trading history on Solana
***
## Key Features
* **Native SOL Balance** - Current SOL holdings with USD value
* **SPL Token Support** - All SPL tokens with metadata
* **NFT Holdings** - Solana NFT balances and metadata
* **Portfolio Valuation** - Total portfolio value in USD
* **Swap History** - Trading activity on Solana DEXs
* **Real-Time Data** - Up-to-date wallet state
***
## Common Use Cases
* **Solana Wallets**\
(display SOL and token balances)
* **Portfolio Trackers**\
(aggregate holdings with valuations)
* **Trading Apps**\
(show swap history and activity)
* **NFT Galleries**\
(display Solana NFT collections)
* **DeFi Dashboards**\
(track wallet activity on Solana)
***
## Get Started
Explore the Solana Wallet API endpoints:
* [**Native Balance**](/data-api/solana/wallet/native-balance) - Get SOL balance
* [**Token Balances**](/data-api/solana/wallet/token-balances) - Get SPL token holdings
* [**NFT Balances**](/data-api/solana/wallet/nft-balances) - Get NFT holdings
* [**Portfolio**](/data-api/solana/wallet/portfolio) - Get complete portfolio
* [**Wallet Swaps**](/data-api/solana/wallet/wallet-swaps) - Get swap history
# Wallet Portfolio
Source: https://docs.moralis.com/data-api/solana/wallet/portfolio
openapi-files/data-api/solana-api.json GET /account/{network}/{address}/portfolio
Gets all the native and token balances of the given address
> [!TIP]
>
> Set `excludeSpam=true` to keep spam tokens out of the response. See [Accurate Net Worth & Token Balances](/data-api/data-features/safety-and-trust/accurate-net-worth-and-balances) for more checks.
# Token Balances
Source: https://docs.moralis.com/data-api/solana/wallet/token-balances
openapi-files/data-api/solana-api.json GET /account/{network}/{address}/tokens
Gets token balances owned by the given address
> [!TIP]
>
> Set `excludeSpam=true` to keep spam tokens out of the response. See [Accurate Net Worth & Token Balances](/data-api/data-features/safety-and-trust/accurate-net-worth-and-balances) for more checks.
# Wallet Swaps
Source: https://docs.moralis.com/data-api/solana/wallet/wallet-swaps
openapi-files/data-api/solana-api.json GET /account/{network}/{address}/swaps
Get all swap related transactions (buy, sell) for a specific wallet address.
# Data API Supported Chains
Source: https://docs.moralis.com/data-api/supported-chains
Blockchains supported by the Moralis Data APIs for tokens, wallets, NFTs, DeFi, and pricing.
### Data API Supported ChainsThe Moralis Data APIs support multiple blockchain networks for **onchain data access**, including wallets, tokens, NFTs, DeFi, and prices.Chain support may vary by feature. Some chains support the full Data API surface, while others support a subset depending on:- Indexing depth
- Protocol availability
- Onchain data structureUse the selector below to filter the table by feature, or view all features at once.⚠️**Moonbeam and Moonriver are deprecated.** Both chains stopped
producing new blocks on August 1, 2026, and Moralis support is removed on
**September 25, 2026**, following Moonbeam's network
relaunch on Base. GLMR and MOVR are now ERC-20 tokens on Base, so migrate to
the `base` chain parameter and export any history you still need
before that date. See the
[deprecation notice](/changelog#moonbeam-moonriver-and-lisk-support-ends-september-25-2026) for contract addresses and
details.⚠️**Lisk is deprecated.** Moralis support for Lisk (
`0x46f`) is removed on **September 25, 2026**,
ahead of the Lisk Chain wind-down. Migrate to the `eth` or
`base` chain parameter and export any history you still need
before that date. See the
[deprecation notice](/changelog#moonbeam-moonriver-and-lisk-support-ends-september-25-2026)
for the full timeline.
Showing chain
.
\
Chain
\
Type
\
Chain ID
\
Query Params
\
> [!NOTE]
>
> **Robinhood Chain** is currently supported through the [Universal API](/data-api/universal/overview) only; its checks reflect Universal API support. Internal transactions are not supported.
# DeFi API
Source: https://docs.moralis.com/data-api/universal/defi/overview
Track DeFi positions, balances, rewards, and protocol interactions with enriched, protocol-aware data across EVM chains and Solana — through one unified set of endpoints.
## Overview
The **DeFi API** provides a unified view of a wallet's DeFi positions across protocols - lending, borrowing, staking, liquid staking, and liquidity pools - on both **EVM chains and Solana**.
It is one cross-chain endpoint set: the **same three endpoints** return EVM and Solana positions, with an identical response shape. Pass the `chain` parameter (for example `eth`, `base`, `polygon`, or `solana`) to choose the network - no separate integration per chain.
***
## What Is the DeFi API?
The DeFi API lets you query:
* **Protocol Summary** - overview of all DeFi protocols a wallet uses
* **Positions** - detailed position data per protocol
* **Position Details** - enhanced breakdown with underlying assets
* **Multi-Chain in One Integration** - query EVM and Solana wallets through the same endpoints and schema
***
## Key Features
* **Protocol Detection** - automatically identifies which protocols a wallet uses
* **Position Breakdown** - detailed view of deposits, borrows, staking, and rewards
* **USD Valuations** - position values calculated in USD
* **Unified Schema** - identical response shape across EVM and Solana
* **Single Integration** - the same filters and parameters across every supported chain
***
## Supported Protocols
Coverage spans **thousands of EVM protocols** and the **top Solana protocols**:
* **EVM** - 3,000+ protocols including Aave, Compound, Uniswap, Lido, Rocket Pool, Eigenlayer, and all forked Uniswap v2 protocols.
* **Solana** - 10 of the most-used protocols, together covering roughly 90% of Solana DeFi TVL: Jito, Save (formerly Solend), Jupiter Lend, Jupiter Perpetual Exchange, Kamino Lend, Sanctum, Raydium, Orca, Drift, and Marinade.
For the full, always-current list per chain, see [DeFi Protocols](/data-api/data-features/integrations/defi-protocols) or call the Get Supported DeFi Protocols endpoint with the `chain` parameter.
***
## Common Use Cases
* **Portfolio Trackers** - show DeFi positions alongside tokens and NFTs
* **Cross-Ecosystem Wallets** - display EVM and Solana DeFi positions side by side
* **DeFi Dashboards** - aggregate positions across protocols and chains
* **Risk Monitoring** - track lending health factors and exposure
* **Yield Tracking** - monitor staking rewards and LP positions
* **Tax Reporting** - calculate DeFi gains and income
***
## Popular Endpoints
| Endpoint | Description |
| - | - |
| [Wallet Protocols](/data-api/universal/defi/wallet-protocols) | Summary of protocols a wallet uses |
| [Wallet Positions](/data-api/universal/defi/wallet-positions) | Detailed positions per protocol |
| [Detailed Positions](/data-api/universal/defi/wallet-positions-detailed) | Enhanced position breakdown |
Each endpoint accepts the `chain` parameter to target an EVM chain or Solana.
***
## Get Started
* [Get Wallet Protocols](/data-api/universal/defi/wallet-protocols)
* [Get Wallet Positions](/data-api/universal/defi/wallet-positions)
* [Get Detailed Positions](/data-api/universal/defi/wallet-positions-detailed)
***
## DeFi API Overview Video
[Moralis DeFi API Overview](https://www.youtube.com/embed/dLcoB3vFf38)
# Supported Protocols
Source: https://docs.moralis.com/data-api/universal/defi/supported-protocols
openapi-files/data-api/api-v1.json GET /v1/defi/protocols
Returns the full list of DeFi protocols supported by Moralis, with their chain coverage. Use the optional `chains` filter to narrow results to specific chains.
Returns the full list of DeFi protocols supported by Moralis, with their chain coverage. Use the optional `chains` filter to narrow results to specific chains — ideal for keeping your own UI or coverage checks in sync.
# Wallet Positions
Source: https://docs.moralis.com/data-api/universal/defi/wallet-positions
openapi-files/data-api/api-v1.json GET /v1/wallets/{walletAddress}/defi/positions
Returns all DeFi positions (lending, liquidity, staking) for a wallet address across specified chains in a unified schema.
# Detailed Positions
Source: https://docs.moralis.com/data-api/universal/defi/wallet-positions-detailed
openapi-files/data-api/api-v1.json GET /v1/wallets/{walletAddress}/defi/{protocol}/positions
Returns DeFi positions for a wallet address filtered by a specific protocol across specified chains.
# Wallet Protocols
Source: https://docs.moralis.com/data-api/universal/defi/wallet-protocols
openapi-files/data-api/api-v1.json GET /v1/wallets/{walletAddress}/defi/summary
Returns a summary of all DeFi positions for a wallet address across specified chains.
# Get Entities by Category
Source: https://docs.moralis.com/data-api/universal/entity/endpoints/entity-by-category
openapi-files/data-api/api.json GET /entities/categories/{categoryId}
Fetch entities belonging to a specific category. Each entity returns name, logo, description, external links, total addresses and more.
# Get Entity
Source: https://docs.moralis.com/data-api/universal/entity/endpoints/entity-by-id
openapi-files/data-api/api.json GET /entities/{entityId}
Retrieve details for a specific entity using its unique ID. Returns name, logo, description, external links and related addresses.
# Get Entity Categories
Source: https://docs.moralis.com/data-api/universal/entity/endpoints/entity-categories
openapi-files/data-api/api.json GET /entities/categories
List available categories for blockchain entities.
# Entity Search
Source: https://docs.moralis.com/data-api/universal/entity/endpoints/entity-search
openapi-files/data-api/api.json GET /entities/search
Find entities, organizations, addresses or wallets linked to blockchain addresses. Results are categorised into 3 arrays: entities, addresses, categories.
# Entity API Overview
Source: https://docs.moralis.com/data-api/universal/entity/overview
Search and discover blockchain entities including exchanges, institutions, protocols, and notable addresses with verified labels.
## Overview
The **Entity API** lets you search and discover blockchain entities - organizations, protocols, exchanges, and notable addresses with verified labels and metadata.
Instead of working with raw addresses, the Entity API provides context about who owns and operates wallets across the blockchain ecosystem.
***
## What Is the Entity API?
The Entity API lets you:
* **Search Entities** - Find entities by name (e.g., "Coinbase", "BlackRock")
* **Discover Addresses** - Get known addresses associated with an entity
* **Get Labels** - Retrieve verified labels and categories for addresses
* **Explore Protocols** - Find addresses related to dApps and protocols
***
## Key Features
* **Entity Search** - Query by name to find organizations and protocols
* **Address Discovery** - Find all addresses linked to an entity
* **Verified Labels** - Trusted address labels and categorization
* **Cross-Chain** - Entity data spans EVM and Solana chains
* **Rich Metadata** - Entity descriptions, logos, and categories
***
## Supported Entities
The Entity API covers:
* **Exchanges** - Coinbase, Kraken, Binance, and more
* **Institutions** - BlackRock, Grayscale, and asset managers
* **Protocols** - Uniswap, Aave, Compound, and DeFi protocols
* **DAOs** - Major DAOs and governance entities
* **Notable Wallets** - Whales, founders, and known addresses
***
## Common Use Cases
* **Address Labels**\
(display human-readable names for addresses)
* **Whale Tracking**\
(monitor institutional and large holder activity)
* **Compliance**\
(identify exchange and custodian addresses)
* **Analytics**\
(understand flows between known entities)
* **Portfolio Context**\
(show which entities hold similar assets)
***
## Get Started
Explore the Entity API to search and discover blockchain entities.
# Market Metrics Overview
Source: https://docs.moralis.com/data-api/universal/market-metrics/overview
Access market-wide metrics and analytics across chains including volume, market cap, and trending data.
## Overview
The **Market Metrics API** provides market-wide analytics and metrics across blockchain ecosystems, helping you understand broader market trends and activity.
Get aggregated market data without building your own analytics infrastructure.
***
## What Is the Market Metrics API?
The Market Metrics API lets you query:
* **Market Overview** - Aggregate market statistics
* **Volume Data** - Trading volume across markets
* **Trending Metrics** - Popular tokens and collections
* **Cross-Chain Data** - Unified metrics across chains
***
## Key Features
* **Aggregated Data** - Market-wide statistics and summaries
* **Volume Tracking** - Trading volume and activity metrics
* **Trend Analysis** - Identify trending assets and markets
* **Cross-Chain** - Unified view across EVM and Solana
* **Real-Time Updates** - Current market state
***
## Common Use Cases
* **Market Dashboards**\
(display overall market health and activity)
* **Analytics Platforms**\
(aggregate market metrics for analysis)
* **Trading Apps**\
(show market context and trends)
* **Research Tools**\
(track market-wide patterns)
***
## Get Started
Explore the Market Metrics API to access market-wide analytics and trends.
# Universal API
Source: https://docs.moralis.com/data-api/universal/overview
A unified, multichain API for accessing blockchain data across 30+ EVM networks, Solana, and Bitcoin through a single, consistent interface.
### Overview
The **Universal API** is Moralis’ unified, multichain Data API, designed to provide a **single, consistent interface** for accessing blockchain data across **30+ supported chains**, including **EVM networks, Solana, and Bitcoin**.
It standardizes complex on-chain data into **clean, developer-friendly formats**, allowing you to build multichain applications without handling chain-specific differences.
***
### What the Universal API Is For
The Universal API is intended for:
* Applications that support **EVM, Solana, and Bitcoin**
* Teams building **chain-agnostic** products
* Use cases where a **consistent data model** across chains is more important than chain-specific depth
Where possible, new endpoints are introduced in the Universal API first. Robinhood Chain Data API support is currently available only through the Universal API. See [Supported Chains](/data-api/supported-chains) for details.
***
### Selecting a Chain
Universal API endpoints take the chain in one of two ways, depending on the endpoint:
| Parameter | Where | Chains per request | Example |
| - | - | - | - |
| `chainAlias` | Path | One | `GET /v1/chains/ethereum/tokens/{tokenAddress}/price` |
| `chains` | Query | One or more | `GET /v1/wallets/{walletAddress}/tokens?chains=ethereum&chains=base` |
When using `chains`:
* To query several chains, repeat the parameter once per chain. Comma-separated values are not supported.
* Use `chains` (plural). The singular `chain` parameter is rejected with a `400` error.
* If you omit `chains`, the request covers every mainnet the endpoint supports.
* The shortcuts `all`, `mainnets`, and `testnets` are also accepted. They work only with `chains`, not with `chainAlias`.
EVM chains accept either the hex chain ID or an alias. Solana and Bitcoin accept aliases only. Common values:
| Chain | Accepted values |
| - | - |
| Ethereum | `0x1`, `ethereum`, `eth` |
| Base | `0x2105`, `base` |
| BNB Chain | `0x38`, `binance`, `bsc` |
| Polygon | `0x89`, `polygon`, `matic` |
| Robinhood Chain | `0x1237`, `robinhood` |
| Tempo | `0x1079`, `tempo` |
| Solana | `solana-mainnet`, `sol`, `solana` |
| Bitcoin | `bitcoin-mainnet`, `bitcoin` |
> [!NOTE]
>
> Supported chains vary by endpoint. Each endpoint page lists one accepted value per chain; the other values in this table work too. For the full chain list, see [Supported Chains](/data-api/supported-chains).
> [!TIP]
>
> [Streams](/streams/supported-chains) uses hex chain IDs only (for example, `0x1`). Aliases such as `ethereum` or `robinhood` are not accepted there.
***
### Consolidation Strategy
Moralis is **gradually consolidating cross-chain functionality into the Universal API**.
This means:
* New multichain endpoints are added to the Universal API
* Existing EVM- or Solana-specific endpoints may be mirrored or superseded over time
* No breaking changes are introduced without notice
The Universal API represents the **long-term direction** for multichain data access at Moralis.
***
### When to Use the Universal API
Use the Universal API if you:
* Need the **same endpoint to work across EVM, Solana, and Bitcoin**
* Want to minimize chain-specific logic
* Are building dashboards, analytics, or wallets that span multiple ecosystems
***
### When Not to Use It
For advanced, chain-specific features, you may still want:
* **EVM API** for deep EVM-only functionality
* **Solana Data API** for Solana-specific data and semantics
* **Bitcoin API** for Bitcoin-specific endpoints including the [xpub utility](/data-api/bitcoin/utility/addresses-from-xpub)
# PnL API
Source: https://docs.moralis.com/data-api/universal/pnl/overview
Multi-chain profit and loss endpoints in the Universal API - wallet profitability, wallet PnL summaries, and top-trader leaderboards per token.
## Overview
The **Universal PnL API** answers the question every trading, portfolio, and analytics product gets asked: *is this wallet (or this token's traders) making money?* It replaces the legacy Deep Index profitability endpoints with multi-chain versions that query several chains in a single request.
***
## Endpoints
| Endpoint | Purpose |
| - | - |
| [Wallet PnL](/data-api/universal/pnl/wallet-pnl) | Per-token profitability rows for a wallet across multiple chains - realized and unrealized PnL, ROI, volumes, and trade counts |
| [Wallet PnL Summary](/data-api/universal/pnl/wallet-pnl-summary) | Aggregated wallet-level totals across all queried chains - PnL, volumes, trade counts, and win rate |
| [Top Traders by Token](/data-api/universal/pnl/top-traders) | Leaderboard of top traders for a (chain, token) pair, ranked by a selectable PnL metric |
***
## Migrating from the legacy Deep Index endpoints
These endpoints supersede the single-chain Deep Index profitability endpoints. The headline change is **multi-chain in one request**, plus new filters (`excludeLowLiquidity`, `minVolumeUsd`, `minTradeCount`) and flexible time ranges (`period` or explicit timestamps).
| Legacy (Deep Index) | New (Universal) |
| - | - |
| [Wallet PnL Breakdown](/data-api/evm/wallet/wallet-pnl) - `GET /wallets/{address}/profitability` | [Wallet PnL](/data-api/universal/pnl/wallet-pnl) - `GET /v1/wallets/{walletAddress}/pnl` |
| [Wallet PnL Summary](/data-api/evm/wallet/wallet-pnl-summary) - `GET /wallets/{address}/profitability/summary` | [Wallet PnL Summary](/data-api/universal/pnl/wallet-pnl-summary) - `GET /v1/wallets/{walletAddress}/pnl/summary` |
| [Top Traders by Token](/data-api/evm/token/signals/top-traders) - `GET /erc20/{address}/top-gainers` | [Top Traders by Token](/data-api/universal/pnl/top-traders) - `GET /v1/chains/{chainAlias}/tokens/{tokenAddress}/top-traders` |
***
## Common Use Cases
* **Portfolio Trackers** - show realized/unrealized PnL and ROI per holding across every chain in one call
* **Trading Platforms** - surface win rate and PnL summaries on wallet profiles
* **Token Analytics** - rank a token's top traders by realized PnL, volume, or trade count to spot smart money
* **Copy Trading & Signals** - find consistently profitable wallets for a token and follow their activity
* **AI Agents** - hand the model a wallet's full multi-chain profitability picture in a single response
***
## Get Started
* [Wallet PnL](/data-api/universal/pnl/wallet-pnl)
* [Wallet PnL Summary](/data-api/universal/pnl/wallet-pnl-summary)
* [Top Traders by Token](/data-api/universal/pnl/top-traders)
# Top Traders by Token
Source: https://docs.moralis.com/data-api/universal/pnl/top-traders
openapi-files/data-api/api-v1.json GET /v1/chains/{chainAlias}/tokens/{tokenAddress}/top-traders
Leaderboard of top traders for a (chain, token) pair, ranked by a selectable PnL metric, with per-trader volumes and realized/unrealized profit.
> [!NOTE]
>
> This is the successor to the legacy Deep Index [Top Traders by Token](/data-api/evm/token/signals/top-traders) endpoint, with a selectable ranking metric (`sortBy`) and low-liquidity, volume, and trade-count filters.
# Wallet PnL
Source: https://docs.moralis.com/data-api/universal/pnl/wallet-pnl
openapi-files/data-api/api-v1.json GET /v1/wallets/{walletAddress}/pnl
Per-token profitability rows for a wallet, including realized and unrealized PnL, ROI, volumes, and trade counts.
> [!NOTE]
>
> This is the multi-chain successor to the legacy Deep Index [Wallet PnL Breakdown](/data-api/evm/wallet/wallet-pnl) endpoint. Pass multiple `chains` (or `mainnets`) to get per-token profitability across chains in a single request.
# Wallet PnL Summary
Source: https://docs.moralis.com/data-api/universal/pnl/wallet-pnl-summary
openapi-files/data-api/api-v1.json GET /v1/wallets/{walletAddress}/pnl/summary
Aggregated wallet-level profitability totals across all queried chains: PnL, volumes, trade counts, and win rate.
> [!NOTE]
>
> This is the multi-chain successor to the legacy Deep Index [Wallet PnL Summary](/data-api/evm/wallet/wallet-pnl-summary) endpoint. Pass multiple `chains` (or `mainnets`) to get aggregated wallet-level totals across chains in a single request.
# Token Analytics
Source: https://docs.moralis.com/data-api/universal/token/analytics/token-analytics
openapi-files/data-api/api.json GET /tokens/{tokenAddress}/analytics
Retrieve detailed trading analytics for a specific token, including buy volume, sell volume, buyers, sellers, transactions, liquidity and FDV trends over time.
📦
**Own this data instead.** Move this endpoint onto your own
infrastructure with [Data Feeds](/data-feeds/migration/token-analytics) — the same decoded
onchain dataset, in real time, with no per-call limits.
# Token Analytics (Batch)
Source: https://docs.moralis.com/data-api/universal/token/analytics/token-analytics-multi
openapi-files/data-api/api.json POST /tokens/analytics
Fetch analytics for multiple tokens, including buy volume, sell volume, buyers, sellers, transactions, liquidity and FDV trends over time. Accepts an array of up to 200 tokens, each requiring chain and tokenAddress.
# Token Analytics - Timeseries
Source: https://docs.moralis.com/data-api/universal/token/analytics/token-analytics-timeseries
openapi-files/data-api/api.json POST /tokens/analytics/timeseries
Fetch timeseries swap buy volume, sell volume, liquidity and FDV for multiple tokens. Accepts an array of up to 200 tokens, each requiring chain and tokenAddress.
# Token API Overview
Source: https://docs.moralis.com/data-api/universal/token/overview
Search, score, rank, and analyze tokens across EVM chains and Solana through a single, multichain interface.
## Overview
The **Token API** gives you a unified, multichain interface for discovering and analyzing tokens across EVM networks and Solana. Search by address, name, or symbol, pull token scores and analytics, and surface trending or top-moving tokens — all without writing chain-specific logic.
***
## What Is the Token API?
The Token API lets you:
* **Search Tokens** — find tokens by contract address, pair address, name, or symbol
* **Score Tokens** — retrieve a token score and historical score timeseries
* **Discover Tokens** — list filtered, trending, and top-gaining / top-losing tokens
* **Analyze Tokens** — get buy/sell volume, buyers, sellers, transactions, liquidity, and FDV trends
***
## Key Features
* **Cross-chain by default** — one endpoint shape spans EVM and Solana
* **Discovery and ranking** — trending, top gainers, top losers, and customizable filtering
* **Scoring** — current token score plus historical timeseries to track quality over time
* **Deep analytics** — buy/sell volume, buyer/seller counts, transactions, liquidity, and FDV — single token, multi-token, or timeseries
* **Sort and filter** — rank results by market cap, liquidity, volume, and more
***
## Endpoints
| Group | Endpoint | Purpose |
| - | - | - |
| Search | [Token Search](/data-api/universal/token/search/token-search) | Find tokens by address, name, or symbol |
| Score | [Token Score](/data-api/universal/token/score/token-score) | Current score and quality metrics for a token |
| Score | [Token Score Timeseries](/data-api/universal/token/score/token-score-timeseries) | Historical score for a token |
| Discovery | [Trending Tokens](/data-api/universal/token/trending-tokens) | Tokens trending across the market |
| Analytics | [Token Analytics](/data-api/universal/token/analytics/token-analytics) | Trading analytics for a single token |
| Analytics | [Multi-Token Analytics](/data-api/universal/token/analytics/token-analytics-multi) | Trading analytics for a batch of tokens |
| Analytics | [Token Analytics Timeseries](/data-api/universal/token/analytics/token-analytics-timeseries) | Historical trading analytics for a token |
| Prices | [Token Price Timeseries](/data-api/universal/token/price/token-price-timeseries) | Historical price points for line charts |
| Prices | [Token Price Sparkline](/data-api/universal/token/price/token-price-sparkline) | Compact, chart-ready price array for sparklines |
***
## Common Use Cases
* **Token discovery**\
(surface trending, top-gaining, and newly notable tokens)
* **Wallet and portfolio apps**\
(resolve token metadata and show market context next to holdings)
* **Trading and analytics platforms**\
(rank tokens by quality, momentum, or liquidity and dive into per-token analytics)
* **Research and screening**\
(filter the long tail by score, volume, or liquidity to find candidates)
* **Risk and quality signals**\
(combine score and analytics to flag illiquid or low-quality tokens)
***
## Get Started
Pick an endpoint above to start querying tokens, or head to the [Universal API overview](/data-api/universal/overview) to see how the Token API fits alongside the rest of the multichain Data API.
# Token Price Sparkline
Source: https://docs.moralis.com/data-api/universal/token/price/token-price-sparkline
openapi-files/data-api/api-v1.json GET /v1/chains/{chainAlias}/tokens/{tokenAliasOrTokenAddress}/price/sparkline
Get a small set of historical price points suitable for sparkline charts (tiny charts in token lists, watchlists, portfolio rows). Returns a fixed number of points based on the selected range.
> [!NOTE]
>
> Returns a fixed number of price points for the selected `range` (`24h` to `1y`) - a compact, chart-ready array you can drop directly into a sparkline widget without resampling. For native coins, pass `native` as `tokenAliasOrTokenAddress`.
# Token Price Timeseries
Source: https://docs.moralis.com/data-api/universal/token/price/token-price-timeseries
openapi-files/data-api/api-v1.json GET /v1/chains/{chainAlias}/tokens/{tokenAliasOrTokenAddress}/price/timeseries
Get historical price data points for a specific token address, suitable for rendering line charts. Supports various time intervals from 5 minutes to monthly.
> [!NOTE]
>
> Returns historical price data points for a token, ready for line charts. Choose an `interval` from `5m` up to `monthly`, and set `forwardFill=true` to fill gaps with the last known price. For native coins, pass `native` as `tokenAliasOrTokenAddress`.
# Token Score
Source: https://docs.moralis.com/data-api/universal/token/score/token-score
openapi-files/data-api/api.json GET /tokens/{tokenAddress}/score
Retrieve a score for a specific token along with detailed metrics including price, volume, liquidity, transaction counts, and supply information.
# Token Score - Timeseries
Source: https://docs.moralis.com/data-api/universal/token/score/token-score-timeseries
openapi-files/data-api/api.json GET /tokens/{tokenAddress}/score/historical
Retrieve historical score data for a specific token over time.
# Token Search
Source: https://docs.moralis.com/data-api/universal/token/search/token-search
openapi-files/data-api/api.json GET /tokens/search
Search for tokens using their contract address, pair address, name, or symbol. Cross-chain by default with support to filter by chains. Additional options to sortBy various metrics, such as market cap, liquidity or volume.
# Trending Tokens
Source: https://docs.moralis.com/data-api/universal/token/trending-tokens
openapi-files/data-api/api.json GET /tokens/trending
List top tokens trending based on trading activity, volume, liquidity and more. By default this returns cross-chain results, including Solana. Optionally filter by `chain` for single chain results.
# Cross-Chain Token Balances
Source: https://docs.moralis.com/data-api/universal/wallet/cross-chain-token-balances
openapi-files/data-api/api-v1.json GET /v1/wallets/{walletAddressOrPublicKey}/tokens
Get token balances from multiple chains for a specific wallet address. For Bitcoin wallets, filter parameters (excludeNative, excludeSpam, etc.) are ignored — only the native BTC balance is returned.
> [!TIP]
>
> Seeing spam tokens or inflated USD values? Set `excludeSpam`, `liquidityThreshold` and `maxTokenInactivity`. See [Accurate Net Worth & Token Balances](/data-api/data-features/safety-and-trust/accurate-net-worth-and-balances) for recommended values.
> [!NOTE]
>
> This is the multi-chain successor to the legacy Deep Index [Token Balances](/data-api/evm/wallet/token-balances-legacy) endpoint. The same filters - spam exclusion, unverified contracts, liquidity thresholds, USD pricing - are preserved. The headline change is that **a single request now returns balances across multiple chains.**
>
> Covers EVM chains and Bitcoin (pass `bitcoin` in `chains`, with an address or xpub as the path parameter). Solana balances are available today through the dedicated [Solana Wallet API](/data-api/solana/wallet/overview); bringing them into this endpoint is on the roadmap. Set `includeSparklines` or `includePnl` to enrich each token with a 7-day price sparkline or a PnL summary.
## How to Fetch Cross-Chain Token Balances
[How to Fetch Cross-Chain Token Balances with One API Call | Moralis Data APIs](https://www.youtube.com/embed/zjL5oEp8MFM)
# Wallets API
Source: https://docs.moralis.com/data-api/universal/wallet/overview
Multi-chain wallet endpoints in the Universal API - return balances and holdings across multiple chains in a single request.
## Overview
The **Universal Wallets API** brings multi-chain wallet data into a single, consistent request shape. Instead of querying one chain at a time and stitching responses together client-side, you ask for the chains you care about in one call and receive a unified response.
The first endpoint in this group is **Cross-Chain Token Balances** - a multi-chain version of one of our most-used Deep Index endpoints.
***
## What Is the Universal Wallets API?
The Universal Wallets API lets you query:
* **Cross-Chain Token Balances** - Token balances for a wallet across multiple chains in one call
Wallet profitability also went multi-chain: see [Wallet PnL](/data-api/universal/pnl/wallet-pnl) and [Wallet PnL Summary](/data-api/universal/pnl/wallet-pnl-summary) in the [PnL API](/data-api/universal/pnl/overview). More multi-chain wallet endpoints are on the way as we consolidate cross-chain functionality into the Universal API.
***
## Key Features
* **Multi-chain in one call** - Query a wallet across many chains in a single request
* **Same trusted filters** - Spam exclusion, unverified contracts, liquidity thresholds, USD pricing - all carry over from the legacy Deep Index endpoints
* **Unified response shape** - One schema across chains, no client-side stitching
* **Direct migration path** - Existing implementations port cleanly with minimal changes
***
## Common Use Cases
* **Wallets** - Show full multi-chain holdings on a single screen
* **Exchanges** - Surface a user's deposit balances across networks
* **Portfolio Trackers** - Aggregate token holdings across EVM and Bitcoin in one query, with Solana available today through its [dedicated Wallet API](/data-api/solana/wallet/overview)
* **Tax Tools** - Pull a complete asset list per wallet for cost-basis and reporting flows
* **AI Agents** - Hand the model a single response containing the wallet's full token footprint
***
## Roadmap
Cross-Chain Token Balances currently covers EVM chains and Bitcoin (address or xpub) in the same multi-chain request. Solana already has full standalone coverage through its dedicated API:
* [**Solana Wallet API**](/data-api/solana/wallet/overview) - Solana balances, NFTs, and portfolio, today
Next on this endpoint: bringing Solana into the same multi-chain request shape, so one call returns balances across EVM, Bitcoin, and Solana wallets.
***
## Get Started
* [Cross-Chain Token Balances](/data-api/universal/wallet/cross-chain-token-balances)
# Direct Reads: REST/HTTP and Arrow Flight
Source: https://docs.moralis.com/data-feeds/access-methods/direct-reads
Read Data Feeds directly over REST/HTTP for simple pulls, or over Arrow Flight (gRPC) for high-throughput columnar transfers into analytical tooling.
Not every workload needs a database sink or a streaming consumer. When you want to **pull feed
data on demand**, Data Feeds supports two direct read paths.
## REST / HTTP
Read feed data over plain HTTP. This is the simplest way in: no client libraries beyond an HTTP client, no
infrastructure to run.
**Use it for** spot checks, low-volume integrations, and getting a feel for a feed's shape before committing
to a heavier access method.
## Arrow Flight (gRPC)
[Arrow Flight](https://arrow.apache.org/docs/format/Flight.html) is a gRPC-based protocol for moving
[Apache Arrow](https://arrow.apache.org/) columnar data at high throughput. Instead of serializing rows one
at a time, it transfers column batches that land directly in Arrow-native tooling (dataframes, query
engines, and analytical libraries) without a conversion step.
**Use it for** bulk pulls into Python or other analytical environments, where row-oriented HTTP APIs become
the bottleneck.
## Choosing a direct read path
| You want… | Use |
| - | - |
| A quick look at a feed, or a simple low-volume integration | **REST / HTTP** |
| Bulk, high-throughput pulls into dataframes or analytics | **Arrow Flight** |
| The same data continuously landed or streamed instead | See the [access methods overview](./overview) |
> [!NOTE]
>
> **Availability.** Endpoint details and availability vary per feed. Check the feed configuration in Moralis Admin.
[Try it today](https://admin.moralis.com/data-feeds)
# Access Methods: Databases, Streams, and Direct Reads
Source: https://docs.moralis.com/data-feeds/access-methods/overview
One data lake, many ways out. Compare the three ways to consume Data Feeds (database sinks, streaming clients, and direct reads) and pick the right path for your workload.
Data Feeds is a single service over **one data lake**. Moralis writes each chain's decoded data once, then
exposes that same data through several interfaces, so you consume it with the tools your team already works
with, **without building the blockchain indexing layer behind it**.
There are three ways out. They are access modes of one service, not separate products, so you can mix them and
switch between them without re-tooling.
## Database sinks: Postgres, MySQL, ClickHouse
Point a [template](../templates/overview) at your own **Postgres, MySQL, or ClickHouse** database and the sink
continuously lands **ready-to-query tables**. Moralis does the heavy lifting in the template, decoding,
enrichment, and reorg correction, so you query a production-grade dataset inside your own stack.
**Use this if** you want queryable tables in a database you control, especially for request/response needs
like "a wallet's balances." See [Database sinks](../concepts/destinations) for choosing between the three.
## Streaming: Kafka, RabbitMQ, SQS
Consume feeds through **supported streaming interfaces** using **Kafka-compatible**, **RabbitMQ/AMQP**, or
**SQS-compatible** clients, depending on the feed and current availability. Bring the consumers you already
run instead of building a new ingestion path.
**Use this if** you already operate an event pipeline and want onchain data flowing through it. See
[Streaming](./streaming).
## Direct reads: REST/HTTP and Arrow Flight
Read feed data directly over **REST/HTTP** for simple pulls, or over **Arrow Flight (gRPC)** for
high-throughput columnar transfers straight into analytical tooling.
**Use this if** you want to pull data on demand without running a sink or a streaming consumer. See
[Direct reads](./direct-reads).
## Which path fits your workload?
| You need… | Best path |
| - | - |
| Real-time, high-volume analytics you query yourself | **ClickHouse sink** |
| Tables inside an existing relational app | **Postgres or MySQL sink** |
| Events flowing into an existing pipeline | **Streaming** (Kafka-compatible, RabbitMQ/AMQP, or SQS-compatible) |
| High-throughput columnar pulls into dataframes | **Arrow Flight** |
| Simple, occasional request/response reads | **REST/HTTP** (or a database sink for repeated queries) |
> [!NOTE]
>
> **Availability.** Supported interfaces can vary by feed and chain. Confirm availability for the protocols and platforms you plan to use.
Whichever path you choose, it's the **same data lake** underneath: each record is a block carrying decoded
balances, transfers, swaps, prices, approvals, NFT activity, and raw logs. See
[What Are Data Feeds?](../concepts/what-are-data-feeds) and
[The `block` array](../concepts/the-block-array).
[Try it today](https://admin.moralis.com/data-feeds)
# Streaming Data Feeds: Kafka, RabbitMQ, and SQS
Source: https://docs.moralis.com/data-feeds/access-methods/streaming
Consume Data Feeds through supported streaming interfaces using Kafka-compatible, RabbitMQ/AMQP, or SQS-compatible clients. Bring your existing consumers instead of building new ingestion.
If your infrastructure already moves events through Kafka, RabbitMQ, or SQS, you don't need to build a new
ingestion path for onchain data. Data Feeds supports **familiar streaming interfaces**, so you can consume
feeds with the client libraries your team already runs:
* **Kafka-compatible**: consume feeds using Kafka client libraries.
* **RabbitMQ / AMQP**: consume feeds using standard AMQP clients.
* **SQS-compatible**: poll feeds through an SQS-style HTTP API.
Which interfaces are available can depend on the feed and current availability, so confirm the protocols available for your feed before you build.
## What you receive
Each message carries **block-level decoded data**: the block's token transfers, swaps, price updates,
balances, NFT activity, approvals, and the raw block/transaction/log data, laid out as typed arrays. You
consume decoded records, not raw RPC payloads. See
[The `block` array](../concepts/the-block-array) for the exact layout.
## Reorg handling
Streaming consumers see blocks as they land. Each block records its **position and parent**, so when the
chain reorganizes, your consumer (or a downstream process) can detect the rollback and correct affected
records. This differs from the [database sinks](../concepts/destinations), where templates apply reorg
corrections for you. See [Reorgs](../concepts/reorgs) for how rollbacks are signaled.
## Streaming vs. the sink
| Choose… | When… |
| - | - |
| **Streaming** | You already run an event pipeline, want fan-out to multiple consumers, or apply your own processing before storage |
| **Database sink** | You want ready-to-query tables with decoding, enrichment, and reorg correction handled for you |
You can also combine them: land ready-to-query tables with the sink while streaming the same feed into an
existing pipeline. It's the same data lake underneath, see the
[access methods overview](./overview).
[Try it today](https://admin.moralis.com/data-feeds)
# Data Feeds vs. the REST API
Source: https://docs.moralis.com/data-feeds/concepts/data-feeds-vs-the-rest-api
How results from Moralis Data Feeds compare to a Web3 API endpoint, what comes through exactly, what you calculate, and what you add yourself.
A Moralis Web3 API endpoint hands you a single, **pre-packaged, enriched response**. Data Feeds give you
the **decoded onchain dataset that produces it**, which is exactly what lets you own the data and query it
freely. Migrating means thinking in terms of that dataset rather than one fixed response. This page explains
what to expect in general; each migration guide then says precisely how it applies to that endpoint.
## The one idea
> The REST endpoint is a *finished dish*. A Data Feed is the *ingredients*, the same onchain facts, plus
> live prices, ready for you to plate however you like (or let a template plate them for you).
That's a feature, not a compromise: you get the underlying data, in real time, with no per-call limits and full
control over shape, storage, and queries.
## How values compare
Every migration guide classifies each field into one of these, so there are no surprises:
| Class | What it means | Examples |
| - | - | - |
| **Exact** | Comes straight from the chain, identical to the endpoint | balances, transfers, token name/symbol/decimals, supply |
| **Calculated** | Computed from the feed (often from live DEX trades). Tracks the endpoint closely; compare with a small **tolerance** rather than expecting penny-for-penny equality | USD price, USD value, portfolio %, 24-hour change |
| **Yours to control** | The feed gives you everything; you apply your own rules. A gain in control, not a gap | spam/dust filtering, which rows count as a "holding" |
| **Add yourself** | Off-chain signals that aren't part of onchain data, so they aren't in the feed | token **logo**/thumbnail, **spam**/**verified** labels, **security score** |
## Why these differences exist
* **Prices come from real onchain trades.** Data Feeds derive USD values from DEX activity in the data lake, so
they're live and verifiable, and may differ slightly from the REST API's pricing engine. A token that hasn't
traded recently may not have a price yet.
* **Off-chain signals live off-chain.** Logos, spam/verification labels, and security scores are curation Moralis
layers on top of the chain. They aren't onchain facts, so they aren't in a feed. Bring your own source (e.g. a
public token list), or layer them in alongside your Data Feeds tables.
* **You own the filtering.** The REST endpoint bakes in choices (which tokens to include, spam rules); with a
feed those choices are yours, so you can match your product exactly.
## Adding the off-chain extras
When you need logos, spam/verification, or security scores, you have options:
* **Skip them** if your app doesn't use them.
* **Bring your own source**, a public token list for logos, or your own allow/deny lists.
* **Layer them in** from a dedicated metadata source alongside your Data Feeds tables.
## How this shows up in a migration guide
Each guide includes a **What to expect** section that applies this model to the specific endpoint, listing its
fields as *exact / calculated / add yourself*, plus a field-mapping table. Read it before you start so the
differences are choices you made, not surprises in production.
# Database Sinks: ClickHouse, Postgres, and MySQL
Source: https://docs.moralis.com/data-feeds/concepts/destinations
The sink writes template data into your own database. Each template ships for ClickHouse, Postgres, and MySQL. Here's how to choose, and what changes between them.
# Database sinks
Data Feeds land in **your own database**. You run the sink, point it at a template, and it writes rows into a
schema you own. Every template ships three destination variants, ClickHouse, Postgres, and MySQL, built from
the same source data. The template and the columns are the same across all three. What differs is how each
store handles **live data, chain reorgs, and scale**, and that is what should drive your choice.
The sink is one of three ways to consume Data Feeds, alongside streaming and direct
reads, see the [access methods overview](../access-methods/overview) if you're still choosing a path.
## The short version
> **Going live or going big, use ClickHouse. Backfilling into an existing relational app, Postgres or MySQL
> are first-class.**
## ClickHouse
The recommended destination for **realtime, hybrid, and high-volume** workloads.
* **Corrects reorgs automatically, at the block level.** ClickHouse templates use a collapsing table that
emits a balancing row when a block is rolled back, so the corrected view is always available (see
[Reorgs](./reorgs)). This is why every live mode prefers ClickHouse.
* **Columnar and fast for analytics.** Aggregations over millions of swaps, transfers, or logs stay quick,
which suits the event-list templates and dashboards.
* **One reading rule to remember:** add `FINAL` to a query (or use sign-aware sums) so reorg corrections are
applied. The template's example queries already show this.
## Postgres and MySQL
First-class for **historical backfills** and for slotting Data Feeds into an existing relational app.
* **Familiar and transactional.** If your product already runs on Postgres or MySQL, a template table drops
straight in next to your other tables, with ordinary indexes and SQL.
* **Best for current-state and backfill loads.** Balances, holders, metadata, and one-off history windows
map cleanly.
* **Realtime has a constraint.** The live reorg path needs a single-column unique key on the block position,
but event-list templates expand many rows per block, so they cannot carry that key. For those templates the
Postgres and MySQL variants ship in `historical` mode, and live tailing should run on ClickHouse. (See the
realtime caveat in any event-list template.)
## Quick reference
| You want to… | Recommended destination |
| - | - |
| Run a template in `realtime` or `hybrid` | **ClickHouse** |
| Index high-volume event lists (swaps, transfers, logs) and query analytics | **ClickHouse** |
| Backfill current-state data (balances, holders, metadata) into an app DB | **Postgres** or **MySQL** |
| Keep everything in the relational store your app already uses | **Postgres** or **MySQL** (historical) |
## What stays the same
Whichever you choose, the **template, the column names, and the meaning of each field are identical**. The
schema variant only adapts storage details: ClickHouse uses a collapsing fact table plus skip indexes,
Postgres and MySQL use plain tables with B-tree indexes. You can develop a query against one and port it with
minimal change, the main difference being the `FINAL` / sign-aware reading rule that ClickHouse needs for
reorg correctness.
> [!NOTE]
>
> **Choosing by template type.** Current-state templates (balances, holders, approvals) sit comfortably in any of
> the three. Live, high-volume event-list templates (swaps, transfers, logs, prices) are best on ClickHouse,
> which is also where their `realtime` / `hybrid` modes are supported. See [Modes](./modes) and
> [History & backfill](./history-and-backfill).
[Try it today](https://admin.moralis.com/data-feeds)
# History & Backfill: How Far Back Do You Need to Index?
Source: https://docs.moralis.com/data-feeds/concepts/history-and-backfill
Some Data Feeds answers need full history to be correct (balances, holders); others only need as much history as you want to show (swaps, logs, prices). Here's how to tell, and how to scope your backfill.
When you move an endpoint onto Data Feeds, one early decision shapes your setup cost: **how far back does the
sink need to index?** Get it right and you avoid both wasted backfill and, more importantly, silently wrong
results. The answer depends on whether the endpoint returns **current state** or an **event list**.
## The rule of thumb
> **Current-state answers need full history. Event-list answers need only as much history as you want to show.**
### Current state → needs full history
Balances, holders, approvals, native balances, total supply, token metadata, these describe **what is true
right now**, and "right now" is the cumulative result of **every past event**. You can't know a wallet's current
balance without its most recent transfer, and that transfer could have happened at any point since the token
launched.
Data Feeds make this efficient, each transfer carries the **absolute balance after it** (`*PostBalance`), so a
template just keeps the *latest* observation per holder rather than replaying every delta. But "latest" still
means you must have **seen** each holder's most recent transfer. Start indexing too late and you simply **miss**
every holder whose last activity predates your start, an incomplete, quietly wrong result.
So for correctness, backfill from the beginning of the relevant history:
* **By a single token** (e.g. all holders of token X) → from **that token's first block** (its deployment).
You don't need chain genesis, just everything since the token existed. Much cheaper.
* **By a wallet across all tokens** (e.g. a wallet's full balance set) → effectively **full history**, because
the wallet may still hold something it last touched years ago.
### Event list → your choice
Swaps, transfers, raw logs, price history, NFT trades, a wallet's activity feed, these are **append-only
streams of past events**. Each event is independent, so there's no cumulative state to reconstruct. Backfill is
purely a **product decision**: how much history do you want to display or analyze?
* Only need new activity from now on? Run **realtime** with no backfill.
* Want the last 90 days, or since a token launched, or everything? Backfill to that point.
* Either way the data is correct, you're just choosing the window.
## Quick reference
| If the endpoint returns… | Type | Backfill you need |
| - | - | - |
| Token holders / balances **by token** | current state | from the **token's first block** |
| Wallet token balances / net worth **by wallet** | current state | **full history** |
| Native balance, approvals, total supply | current state | full history (or token's first block, if token-scoped) |
| Token metadata (name/symbol/decimals) | current state | back to the **token's deployment** (or read from chain) |
| Swaps / transfers / logs / prices / trades / wallet activity | event list | **your choice** (realtime, or any window) |
## How to set it
Templates run in three modes, **historical** (backfill a window), **realtime** (live tail), or **hybrid**
(backfill then hand off to live). For current-state answers, use historical or hybrid with the start block set
to the beginning of the relevant history (`MORALIS_HISTORICAL_FROM_BLOCK`); for event lists, pick whatever
window your product needs, or realtime-only.
> [!NOTE]
>
> **Scope your backfill to save time.** Indexing a single token's holders from its deployment block is far
> cheaper than indexing the whole chain from genesis. Only the broad, by-wallet/chain-wide current-state cases
> truly need full history.
Each migration guide states the specific answer for its endpoint up front, so you can size the backfill before
you start.
# Modes: Historical, Realtime, and Hybrid
Source: https://docs.moralis.com/data-feeds/concepts/modes
A template runs in one of three modes. The mode decides whether the sink backfills past history, tails live blocks, or does both. Here's how to pick.
# Modes
Every template runs in one of three modes. The mode is a single setting, but it decides the shape of your
whole setup: whether the sink fills in **past history**, follows **new blocks** as they arrive, or does
**both**. Pick the mode from what your product needs to show, then size the backfill window to match.
## The three modes
> **Most production setups want hybrid: backfill the history you need, then stay live automatically.**
### historical
Backfill a fixed window of past blocks, then stop. The sink indexes everything from your start block
(`MORALIS_HISTORICAL_FROM_BLOCK`) up to the chain tip at the time it runs, and finishes. Use it for
one-off loads, analytics snapshots, or to seed a table you will keep current another way.
### realtime
Tail live blocks from now on, with no backfill. The sink starts at the current tip and writes each new
block as it arrives. Use it when you only care about activity going forward, for example a live trade tape
or a transfer alert, and you do not need any history.
### hybrid
Backfill first, then hand off to live with no gap. The sink indexes your history window, then continues
straight into realtime tailing. This is the default for most templates because it gives you a complete table
that also stays current. Use it whenever you want both history and live data, which is most of the time.
## Quick reference
| Mode | What the sink does | Use when |
| - | - | - |
| `historical` | Backfill a window, then stop | One-off load, analytics snapshot, seed-then-maintain-elsewhere |
| `realtime` | Tail new blocks from now, no backfill | You only need activity going forward |
| `hybrid` | Backfill, then continue live with no gap | You want history **and** live data (most cases) |
## How the mode relates to backfill
The mode is only half the decision. The other half is **how far back** to set your start block, and that
depends on whether your answer is current state or an event list, covered in
[History & backfill](./history-and-backfill). In short:
* **Current-state answers** (balances, holders, approvals) must backfill from the beginning of the relevant
history to be correct, so they run `historical` or `hybrid` with the start block set accordingly.
* **Event-list answers** (swaps, transfers, logs, prices) are correct at any window, so the start block is
purely a product choice, and `realtime` with no backfill is a valid option.
## How to set it
The mode is set in the template's sink config, alongside the start block:
```yaml theme={null}
mode: hybrid
source:
filters:
- "blockNumber >= ${MORALIS_HISTORICAL_FROM_BLOCK}" # e.g. tip-50000, or a token's deploy block
cutoff:
auto: true # let the sink choose the historical/realtime handoff point
```
> [!NOTE]
>
> **Realtime and hybrid run best on ClickHouse.** ClickHouse corrects chain reorgs at the block level
> automatically (see [Reorgs](./reorgs)), so it is the recommended destination for any live mode. The Postgres
> and MySQL template variants ship in `historical` mode for backfill loads. See [Destinations](./destinations)
> for the full trade-off.
# Reorgs: How Chain Reorganizations Surface, and How Templates Correct Them
Source: https://docs.moralis.com/data-feeds/concepts/reorgs
Near the chain tip, a block can be replaced by another. Data Feeds detect this and emit a correction, so your table converges on the canonical chain. Here's what that means for your queries.
# Reorgs
Blockchains do not always agree on the most recent blocks. For a short window near the tip, the network can
**reorganize**: a block that looked final gets replaced by a competing block at the same height, and anything
only in the replaced block is no longer part of the canonical chain. Data Feeds handle this for you, but it
shapes one thing you must get right: **how you read the most recent rows.**
## How a reorg surfaces
Each block carries its **position** (the block number) and its **block hash**, and the feed tracks the link
back to the parent block. When the sink sees that a block at a given position has been replaced by a
different hash, it knows the earlier block's rows are no longer canonical.
Rather than silently deleting them, the sink writes a **correction**. The original rows were written with a
`+1` marker; the reorg emits matching `-1` rows for the same data. The pair cancels out, and the rows from
the new, canonical block are written in their place. Your table converges on the true chain without you
re-running anything.
## What this means for your queries
The correction rows are how reorgs stay safe, but they mean a naive `SELECT *` over a ClickHouse fact table
can briefly show both the original and its `-1` cancel. You apply the corrections at read time:
> **On ClickHouse fact tables, read with `FINAL` (or use sign-aware sums). That applies reorg corrections and
> gives you the canonical result.**
```sql theme={null}
-- Correct: FINAL applies the collapse
SELECT block_number, from_address, to_address, amount
FROM recipe_token_transfers.fact_token_transfers FINAL
WHERE chain_id = 1 AND token_address = lower('0x...')
ORDER BY block_number DESC LIMIT 50;
-- For aggregates, sign-aware sums are cheaper than FINAL and equally correct:
SELECT sum(toFloat64OrZero(amount) * sign) AS net
FROM recipe_token_transfers.fact_token_transfers
WHERE chain_id = 1 AND token_address = lower('0x...');
```
The template's own example queries already follow this rule, so if you start from those you get it automatically.
Postgres and MySQL template variants are intended for `historical` backfill of settled blocks, where reorgs do
not apply, which is why the live reorg path is a ClickHouse strength (see [Destinations](./destinations)).
## Only the tip is provisional
Reorgs only affect the **most recent** blocks. Once a block is buried under enough confirmations it is
settled and will not change. So:
* **Historical and settled data is stable.** A backfill of last month's swaps will not be revised.
* **Near-tip data is provisional for a short window.** A row for a block from a few seconds ago may be
corrected if that block reorganizes. This is normal and expected, not data loss.
> [!WARNING]
>
> **Do not treat a brand-new tip block as final.** If your product acts on the very latest blocks (live
> balances, instant alerts), expect occasional corrections in that tip window and read with `FINAL` so a
> reorged row is collapsed away rather than double-counted. For settled history, no special handling is needed.
## Related
* [The `block` array](./the-block-array) for where `position` and the block hash live on each row.
* [Destinations](./destinations) for why ClickHouse is the home for live, reorg-correcting workloads.
* [Modes](./modes) for choosing realtime or hybrid, the modes where reorg handling matters.
# The `block` Array: How Transactions and Logs Are Laid Out
Source: https://docs.moralis.com/data-feeds/concepts/the-block-array
How raw transactions, logs, withdrawals, and block headers are packed into a single flattened array per block, and how to read them.
# The `block` array
A Data Feed delivers **one row per block**. Most onchain activity is exposed as typed arrays on that row
(`tokenSwaps`, `tokenTransfers`, …), but the **raw** block header, transactions, logs, withdrawals, and access
lists all arrive together in a single flattened array called `block`.
If you're coming from the REST API, where `GET /{address}/logs` hands you ready-made log objects, this is the
biggest shape change to understand.
## One array, many row types
Every element of `block` has the **same wide shape**: all the `block*`, `transaction*`, `log*`, and
`withdrawal*` columns exist on every element. A discriminator column, **`itemType`**, tells you what each
element actually is; only the columns matching that `itemType` are populated, the rest are `null`.
`itemType` is one of: `block`, `transaction`, `log`, `withdrawal`, `accessList`.
So for a block with **110 transactions, each emitting 4 logs**, the `block` array contains roughly:
| `itemType` | Count | Populated columns |
| - | - | - |
| `block` | 1 | `block*` (number, hash, timestamp, miner, gas…) |
| `transaction` | 110 | `transaction*` (hash, from, to, value, receipt…) |
| `log` | 440 | `log*` (index, address, topic0-3, data) |
≈ **551 elements** in that one block row (plus any `withdrawal` / `accessList` rows).
## ⚠️ Log rows don't carry the transaction hash
This is the detail that trips people up. A `log` element has its `transactionIndex` and `logIndex`, the
emitting `logAddress`, the four topics, and the raw `logData`, but **no `transactionHash`**.
To attach the hash, join each log to its sibling `transaction` element on `transactionIndex`:
* `itemType = 'transaction' AND transactionIndex = N` → the tx hash + metadata
* `itemType = 'log' AND transactionIndex = N` → that transaction's logs
Block-level context (`blockNumber`, `timestamp`, `blockHash`) comes from the **top-level row** (`position`,
`timestamp`, `hash`), not from the log element.
## Worked example, two transactions, four logs each
Top-level row for the block: `position = 21000000`, `hash = "0xblk…"`, `timestamp = 1718800000`.
Below is an excerpt of its `block` array showing transactions `#5` and `#6` with their logs. Only populated
columns are shown; everything else on each element is `null`.
```jsonc theme={null}
[
// transaction #5, the hash lives here
{ "itemType": "transaction", "transactionIndex": 5, "sequenceIndex": 21,
"transactionHash": "0xTX5", "transactionFrom": "0xalice", "transactionTo": "0xrouter",
"transactionValue": "0", "transactionReceiptStatus": "1" /* …more tx* fields… */ },
// transaction #5's 4 logs, note: NO transactionHash, only transactionIndex = 5
{ "itemType": "log", "transactionIndex": 5, "logIndex": 30, "sequenceIndex": 22,
"logAddress": "0xUSDC", "logTopic0": "0xddf252ad… (Transfer)",
"logTopic1": "0x…alice", "logTopic2": "0x…router", "logTopic3": null, "logData": "0x…amount" },
{ "itemType": "log", "transactionIndex": 5, "logIndex": 31, "sequenceIndex": 23,
"logAddress": "0xPair", "logTopic0": "0x1c411e9a… (Sync)",
"logTopic1": null, "logTopic2": null, "logTopic3": null, "logData": "0x…reserves" },
{ "itemType": "log", "transactionIndex": 5, "logIndex": 32, "sequenceIndex": 24,
"logAddress": "0xPair", "logTopic0": "0xd78ad95f… (Swap)",
"logTopic1": "0x…router", "logTopic2": "0x…alice", "logTopic3": null, "logData": "0x…amounts" },
{ "itemType": "log", "transactionIndex": 5, "logIndex": 33, "sequenceIndex": 25,
"logAddress": "0xWETH", "logTopic0": "0xe1fffcc4… (Withdrawal)",
"logTopic1": "0x…router", "logTopic2": null, "logTopic3": null, "logData": "0x…amount" },
// transaction #6
{ "itemType": "transaction", "transactionIndex": 6, "sequenceIndex": 26,
"transactionHash": "0xTX6", "transactionFrom": "0xbob", "transactionTo": "0xnft",
"transactionValue": "1000000000000000000", "transactionReceiptStatus": "1" },
// transaction #6's 4 logs
{ "itemType": "log", "transactionIndex": 6, "logIndex": 34, "sequenceIndex": 27,
"logAddress": "0xNFT", "logTopic0": "0xddf252ad… (Transfer)",
"logTopic1": "0x0… (mint)", "logTopic2": "0x…bob", "logTopic3": "0x…tokenId", "logData": "0x" },
{ "itemType": "log", "transactionIndex": 6, "logIndex": 35, "sequenceIndex": 28,
"logAddress": "0xMarket", "logTopic0": "0x… (Sale)",
"logTopic1": "0x…bob", "logTopic2": null, "logTopic3": null, "logData": "0x…price" },
{ "itemType": "log", "transactionIndex": 6, "logIndex": 36, "sequenceIndex": 29,
"logAddress": "0xMarket", "logTopic0": "0x… (Fee)",
"logTopic1": null, "logTopic2": null, "logTopic3": null, "logData": "0x…fee" },
{ "itemType": "log", "transactionIndex": 6, "logIndex": 37, "sequenceIndex": 30,
"logAddress": "0xRoyalty", "logTopic0": "0x… (Paid)",
"logTopic1": null, "logTopic2": null, "logTopic3": null, "logData": "0x…amount" }
]
```
## Reading it
* **Get a transaction with its logs:** filter `itemType='transaction'` for the hash/metadata and
`itemType='log'` for the events, both on the same `transactionIndex`, then join on `transactionIndex`.
* **On-chain order** of a log is `(blockNumber, transactionIndex, logIndex)`, don't rely on physical array
position; use the index columns (or `sequenceIndex` for the raw interleaving).
* **Topics are flat columns.** `topic0` (the event signature hash) is always present; `topic1..topic3` are
`null` when the event has fewer topics. Re-assemble a `topics[]` array if your downstream expects one.
* **No decoding.** `logData` + topics are raw hex, the event name and parameters are yours to decode from the
contract ABI. (The REST API's decoded/"verbose" responses do this for you; on a raw feed it's a
derive-yourself step.)
> The `logsByContract` and `logsByTopic0` templates do exactly this filtering+join for you and write a flat
> one-row-per-log table, a drop-in for `GET /{address}/logs`.
# What Are Data Feeds?
Source: https://docs.moralis.com/data-feeds/concepts/what-are-data-feeds
Moralis Data Feeds deliver the decoded onchain dataset as a real-time stream available inside your own stack, consumed through whatever already fits it.
Moralis **Data Feeds** give you the **decoded onchain dataset**, every block turned into balances,
transfers, swaps, prices, approvals, NFT activity, and raw logs, as a **real-time stream available inside
your own stack**. It's the same data that powers Moralis, available for you to consume directly, without
building the blockchain indexing layer behind it.
## One data lake, many ways out
Data Feeds is a single service over one data lake. Moralis writes each chain's data **once**, then exposes that
same data through whatever interface fits your stack, so you adopt it **without re-tooling**:
### Stream it with the tools you already use
Consume feeds through **supported streaming interfaces**, using the client libraries your team already runs,
depending on the feed and current availability:
* **Kafka-compatible** clients.
* **RabbitMQ / AMQP** clients.
* **SQS-compatible** clients.
…or read directly over **REST / HTTP** or **Arrow Flight (gRPC)** when you want high-throughput columnar
pulls. See [Streaming](../access-methods/streaming) and [Direct reads](../access-methods/direct-reads).
### Land it with the sink
Point a **template** at your own **Postgres, MySQL, or ClickHouse** and the sink continuously lands
ready-to-query tables. Moralis does the heavy lifting in the template, decoding, enrichment, and reorg
correction, so you get a production-grade dataset inside your own stack, queried however you like. This is
the smoothest path for request/response needs (e.g. "a wallet's balances"). See
[Database sinks](./destinations).
> It's the **same data lake** under all of these, they're access modes of one service, not separate products.
> Choose by your stack and use case; you're never locked into one shape.
## What's in a feed
Each record is a **block**, carrying the decoded onchain activity for that block as typed arrays, token
transfers, swaps, price updates, balances, NFT transfers, approvals, and the raw block/transaction/log data.
See [The `block` array](./the-block-array) for how transactions and logs are laid out.
A few properties worth knowing:
* **Decoded, not raw RPC.** Swaps, transfers, balances, and prices are already extracted, you don't decode
logs yourself (though the raw logs are there if you want them).
* **Real-time and historical.** Read the latest blocks as they land, backfill history, or both.
* **Reorg-aware.** Each block records its position and parent, so consumers (and the sink's templates) correct
for chain reorganizations rather than serving stale data.
* **Onchain data.** A feed contains what's on the chain. Off-chain signals (token logos, spam/verification
labels, security scores) are layered on separately, see
[Data Feeds vs. the REST API](./data-feeds-vs-the-rest-api).
## Where to go next
* **Migrating from a Moralis REST endpoint?** Start with the relevant migration guide.
* **Building something new?** Browse the template cookbook for a ready-to-run feed.
* **Choosing how to consume it?** The [access methods overview](../access-methods/overview) compares all three
paths with a decision table.
# Data Feeds Features
Source: https://docs.moralis.com/data-feeds/features
Core capabilities of Moralis Data Feeds: custom indexing pipelines, real-time and historical data, multi-chain support, and enterprise-grade reliability.
### Custom indexing pipelines
Build custom indexing pipelines with full control over your blockchain data.
| Capability | Description |
| - | - |
| **Custom Schemas** | Define your own data models and schemas tailored to your use case |
| **Full Control** | Configure exactly which data to index, how to transform it, and where to deliver it |
| **Enterprise SLAs** | Guaranteed performance and uptime for mission-critical applications |
### Real-time & historical data
Stream live events and backfill historical data across chains.
| Capability | Description |
| - | - |
| **Live Streaming** | Stream events in real-time from any wallet, contract, or address |
| **Custom Filters** | Apply custom filters with guaranteed delivery |
| **Historical Backfills** | Fast backfills across chains to populate your data infrastructure |
### Ready-made templates
Skip the schema design. Start from a **template** that reconstructs a popular Moralis endpoint as a continuous sync into your own database.
| Capability | Description |
| - | - |
| **Endpoint clones** | Wallet history, token balances, prices, swaps, holders, NFT data, and raw logs: each as a copy-and-run template |
| **Your schema, your control** | Templates are blueprints: keep the columns and events you want, drop the rest |
| **Use-case bundles** | Group templates for a full workflow: accounting, portfolio, analytics, compliance |
[Browse the template catalogue →](/data-feeds/templates/overview)
### Multi-chain support
A single unified schema across EVM, Solana, and Bitcoin chains.
> [card] EVM
> [card] Solana
> [card] Bitcoin
Support across **EVM, Solana, and Bitcoin chains**, including 50+ EVM chains such as Ethereum, Polygon, Arbitrum, Base, Optimism, Avalanche, BNB Chain, and Tempo. Data is normalised into a unified schema, making cross-chain analytics straightforward.
### Enterprise-grade infrastructure
Built for teams with strict compliance, security, and reliability requirements.
| Capability | Description |
| - | - |
| **SOC 2 Type II Certified** | Pipelines meet enterprise security and compliance standards |
| **Dedicated Support** | Direct access to Moralis engineering and support teams |
| **Audit-Grade Data** | Data integrity verified for compliance and audit requirements |
| **High Availability** | Redundant infrastructure with guaranteed uptime SLAs |
### Get started
Build your first Data Feed from a template, or configure one from scratch in Moralis Admin.
> [card] [Get started with Data Feeds](https://admin.moralis.com/data-feeds)
>
> Open Data Feeds in Moralis Admin and set up your first pipeline.
# How Data Feeds Works
Source: https://docs.moralis.com/data-feeds/how-it-works
Understand the Data Feeds workflow: start from a template or a custom schema, configure your pipeline, and have indexed blockchain data delivered into your own database.
### Overview
Moralis Data Feeds handles the complexity of blockchain data indexing so you can focus on building. It reads Moralis-indexed, normalized per-block onchain data and continuously projects it into your own database. The workflow is straightforward:
### 1. Define
Start from a **template** or define a **custom schema**:
* **Templates** – ready-made blueprints that reconstruct popular Moralis endpoints (wallet history, balances, prices, swaps, holders, raw logs). The fastest on-ramp. [Browse templates →](/data-feeds/templates/overview)
* **Custom** – specify exactly which chains, contracts, events, and data types to index, with your own schema
* **Chains** – EVM, Solana, and Bitcoin chains
* **Data types** – raw data, decoded data, or both
### 2. Configure
Set up your schema and transformation rules:
* Define your data models and field mappings (or adapt a template's)
* Configure transformations and enrichments (e.g. inline USD valuation)
* Set up filters to capture only the data you need
* Choose your mode: **historical** backfill, **realtime** tail, or **hybrid** (both)
### 3. Deploy
Moralis deploys and manages the indexing infrastructure:
* No infrastructure to provision or maintain
* Automatic scaling based on data volume
* Built-in redundancy and fault tolerance
* Continuous monitoring and alerting
### 4. Deliver
Data lands directly in your own database:
* Real-time delivery as events occur on-chain
* Historical backfills delivered in parallel
* Reorg-safe: corrections converge your tables on canonical state automatically
* Data arrives in your schema, ready to query
### Delivery destinations
Data Feeds syncs into the database you run, indexed for your access pattern.
| Destination | Notes |
| - | - |
| **ClickHouse** | First-class: the only destination with live, reorg-safe ingestion. Best for production and large windows. |
| **Postgres** | Historical backfill, analytics, and smaller windows. |
| **MySQL** | Historical backfill and existing MySQL stacks. |
### Architecture benefits
| Benefit | Description |
| - | - |
| **Fully Managed** | Moralis handles all infrastructure, scaling, and maintenance |
| **Low Latency** | Optimised pipelines for minimal delay between on-chain events and delivery |
| **Guaranteed Delivery** | No data loss, with built-in retries and exactly-once-effective semantics |
| **Reorg-Safe** | Chain reorganizations are corrected automatically so your data stays canonical |
| **Cost Efficient** | Pay for the data you need, not unused infrastructure |
### Get started
Build your first Data Feed from a template, or configure one from scratch in Moralis Admin.
> [card] [Get started with Data Feeds](https://admin.moralis.com/data-feeds)
>
> Open Data Feeds in Moralis Admin and set up your first pipeline.
# Map Endpoints to Templates
Source: https://docs.moralis.com/data-feeds/migration/endpoints
Every covered Moralis REST API endpoint, mapped to the template (or combination of templates) that replaces it. Find the endpoint you call today and see exactly what to turn on.
This is the full list of Moralis REST endpoints covered by Data Feeds, **ordered by how widely each is used**
(most-used first). Find the endpoint you call today; the **Templates** column tells you exactly what to turn on.
Each template page has a **"Migrating from the REST API"** section with the field-by-field mapping for the
endpoints it replaces.
> [!WARNING]
>
> **Data Feeds are not a 1:1 endpoint swap.** Many endpoints return pre-joined objects that map to **a
> combination of templates**: the first template listed is the core dataset, the rest complete the response. Plan
> for a join (usually one SQL view) rather than a drop-in replacement.
New to Data Feeds first? Read the [migration overview](/data-feeds/migration/overview) for how the API and
Data Feeds differ, then come back here to pick your endpoint.
## Endpoints by usage
| # | REST endpoint | Templates you need | Headline fidelity |
| - | - | - | - |
| 1 | `GET /wallets/:address/tokens` | [Token Balances by Wallet](/data-feeds/templates/wallet/token-balances-by-wallet) + [Native Balances](/data-feeds/templates/wallet/native-balances) + [Token Prices](/data-feeds/templates/token/token-prices) + [Token Metadata](/data-feeds/templates/token/token-metadata) | balances exact, prices calculated |
| 2 | `GET /erc20/:token_address/owners` | [Token Holders](/data-feeds/templates/token/token-holders) + [Token Metadata](/data-feeds/templates/token/token-metadata) | exact |
| 3 | `GET /wallets/:address/history` | [Wallet History](/data-feeds/templates/wallet/wallet-history) | exact, decode-yourself + off-chain labels |
| 4 | `GET /:address/nft` | [NFTs by Wallet](/data-feeds/templates/wallet/nfts-by-wallet) + [NFT Collection Metadata](/data-feeds/templates/nft/nft-collection-metadata) | onchain exact, metadata add-yourself |
| 5 | `GET /:address/erc20` | [Token Balances by Wallet](/data-feeds/templates/wallet/token-balances-by-wallet) + [Token Metadata](/data-feeds/templates/token/token-metadata) | exact |
| 6 | `GET /erc20/prices` | [Token Prices](/data-feeds/templates/token/token-prices) + [Token Metadata](/data-feeds/templates/token/token-metadata) | calculated |
| 7 | `GET /erc20/:tokenAddress/holders` | [Token Holders](/data-feeds/templates/token/token-holders) + [Token Transfers](/data-feeds/templates/token/token-transfers) | counts exact, tiers your-definition |
| 8 | `GET /:address/erc20/transfers` | [Token Transfers](/data-feeds/templates/token/token-transfers) + [Token Metadata](/data-feeds/templates/token/token-metadata) | exact |
| 9 | `POST /nft/getMultipleNFTs` | [NFT Collection Metadata](/data-feeds/templates/nft/nft-collection-metadata) + [NFT Owners by Contract](/data-feeds/templates/nft/nft-owners-by-contract) | onchain exact, metadata add-yourself |
| 10 | `GET /:address/nft/transfers` | [NFT Transfers](/data-feeds/templates/nft/nft-transfers) | exact |
| 11 | `GET /:address/nft/collections` | [NFTs by Wallet](/data-feeds/templates/wallet/nfts-by-wallet) + [NFT Collection Metadata](/data-feeds/templates/nft/nft-collection-metadata) | exact |
| 12 | `GET /erc20/:address/price` | [Token Prices](/data-feeds/templates/token/token-prices) | calculated |
| 13 | `GET /transaction/:hash/verbose` | [Contract Logs](/data-feeds/templates/logs/contract-logs) + [the block array](/data-feeds/concepts/the-block-array) | raw exact, ABI decode-yourself |
| 14 | `GET /block/:block_number_or_hash` | [Contract Logs](/data-feeds/templates/logs/contract-logs) + [the block array](/data-feeds/concepts/the-block-array) | exact |
| 15 | `GET /:address` (native txns) | [Wallet History](/data-feeds/templates/wallet/wallet-history) | exact |
| 16 | `GET /wallets/:address/net-worth` | [Token Balances by Wallet](/data-feeds/templates/wallet/token-balances-by-wallet) + [Native Balances](/data-feeds/templates/wallet/native-balances) + [Token Prices](/data-feeds/templates/token/token-prices) | calculated |
| 17 | `GET /wallets/:address/approvals` | [Token Approvals](/data-feeds/templates/wallet/token-approvals) + [Token Metadata](/data-feeds/templates/token/token-metadata) + [Token Prices](/data-feeds/templates/token/token-prices) | exact, USD-at-risk calculated |
| 18 | `GET /wallets/:address/chains` | [Wallet History](/data-feeds/templates/wallet/wallet-history) | exact |
| 19 | `GET /erc20/metadata` | [Token Metadata](/data-feeds/templates/token/token-metadata) + [Token Prices](/data-feeds/templates/token/token-prices) | exact, market data calculated |
| 20 | `GET /pairs/:address/ohlcv` | [Pair OHLCV](/data-feeds/templates/markets/pair-ohlcv) | calculated from real trades |
| 21 | `GET /erc20/:token_address/pairs` | [Swaps by Pair](/data-feeds/templates/markets/swaps-by-pair) + [Pair Reserves](/data-feeds/templates/markets/pair-reserves) + [Token Metadata](/data-feeds/templates/token/token-metadata) | pools exact, market data calculated |
| 22 | `GET /erc20/:address/transfers` | [Token Transfers](/data-feeds/templates/token/token-transfers) | exact |
| 23 | `GET /erc20/:tokenAddress/holders/historical` | [Historical Balances](/data-feeds/templates/token/historical-balances) + [Token Transfers](/data-feeds/templates/token/token-transfers) | exact + calculated |
| 24 | `GET /nft/:address/metadata` | [NFT Collection Metadata](/data-feeds/templates/nft/nft-collection-metadata) | exact, off-chain extras |
| 25 | `GET /tokens/:tokenAddress/analytics` | [Swaps by Token](/data-feeds/templates/markets/swaps-by-token) + [Token Prices](/data-feeds/templates/token/token-prices) + [Pair Reserves](/data-feeds/templates/markets/pair-reserves) | calculated |
| 26 | `GET /:address/balance` | [Native Balances](/data-feeds/templates/wallet/native-balances) | exact |
| 27 | `GET /nft/:address` | [NFT Owners by Contract](/data-feeds/templates/nft/nft-owners-by-contract) + [NFT Collection Metadata](/data-feeds/templates/nft/nft-collection-metadata) | onchain exact, metadata add-yourself |
| 28 | `GET /wallets/:address/stats` | [Wallet History](/data-feeds/templates/wallet/wallet-history) + [NFTs by Wallet](/data-feeds/templates/wallet/nfts-by-wallet) | exact |
| 29 | `GET /wallets/:address/swaps` | [Swaps by Wallet](/data-feeds/templates/markets/swaps-by-wallet) | onchain exact, USD calculated |
| 30 | `GET /nft/:address/owners` | [NFT Owners by Contract](/data-feeds/templates/nft/nft-owners-by-contract) | onchain exact |
## Solana endpoints
The removed Solana **token-holder** endpoints map onto the same holder templates, pointed at Solana (the feed's
SPL `tokenTransfers` carry absolute post-balances, so the templates run unchanged):
| REST endpoint | Templates you need | Headline fidelity |
| - | - | - |
| `GET /token/:network/:address/top-holders` | [Token Holders](/data-feeds/templates/token/token-holders) | exact, USD calculated |
| `GET /token/:network/holders/:address` | [Token Holders](/data-feeds/templates/token/token-holders) + [Token Transfers](/data-feeds/templates/token/token-transfers) | totalHolders exact, tiers your-definition |
| `GET /token/:network/holders/:address/historical` | [Historical Balances](/data-feeds/templates/token/historical-balances) | per-bucket totals exact, change calculated |
The removed **launchpad / discovery** endpoints (pump.fun, Raydium LaunchLab) are all served by the one
[Token Bonding Status](/data-feeds/templates/token/token-bonding-status) template over the `launchpadEvents` feed:
| REST endpoint | Templates you need | Headline fidelity |
| - | - | - |
| `GET /token/:network/exchange/:exchange/new` | [Token Bonding Status](/data-feeds/templates/token/token-bonding-status) | exact, price calculated |
| `GET /token/:network/exchange/:exchange/bonding` | [Token Bonding Status](/data-feeds/templates/token/token-bonding-status) | progress exact, price calculated |
| `GET /token/:network/exchange/:exchange/graduated` | [Token Bonding Status](/data-feeds/templates/token/token-bonding-status) + [Token Prices](/data-feeds/templates/token/token-prices) | exact (+ DEX pool) |
| `GET /token/:network/:address/bonding-status` | [Token Bonding Status](/data-feeds/templates/token/token-bonding-status) | exact |
## Not covered yet
* **Other Solana endpoints** (prices, swaps, portfolio, metadata) are not yet covered.
* **Search and discovery endpoints** (`/tokens/search`) are a search product, not an indexed feed.
* **RPC node methods** (`eth_*`) belong to the node product, not Data Feeds.
# Migrating from the Moralis REST API
Source: https://docs.moralis.com/data-feeds/migration/overview
Already using Moralis REST API endpoints? This is the background you need before you move an endpoint onto Data Feeds: how the two differ, why the schema is not a copy, and the gotchas to plan for.
If you already call the Moralis Web3 Data API, you can move endpoint by endpoint onto **Data Feeds**.
You go from a pre-packaged REST response to the **underlying decoded data that produces it**, served from a
database you own, in real time, with no per-call limits and full control over how you store and query it.
This page is the background to read **once**. When you are ready to move a specific endpoint, go to the
[endpoint list](/data-feeds/migration/endpoints) and pick the one you call today.
## API vs. Data Feeds: why they are different
The Data API hands you a **finished answer**. A single call returns a wallet's tokens, already joined to
prices, metadata, and spam flags, shaped into one JSON response.
Data Feeds hand you the **decoded onchain data that answer is built from**, streamed into a database you own.
You assemble the answer yourself, which is what gives you no per-call limits, full history, and control over
filtering and pricing.
That trade has one consequence worth internalizing before you start:
> [!NOTE]
>
> **A Data Feed reconstructs an endpoint, it is not a byte-for-byte copy of the old response.** The same facts
> are there, but they arrive as raw rows across a few datasets rather than one pre-joined object. You do the
> join (usually one SQL view), and you decide what to do about the off-chain extras.
## Start with the model, once
Two concept pages explain how Data Feeds work, so every template links here instead of repeating it. Read these
first and the per-endpoint migration sections go quickly:
* [What are Data Feeds?](/data-feeds/concepts/what-are-data-feeds) The one data lake, and the
[ways to consume it](/data-feeds/access-methods/overview) (Kafka-compatible / AMQP / SQS-compatible
clients, REST / Arrow Flight, or the sink into your own database).
* [Data Feeds vs. the REST API](/data-feeds/concepts/data-feeds-vs-the-rest-api) The fidelity model: a Data Feed
reconstructs an endpoint from raw onchain data, it is not a byte-for-byte copy of the old response.
## The schema gotchas to plan for
These are the differences that surprise people first. Each template's migration section states the answer for
its own endpoint(s), but the pattern is always one of these:
| You had in the API response | Where it comes from in Data Feeds |
| - | - |
| **One pre-joined object** (e.g. a wallet token with balance, price, metadata) | Several datasets you join yourself, usually in one SQL view. One endpoint often maps to **more than one template**. |
| **A derived USD value** (price, net worth, USD-at-risk) | **Calculated** from live DEX trades. Very close to the old value, best compared with a small tolerance, not byte-equality. |
| **An off-chain signal** (logos, spam flags, security scores) | **Not in the lake.** Bring your own source, or drop the field. |
| **A field that needs full history to be correct** (balances, holders, approvals) | Correct only once you backfill. Decide your [backfill](/data-feeds/concepts/history-and-backfill) before you start. |
### How to read the fidelity of a migration
Every field-mapping table classifies each output value so you can plan with confidence. Throughout, you will
see three labels:
| Label | Meaning |
| - | - |
| **exact** | Comes straight from the chain, identical to the old endpoint (balances, transfers, metadata). |
| **calculated** | Derived from real onchain activity, for example USD prices from live DEX trades. Very close to the old value, best compared with a small tolerance. |
| **add yourself** | An off-chain signal (logos, spam flags, security scores) that is not in the lake. Bring your own source, or skip it. |
## Find your endpoint
When you are ready, the **[Map endpoints to templates](/data-feeds/migration/endpoints)** table maps every covered
Moralis REST endpoint to the template (or **combination of templates**) that replaces it, ordered by usage.
Migration details live **on the template pages themselves**: each template has a "Migrating from the REST API"
section with the field-by-field mapping, the required template combination, one reconstruction query, and the
endpoint-specific gotchas. One page per dataset: the template is the single source of truth.
New to Data Feeds entirely? Start with the **[quickstart](/data-feeds/migration/quickstart)** to get live data
flowing into your own database in about ten minutes, then come back and migrate your endpoints. And skim
[Gotchas & troubleshooting](/data-feeds/migration/troubleshooting) before your first run; it lists every
known failure point with the fix.
## How each migration section is structured
Every template's "Migrating from the REST API" section follows the same shape, so once you have read one you
can skim the rest:
1. **The REST endpoint(s)** it replaces, and whether you need this template alone or a **combination**,
stated up front, with links to the other templates you need.
2. **Field mapping reference**, the per-field table with the fidelity label.
3. **One reconstruction query**, the SQL view that rebuilds the old response shape.
4. **Good to know**, the endpoint-specific gotchas worth knowing before you ship.
# Quickstart: Run Your First Sink
Source: https://docs.moralis.com/data-feeds/migration/quickstart
Get live, decoded onchain data flowing into your own database in about ten minutes. Generate a sink starter pack, run it with Docker, and query your first rows.
This quickstart takes you from nothing to **live onchain data in your own database** in about ten minutes.
You generate a **sink starter pack** in the Admin Panel, run it with Docker, and query your first rows. Every
[template](/data-feeds/templates/overview) and [migration guide](/data-feeds/migration/overview)
then follows the same pattern.
## Before you begin
> [!WARNING]
>
> **Data Feeds is a technical product: you run the infrastructure.** Unlike the REST API, the data lands in a
> database **you own and operate**: you run the Docker sink, you provision Postgres/ClickHouse (locally for this
> quickstart; on your own servers in production), and you are responsible for storing, sizing, and backing up
> the decompressed data. Decoded onchain data expands significantly from its compressed transport size, so budget
> disk accordingly.
* **Docker** and Docker Compose installed and running.
* A **Data Feeds API key** (`cm_live_...`) from Moralis Admin.
* Access to the **Moralis Admin Panel**, where you generate the sink config.
* A machine with enough **disk headroom** for your backfill window: start small (`tip-500`) and widen once
you've seen the per-block footprint for your chain.
[Open Data Feeds in Moralis Admin](https://admin.moralis.com/data-feeds)
## Step 1: generate your sink starter pack
In the Admin Panel, configure a sink (pick your **chain**, **topic**, and **destination database**) and
download the **starter pack** (`continuum-sink-starter.zip`). Unzip it. You get:
| File | What it is |
| - | - |
| `sink-config.yaml` | The sink config you generated: Continuum URL, `namespace` (chain), `topic`, and destination. |
| `docker-compose.yml` | Brings up the sink (`moralisweb3/continuum-sink`) plus a local PostgreSQL. |
| `.env` | Your API key and DB password. **Do not commit or share it.** |
| `schema.sql` | DDL for the destination table(s), auto-applied to Postgres on first start. |
| `README.txt` | The same steps you are reading here. |
> [!NOTE]
>
> **`namespace` is the chain, as a hex chain ID.** For example `0x1` is Ethereum, `0xa4b1` is Arbitrum One. See
> the [chain reference](#chain-reference) below. `topic` (e.g. `master-3`) is the master block stream the sink
> reads.
## Step 2: add your API key
Open `.env` and confirm your key is set; the generated file sometimes ships with a **blank or placeholder**
key:
```bash theme={null}
# .env (do not commit)
MORALIS_API_KEY=cm_live_... # your full key — the sink fails with "api_key is required" if blank
SINK_PG_PASSWORD=... # already set for the bundled Postgres
```
> [!WARNING]
>
> **Keep your key private.** It is a live credential. Never commit `.env` or paste the key into shared docs or
> chat. If a key leaks, rotate it.
## Step 3: start the stack
From the unzipped directory:
```bash theme={null}
docker compose up -d
```
This starts PostgreSQL (with `schema.sql` applied) and the sink. The sink reads a backfill window from the
upstream S3 store, then tails live blocks. Watch it work:
```bash theme={null}
docker compose logs -f sink
```
> [!TIP]
>
> **Querying from your own app on the host?** The bundled Postgres is only reachable inside the Docker network
> by default. Add a port mapping to the `postgres` service so you can connect from your machine:
>
> ```yaml theme={null}
> postgres:
> ports:
> - "5544:5432"
> ```
>
> Then connect to `localhost:5544` (user/db `sdf`, password from `.env`).
## Step 4: query your first rows
The default `tokenTransfers` config writes to a table named after your sink (here, `sdf`):
```bash theme={null}
docker compose exec postgres psql -U sdf -d sdf -c \
"SELECT count(*), max(position) AS latest_block FROM public.sdf;"
```
```sql theme={null}
-- the most recent transfers
SELECT position, tokenaddress, fromaddress, toaddress, value
FROM public.sdf
ORDER BY position DESC
LIMIT 20;
```
You should see the count climb as new blocks land. That is live, decoded onchain data in a store you own: no
API quotas, no per-call limits.
## If no rows arrive
The pipe has a few moving parts. Work down this list:
| Symptom | Cause | Fix |
| - | - | - |
| `continuum.api_key is required` in sink logs | `MORALIS_API_KEY` blank in `.env` | Paste your full `cm_live_...` key, `docker compose up -d --force-recreate sink`. |
| Sink logs stop after `s3-proxy reachable` and rows stay at 0 | Upstream S3 backfill stalled (e.g. "Partition not found") | Not your setup. Confirm the chain/topic backfill is healthy with the team, then it resumes automatically. |
| Can connect but app can't reach Postgres | No host port mapping | Add the `ports` block from Step 3. |
## Chain reference
`namespace` in `sink-config.yaml` is the chain's ID in hex:
| Chain | Chain ID | `namespace` |
| - | - | - |
| Ethereum | 1 | `0x1` |
| Optimism | 10 | `0xa` |
| BNB Chain | 56 | `0x38` |
| Polygon | 137 | `0x89` |
| Base | 8453 | `0x2105` |
| Arbitrum One | 42161 | `0xa4b1` |
| Avalanche | 43114 | `0xa86a` |
## What just happened
* The **starter pack** carried a generated `sink-config.yaml` (chain, topic, destination) and a matching schema.
* The **sink** (`moralisweb3/continuum-sink`) read the master block stream, backfilled history, then stayed live.
* You queried a normal SQL table, yours to join and shape freely.
## Next steps
* **Migrating an existing integration?** Find your endpoint in the [Migration guides](/data-feeds/migration/overview).
* **Want a different dataset?** Browse the [templates](/data-feeds/templates/overview): swaps, balances, holders, prices,
NFT activity. They all run the same way; swap the transform and schema.
* **Understand the model:** [What are Data Feeds?](/data-feeds/concepts/what-are-data-feeds),
[History & backfill](/data-feeds/concepts/history-and-backfill), and [Destinations](/data-feeds/concepts/destinations).
* **Hit something surprising?** The [Troubleshooting](/data-feeds/migration/troubleshooting) page covers the common
first-run questions.
# Migrating from Moralis Streams
Source: https://docs.moralis.com/data-feeds/migration/streams-overview
Using Streams webhooks today? Here is how the model maps onto Data Feeds: push webhooks vs. data flowing into a database you own.
If you use **Moralis Streams**, you receive webhooks: you define a stream (addresses, topics, chains), Moralis
watches the chain, and decoded events are **pushed** to your server as they happen.
**Data Feeds** deliver the same decoded onchain data with the direction reversed: instead of receiving pushes
and storing what you need, the data **flows directly into a database you own**: historical backfill and live
tail through one pipe. Your webhook handler, retry logic, and ingestion queue disappear; what remains is a
table you query.
## How the concepts map
| In Streams | In Data Feeds |
| - | - |
| A **stream config** (addresses, topics, ABIs) | A **template** plus SQL filters, e.g. [token-transfers](/data-feeds/templates/token/token-transfers), [contract-logs](/data-feeds/templates/logs/contract-logs) filtered to your addresses or topics |
| A **webhook payload** pushed per event | **Rows in your own database**, written by the sink as blocks land |
| Your **webhook endpoint + retries + queue** | Nothing: delivery, ordering, and resume are the sink's job |
| `confirmed: true/false` payloads for reorg safety | [Reorg handling](/data-feeds/concepts/reorgs) built into the pipe |
| **Replay / history** (limited) | **Full backfill**: the same feed serves history and live data ([how backfill works](/data-feeds/concepts/history-and-backfill)) |
The practical difference: a webhook tells you *something happened*, and building state from webhooks (balances,
holder counts, volumes) is your accounting problem. A Data Feed hands you the rows already in SQL: state is a
query, not a pipeline you maintain.
## Why teams move
* **No delivery infrastructure.** No public webhook endpoint, no signature checks, no retry handling, no
ingestion queue. Data lands in your database directly.
* **History and live in one pipe.** A new stream starts at "now"; a feed backfills as deep as you need, then
stays live.
* **Consume it your way.** The same feed can flow into Postgres today and your own Kafka, AMQP, or SQS
consumers as the platform's export options roll out; see
[What are Data Feeds?](/data-feeds/concepts/what-are-data-feeds) for the consumption model.
## Try the model now
You can evaluate Data Feeds against your current Streams setup today:
1. Run the **[quickstart](/data-feeds/migration/quickstart)**: live decoded data in your own Postgres in about
ten minutes.
2. Find the [template](/data-feeds/templates/overview) closest to what your stream watches (token transfers, contract
logs, swaps, NFT activity).
3. Keep your stream running in parallel while you compare; nothing about trying Data Feeds disturbs your
existing Streams setup.
# Gotchas & Troubleshooting
Source: https://docs.moralis.com/data-feeds/migration/troubleshooting
Every known failure point when consuming Data Feeds (symptom, why it happens, and the fix) so you don't discover them the hard way. Covers the sink pipe, the live-vs-settled data boundary, and query-time surprises.
The complete list of things that surprise people when consuming Data Feeds. Each entry is **symptom, why, and
what to do**. Skim the headings before your first run; five minutes here saves hours of debugging.
> [!WARNING]
>
> **You are running real infrastructure.** Data Feeds deliver decoded onchain data into a database **you own and
> operate**: Docker, Postgres/ClickHouse, disk, and backfill windows are your responsibility. If you have not
> run the pipe yet, start with the [quickstart](/data-feeds/migration/quickstart).
## Sink pipe gotchas
### The sink exits with `NUMBER_OF_COLUMNS_DOESNT_MATCH`
**Symptom:** every batch fails with `Code: 20. DB::Exception: Number of columns doesn't match (source: 1 and
result: 7)`.
**Why:** the sink's `transform_sql` output must **positionally match** the destination table's columns. With no
transform configured, the sink falls back to selecting a single column, which can never match a multi-column
schema.
**Do this:** make sure `sink-config.yaml` has a `transform_sql` whose SELECT list matches your destination
table column-for-column, and a `parquet_columns` list naming the top-level fields the transform reads (e.g.
`[position, tokenTransfers]`). If your starter pack shipped without one, add it; the config schema inside the
sink image documents the pattern.
### The sink logs `api_key is required`
**Why:** the generated `.env` sometimes ships with a blank or placeholder key.
**Do this:** paste your full `cm_live_...` key into `.env`, then `docker compose up -d --force-recreate sink`.
### Every request returns HTTP 500 immediately
**Why:** usually the wrong Continuum URL. The config must point at the **read-replica host**, not the admin
panel host. Also check you are connected through your assigned VPN gateway if your access is VPN-gated.
**Do this:** verify `continuum.url` in `sink-config.yaml` and your VPN connection before debugging anything
else.
### The backfill fails with `Partition not found`
**Symptom:** `HTTP 500: Failed to read Parquet footer: Partition not found: s3://...`.
**Why:** your backfill window includes blocks whose settled files are not available: either the window
reaches **too close to the tip** (recent blocks are served live, not as files yet), **too far back** on a
chain with a thin retention window, or the settled store is **temporarily lagging**. The window is validated
up front, so one missing partition fails the whole job; there is no partial backfill.
**Do this:** shrink the window (`tip-500` instead of `tip-5000`) and retry. You can also cap the upper end
with a `blockNumber <= N` filter to pin the window entirely inside available history. If a modest window
still fails for hours, the settled store is lagging. Report it with the exact error; it resumes
automatically once fixed upstream.
### The sink completes instantly with 0 rows, and no error
**Symptom:** logs show `Complete: 0 URL(s) processed`, exit code 0, empty table. **Looks like success; isn't.**
**Why:** the window resolved to a range with no settled files in it: typically a window so close to the tip
that no complete partition exists yet, or a range the store is still catching up on.
**Do this:** always verify with a row count (`SELECT count(*) FROM ...`) after a run, never trust a clean
exit alone. Widen the window backward until files exist.
### Sizing the backfill window
**Why it matters:** the window is set as a filter, e.g. `blockNumber >= tip-1000`; `tip-` resolves against
the chain tip at start. Too deep on a thin-retention chain fails with `Partition not found`; too shallow
returns 0 rows (see above). A `blockNumber <= N` filter caps the upper end when you need to pin a range.
**Do this:** start small (`tip-500`), confirm rows land, then widen to the depth your use case needs. Remember
[current-state answers need deep history](/data-feeds/concepts/history-and-backfill): balances and holders
are only correct once you've backfilled the relevant range.
## The live vs. settled boundary
### Live data and file storage are two different stores
**Why:** the chain status can show the feed tracking the tip (live, in-memory) while the most recent blocks
are **not yet flushed to settled file storage**. These are different systems with different lag: "the feed is
live" does not mean "every recent block is downloadable."
**Do this:** read near-tip data from the live stream and settled history from files; the chain status tells
you where the boundary sits. If you only consume through the sink, this is why a very shallow backfill can
find nothing while the feed is demonstrably live.
### Do not hard-code the feed version
**Why:** each chain's feed carries a version that can roll over when the producer is upgraded; a hard-coded
version can start returning a lagging tip or stop resolving.
**Do this:** resolve the active topic from the chain's status before reading.
### Older history may be missing newer fields
**Why:** the decoded schema has gained fields over time; partitions from before a field existed genuinely do
not carry it. On some chains, always-null struct fields are stripped from the files entirely.
**Do this:** discover the columns actually present for the range you read, and treat an absent field as
zero/none rather than a failure. When reading nested structs, wrap optional fields defensively so a missing
field yields a default instead of an error.
## Query-time gotchas
### The sink started but no rows have appeared yet
**Why:** a template in `historical` or `hybrid` mode backfills a window of past blocks before (or while) it goes
live, so there is a short warm-up before rows land.
**Do this:** give it a minute, then check the sink logs: healthy output shows the cursor seeded near the tip
and block windows advancing without errors. Still nothing? Confirm your chain ID and start block, then see
[Modes](/data-feeds/concepts/modes), and the 0-rows gotcha above.
### The newest rows look duplicated or briefly wrong
**Why:** near the tip a block can be replaced by a reorg. ClickHouse templates write a **correcting row** rather
than silently deleting, so a naive `SELECT *` can momentarily show both the original and its cancel.
**Do this:** read ClickHouse fact tables with **`FINAL`** (or sign-aware sums for aggregates). Settled history
is never affected, only the tip. See [Reorgs](/data-feeds/concepts/reorgs).
### A token has no price
**Why:** prices are **calculated from real onchain DEX trades**, not a pricing engine. A token that has not
traded recently has no current mark.
**Do this:** treat a missing price as "no recent trades", not an error, and fall back gracefully. USD values
are **calculated**: compare with a small tolerance, never byte-equality. See
[Data Feeds vs. the REST API](/data-feeds/concepts/data-feeds-vs-the-rest-api).
### My current-state results are incomplete
**Why:** balances, holders, and approvals are **cumulative state**: start indexing too late and anyone whose
last activity predates your start block is quietly missing.
**Do this:** backfill from the beginning of the relevant history (the token's deploy block for by-token
answers, full history for by-wallet answers). Event-list answers (swaps, transfers, logs) don't have this
constraint. See [History & backfill](/data-feeds/concepts/history-and-backfill).
### I get a 403 or a 402 from the API
**Why:** **403** = your key is not scoped to that chain. **402** = your subscription or access is inactive
(account-level, not per-chain).
**Do this:** for 403, use a key that includes the chain, or add the chain to your key in [Moralis Admin](https://admin.moralis.com/data-feeds); for 402, check your Data Feeds access is active.
## Reading the lake directly (REST / Arrow Flight)
### Keep direct-read concurrency modest
**Why:** each direct read does real work to prepare data, so very high concurrency degrades rather than
cleanly rate-limiting.
**Do this:** keep concurrency modest and retry transient `5xx` with exponential backoff.
> [!NOTE]
>
> **Still stuck?** Most first-run issues come down to the backfill window (too shallow → 0 rows, too deep →
> `Partition not found`), the `FINAL` reading rule, or an access/chain scope mismatch. If you have ruled those
> out, capture the template, chain, window, and the exact error, and reach out through your Data Feeds support
> channel.
# Data Feeds
Source: https://docs.moralis.com/data-feeds/overview
Moralis Data Feeds is a blockchain indexing engine for building custom, enterprise-grade data pipelines. It combines real-time and historical indexing with rich schema controls and delivers data straight into your own database, with high performance and reliability.
### At a glance
> [card] Custom Indexing
>
> Index exactly the contracts, events, and data types you need.
> [card] Real-time Pipelines
>
> Live tail from the chain head as events occur on-chain.
> [card] Historical Backfill
>
> Fast backfills to populate your database with full history.
> [card] Multichain Support
>
> EVM, Solana, and Bitcoin chains.
> [card] Custom Schemas
>
> Define your own data models, or start from a ready-made template.
> [card] Raw & Enriched Data
>
> Raw logs through to decoded, USD-valued events.
### Templates & use cases
The fastest way to start is a **template**: a ready-made blueprint that reconstructs a popular Moralis endpoint (wallet history, token balances, prices, swaps, holders, raw logs) as a continuous sync into your own database. Bundle several into a **use case** for a complete workflow.
> [card] [Browse templates](/data-feeds/templates/overview)
>
> Per-endpoint sync blueprints with schema, queries, and reorg strategy.
> [card] [Use cases](/data-feeds/use-cases/accounting)
>
> Ready-made template bundles: accounting, portfolio, analytics, compliance, and more.
### Types of use cases
* Self-hosted clones of popular Moralis endpoints, queryable in your own database
* Custom blockchain data pipelines for internal applications
* Real-time and historical on-chain analytics
* Back-office and accounting systems needing structured, valued blockchain data
* Apps needing tailored data models, beyond generic APIs
* Institutional workflows with compliance and SLA requirements
### For which teams
* **Data engineering & backend teams** who build in-house infrastructure
* **Analytics teams** requiring custom indexed datasets
* **Product teams** that need high control over how on-chain data is structured
* **Enterprise & institutional teams** with compliance, security, and SLA needs
* **Quant/trading and risk teams** building mission-critical data pipelines
# Contract Logs
Source: https://docs.moralis.com/data-feeds/templates/logs/contract-logs
Sync every raw event log emitted by a contract, all topics and raw data, in on-chain order, into your own database. Mirrors the Moralis GET /{address}/logs endpoint.
### Question it answers
> "Give me every raw event log emitted by contract **0x…**, in on-chain order." Mirrors Moralis `GET /{address}/logs`.
This is the **raw** event log, `topic0…topic3` plus the ABI-encoded `data` payload, keyed by the emitting contract. Unlike the decoded templates (Token Transfers, Token Approvals, Swaps), it does not decode event names or arguments; you decode `data` in your application against the contract's ABI. Use it to index **any contract's events**, including custom or non-standard ones the decoded templates don't cover.
### What you get
One row per log, keyed by the emitting contract:
| Column | Description |
| - | - |
| `contract_address` | The emitting contract (the log's address) |
| `block_number`, `transaction_index`, `log_index` | On-chain ordering tuple |
| `tx_hash` | Transaction that produced the log |
| `topic0` | Event signature hash (`keccak256` of the canonical signature), always present |
| `topic1`, `topic2`, `topic3` | Indexed event parameters; `NULL` when the log has fewer topics |
| `data` | Raw, ABI-encoded, non-indexed payload as hex, decode in your app |
| `block_timestamp` | Block time |
### On-chain ordering
A log's canonical position is the tuple **`(block_number, transaction_index, log_index)`**, block height, then the transaction's position in the block, then the log's index within the transaction. Every destination is keyed `contract_address` first, then that tuple, so "all logs for a contract, in order" is a sort-free range scan:
* **ClickHouse**: `ORDER BY (chain_id, contract_address, block_number, transaction_index, log_index, …)`; a prefix scan returns rows already ordered.
* **Postgres / MySQL**: a composite index on `(contract_address, block_number, transaction_index, log_index)` answers the read with no filesort step.
### Optional: group by event signature (topic0)
The primary key already leads with `contract_address`, so "all `Transfer` logs for contract X" prefix-scans to the contract and filters `topic0` within it. On a **high-volume contract that emits many event types**, an opt-in `(contract_address, topic0, …)` structure makes that read a tight `(contract, topic0)` range that stays sort-free *and* skips the contract's other event types.
These are shipped **commented-out** in each schema (extra write cost + storage), uncomment to enable:
| Destination | Optional structure |
| - | - |
| Postgres | `CREATE INDEX … (contract_address, topic0, block_number, transaction_index, log_index)` |
| MySQL | `ADD KEY (contract_address, topic0, block_number, transaction_index, log_index)` |
| ClickHouse | A `topic0` `bloom_filter` skip-index (light), or a projection sorted by `(chain_id, contract_address, topic0, …)` (sort-free, heavier) |
### Source
Raw logs aren't a decoded entity array, they live in the flattened `block` raw-passthrough array, where each block is expanded into items discriminated by `itemType` (`log` / `transaction` / …). The transform `ARRAY JOIN`s `block`, keeps `itemType = 'log'`, and lands one row per log. A log row carries **no transaction hash**, so `tx_hash` is recovered by joining each log to its sibling `itemType = 'transaction'` row on `(block_number, transaction_index)`.
### Destination
| Destination | Table | By-contract access |
| - | - | - |
| **ClickHouse** (first-class) | `fact_logs` | Prefix scan on `(chain_id, contract_address, …)`; read with `FINAL` |
| **Postgres** | `contract_logs` | Composite index `(contract_address, block_number, transaction_index, log_index)` |
| **MySQL** | `contract_logs` | Composite key `(contract_address, block_number, transaction_index, log_index)` |
Logs are immutable append-only events, so the ClickHouse fact table is a plain collapsing table, each log is one row, and a chain reorganization cancels it via the companion log table. There's no latest-wins logic; every log is a distinct row.
### Full schema
The complete read table. Keep the columns you need; `topic1…topic3` and `data` are nullable raw fields you decode in your app (see [Schema & flexibility](/data-feeds/templates/overview#schema--flexibility)).
> [accordion] ClickHouse, fact\_logs (contract-keyed)
>
> ```sql theme={null}
> CREATE TABLE recipe_logs_by_contract.fact_logs
> (
> vendor_event_id String,
> ingested_at DateTime64(3),
> chain_id UInt32,
> block_hash String,
> block_number UInt64,
> transaction_index UInt32,
> log_index UInt32,
> event_ts DateTime64(3),
> tx_hash String,
> contract_address String,
> topic0 String,
> topic1 Nullable(String),
> topic2 Nullable(String),
> topic3 Nullable(String),
> data Nullable(String), -- raw ABI-encoded payload (hex)
> sign Int8
> )
> ENGINE = ReplicatedCollapsingMergeTree(
> '/clickhouse/tables/{database}/fact_logs', '{replica}', sign)
> PARTITION BY (chain_id, toYYYYMM(event_ts))
> ORDER BY (chain_id, contract_address, block_number, transaction_index, log_index, vendor_event_id);
>
> -- OPTIONAL (commented out by default): accelerate "specific event type for this
> -- contract" reads on high-volume contracts. Enable at most one.
> -- (a) lightweight topic0 skip-index:
> -- ALTER TABLE recipe_logs_by_contract.fact_logs
> -- ADD INDEX idx_topic0 topic0 TYPE bloom_filter GRANULARITY 4;
> -- (b) sort-free projection keyed (contract_address, topic0, …):
> -- ALTER TABLE recipe_logs_by_contract.fact_logs
> -- ADD PROJECTION proj_contract_topic0
> -- (SELECT * ORDER BY (chain_id, contract_address, topic0, block_number, transaction_index, log_index));
> ```
>
> Postgres / MySQL mirror this as a flat `contract_logs` table with a composite index `(contract_address, block_number, transaction_index, log_index)` and the optional `(contract_address, topic0, …)` index commented out.
### Example reads
All logs emitted by a contract, in on-chain order (ClickHouse):
```sql theme={null}
SELECT block_number, transaction_index, log_index, tx_hash,
topic0, topic1, topic2, topic3, data
FROM recipe_logs_by_contract.fact_logs FINAL
WHERE chain_id = 1 AND contract_address = lower('0x...')
ORDER BY block_number, transaction_index, log_index
LIMIT 100;
```
Only a specific event type (`0xddf2…` = `keccak("Transfer(address,address,uint256)")`):
```sql theme={null}
SELECT block_number, transaction_index, log_index, tx_hash, topic1, topic2, data
FROM recipe_logs_by_contract.fact_logs FINAL
WHERE chain_id = 1 AND contract_address = lower('0x...')
AND topic0 = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'
ORDER BY block_number, transaction_index, log_index
LIMIT 100;
```
### Modes
Shipped defaults: **ClickHouse `hybrid`**, **Postgres / MySQL `historical`**. For live/reorg-safe ingestion use ClickHouse, see the [overview](/data-feeds/templates/overview#modes).
> [!NOTE]
>
> This template reads the wide raw `block` column (every log **and** transaction per block), so per-block bytes are higher than the decoded templates. The transaction rows are read only to recover `tx_hash`, drop that join if you don't need it.
### EVM only
Contract Logs extracts EVM event logs (`topic0…3` + `data`). Solana program logs are a different model and aren't emitted into this array.
### Fidelity gaps
Raw on-chain log primitives, emitter, all topics, raw data, block, tx hash, on-chain ordering, are fully covered. Fields with no onchain source are omitted: `decoded_event` (needs the contract ABI, decode in your app) and transaction receipt fields beyond `tx_hash`.
## Migrating from the REST API
This template is the landing point for the two **Blockchain API** REST endpoints. Neither maps 1:1 to a single template: both responses are assembled from the raw `block` array, the flattened header / transaction / log rows this template already reads (see [The block array](/data-feeds/concepts/the-block-array)). This template lands the **log** rows in a queryable table; the transaction and header fields come from the sibling rows in the same array. The subsections below cover each endpoint: what replaces it, the field mapping (**exact** = straight from the chain, **decoded** = you decode from the ABI or a typed template covers it, **gap** = not delivered today, **off-chain** = add yourself), and the gotchas specific to that endpoint.
### GET /transaction/:transaction\_hash/verbose
The decoded-transaction-by-hash endpoint. Replaced by reading the transaction's logs from this template's table and its raw fields from the transaction row of [the block array](/data-feeds/concepts/the-block-array), the "verbose" ABI decoding becomes a step you own.
> [!WARNING]
>
> This is **not** a 1:1 table swap, it's a three-part workflow. **Logs** come from this template's table, keyed by `tx_hash`. **The transaction's own fields** (`from`, `to`, `value`, `input`, gas, receipt) come from the sibling `itemType = 'transaction'` row in the block array, the matching log rows give you its `block_number`. **Decoding** is yours: standard events are already typed rows in the decoded templates ([Token Transfers](/data-feeds/templates/token/token-transfers), [NFT Transfers](/data-feeds/templates/nft/nft-transfers), [Swaps by Pair](/data-feeds/templates/markets/swaps-by-pair)); custom events and `decoded_call` decode from the contract ABI.
| `/transaction/:hash/verbose` | Data Feeds | Fidelity |
| - | - | - |
| `hash`, `nonce`, `transaction_index`, `from/to_address`, `value`, `input`, `gas*`, `receipt_*` | `block` array transaction row | exact |
| `transaction_fee` | derive: `receipt_gas_used × gas_price` | exact |
| `block_number`, `block_timestamp`, `block_hash` | transaction row / this template's table | exact |
| `logs[]` (address, topics, data, indices) | this template (`fact_logs` / `contract_logs`) | exact |
| `logs[].decoded_event` (standard events) | decoded templates (Token Transfers, NFT Transfers, Swaps) | decoded |
| `logs[].decoded_event` (custom), `decoded_call` | decode topics/`data`/`input` with the contract ABI | decoded |
| `internal_transactions` | not carried in the `block` array today | gap |
| `from/to_address_entity`, `*_label`, `*_entity_logo` | add yourself | off-chain |
A transaction's logs by hash (Postgres, same shape on ClickHouse with `FINAL`):
```sql theme={null}
SELECT block_number, transaction_index, log_index, contract_address,
topic0, topic1, topic2, topic3, data
FROM contract_logs
WHERE tx_hash = lower('0x...')
ORDER BY log_index;
```
**Gotchas**
* **By-hash is a point lookup, but the shipped keys are contract-first.** Add an index on `tx_hash` (or keep your own hash-to-block map), the shipped `(contract_address, block_number, …)` ordering doesn't serve it.
* **Index the history you'll look up.** Arbitrary historical hashes need a `historical`/`hybrid` backfill across the range; recent-only lookups need only a recent window, see [History & backfill](/data-feeds/concepts/history-and-backfill).
* `internal_transactions` is a gap today, it isn't carried in the `block` array.
* The `*_entity` / `*_label` / `*_entity_logo` fields are off-chain address labels; bring your own directory or drop them.
### GET /block/:block\_number\_or\_hash
The whole-block endpoint. Replaced by reading the block directly from the feed, a feed row's native unit **is** a block, so the header, transactions, and logs arrive together in [the block array](/data-feeds/concepts/the-block-array) and a by-number read is a direct positional read (a block's position is its block number).
> [!WARNING]
>
> This template's table alone does **not** reconstruct the response, it holds only the log rows. The header and transaction rows come from the block array itself (`itemType = 'block'` / `'transaction'` / `'log'`): read the block's row from the feed, split the array by `itemType`, and join each log to its transaction on `transaction_index`. Keep this template running alongside to make logs queryable by block without re-reading whole blocks, and to resolve `block_hash → block_number` for by-hash reads.
| `/block/:block_number_or_hash` | Data Feeds | Fidelity |
| - | - | - |
| Header (`number`, `hash`, `parent_hash`, `timestamp`, `miner`, `gas_*`, `base_fee_per_gas`, roots, …) | `block` array block row | exact |
| `transaction_count` | count of transaction rows | exact |
| `transactions[]` (hash, from, to, value, input, gas, receipt\_\*) | `block` array transaction rows | exact |
| `transaction_fee` | derive: `receipt_gas_used × gas_price` | exact |
| `logs[]` (address, topics, data, indices) | `block` array log rows / this template | exact |
| `internal_transactions` | not carried in the `block` array today | gap |
| `from/to_address_entity`, `*_label`, `*_entity_logo` | add yourself | off-chain |
Resolve a by-hash read to a position, then all of that block's logs (ClickHouse):
```sql theme={null}
SELECT block_number, transaction_index, log_index, tx_hash,
contract_address, topic0, topic1, topic2, topic3, data
FROM recipe_logs_by_contract.fact_logs FINAL
WHERE chain_id = 1 AND block_hash = lower('0x...')
ORDER BY transaction_index, log_index;
```
**Gotchas**
* **By-hash resolves to a number first**: the feed is positioned by block number; this template's `block_hash` column (or your own index) does the resolve.
* **Raw log rows carry no tx hash**: they join to their transaction on `(block_number, transaction_index)`; this template already attaches `tx_hash` for you.
* **Busy blocks are large** (a megabyte or two of JSON), read by position and process the array.
* The REST responses return **raw** logs, matching this template exactly; if you also want decoded events, add the decoded templates or decode from the ABI.
* `internal_transactions` and address labels: same gaps as above.
### Related
> [card] [Logs by Event Signature](/data-feeds/templates/logs/logs-by-topic0)
>
> The sibling, index one event type across all contracts.
> [card] [Onchain Event Indexing](/data-feeds/use-cases/event-indexing)
>
> The use case these raw-log templates power.
# Logs by Event Signature
Source: https://docs.moralis.com/data-feeds/templates/logs/logs-by-topic0
Sync every raw event log of one signature, every Transfer, Approval, or Swap, across all contracts, chain-wide, into your own database. The by-event-type sibling of Contract Logs.
### Question it answers
> "Give me every raw event log of signature **T** (`topic0`), chain-wide, in on-chain order."
The by-event-type mirror of [Contract Logs](/data-feeds/templates/logs/contract-logs), the **same** raw-log extraction, but keyed by the event signature (`topic0`) instead of the emitting contract. Use it to index one event **across all contracts**: every `Transfer`, every `Approval`, every Uniswap `Swap`, typically scoped to a block range.
### What you get
One row per log, keyed by event signature. Same columns as Contract Logs, `topic0…topic3`, `data`, `contract_address`, `tx_hash`, and the `(block_number, transaction_index, log_index)` ordering tuple, but `topic0` leads the sort key so a chain-wide "all logs of this signature" read is a contiguous range.
### On-chain ordering
Every destination is keyed `topic0` first, then the on-chain tuple:
* **ClickHouse**: `ORDER BY (chain_id, topic0, block_number, transaction_index, log_index, …)`. `topic0` is low cardinality (one value per signature), so it's a cheap, highly selective leading key.
* **Postgres / MySQL**: a composite index on `(topic0, block_number, transaction_index, log_index)`; `WHERE topic0 = T AND block_number BETWEEN … ORDER BY …` is answered by an index range scan with no filesort.
Logs with an empty `topic0` (anonymous events) are filtered out, they have no signature to key on.
### Optional: scope to a contract (topic0 + contract)
The primary key leads with `topic0`, so "all `Transfer` logs emitted by contract X" prefix-scans to the signature and filters `contract_address` within it. Because a popular signature (`Transfer`, `Approval`) spans **millions of contracts**, an opt-in `(topic0, contract_address, …)` structure makes that read a tight `(topic0, contract)` range that stays sort-free *and* skips the signature's other contracts. Shipped **commented-out** in each schema:
| Destination | Optional structure |
| - | - |
| Postgres | `CREATE INDEX … (topic0, contract_address, block_number, transaction_index, log_index)` |
| MySQL | `ADD KEY (topic0, contract_address, block_number, transaction_index, log_index)` |
| ClickHouse | A `contract_address` `bloom_filter` skip-index (light), or a projection sorted by `(chain_id, topic0, contract_address, …)` (sort-free, heavier) |
### Destination
| Destination | Table | By-signature access |
| - | - | - |
| **ClickHouse** (first-class) | `fact_logs` | Prefix scan on `(chain_id, topic0, …)`; read with `FINAL` |
| **Postgres** | `topic_logs` | Composite index `(topic0, block_number, transaction_index, log_index)` |
| **MySQL** | `topic_logs` | Composite key `(topic0, block_number, transaction_index, log_index)` |
Same source and reorg model as Contract Logs (raw `block` array → `itemType = 'log'`, `tx_hash` recovered from the sibling transaction row; immutable append-only logs in a collapsing table).
### Full schema
Identical columns to [Contract Logs](/data-feeds/templates/logs/contract-logs#full-schema), the only difference is the sort key leads with `topic0`. Keep the columns you need (see [Schema & flexibility](/data-feeds/templates/overview#schema--flexibility)).
> [accordion] ClickHouse, fact\_logs (topic0-keyed)
>
> ```sql theme={null}
> CREATE TABLE recipe_logs_by_topic0.fact_logs
> (
> vendor_event_id String,
> ingested_at DateTime64(3),
> chain_id UInt32,
> block_hash String,
> block_number UInt64,
> transaction_index UInt32,
> log_index UInt32,
> event_ts DateTime64(3),
> tx_hash String,
> contract_address String,
> topic0 String,
> topic1 Nullable(String),
> topic2 Nullable(String),
> topic3 Nullable(String),
> data Nullable(String), -- raw ABI-encoded payload (hex)
> sign Int8
> )
> ENGINE = ReplicatedCollapsingMergeTree(
> '/clickhouse/tables/{database}/fact_logs', '{replica}', sign)
> PARTITION BY (chain_id, toYYYYMM(event_ts))
> ORDER BY (chain_id, topic0, block_number, transaction_index, log_index, vendor_event_id);
>
> -- OPTIONAL (commented out by default): accelerate "specific contract within a
> -- signature" reads. Enable at most one.
> -- (a) lightweight contract_address skip-index:
> -- ALTER TABLE recipe_logs_by_topic0.fact_logs
> -- ADD INDEX idx_contract contract_address TYPE bloom_filter GRANULARITY 4;
> -- (b) sort-free projection keyed (topic0, contract_address, …):
> -- ALTER TABLE recipe_logs_by_topic0.fact_logs
> -- ADD PROJECTION proj_topic0_contract
> -- (SELECT * ORDER BY (chain_id, topic0, contract_address, block_number, transaction_index, log_index));
> ```
>
> Postgres / MySQL mirror this as a flat `topic_logs` table keyed `(topic0, block_number, transaction_index, log_index)`, with the optional `(topic0, contract_address, …)` index commented out.
### Example reads
All logs of an event signature in a block range, in on-chain order (ClickHouse):
```sql theme={null}
SELECT block_number, transaction_index, log_index, contract_address,
tx_hash, topic1, topic2, topic3, data
FROM recipe_logs_by_topic0.fact_logs FINAL
WHERE chain_id = 1
AND topic0 = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'
AND block_number BETWEEN 18000000 AND 18010000
ORDER BY block_number, transaction_index, log_index
LIMIT 100;
```
### Modes
Shipped defaults: **ClickHouse `hybrid`**, **Postgres / MySQL `historical`**. For live/reorg-safe ingestion use ClickHouse.
> [!WARNING]
>
> A `topic0`-keyed sync is heavy for popular signatures, `Transfer` and `Approval` span the whole chain. Scope reads to a block range, and for chain-heavy backfills run the ClickHouse path.
### EVM only
Like Contract Logs, this extracts EVM event logs (`topic0…3` + `data`); Solana program logs are a different model.
### Related
> [card] [Contract Logs](/data-feeds/templates/logs/contract-logs)
>
> The sibling, every log from one contract, keyed by emitter.
> [card] [Onchain Event Indexing](/data-feeds/use-cases/event-indexing)
>
> The use case these raw-log templates power.
# Pair OHLCV
Source: https://docs.moralis.com/data-feeds/templates/markets/pair-ohlcv
Sync time-bucketed OHLCV candles, open, high, low, close, volume, and trade count per DEX pair, built by aggregating on-chain swaps, into your own database. Mirrors the Moralis GET /pairs/{address}/ohlcv endpoint.
### Question it answers
> "Give me 1-hour OHLCV candles for pool/pair **0x…**, open, high, low, close, volume, and trade count per hour." Mirrors Moralis `GET /pairs/{address}/ohlcv`.
Candles are built by **aggregating swaps**, not reported by an exchange. This template is a downstream aggregation on top of the same trade ingest as Swaps by Pair: the sync lands every trade once (USD-enriched in-block), then a candle surface buckets those trades into fixed **1-hour** candles per `(pool_address, hour)`. "Price" per fill is the bought-leg (token1) in-block USD price already on the trade (`price_usd`); `volume` is `sum(abs(notional_usd))` and `trades` is the fill count.
### What you get
One candle row per `(pool_address, bucket_start)`, where `bucket_start` is the start of a 1-hour window. Only **priced** trades (a same-block USD price update for the bought leg) contribute:
| Column | Description |
| - | - |
| `chain_id` | Chain the pool lives on |
| `pool_address` | The DEX pair / pool |
| `bucket_start` | Start of the 1-hour candle window |
| `open` | First trade's `price_usd` in the bucket (by `event_ts`, tiebroken by `vendor_event_id`) |
| `high` | `max(price_usd)` across the bucket |
| `low` | `min(price_usd)` across the bucket |
| `close` | Last trade's `price_usd` in the bucket |
| `volume` | `sum(abs(notional_usd))`: absolute traded USD over the bucket |
| `trades` | Count of priced fills in the bucket |
The candles sit on top of a trade fact table (`fact_swaps` / `swaps`) carrying every fill, `tx_hash`, `trader_address`, `token0/1_address`, `amount0/1`, `side`, `source_kind`, `protocol`, `price_usd`, `notional_usd`, so you can drop to the underlying trades whenever you need detail behind a candle.
### Source
The trade ingest is identical to Swaps by Pair: two projection branches expand the per-block swap arrays into one row per fill:
`tokenSwaps` (pool fills) · `aggregateTokenSwaps` (aggregator routes)
Each fill is USD-enriched **inline** from the same block's `tokenPriceUpdates` (reversed so the chronologically-last update wins on duplicate keys), no separate price join at read time. The candle surface then aggregates these priced fills by hour.
### Destination
| Destination | Trade table | Candle surface | Read pattern |
| - | - | - | - |
| **ClickHouse** (first-class) | `fact_swaps` | `candles` (VIEW over `candles_agg`); `candles_exact` (reorg-exact) | Prefix scan on `(chain_id, pool_address, bucket_start)` |
| **Postgres** | `swaps` | `candles` (always-fresh VIEW) + `candles_mat` (REFRESHable matview) | Index on `(pool_address, bucket_start DESC)` |
| **MySQL** | `swaps` | `candles` (always-fresh VIEW) | Index on `(pool_address, block_timestamp)` |
ClickHouse uses the collapsing log-table pattern (see the [templates overview](/data-feeds/templates/overview#destinations)) so chain reorganizations self-correct. Two candle surfaces ship on ClickHouse: `candles` is a low-latency accelerator backed by an `AggregatingMergeTree` that is sign-aware for additive measures, and `candles_exact` reads `fact_swaps FINAL` for always-exact OHLC. On Postgres/MySQL the `candles` VIEW aggregates `swaps` at read time and is correct the moment a backfill lands.
### Full schema
Below are the trade fact table and the candle surfaces this template produces. The candle columns are a fixed shape (`open`/`high`/`low`/`close`/`volume`/`trades`); the underlying trade table is the wider starting point, keep the columns you need (see [Schema & flexibility](/data-feeds/templates/overview#schema--flexibility)). Raw `uint256` amounts are stored as text on ClickHouse and `NUMERIC(76,0)` on Postgres (they exceed standard numeric precision); USD columns are wide decimals so a low-decimals token × price never overflows.
> [accordion] ClickHouse, fact\_swaps + candles
>
> ```sql theme={null}
> -- Trade fact: one row per fill, sign-carrying for reorg collapse.
> CREATE TABLE recipe_pair_ohlcv.fact_swaps
> (
> vendor_event_id String,
> ingested_at DateTime64(3),
> chain_id UInt32,
> block_hash String,
> block_number UInt64,
> event_ts DateTime64(3),
> pool_address String, -- pair (pool_fill) or aggregator
> token0_address String,
> token1_address String,
> amount0 String, -- raw uint256
> amount1 String, -- raw uint256
> trader_address String,
> price_usd Nullable(String), -- bought-leg (token1) USD price
> notional_usd Nullable(String), -- signed token1 amount × price
> side LowCardinality(String), -- buy | sell
> source_kind LowCardinality(String), -- aggregator | pool_fill
> protocol LowCardinality(String),
> sign Int8
> )
> ENGINE = ReplicatedCollapsingMergeTree(
> '/clickhouse/tables/{database}/fact_swaps', '{replica}', sign)
> PARTITION BY (chain_id, toYYYYMM(event_ts))
> ORDER BY (chain_id, pool_address, event_ts, vendor_event_id);
>
> -- Candle accelerator: one state-row per (chain, pool, hour).
> -- Additive measures are sign-weighted so reorg −1 rows subtract cleanly.
> CREATE TABLE recipe_pair_ohlcv.candles_agg
> (
> chain_id UInt32,
> pool_address String,
> bucket_start DateTime, -- toStartOfHour(event_ts)
> open_state AggregateFunction(argMin, Float64, DateTime64(3)),
> high_state AggregateFunction(max, Float64),
> low_state AggregateFunction(min, Float64),
> close_state AggregateFunction(argMax, Float64, DateTime64(3)),
> volume_state AggregateFunction(sum, Float64),
> trades_state AggregateFunction(sum, Int64)
> )
> ENGINE = ReplicatedAggregatingMergeTree(
> '/clickhouse/tables/{database}/candles_agg', '{replica}')
> PARTITION BY (chain_id, toYYYYMM(bucket_start))
> ORDER BY (chain_id, pool_address, bucket_start);
>
> -- candles VIEW: finalizes the aggregate state to scalars (the fast surface).
> CREATE VIEW recipe_pair_ohlcv.candles AS
> SELECT
> chain_id,
> pool_address,
> bucket_start,
> argMinMerge(open_state) AS open,
> maxMerge(high_state) AS high,
> minMerge(low_state) AS low,
> argMaxMerge(close_state) AS close,
> sumMerge(volume_state) AS volume,
> sumMerge(trades_state) AS trades
> FROM recipe_pair_ohlcv.candles_agg
> GROUP BY chain_id, pool_address, bucket_start
> HAVING trades > 0;
>
> -- candles_exact VIEW: reorg-EXACT — FINAL collapses each +1/−1 pair before
> -- aggregating, so OHLC reflects only canonical trades. Slower; use after a reorg
> -- may have retracted an hour's all-time high/low.
> CREATE VIEW recipe_pair_ohlcv.candles_exact AS
> SELECT
> chain_id,
> pool_address,
> toStartOfHour(event_ts) AS bucket_start,
> argMin(toFloat64OrZero(price_usd), event_ts) AS open,
> max(toFloat64OrZero(price_usd)) AS high,
> min(toFloat64OrZero(price_usd)) AS low,
> argMax(toFloat64OrZero(price_usd), event_ts) AS close,
> sum(abs(toFloat64OrZero(notional_usd))) AS volume, -- absolute traded USD
> count() AS trades
> FROM recipe_pair_ohlcv.fact_swaps FINAL
> WHERE price_usd IS NOT NULL AND price_usd != ''
> GROUP BY chain_id, pool_address, bucket_start;
> ```
>
> The `sign` column on `fact_swaps` drives reorg collapsing. `candles` is the low-latency accelerator; `candles_exact` is always reorg-exact (see fidelity gaps). A single-node setup can use the non-replicated engines (`CollapsingMergeTree(sign)`, `AggregatingMergeTree`) without the replication path.
> [accordion] Postgres, swaps + candles
>
> ```sql theme={null}
> -- Flat one-row-per-trade landing table (the Swaps by Pair ingest).
> CREATE TABLE public.swaps (
> position BIGINT NOT NULL,
> log_index BIGINT, -- NULL for aggregator rows
> transaction_index BIGINT,
> block_number BIGINT NOT NULL,
> block_timestamp BIGINT NOT NULL, -- unix seconds
> tx_hash TEXT NOT NULL,
> vendor_event_id TEXT NOT NULL,
> trader_address TEXT NOT NULL,
> pool_address TEXT NOT NULL, -- pair (pool_fill) or aggregator
> token0_address TEXT NOT NULL,
> token1_address TEXT NOT NULL,
> amount0 NUMERIC(76, 0) NOT NULL,
> amount1 NUMERIC(76, 0) NOT NULL,
> price_usd NUMERIC(38, 18),
> notional_usd NUMERIC(38, 18),
> side TEXT NOT NULL,
> source_kind TEXT NOT NULL, -- aggregator | pool_fill
> protocol TEXT NOT NULL
> );
>
> -- Candle aggregation reads pool_address + block_timestamp.
> CREATE INDEX swaps_pool_ts_idx ON public.swaps (pool_address, block_timestamp);
> CREATE INDEX swaps_block_idx ON public.swaps (block_number);
>
> -- candles: always-fresh 1-hour OHLCV VIEW (the read surface).
> -- Only priced trades participate; open/close use the array_agg-ORDER-BY idiom.
> CREATE VIEW public.candles AS
> SELECT
> pool_address,
> date_trunc('hour', to_timestamp(block_timestamp)) AS bucket_start,
> (array_agg(price_usd ORDER BY block_timestamp ASC, vendor_event_id ASC))[1] AS open,
> max(price_usd) AS high,
> min(price_usd) AS low,
> (array_agg(price_usd ORDER BY block_timestamp DESC, vendor_event_id DESC))[1] AS close,
> sum(abs(notional_usd)) AS volume, -- absolute traded USD
> count(*) AS trades
> FROM public.swaps
> WHERE price_usd IS NOT NULL
> GROUP BY pool_address, date_trunc('hour', to_timestamp(block_timestamp));
>
> -- OPTIONAL accelerator: a REFRESHable matview when read-time aggregation gets
> -- expensive. Refresh on a schedule (cron / pg_cron) after the backfill lands.
> -- CREATE MATERIALIZED VIEW public.candles_mat AS
> -- SELECT * FROM public.candles WITH NO DATA;
> -- CREATE UNIQUE INDEX candles_mat_pk ON public.candles_mat (pool_address, bucket_start);
> -- SELECT public.refresh_candles(); -- REFRESH MATERIALIZED VIEW CONCURRENTLY
> ```
>
> MySQL is the same shape with `DECIMAL(38,18)` for the USD columns and `DECIMAL(76,0)` for raw amounts, and ships the `candles` VIEW only. `position` is the block-level cursor used during backfill. To change the bucket interval, swap `date_trunc('hour', …)` (and the ClickHouse `toStartOfHour` / partition expression) for your target window.
### Example reads
Newest 24 hourly candles for one pool (ClickHouse, fast accelerator):
```sql theme={null}
SELECT bucket_start, open, high, low, close, volume, trades
FROM recipe_pair_ohlcv.candles
WHERE chain_id = 1
AND pool_address = lower('0x88e6A0c2dDD26FEEb64F039a2c41296FcB3f5640') -- USDC/WETH 0.05% v3
ORDER BY bucket_start DESC
LIMIT 24;
```
Same window, reorg-exact (collapses +1/−1 pairs via `FINAL` before aggregating):
```sql theme={null}
SELECT bucket_start, open, high, low, close, volume, trades
FROM recipe_pair_ohlcv.candles_exact
WHERE chain_id = 1
AND pool_address = lower('0x88e6A0c2dDD26FEEb64F039a2c41296FcB3f5640')
ORDER BY bucket_start DESC
LIMIT 24;
```
Sanity-check OHLC ordering across every candle (should return 0):
```sql theme={null}
SELECT count() FROM recipe_pair_ohlcv.candles
WHERE NOT (low <= open AND low <= close AND open <= high AND close <= high
AND volume > 0 AND trades > 0);
```
On Postgres / MySQL the `candles` VIEW reads the same way, keyed on `pool_address`:
```sql theme={null}
SELECT pool_address, bucket_start, open, high, low, close, volume, trades
FROM candles
WHERE pool_address = lower('0x88e6A0c2dDD26FEEb64F039a2c41296FcB3f5640')
ORDER BY bucket_start DESC
LIMIT 24;
```
### Modes
Shipped defaults: **ClickHouse `hybrid`** (backfill → realtime), **Postgres / MySQL `historical`** (one-shot backfill). For live/reorg-safe ingestion, use ClickHouse, see the [overview](/data-feeds/templates/overview#modes).
> [!NOTE]
>
> **Realtime on Postgres / MySQL is not supported for this shape.** The realtime reorg path needs a single-column unique on the block-level position, but trades are array-expanded (many per block), so these tables can only carry a composite unique. Run realtime/hybrid on ClickHouse, where the collapsing log table corrects reorgs per-block and the candle accelerator is sign-aware. The Postgres/MySQL configs are intended for `historical` backfill, re-run the backfill (and `REFRESH` the candle matview) to pick up corrections.
### Multichain
The template is chain-parametrized, point it at any supported EVM chain or Solana, and the candle math is chain-agnostic. On Solana, the same `logIndex` can repeat across events in one instruction, so the pool-fill event identity is widened (with `token0Address`, `token1Address`, `token0Amount`) to keep trade rows distinct; the candle surface it produces is identical in shape.
### Fidelity gaps
* **Fixed 1-hour interval (v1).** Moralis' `/pairs/{address}/ohlcv` takes a `timeframe` param (1m/5m/1h/1d/…); this template ships a single fixed **1-hour** bucket. For other intervals, change the bucket expression (`toStartOfHour` / `date_trunc('hour', …)` / the MySQL modulus) to your target window.
* **Trade-reconstructed, not exchange-reported.** Candles are built from on-chain swap fills, so they may differ slightly from a DEX's own reported OHLC (which can apply off-chain smoothing or a different price reference). No off-chain smoothing is applied.
* **Price = bought-leg in-block USD; no carry-forward.** A candle only includes trades whose bought-leg token had a same-block `tokenPriceUpdate`. Thin/illiquid pools with no in-block price update in an hour produce **no candle for that hour** (a gap), rather than a flat carry-forward candle. Dense pools (the majority of volume) are unaffected.
* **ClickHouse `candles` high/low under reorg.** The fast accelerator's `high`/`low` are monotonic state functions; a reorg `−1` row cannot retract an extreme, so if a reorg removes an hour's all-time high/low, `candles` may stay slightly wide until the next canonical trade re-establishes the range. Read **`candles_exact`** when post-reorg precision matters. `volume` and `trades` are sign-weighted and always exact on both surfaces.
* **`volume` is absolute traded USD.** `notional_usd` carries the **signed** token1 delta (V3/V4 report signed swap amounts, negative when the token leaves the pool), so `volume` uses `abs(notional_usd)` (×reorg-sign on ClickHouse), otherwise buy/sell legs cancel and volume goes negative. This is the canonical OHLCV "traded value" definition.
* **Missing-decimals volume outliers.** A handful of exotic tokens arrive with `token1` decimals absent/0 (coalesced to 0 in the shared swap transform); their raw amount isn't decimal-scaled and `notional_usd` is wildly inflated, producing an implausibly large candle `volume`. OHLC prices are unaffected (they use per-unit `price_usd`). Filter `volume < 1e12` for a clean volume distribution; a production deployment should source token decimals from a metadata table rather than the in-event field.
## Migrating from the REST API
This template replaces the pair-OHLCV REST endpoint, and it's the closest to 1:1 in the swaps family: the shipped candle surface mirrors the endpoint at a 1-hour timeframe, and because the underlying `swaps` table is trade-level, any other timeframe is a `GROUP BY` you own rather than a fixed parameter. Fidelity labels: **exact** = straight from the chain, **calculated** = aggregated from real DEX trades (very close, compare with a tolerance).
### GET /pairs/:address/ohlcv
Candlestick data for a pool/pair. Replaced by this template's `candles` surface for 1-hour candles, or a bucket query over `swaps` for any other timeframe.
| `/pairs/:address/ohlcv` | Data Feeds | Fidelity |
| - | - | - |
| `timestamp` | `candles.bucket_start` / your time bucket | exact |
| `open`, `high`, `low`, `close` | first / max / min / last `price_usd` in the bucket | calculated |
| `volume` | `sum(abs(notional_usd))` | calculated |
| `trades` | count of priced fills in the bucket | exact |
| `pairAddress` | `pool_address` | exact |
| `tokenAddress` (priced leg) | the bought leg (`token1`), priced in USD | exact |
| `timeframe`, `currency` | your `GROUP BY` bucket + price leg | your choice |
The REST `timeframe` parameter becomes the bucket expression. A 5-minute example over `swaps` (Postgres, use 60 / 3600 / 86400 for 1m / 1h / 1d):
```sql theme={null}
SELECT
to_timestamp(floor(block_timestamp / 300) * 300) AS timestamp,
(array_agg(price_usd ORDER BY block_timestamp, vendor_event_id))[1] AS open,
max(price_usd) AS high,
min(price_usd) AS low,
(array_agg(price_usd ORDER BY block_timestamp DESC, vendor_event_id DESC))[1] AS close,
sum(abs(notional_usd)) AS volume, -- abs: notional is signed on V3/V4
count(*) AS trades
FROM swaps
WHERE pool_address = lower($1)
AND price_usd IS NOT NULL
AND block_timestamp BETWEEN $2 AND $3
GROUP BY 1
ORDER BY 1;
```
**Gotchas**
* OHLC is trade-reconstructed, not exchange-reported, it tracks the old endpoint closely, but compare with a tolerance rather than expecting identical figures.
* The REST `currency` parameter has no direct analog: candles here are priced in the bought leg's in-block USD price, so be explicit about which token the OHLC is quoted in.
* Thinly-traded pairs produce sparse candles, gaps where no priced trade occurred, not flat carry-forward candles (see [Fidelity gaps](#fidelity-gaps)).
* `volume` must be `sum(abs(notional_usd))`, the notional is signed on V3/V4 pools, so a plain `sum` lets buy and sell legs cancel.
* For live charts, run the template `realtime` on ClickHouse and read `candles` (or `candles_exact` after a reorg); for historical candles back to a date, backfill `historical` / `hybrid` from that date, no need to index from genesis. See [History & backfill](/data-feeds/concepts/history-and-backfill).
### Related
> [card] [Swaps by Pair](/data-feeds/templates/markets/swaps-by-pair)
>
> The per-trade ingest these candles aggregate, every fill on a pair.
> [card] [Trading & Charting](/data-feeds/use-cases/trading-charting)
>
> The use case OHLCV candles power.
# Pair Reserves
Source: https://docs.moralis.com/data-feeds/templates/markets/pair-reserves
Sync the current reserve0 / reserve1 of any DEX pair, the pool's absolute token balances, kept latest-wins per pair, into your own database. Mirrors the Moralis GET /{pair_address}/reserves endpoint.
### Question it answers
> "What are the current `reserve0` / `reserve1` of DEX pair **0x…**?"
Mirrors Moralis `GET /{pair_address}/reserves` → `{ reserve0, reserve1 }`. The template lands the pool's absolute token balances and keeps the **latest observation per pair**, so a single read returns each pair's current reserves.
### What you get
The template lands **one observation per swap**, the pool's absolute token balances captured *after* each trade, and the current reserves of a pair are the highest-`(block_number, log_index)` observation for that pair:
| Column | Description |
| - | - |
| `pair_address` | The DEX pair (pool) the reserves belong to |
| `token0_address`, `token1_address` | The pool's two token sides |
| `reserve0` | Pool's absolute `token0` balance after the swap (raw `uint256`, as text) |
| `reserve1` | Pool's absolute `token1` balance after the swap (raw `uint256`, as text) |
| `block_number`, `log_index` | Recency key, the latest pair wins |
| `event_ts` / `block_timestamp` | Block time of the observation |
These are **absolute snapshots, not deltas**, no running sum, no pre-window baseline, no genesis requirement. The latest snapshot in any window is the answer (**window-safe**).
### Source
The faithful source for reserves is `tokenSwaps`. Each swap carries `token0PostBalance` / `token1PostBalance`, the pool's absolute balances after the trade, which are exactly the pair's reserves. The transform projects one reserve observation per swap, keyed by pair.
`pairLiquidityChanges` is **not** used: it only fires on add/remove liquidity, so a running sum of its deltas misses all swap-driven reserve movement and is window-relative. Aggregated swaps are also not used, they carry an aggregator address, not a `pair_address`, so their post-balances can't be attributed to a specific pool.
### Destination
| Destination | Table | By-pair access |
| - | - | - |
| **ClickHouse** (first-class) | `fact_pair_reserves` | `argMax(reserveN, (block_number, log_index))` per pair over `FINAL` |
| **Postgres** | `pair_reserves` (materialized view over `pair_reserve_observations`) | Unique index `(pair_address)` |
| **MySQL** | `pair_reserves` (trigger-maintained over `pair_reserve_observations`) | Primary key `(pair_address)` |
ClickHouse uses the collapsing log-table pattern (see the [templates overview](/data-feeds/templates/overview#destinations)) so chain reorganizations self-correct: a reorg negates the rolled-back block's observations (`sign = -1`) and re-emits the corrected ones. Read with `FINAL` to collapse the `±1` pair, then `argMax` to pick the latest observation, never a bare `WHERE sign = 1`.
Postgres and MySQL append append-only observations and derive a **latest-wins** current-reserves surface per pair: Postgres via a `DISTINCT ON (pair_address) … ORDER BY block_number DESC, log_index DESC` materialized view, MySQL via an `AFTER INSERT` upsert trigger.
### Full schema
The ClickHouse fact table is the per-pair observation table; the current reserves are an `argMax` over it. Reserves are raw `uint256` stored as text (matching the API's string reserves), `argMax` over text ordered by the numeric recency key is exact. Keep the columns you need (see [Schema & flexibility](/data-feeds/templates/overview#schema--flexibility)).
> [accordion] ClickHouse, fact\_pair\_reserves
>
> ```sql theme={null}
> CREATE TABLE recipe_pair_reserves.fact_pair_reserves
> (
> vendor_event_id String,
> ingested_at DateTime64(3),
> chain_id UInt32,
> block_hash String,
> block_number UInt64,
> log_index UInt32,
> event_ts DateTime64(3),
> pair_address String,
> token0_address String,
> token1_address String,
> reserve0 String, -- absolute pool reserve0 after this swap
> reserve1 String,
> sign Int8
> )
> ENGINE = ReplicatedCollapsingMergeTree(
> '/clickhouse/tables/{database}/fact_pair_reserves', '{replica}', sign)
> PARTITION BY (chain_id, toYYYYMM(event_ts))
> ORDER BY (chain_id, pair_address, block_number, log_index, vendor_event_id);
> ```
>
> The `sign` column drives reorg collapsing, read with `FINAL` then `argMax`. A single-node setup can use `CollapsingMergeTree(sign)` without the replication path.
> [accordion] Postgres, pair\_reserves
>
> ```sql theme={null}
> -- 1. Observations (sink target): one raw row per swap.
> CREATE TABLE public.pair_reserve_observations (
> position BIGINT NOT NULL,
> log_index BIGINT NOT NULL,
> block_number BIGINT NOT NULL,
> block_timestamp BIGINT NOT NULL, -- unix seconds
> pair_address TEXT NOT NULL,
> token0_address TEXT NOT NULL,
> token1_address TEXT NOT NULL,
> reserve0 NUMERIC(76, 0) NOT NULL, -- absolute pool reserve0 post-swap
> reserve1 NUMERIC(76, 0) NOT NULL,
> vendor_event_id TEXT NOT NULL
> );
>
> -- Speeds the DISTINCT ON (latest-per-pair) the materialized view computes.
> CREATE INDEX IF NOT EXISTS pro_pair_recency_idx
> ON public.pair_reserve_observations
> (pair_address, block_number DESC, log_index DESC);
>
> -- 2. Current-reserves materialized view: latest observation per pair.
> CREATE MATERIALIZED VIEW public.pair_reserves AS
> SELECT DISTINCT ON (pair_address)
> pair_address,
> token0_address,
> token1_address,
> reserve0,
> reserve1,
> block_number,
> log_index,
> block_timestamp
> FROM public.pair_reserve_observations
> ORDER BY pair_address, block_number DESC, log_index DESC;
>
> -- Required by REFRESH MATERIALIZED VIEW CONCURRENTLY and the by-pair lookup.
> CREATE UNIQUE INDEX IF NOT EXISTS pair_reserves_pk
> ON public.pair_reserves (pair_address);
> ```
>
> MySQL is the same shape: an append-only `pair_reserve_observations` table plus a `pair_reserves` table kept current by an `AFTER INSERT` latest-wins upsert trigger, with `reserve0` / `reserve1` as `DECIMAL(65,0)`. `position` is the block-level cursor used during backfill.
### Example reads
Current reserves of a pair, latest observation; `FINAL` collapses reorg `±1` pairs before `argMax` (ClickHouse):
```sql theme={null}
SELECT pair_address,
argMax(token0_address, (block_number, log_index)) AS token0,
argMax(token1_address, (block_number, log_index)) AS token1,
argMax(reserve0, (block_number, log_index)) AS reserve0,
argMax(reserve1, (block_number, log_index)) AS reserve1
FROM recipe_pair_reserves.fact_pair_reserves FINAL
WHERE chain_id = 1 AND pair_address = lower('0x...')
GROUP BY pair_address;
```
Largest pools by latest `reserve0` (ClickHouse):
```sql theme={null}
SELECT pair_address,
argMax(reserve0, (block_number, log_index)) AS reserve0
FROM recipe_pair_reserves.fact_pair_reserves FINAL
WHERE chain_id = 1
GROUP BY pair_address
ORDER BY toFloat64OrZero(reserve0) DESC
LIMIT 100;
```
Postgres, refresh the view, then look up the pair:
```sql theme={null}
REFRESH MATERIALIZED VIEW CONCURRENTLY pair_reserves;
SELECT reserve0, reserve1 FROM public.pair_reserves
WHERE pair_address = lower('0x...');
```
### Modes
Shipped defaults: **ClickHouse `hybrid`** (backfill → realtime), **Postgres / MySQL `historical`** (one-shot backfill). For live/reorg-safe ingestion, use ClickHouse, see the [overview](/data-feeds/templates/overview#modes).
> [!NOTE]
>
> The Postgres / MySQL realtime reorg path needs a single-column `UNIQUE` on the position column, but `position` is block-level. Run **realtime / hybrid on ClickHouse** (the collapsing log table corrects reorgs per block); the Postgres / MySQL configs target `historical` backfill and re-derive their current-reserves surface on refresh.
### Multichain
The template is chain-parametrized via the `chain` setting, point it at any supported EVM chain or Solana. On Solana, the event identity already folds in `(pair_address, token0PostBalance, token1PostBalance)` on top of `(transaction_hash, log_index)`, so it stays row-unique despite Solana's repeated log indices within an instruction.
### Fidelity gaps
* **Only pairs with a swap in-window get current reserves.** Reserves are read from swap post-balances, so a pair appears only if it had at least one swap with resolved post-balances in the ingested window. A pool that is quiet (no swaps) for the whole window won't be present, but quiet pools have unchanged reserves by definition, so widening the window picks them up.
* **Swaps without resolved post-balances are skipped.** `token0PostBalance` / `token1PostBalance` are nullable; rows where either is null/empty, or where the swap has no pair address, are filtered out.
* **V4 pair addresses** arrive as `poolId_0xaddress` (\~109 chars) and are stored **raw** for a key that's consistent across destinations. MySQL caps `pair_address` at `VARCHAR(160)`; Postgres `TEXT` and ClickHouse `String` are unbounded.
* **MySQL precision ceiling.** MySQL `DECIMAL(65,0)` cannot represent a full 78-digit `uint256`, though no real reserve approaches that magnitude. Postgres (`NUMERIC(76,0)`) and ClickHouse (`String`) carry the larger range.
### Related
> [card] [Swaps by Pair](/data-feeds/templates/markets/swaps-by-pair)
>
> Every DEX trade for a pair, the same swap stream these reserves derive from.
> [card] [Pair OHLCV](/data-feeds/templates/markets/pair-ohlcv)
>
> Per-pair price candles for charting.
# Swaps by Pair
Source: https://docs.moralis.com/data-feeds/templates/markets/swaps-by-pair
Sync every DEX trade on a pool/pair, direct pool fills and aggregator-routed trades, USD-enriched in-block, keyed by pool address so a pair's trade feed is a prefix scan, into your own database.
### Question it answers
> "Give me every DEX trade on pool/pair **0x…**, newest first, each row is one trade with both token legs, the side, the protocol, and a USD notional."
Same trade projection as [Swaps by Token](/data-feeds/templates/markets/swaps-by-token), but keyed by the **pool/pair address** with **one row per trade** (no per-token-side unpivot). `pool_address` is the **pair address** for direct pool fills and the **aggregator address** for aggregator-routed trades.
### What you get
One row per trade, keyed by `pool_address`:
| Column | Description |
| - | - |
| `pool_address` | Pair address (pool fills) or aggregator address (aggregator-routed trades) |
| `token0_address`, `token1_address` | The pair's two tokens |
| `amount0`, `amount1` | Raw token-unit deltas for each leg (`uint256` as text) |
| `side` | `buy` · `sell`, derived from the base token's pool-balance delta |
| `source_kind` | `pool_fill` (direct pool) · `aggregator` (aggregator-routed) |
| `price_usd` | Bought-leg (`token1`) USD price; `NULL` with no in-block price update |
| `notional_usd` | `token1Amount / 10^token1Decimals × price_usd`; `NULL` if unpriced |
| `protocol` | DEX/protocol identifier |
| `fee_amount`, `fee_token`, `fee_usd` | Trade fee, pool fills only (`NULL` on aggregator rows) |
| `trader_address` | The trading wallet |
| `block_number`, `event_ts`, `tx_hash`, `vendor_event_id` | On-chain ordering and identity |
### Source
The transform reads two per-block trade arrays and projects them into one feed:
`tokenSwaps` (direct pool fills, `source_kind='pool_fill'`, `pool_address = pairAddress`) · `aggregateTokenSwaps` (aggregator-routed trades, `source_kind='aggregator'`, `pool_address = aggregatorAddress`)
The two branches are disjoint by construction, together they give every fill exactly once. USD values are computed **inline** from the same block's `tokenPriceUpdates` (the chronologically-last update wins on duplicate keys), no separate price join at read time.
### Destination
| Destination | Table | By-pair access |
| - | - | - |
| **ClickHouse** (first-class) | `fact_swaps_by_pair` | Prefix scan on `(chain_id, pool_address, event_ts, …)`; read with `FINAL` or `sum(sign)` |
| **Postgres** | `swaps` | Index lead `(pool_address, block_number DESC)` |
| **MySQL** | `swaps` | Index lead `(pool_address, block_number)` |
ClickHouse uses the collapsing log-table pattern (see the [templates overview](/data-feeds/templates/overview#destinations)) so chain reorganizations self-correct, the `+1/−1` reorg pair for a trade shares an identical key and collapses cleanly. The fact table's sort key is pool-first, so a pair's full trade feed is a contiguous range read.
### Full schema
The complete read table this template produces, one row per trade. Keep the columns you need and drop the rest (see [Schema & flexibility](/data-feeds/templates/overview#schema--flexibility)). Raw `uint256` amounts are stored as text in ClickHouse (they exceed numeric precision); USD columns are nullable so an unpriced token leaves them empty.
> [accordion] ClickHouse, fact\_swaps\_by\_pair
>
> ```sql theme={null}
> CREATE TABLE recipe_swaps_by_pair.fact_swaps_by_pair
> (
> vendor_event_id String,
> ingested_at DateTime64(3),
> chain_id UInt32,
> block_hash String,
> block_number UInt64,
> event_ts DateTime64(3),
> pool_address String, -- pair (pool_fill) or aggregator
> token0_address String,
> token1_address String,
> amount0 String, -- raw uint256
> amount1 String, -- raw uint256
> trader_address String,
> price_usd Nullable(String),
> notional_usd Nullable(String),
> side LowCardinality(String), -- buy | sell
> source_kind LowCardinality(String), -- aggregator | pool_fill
> protocol LowCardinality(String),
> fee_amount Nullable(String),
> fee_token Nullable(String),
> fee_usd Nullable(String),
> sign Int8
> )
> ENGINE = ReplicatedCollapsingMergeTree(
> '/clickhouse/tables/{database}/fact_swaps_by_pair', '{replica}', sign)
> PARTITION BY (chain_id, toYYYYMM(event_ts))
> ORDER BY (chain_id, pool_address, event_ts, vendor_event_id);
> ```
>
> The `sign` column drives reorg collapsing, read with `FINAL` or `sum(sign)`, never a bare `WHERE sign=1`. A single-node setup can use `CollapsingMergeTree(sign)` without the replication path.
> [accordion] Postgres, swaps
>
> ```sql theme={null}
> CREATE TABLE public.swaps (
> position BIGINT NOT NULL,
> log_index BIGINT, -- NULL for aggregator rows
> transaction_index BIGINT,
> block_number BIGINT NOT NULL,
> block_timestamp BIGINT NOT NULL, -- unix seconds
> tx_hash TEXT NOT NULL,
> vendor_event_id TEXT NOT NULL,
> trader_address TEXT NOT NULL,
> pool_address TEXT NOT NULL, -- pair (pool_fill) or aggregator
> token0_address TEXT NOT NULL,
> token1_address TEXT NOT NULL,
> amount0 NUMERIC(76, 0) NOT NULL,
> amount1 NUMERIC(76, 0) NOT NULL,
> price_usd NUMERIC(38, 18),
> notional_usd NUMERIC(38, 18),
> side TEXT NOT NULL,
> source_kind TEXT NOT NULL, -- aggregator | pool_fill
> protocol TEXT NOT NULL,
> fee_amount NUMERIC(76, 0),
> fee_token TEXT,
> fee_usd NUMERIC(38, 18)
> );
>
> -- By-pair access (the template's primary purpose).
> CREATE INDEX IF NOT EXISTS swaps_pool_block_idx
> ON public.swaps (pool_address, block_number DESC);
> -- Token + trader + block-range helpers.
> CREATE INDEX IF NOT EXISTS swaps_token0_block_idx
> ON public.swaps (token0_address, block_number DESC);
> CREATE INDEX IF NOT EXISTS swaps_token1_block_idx
> ON public.swaps (token1_address, block_number DESC);
> CREATE INDEX IF NOT EXISTS swaps_trader_block_idx
> ON public.swaps (trader_address, block_number DESC);
> CREATE INDEX IF NOT EXISTS swaps_block_idx
> ON public.swaps (block_number);
> ```
>
> MySQL is the same shape with `DECIMAL(38,18)` for the USD columns. Amounts use `NUMERIC(76,0)` so large raw `uint256` balances never overflow. `position` is the block-level cursor used during backfill.
### Example reads
All trades on a pool/pair, newest first (ClickHouse):
```sql theme={null}
SELECT event_ts, side, source_kind, token0_address, token1_address,
amount0, amount1, notional_usd, protocol
FROM recipe_swaps_by_pair.fact_swaps_by_pair FINAL
WHERE chain_id = 1
AND pool_address = lower('0x88e6A0c2dDD26FEEb64F039a2c41296FcB3f5640')
ORDER BY event_ts DESC
LIMIT 50;
```
24h USD volume per pool (sign-aware, cheaper than `FINAL`):
```sql theme={null}
SELECT pool_address,
sumIf(toFloat64OrZero(notional_usd), sign = 1)
- sumIf(toFloat64OrZero(notional_usd), sign = -1) AS volume_usd
FROM recipe_swaps_by_pair.fact_swaps_by_pair
WHERE chain_id = 1 AND event_ts >= now() - INTERVAL 1 DAY
GROUP BY pool_address
ORDER BY volume_usd DESC
LIMIT 25;
```
Postgres / MySQL:
```sql theme={null}
SELECT block_number, side, source_kind, token0_address, token1_address,
amount0, amount1, notional_usd, protocol
FROM swaps
WHERE pool_address = lower('0x88e6...')
ORDER BY block_number DESC
LIMIT 50;
```
### Modes
Shipped defaults: **ClickHouse `hybrid`** (backfill → realtime), **Postgres / MySQL `historical`** (one-shot backfill). For live/reorg-safe ingestion use ClickHouse, see the [overview](/data-feeds/templates/overview#modes).
> [!NOTE]
>
> The realtime reorg path needs a single-column `UNIQUE` on the position column, but `position` is block-level (many trades per block), so array-expanded trade rows can only carry a composite unique. Run realtime/hybrid on **ClickHouse** (the log table corrects reorgs per-block via the collapsing companion table); the Postgres / MySQL configs are intended for `historical` backfill.
### Multichain
The template is chain-parametrized, point it at any supported EVM chain or Solana. On Solana, the same `logIndex` can be assigned to multiple events in one instruction, so for production the pool-fill event identity is widened with `(token0_address, token1_address, token0_amount)` to keep rows distinct; the trade feed it produces is identical in shape.
### How much data does this consume?
This template's exact selection has not been measured end to end yet. The closest measured scope: on **Solana mainnet**, a continuous real-time feed of `tokenSwaps` plus `tokenPriceUpdates` (plus the negligible `launchpadEvents` slice) measured **\~250 GB** in a typical month and **\~330 GB** in a busy one (measured 2026-08-04, 30 sampled partitions, `metered` delivery, uncompressed bytes).
This template additionally reads `aggregateTokenSwaps`, so expect a somewhat larger figure than that band. Three caveats:
* **Real-time only.** A historical backfill is billed separately and is usually the larger number; its size depends entirely on how far back you go.
* **Solana only.** Volume concentrates hard per chain, so this figure does not extrapolate to other chains.
* **Filtering does not reduce it.** Restricting to specific pairs or tokens happens after the data is delivered. To reduce cost, narrow the **block range**, not the entity set.
If you want your exact scope measured before you commit to a plan, [reach out](https://admin.moralis.com/data-feeds) and we will probe it against the live feed rather than estimate it.
### Fidelity gaps
* **`price_usd` / `notional_usd` / `fee_usd` are `NULL`** when the relevant token had no in-block `tokenPriceUpdate` (illiquid or brand-new tokens). The template enriches only from same-block price updates, there is no cross-block carry-forward.
* **`fee_*` is populated for pool fills only.** Aggregator-routed trades carry no per-fill fee, so `fee_amount` / `fee_token` / `fee_usd` are `NULL` on `source_kind='aggregator'` rows.
* **One trade can appear under two `pool_address` values** when it is observed both as a direct pool fill (the pair address) and as part of an aggregator route (the aggregator address). These are distinct events with distinct `vendor_event_id`s by design, the two source arrays are disjoint per event.
## Migrating from the REST API
This template supplies the volume leg of the token-pairs REST endpoint. That endpoint composes a pool registry with live numbers, so there is **no 1:1 replacement**, you land the pieces and join them in one view. Fidelity labels: **exact** = straight from the chain, **calculated** = derived from real DEX trades (very close, compare with a tolerance), **add yourself** = off-chain signal not in the feed.
### GET /erc20/:token\_address/pairs
Lists every DEX pool that trades a token, with price, liquidity, and 24h volume per pool. The pool list itself comes through exactly from a purpose-built registry; the live figures are computed from the same onchain trades the old endpoint uses.
> [!WARNING]
>
> This endpoint needs a **combination of templates**, not one. The pool list comes from the `pairAddressLookup` registry template (`pair_address_lookup_observations`, one row per pool with exchange, protocol, fee, and both tokens); this template's `swaps` table supplies the 24h volume; add [Pair Reserves](/data-feeds/templates/markets/pair-reserves) for liquidity, [Token Prices](/data-feeds/templates/token/token-prices) for `usd_price` and the 24h change, and [Token Metadata](/data-feeds/templates/token/token-metadata) for symbols and `pair_label`, then join them in one view.
| `/erc20/:token_address/pairs` | Data Feeds | Fidelity |
| - | - | - |
| `pair_address`, `exchange_address` | `pair_address_lookup_observations.*` | exact |
| `exchange_name` | `.protocol` | exact |
| `base_token`, `quote_token` | `.token0_address` / `.token1_address` | exact |
| `pair_label`, `token_name`, `token_symbol`, `token_decimals` | `token_metadata` / registry, derive the label | exact |
| `usd_price`, `usd_price_24hr*` | `token_price_updates` | calculated |
| `liquidity_usd`, `liquidity_skew` | `pair_reserves` × price | calculated |
| `volume_24h_usd`, `volume_24h_native` | `sum(swaps.notional_usd)` over 24h | calculated |
| `inactive_pair` | no trades in the window | calculated |
| `exchange_logo`, `token_logo` | add yourself | add yourself |
The composed view (Postgres, query it with `WHERE base_token = $1 OR quote_token = $1 ORDER BY liquidity_usd DESC NULLS LAST`):
```sql theme={null}
CREATE VIEW token_pairs AS
SELECT
r.pair_address,
r.exchange_address,
r.protocol AS exchange_name,
m0.symbol || '/' || m1.symbol AS pair_label,
r.token0_address AS base_token,
r.token1_address AS quote_token,
p0.usd_price,
(res.reserve0 / power(10, r.token0_decimals) * p0.usd_price)
+ (res.reserve1 / power(10, r.token1_decimals) * p1.usd_price) AS liquidity_usd,
v.volume_24h_usd,
(v.volume_24h_usd IS NULL) AS inactive_pair
FROM pair_address_lookup_observations r
LEFT JOIN token_metadata m0 ON m0.token_address = r.token0_address
LEFT JOIN token_metadata m1 ON m1.token_address = r.token1_address
LEFT JOIN pair_reserves res ON res.pair_address = r.pair_address
LEFT JOIN LATERAL (SELECT usd_price FROM token_price_updates
WHERE token_address = r.token0_address ORDER BY block_number DESC LIMIT 1) p0 ON true
LEFT JOIN LATERAL (SELECT usd_price FROM token_price_updates
WHERE token_address = r.token1_address ORDER BY block_number DESC LIMIT 1) p1 ON true
LEFT JOIN LATERAL (SELECT sum(notional_usd) AS volume_24h_usd FROM swaps
WHERE pool_address = r.pair_address
AND block_timestamp >= extract(epoch FROM now()) - 86400) v ON true;
```
**Gotchas**
* A token trades in **many** pools (fee tiers, DEXes), list them by matching either side of the registry, and sort by liquidity to surface the meaningful ones.
* Backfill is mixed: the pool list needs history far enough back to see each pool's deployment (full history for completeness), while price, liquidity, and 24h volume only need `realtime` plus a 24-hour window. See [History & backfill](/data-feeds/concepts/history-and-backfill).
* The volume join keys on the **pair address**, so it matches this template's `pool_fill` rows only, aggregator-routed fills carry the aggregator's address in `pool_address` (see [Fidelity gaps](#fidelity-gaps)).
* The live figures track the old endpoint closely but come from a pricing computation, compare with a tolerance, not bit-for-bit.
* `exchange_logo` and `token_logo` are off-chain images, layer them in from your own source keyed by address, or drop them.
### Related
> [card] [Swaps by Token](/data-feeds/templates/markets/swaps-by-token)
>
> The same trade projection, keyed by token with one row per token side.
> [card] [Pair OHLCV](/data-feeds/templates/markets/pair-ohlcv)
>
> Roll a pair's trades into candlesticks for charting.
> [card] [Trading & Charting](/data-feeds/use-cases/trading-charting)
>
> The use case this per-pair trade feed powers.
> [card] [Token Analytics](/data-feeds/use-cases/token-analytics)
>
> Pool-level volume and trade flow for token analytics.
# Swaps by Token
Source: https://docs.moralis.com/data-feeds/templates/markets/swaps-by-token
Sync every DEX trade that touched a token, pool fills and aggregator-routed trades, USD-enriched at block time, into your own database, keyed for fast by-token lookups.
### Question it answers
> "Give me every DEX trade that touched token **0x…**, newest first, with the amount on each side, the USD notional, the protocol, and whether it was a buy or a sell."
A single read returns what the public Moralis Swaps endpoints serve by token, stored **pre-shaped and indexed by token** in your own database. Both direct pool fills and aggregator-routed trades are captured, so you see every fill of the token once.
### What you get
The template lands **one row per (trade, token side)**, each trade is unpivoted so it appears under both of its tokens, and a by-token lookup is a prefix scan. Key columns of the fact table:
| Column | Description |
| - | - |
| `token_address` | This side's token (the leg you're querying by) |
| `counter_token_address` | The other token in the trade |
| `leg` | `token0` or `token1`, which side of the underlying trade this row is |
| `side` | `buy` or `sell`, derived from the base token's pool-balance delta |
| `side_amount` | Raw amount of `token_address` (uint256, as text) |
| `counter_amount` | Raw amount of `counter_token_address` |
| `notional_usd` | Trade notional in USD (bought-leg amount × in-block price) |
| `price_usd` | Bought-leg (token1) USD price used for the notional |
| `source_kind` | `pool_fill` (direct pool) or `aggregator` (aggregator-routed) |
| `protocol` | DEX/protocol label |
| `fee_amount`, `fee_token`, `fee_usd` | Trade fee (pool fills only) |
| `trader_address`, `pool_address` | Trader and pool/aggregator address |
| `block_number`, `event_ts`, `tx_hash` | On-chain ordering and time |
### Source
The transform reads two per-block trade arrays and unions them into the trade feed:
`tokenSwaps` (direct pool fills) · `aggregateTokenSwaps` (aggregator-routed trades)
The two branches are disjoint by construction, pool fills are keyed off the pair address, aggregator routes off the aggregator address, so together they give every fill exactly once. USD values are computed **inline** from the same block's `tokenPriceUpdates` (the chronologically-last update wins on duplicate keys), so no separate price join is needed at read time.
### Destination
| Destination | Table | Read pattern |
| - | - | - |
| **ClickHouse** (first-class) | `fact_swaps_by_token` | Prefix scan on `(chain_id, token_address, event_ts)`; read with `FINAL` or `sum(sign)` |
| **Postgres** | `swaps` | Indexes on `token0_address` and `token1_address`, each `(…, block_number DESC)` |
| **MySQL** | `swaps` | Indexes on `token0_address` and `token1_address` |
ClickHouse uses the collapsing log-table pattern (see the [templates overview](/data-feeds/templates/overview#destinations)) so chain reorganizations self-correct. The fact table is token-first, so all trades for a token, newest first, are a contiguous range read. Postgres/MySQL keep a flat one-row-per-trade `swaps` table and reach a token via either side's index.
### Full schema
Below is the complete read table this template produces. It's a starting point: keep the columns you need and drop the rest (see [Schema & flexibility](/data-feeds/templates/overview#schema--flexibility)). Raw `uint256` amounts and fees are stored as text in ClickHouse and as `NUMERIC(76, 0)` in Postgres (explicit precision so large raw balances never overflow); USD columns are nullable wide decimals.
> [accordion] ClickHouse, fact\_swaps\_by\_token
>
> ```sql theme={null}
> CREATE TABLE recipe_swaps_by_token.fact_swaps_by_token
> (
> vendor_event_id String,
> ingested_at DateTime64(3),
> chain_id UInt32,
> block_hash String,
> block_number UInt64,
> event_ts DateTime64(3),
> token_address String, -- this side's token (token0 or token1)
> counter_token_address String,
> leg LowCardinality(String), -- 'token0' | 'token1'
> side_amount String, -- this token's amount (raw uint256)
> counter_amount String,
> trader_address String,
> pool_address String,
> price_usd Nullable(String),
> notional_usd Nullable(String),
> side LowCardinality(String), -- buy | sell
> source_kind LowCardinality(String), -- aggregator | pool_fill
> protocol LowCardinality(String),
> fee_amount Nullable(String),
> fee_token Nullable(String),
> fee_usd Nullable(String),
> sign Int8
> )
> ENGINE = ReplicatedCollapsingMergeTree(
> '/clickhouse/tables/{database}/fact_swaps_by_token', '{replica}', sign)
> PARTITION BY (chain_id, toYYYYMM(event_ts))
> ORDER BY (chain_id, token_address, event_ts, vendor_event_id, leg);
> ```
>
> Each trade is unpivoted into two rows (`leg = 'token0'` and `'token1'`) so it's found under both tokens. `leg` is part of the `ORDER BY` so the two sides never collapse into each other, while the `+1/−1` reorg pair for one side shares an identical key and collapses cleanly. Read with `FINAL` or `sum(sign)`, never a bare `WHERE sign = 1`. A single-node setup can use `CollapsingMergeTree(sign)` without the replication path.
> [accordion] Postgres, swaps
>
> ```sql theme={null}
> CREATE TABLE public.swaps (
> position BIGINT NOT NULL,
> log_index BIGINT, -- NULL for aggregator rows
> transaction_index BIGINT,
> block_number BIGINT NOT NULL,
> block_timestamp BIGINT NOT NULL, -- unix seconds
> tx_hash TEXT NOT NULL,
> vendor_event_id TEXT NOT NULL,
> trader_address TEXT NOT NULL,
> pool_address TEXT NOT NULL,
> token0_address TEXT NOT NULL,
> token1_address TEXT NOT NULL,
> amount0 NUMERIC(76, 0) NOT NULL,
> amount1 NUMERIC(76, 0) NOT NULL,
> price_usd NUMERIC(38, 18),
> notional_usd NUMERIC(38, 18),
> side TEXT NOT NULL,
> source_kind TEXT NOT NULL, -- aggregator | pool_fill
> protocol TEXT NOT NULL,
> fee_amount NUMERIC(76, 0),
> fee_token TEXT,
> fee_usd NUMERIC(38, 18)
> );
>
> -- By-token access (the template's primary purpose).
> CREATE INDEX IF NOT EXISTS swaps_token0_block_idx
> ON public.swaps (token0_address, block_number DESC);
> CREATE INDEX IF NOT EXISTS swaps_token1_block_idx
> ON public.swaps (token1_address, block_number DESC);
> -- Trader + block-range helpers.
> CREATE INDEX IF NOT EXISTS swaps_trader_block_idx
> ON public.swaps (trader_address, block_number DESC);
> CREATE INDEX IF NOT EXISTS swaps_block_idx
> ON public.swaps (block_number);
> ```
>
> MySQL is the same shape with `DECIMAL(38,18)` for the USD columns. The Postgres/MySQL table is one row per trade (not unpivoted), so a by-token read filters either `token0_address` or `token1_address`. `position` is the block-level cursor used during backfill.
### Example reads
All trades touching a token, newest first (ClickHouse):
```sql theme={null}
SELECT event_ts, leg, side, side_amount, counter_amount,
notional_usd, protocol, source_kind
FROM recipe_swaps_by_token.fact_swaps_by_token FINAL
WHERE chain_id = 1
AND token_address = lower('0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48')
ORDER BY event_ts DESC
LIMIT 50;
```
24h USD volume per token (sign-aware, cheaper than `FINAL`):
```sql theme={null}
SELECT token_address,
sumIf(toFloat64OrZero(notional_usd), sign = 1)
- sumIf(toFloat64OrZero(notional_usd), sign = -1) AS volume_usd
FROM recipe_swaps_by_token.fact_swaps_by_token
WHERE chain_id = 1 AND event_ts >= now() - INTERVAL 1 DAY
GROUP BY token_address
ORDER BY volume_usd DESC
LIMIT 25;
```
By-token read on Postgres / MySQL (either side matches):
```sql theme={null}
SELECT block_number, side, source_kind, amount0, amount1, notional_usd, protocol
FROM swaps
WHERE token0_address = lower('0xA0b8...') OR token1_address = lower('0xA0b8...')
ORDER BY block_number DESC
LIMIT 50;
```
### Modes
Shipped defaults: **ClickHouse `hybrid`** (backfill → realtime), **Postgres / MySQL `historical`** (one-shot backfill). For live/reorg-safe ingestion, use ClickHouse, see the [overview](/data-feeds/templates/overview#modes).
> [!NOTE]
>
> The realtime reorg path needs a single-column unique on the position cursor, but `position` is block-level (many trades per block), so the array-expanded trade rows can only carry a composite unique. Run **realtime/hybrid on ClickHouse**, where the collapsing log table corrects reorgs per-block; the Postgres/MySQL configs are intended for `historical` backfill.
### Multichain
The template is chain-parametrized, point it at any supported EVM chain or Solana. On Solana, multiple events in one instruction can share a `logIndex`, so the pool-fill event identity is widened (with the token addresses and amount) to keep rows distinct; the by-token feed it produces is identical in shape.
### USD valuation and fidelity gaps
* **`notional_usd`** is the bought-leg (`token1`) amount scaled by its decimals × the in-block price (`token1Amount / 10^token1Decimals × price`), so it's a true dollar value when the token had an in-block price update.
* **`price_usd`, `notional_usd`, `fee_usd`** are `NULL` when the bought token had **no in-block price update**, there's no off-block price backfill at write time. Join the Token Prices sync for fuller coverage.
* **`fee_*`** is populated for **pool fills only**; bps-style fees (V3/V4/CL) are converted to an absolute amount, and already-absolute fees pass through. Aggregator-routed rows leave fees `NULL`.
* **`side`** (`buy`/`sell`) is derived from the lower-priority (base) token's pool-balance delta on the trade.
## Migrating from the REST API
This template is the trade-level foundation for the token-analytics REST endpoint. That endpoint returns a pre-aggregated dashboard, so there is **no 1:1 replacement table**, you land the token's trades with this template and compute the rolling windows yourself, joining sibling templates for price, liquidity, and FDV. Every figure is **calculated** (aggregated from real trades, prices, reserves, and supply, very close, compare with a tolerance); there are no off-chain fields to add.
### GET /tokens/:tokenAddress/analytics
Buy/sell volume, buyers/sellers, trade counts, unique wallets, price change, liquidity, and FDV per rolling window (5m / 1h / 6h / 24h). On Data Feeds those windows become queries you own, and so does any other window or metric (buy/sell ratio, VWAP, …).
> [!WARNING]
>
> This endpoint needs a **combination of templates**, not one. Run this template (the trades) plus [Token Prices](/data-feeds/templates/token/token-prices) (`token_price_updates`, `usdPrice` and `pricePercentChange`), [Pair Reserves](/data-feeds/templates/markets/pair-reserves) (`pair_reserves`, `totalLiquidityUsd`), and [Token Metadata](/data-feeds/templates/token/token-metadata) (`token_metadata.total_supply`, FDV) against the same database, then aggregate. There is no pre-aggregated analytics template, the composition is the supported path.
| `/tokens/:tokenAddress/analytics` | Data Feeds | Fidelity |
| - | - | - |
| `totalBuyVolume`, `totalSellVolume` (per window) | `sum(swaps.notional_usd)` by side | calculated |
| `totalBuyers`, `totalSellers`, `totalBuys`, `totalSells` | distinct traders / trade counts by side | calculated |
| `uniqueWallets` | distinct traders in the window | calculated |
| `usdPrice`, `pricePercentChange` | latest `token_price_updates.usd_price` / price now vs window-ago | calculated |
| `totalLiquidityUsd` | sum of the token's pool reserves × price | calculated |
| `totalFullyDilutedValuation` | `total_supply` × price | calculated |
The trade-side aggregation for one window (Postgres, run per window: 300 / 3600 / 21600 / 86400 seconds):
```sql theme={null}
SELECT
sum(notional_usd) FILTER (WHERE side = 'buy') AS total_buy_volume,
sum(notional_usd) FILTER (WHERE side = 'sell') AS total_sell_volume,
count(DISTINCT trader_address) FILTER (WHERE side='buy') AS total_buyers,
count(DISTINCT trader_address) FILTER (WHERE side='sell') AS total_sellers,
count(*) FILTER (WHERE side = 'buy') AS total_buys,
count(*) FILTER (WHERE side = 'sell') AS total_sells,
count(DISTINCT trader_address) AS unique_wallets
FROM swaps
WHERE (token0_address = lower($1) OR token1_address = lower($1))
AND block_timestamp >= extract(epoch FROM now()) - 86400;
```
Layer the rest on top: `usdPrice` is the latest price update, `pricePercentChange` compares it to the price a window ago, `totalLiquidityUsd` sums the token's pool reserves valued at price, and `totalFullyDilutedValuation` is `total_supply × price`.
**Gotchas**
* Backfill enough history to cover your longest window, a day or more for the 24h figures, plus price history for the price change. See [History & backfill](/data-feeds/concepts/history-and-backfill).
* Materialize per token and window on a schedule if you serve many tokens, don't recompute per request.
* Thin tokens have sparse windows, and trades whose bought leg had no in-block price carry `NULL` notional and drop out of USD sums.
* On ClickHouse, run the same aggregation over `fact_swaps_by_token` with a prefix scan on `token_address` (the unpivot means a by-token filter already sees each trade once), and make it reorg-safe with `FINAL` or sign-aware sums, never a bare `WHERE sign = 1`.
### Related
> [card] [Swaps by Pair](/data-feeds/templates/markets/swaps-by-pair)
>
> The sibling, every trade keyed by pool/pair address.
> [card] [Token Analytics](/data-feeds/use-cases/token-analytics)
>
> The use case this by-token trade feed powers.
# Swaps by Wallet
Source: https://docs.moralis.com/data-feeds/templates/markets/swaps-by-wallet
Sync every DEX trade made by a wallet, pool fills and aggregator-routed trades, USD-enriched at block time, keyed for by-trader lookups in your own database.
### Question it answers
> "Give me every DEX trade made by wallet **0x…**, newest first, direct pool fills and aggregator-routed trades alike, each with its USD notional, side, and protocol."
A single prefix scan returns what the public Moralis Swaps endpoints serve, pre-shaped and keyed by trader so a wallet's trade history is a contiguous range read.
### What you get
The template lands **one row per trade**, a trade belongs to exactly one trader (`fromAddress`), so there's no per-side fan-out. Both direct pool fills and aggregator-routed trades land in the same table:
| Column | Description |
| - | - |
| `trader_address` | The wallet that made the trade |
| `event_ts`, `block_number` | When the trade happened |
| `tx_hash` | Transaction that produced the trade |
| `pool_address` | The pair (pool fill) or aggregator (aggregator route) |
| `token0_address`, `token1_address` | The two legs of the trade |
| `amount0`, `amount1` | Raw `uint256` amounts moved on each leg |
| `side` | `buy` / `sell`, decided by the base token's pool-balance delta |
| `source_kind` | `pool_fill` (direct pool) or `aggregator` (router) |
| `price_usd` | Bought-leg (`token1`) USD price at block time |
| `notional_usd` | Trade value: `token1Amount / 10^token1Decimals × price_usd` |
| `protocol` | The DEX protocol of the fill |
| `fee_amount`, `fee_token`, `fee_usd` | Pool-fill fees (bps fees converted to absolute), `NULL` for aggregator rows |
### Source
The transform reads two per-block arrays and unions them into the trade feed, so every fill is captured exactly once:
`tokenSwaps` (direct pool fills, `source_kind = 'pool_fill'`) · `aggregateTokenSwaps` (aggregator routes, `source_kind = 'aggregator'`)
The two branches are disjoint by construction. USD enrichment is computed **inline** from the same block's `tokenPriceUpdates`, a per-block price map is built once and the bought leg is priced O(log N) per trade, with no separate price join at read time.
### Destination
| Destination | Table | Read pattern |
| - | - | - |
| **ClickHouse** (first-class) | `fact_swaps_by_wallet` | Prefix scan on `(chain_id, trader_address, event_ts)`; read with `FINAL` or `sum(sign)` |
| **Postgres** | `swaps` | Index on `(trader_address, block_number DESC)` |
| **MySQL** | `swaps` | Index on `(trader_address, block_number)` |
ClickHouse uses the collapsing log-table pattern (see the [templates overview](/data-feeds/templates/overview#destinations)) so chain reorganizations self-correct, a trade's `+1/−1` pair shares an identical key and collapses cleanly. The fact table's sort key is trader-first, so a wallet's trade history is a contiguous range read.
### Full schema
Below is the complete read table this template produces. It's a starting point, keep the columns you need and drop the rest (see [Schema & flexibility](/data-feeds/templates/overview#schema--flexibility)). Raw `uint256` amounts are stored as text in ClickHouse (they exceed numeric precision) and as `NUMERIC(76, 0)` in Postgres; USD columns are wide decimals so a low-decimals token × price never overflows.
> [accordion] ClickHouse, fact\_swaps\_by\_wallet
>
> ```sql theme={null}
> CREATE TABLE recipe_swaps_by_wallet.fact_swaps_by_wallet
> (
> vendor_event_id String,
> ingested_at DateTime64(3),
> chain_id UInt32,
> block_hash String,
> block_number UInt64,
> event_ts DateTime64(3),
> trader_address String,
> pool_address String,
> token0_address String,
> token1_address String,
> amount0 String, -- raw uint256
> amount1 String, -- raw uint256
> price_usd Nullable(String), -- bought-leg (token1) USD price
> notional_usd Nullable(String), -- token1 amount × price_usd
> side LowCardinality(String), -- buy | sell
> source_kind LowCardinality(String), -- aggregator | pool_fill
> protocol LowCardinality(String),
> fee_amount Nullable(String),
> fee_token Nullable(String),
> fee_usd Nullable(String),
> sign Int8
> )
> ENGINE = ReplicatedCollapsingMergeTree(
> '/clickhouse/tables/{database}/fact_swaps_by_wallet', '{replica}', sign)
> PARTITION BY (chain_id, toYYYYMM(event_ts))
> ORDER BY (chain_id, trader_address, event_ts, vendor_event_id);
> ```
>
> The `sign` column drives reorg collapsing, read with `FINAL` or `sum(sign)`. A single-node setup can use `CollapsingMergeTree(sign)` without the replication path.
> [accordion] Postgres, swaps
>
> ```sql theme={null}
> CREATE TABLE public.swaps (
> position BIGINT NOT NULL,
> log_index BIGINT, -- NULL for aggregator rows
> transaction_index BIGINT,
> block_number BIGINT NOT NULL,
> block_timestamp BIGINT NOT NULL, -- unix seconds
> tx_hash TEXT NOT NULL,
> vendor_event_id TEXT NOT NULL,
> trader_address TEXT NOT NULL,
> pool_address TEXT NOT NULL,
> token0_address TEXT NOT NULL,
> token1_address TEXT NOT NULL,
> amount0 NUMERIC(76, 0) NOT NULL, -- raw uint256
> amount1 NUMERIC(76, 0) NOT NULL, -- raw uint256
> price_usd NUMERIC(38, 18),
> notional_usd NUMERIC(38, 18),
> side TEXT NOT NULL,
> source_kind TEXT NOT NULL, -- aggregator | pool_fill
> protocol TEXT NOT NULL,
> fee_amount NUMERIC(76, 0),
> fee_token TEXT,
> fee_usd NUMERIC(38, 18)
> );
>
> -- By-wallet access (the template's primary purpose).
> CREATE INDEX IF NOT EXISTS swaps_trader_block_idx
> ON public.swaps (trader_address, block_number DESC);
> -- By-token access helpers.
> CREATE INDEX IF NOT EXISTS swaps_token0_block_idx
> ON public.swaps (token0_address, block_number DESC);
> CREATE INDEX IF NOT EXISTS swaps_token1_block_idx
> ON public.swaps (token1_address, block_number DESC);
> -- Block-range helper.
> CREATE INDEX IF NOT EXISTS swaps_block_idx
> ON public.swaps (block_number);
> ```
>
> MySQL is the same shape with `DECIMAL(38,18)` for the USD columns and `DECIMAL(76,0)` for raw amounts. `position` is the block-level cursor used during backfill.
### Example reads
All trades made by a wallet, newest first (ClickHouse):
```sql theme={null}
SELECT event_ts, side, source_kind, amount0, amount1, notional_usd, protocol
FROM recipe_swaps_by_wallet.fact_swaps_by_wallet FINAL
WHERE chain_id = 1
AND trader_address = lower('0x28C6c06298d514Db089934071355E5743bf21d60')
ORDER BY event_ts DESC
LIMIT 50;
```
24h USD volume per wallet (sign-aware, cheaper than `FINAL`):
```sql theme={null}
SELECT trader_address,
sumIf(toFloat64OrZero(notional_usd), sign = 1)
- sumIf(toFloat64OrZero(notional_usd), sign = -1) AS volume_usd
FROM recipe_swaps_by_wallet.fact_swaps_by_wallet
WHERE chain_id = 1 AND event_ts >= now() - INTERVAL 1 DAY
GROUP BY trader_address
ORDER BY volume_usd DESC
LIMIT 25;
```
The same by-wallet read on Postgres / MySQL:
```sql theme={null}
SELECT block_number, side, source_kind, amount0, amount1, notional_usd, protocol
FROM swaps
WHERE trader_address = lower('0x28C6...')
ORDER BY block_number DESC
LIMIT 50;
```
### Modes
Shipped defaults: **ClickHouse `hybrid`** (backfill → realtime), **Postgres / MySQL `historical`** (one-shot backfill). For live/reorg-safe ingestion, use ClickHouse, see the [overview](/data-feeds/templates/overview#modes).
> [!NOTE]
>
> The realtime reorg path needs a single-column unique on the block-level position, but `position` is block-level (many trades share one block), so array-expanded trade rows can only carry a composite unique. Run realtime/hybrid on **ClickHouse**, where the collapsing log table corrects reorgs per-block. The Postgres / MySQL configs are intended for `historical` backfill.
### Multichain
The template is chain-parametrized, point it at any supported EVM chain or Solana. On Solana, the same `logIndex` can be assigned to multiple events in one instruction, so the pool-fill event identity is widened with `(token0_address, token1_address, token0_amount)` to keep rows distinct; the trade feed it produces is identical in shape.
### Fidelity gaps
* **`notional_usd` is single-leg.** The trade value is computed from the bought leg (`token1`) only, `token1Amount / 10^token1Decimals × price_usd`. If the bought token had no in-block price update, `price_usd`, `notional_usd`, and `fee_usd` are `NULL`.
* **`amount0` / `amount1` are raw `uint256`.** They are not decimal-scaled, divide by `10^token_decimals` (sourced from a Token Metadata sync) to read human amounts.
* **Fees are pool-fill only.** `fee_*` columns are populated for direct pool fills (bps fees converted to an absolute amount); aggregator rows leave them `NULL`.
## Migrating from the REST API
This template replaces the wallet-swaps REST endpoint. It is **not** a 1:1 replica of the response, you land the trades in your own database and reconstruct the response shape with a query. Fidelity labels: **exact** = straight from the chain, **calculated** = derived from real DEX trades (very close, compare with a tolerance), **add yourself** = off-chain signal not in the feed.
### GET /wallets/:address/swaps
A wallet's DEX trade history with bought/sold legs and USD values. Replaced directly by this template, trades are keyed by `trader_address`, so the REST response is a single by-wallet read, with [Token Metadata](/data-feeds/templates/token/token-metadata) joined in for the leg symbols and `pairLabel`.
| `/wallets/:address/swaps` | Data Feeds | Fidelity |
| - | - | - |
| `transactionHash`, `transactionIndex`, `blockNumber`, `blockTimestamp` | `swaps.*` | exact |
| `transactionType` (buy/sell) | `swaps.side` | exact |
| `pairAddress`, `exchangeName` | `swaps.pool_address` / `protocol` | exact |
| `bought` / `sold` legs (address, amount) | `swaps.token0/1_address`, `amount0/1` | exact |
| `bought/sold.symbol`, `name`, `pairLabel` | `token_metadata` join / derive | exact |
| `usdPrice`, `usdAmount`, `totalValueUsd`, `baseQuotePrice` | `swaps.price_usd` / `notional_usd` | calculated |
| `walletAddressLabel`, `entity`, `entityLogo`, `exchangeLogo`, token logos | add yourself | add yourself |
| `subCategory` (accumulation/distribution) | classify yourself | add yourself |
The REST read with keyset pagination (Postgres, adapt to your destination):
```sql theme={null}
SELECT s.*
FROM swaps s
WHERE s.trader_address = lower($1)
AND ($2::bigint IS NULL OR s.block_number < $2) -- keyset pagination (REST cursor)
ORDER BY s.block_number DESC
LIMIT $3;
```
**Gotchas**
* USD values are calculated from real trades, compare with a tolerance, and they're `NULL` when the bought leg had no in-block price update (see [Fidelity gaps](#fidelity-gaps)).
* Leg symbols and `pairLabel` need the `token_metadata` join, and `amount0`/`amount1` land as raw `uint256`, scale by `10^decimals` from the same table.
* The off-chain extras (`walletAddressLabel`, `entity`, logos) come from your own directory or get dropped; `subCategory` is a classification rule you define over the wallet's trades.
* The REST `transactionTypes` filter becomes `WHERE side = 'buy'` / `'sell'`; date and block windows are plain SQL.
* Both direct pool fills and aggregator-routed trades land in the one table, `source_kind` distinguishes them, matching the old endpoint's mixed feed.
### Related
> [card] [Swaps by Token](/data-feeds/templates/markets/swaps-by-token)
>
> The same trade feed keyed by token instead of trader.
> [card] [Token Analytics](/data-feeds/use-cases/token-analytics)
>
> The use case this trade feed powers.
# NFT Collection Metadata
Source: https://docs.moralis.com/data-feeds/templates/nft/nft-collection-metadata
Sync the on-chain name, symbol, and contract type (ERC-721 / ERC-1155) of every NFT collection, keyed by collection address, into your own database. Mirrors the Moralis GET /nft/{address}/metadata endpoint.
### Question it answers
> "Give me the collection metadata (name, symbol, contract type) for NFT collection **0x…**." Mirrors Moralis `GET /nft/{address}/metadata`.
This is the NFT-collection sibling of [Token Metadata](/data-feeds/templates/token/token-metadata). Both read the same per-block deployed-contracts stream, but this template keeps only **NFT-type** contracts (ERC-721 / ERC-1155) and drops ERC-20 tokens. Collection metadata is fixed at deploy time, so there is normally exactly one row per `(chain_id, token_address)`: the latest deploy by `(block_number, transaction_index)` is canonical (defensive against a CREATE2 re-deploy at a reused address).
### What you get
One row per NFT-type contract deploy, keyed by the collection (`token_address`):
| Column | Description |
| - | - |
| `token_address` | The NFT collection contract address |
| `name` | On-chain collection name, best-effort; may be empty for many ERC-1155 collections |
| `symbol` | On-chain collection symbol, best-effort; may be empty |
| `contract_type` | `ERC721` · `ERC1155` · `NFT` (derived from the EIP-165 interface ids; `NFT` is the fallback when neither interface is advertised) |
| `deployer_address` | Address that deployed the contract |
| `block_number`, `transaction_index` | Deploy position, the recency tiebreaker for latest-wins |
| `block_timestamp` | Block time of the deploy |
Unlike the ERC-20 path, symbol-less contracts are **not** dropped: `name`/`symbol` are best-effort on-chain fields, not filter keys. Far fewer rows land than Token Metadata: only a handful of NFT contracts deploy per \~1000 blocks.
### Source
The transform reads the per-block deployed-contracts stream and keeps the **NFT slice**, contracts whose `type` contains `NFT` (ERC-721 / ERC-1155). A contract is kept when its `deployer_address` is non-empty. `contract_type` is derived from the contract's `supportedInterfaces` (EIP-165 ids): `0xd9b67a26` → `ERC1155`, else `0x80ac58cd` → `ERC721`, else the `NFT` fallback.
### Destination
| Destination | Table | By-collection access |
| - | - | - |
| **ClickHouse** (first-class) | `fact_nft_collection_metadata` | `ORDER BY (chain_id, token_address)`; latest deploy via `argMax(…, (block_number, transaction_index))`, read with `FINAL` |
| **Postgres** | `nft_collection_metadata` (matview over `nft_collection_metadata_observations`) | Unique index on `(token_address)` |
| **MySQL** | `nft_collection_metadata` (latest-wins state table over the observations) | Primary key on `(token_address)` |
ClickHouse uses the collapsing log-table pattern (see the [templates overview](/data-feeds/templates/overview#destinations)) so a reorg of a deploy block self-corrects. Because a collection can in principle deploy more than once at the same address (CREATE2), reads resolve **latest deploy wins** with `argMax(…, (block_number, transaction_index))` rather than assuming a single row. Postgres derives the current-metadata surface as a `DISTINCT ON (token_address)` materialized view; MySQL maintains it incrementally with a latest-wins trigger.
### Full schema
The complete read table this template produces. Keep the columns you need, `name`/`symbol`/`contract_type` are usually enough for a metadata lookup (see [Schema & flexibility](/data-feeds/templates/overview#schema--flexibility)). `name` and `symbol` are stored as text; they can contain quotes and odd characters, which are parameter-bound on insert so there is no quoting breakage.
> [accordion] ClickHouse, fact\_nft\_collection\_metadata
>
> ```sql theme={null}
> CREATE TABLE recipe_nft_collection_metadata.fact_nft_collection_metadata
> (
> vendor_event_id String,
> ingested_at DateTime64(3),
> chain_id UInt32,
> block_hash String,
> block_number UInt64,
> transaction_index UInt32,
> event_ts DateTime64(3),
> token_address String,
> deployer_address String,
> name String,
> symbol String,
> contract_type LowCardinality(String), -- ERC721 | ERC1155 | NFT
> sign Int8
> )
> ENGINE = ReplicatedCollapsingMergeTree(
> '/clickhouse/tables/{database}/fact_nft_collection_metadata', '{replica}', sign)
> PARTITION BY (chain_id, toYYYYMM(event_ts))
> ORDER BY (chain_id, token_address, block_number, transaction_index, vendor_event_id);
> ```
>
> The `sign` column drives reorg collapsing, read with `FINAL` or a sign-aware aggregate, never a bare `WHERE sign = 1`. A single-node setup can use `CollapsingMergeTree(sign)` without the replication path. The collection-keyed sort order makes a single-collection lookup a tight prefix scan.
> [accordion] Postgres, nft\_collection\_metadata
>
> ```sql theme={null}
> -- 1. Observations (sink target): one row per NFT-contract deploy.
> CREATE TABLE public.nft_collection_metadata_observations (
> position BIGINT NOT NULL, -- block-level cursor used during backfill
> transaction_index BIGINT,
> block_number BIGINT NOT NULL,
> block_timestamp BIGINT NOT NULL, -- unix seconds
> tx_hash VARCHAR(66) NOT NULL,
> vendor_event_id TEXT NOT NULL,
> token_address VARCHAR(66) NOT NULL,
> deployer_address VARCHAR(66) NOT NULL,
> name TEXT NOT NULL,
> symbol TEXT NOT NULL,
> contract_type VARCHAR(16) NOT NULL -- ERC721 | ERC1155 | NFT
> );
>
> -- Speeds the DISTINCT ON (latest-per-collection) the materialized view computes.
> CREATE INDEX IF NOT EXISTS ncmo_token_recency_idx
> ON public.nft_collection_metadata_observations
> (token_address, block_number DESC, transaction_index DESC);
>
> -- 2. Current-metadata materialized view: latest deploy per token_address.
> CREATE MATERIALIZED VIEW public.nft_collection_metadata AS
> SELECT DISTINCT ON (token_address)
> token_address,
> name,
> symbol,
> contract_type,
> block_number,
> deployer_address
> FROM public.nft_collection_metadata_observations
> ORDER BY token_address, block_number DESC, transaction_index DESC;
>
> -- Required by REFRESH MATERIALIZED VIEW CONCURRENTLY (one row per collection).
> CREATE UNIQUE INDEX IF NOT EXISTS nft_collection_metadata_pk
> ON public.nft_collection_metadata (token_address);
>
> -- Lookup helpers.
> CREATE INDEX IF NOT EXISTS nft_collection_metadata_symbol_idx
> ON public.nft_collection_metadata (symbol);
> CREATE INDEX IF NOT EXISTS nft_collection_metadata_type_idx
> ON public.nft_collection_metadata (contract_type);
> ```
>
> The sink appends to `nft_collection_metadata_observations`; refresh the current-metadata view on a schedule with `REFRESH MATERIALIZED VIEW CONCURRENTLY nft_collection_metadata;`. MySQL mirrors this shape, `VARCHAR(255)` for `name`/`symbol`, with the current-metadata `nft_collection_metadata` table maintained incrementally by an `AFTER INSERT` latest-wins trigger.
### Example reads
Metadata for one collection, latest deploy wins (ClickHouse):
```sql theme={null}
SELECT
token_address,
argMax(name, (block_number, transaction_index)) AS name,
argMax(symbol, (block_number, transaction_index)) AS symbol,
argMax(contract_type, (block_number, transaction_index)) AS contract_type,
argMax(deployer_address, (block_number, transaction_index)) AS deployer_address
FROM recipe_nft_collection_metadata.fact_nft_collection_metadata FINAL
WHERE chain_id = 1 AND token_address = lower('0x...')
GROUP BY token_address;
```
All NFT collections deployed in a block range (ClickHouse):
```sql theme={null}
SELECT token_address, name, symbol, contract_type, block_number
FROM recipe_nft_collection_metadata.fact_nft_collection_metadata FINAL
WHERE chain_id = 1 AND block_number BETWEEN 19000000 AND 19001000
ORDER BY block_number, transaction_index
LIMIT 100;
```
Metadata for one collection (Postgres, after `REFRESH MATERIALIZED VIEW CONCURRENTLY nft_collection_metadata;`):
```sql theme={null}
SELECT token_address, name, symbol, contract_type
FROM public.nft_collection_metadata
WHERE token_address = lower('0x...');
```
### Modes
Shipped defaults: **ClickHouse `hybrid`** (backfill → realtime), **Postgres / MySQL `historical`** (one-shot backfill). For live/reorg-safe ingestion, use ClickHouse, see the [overview](/data-feeds/templates/overview#modes).
> [!NOTE]
>
> The realtime reorg path on Postgres / MySQL needs a single-column `UNIQUE` on the block-level `position`, but a single block can deploy several NFT contracts, so the array-expanded rows can only carry a composite unique. Run **realtime/hybrid on ClickHouse**, where the collapsing log table corrects reorgs per-block. The Postgres / MySQL configs are intended for `historical` backfill, which is the dominant use of this template, a once-off metadata census.
### EVM only
This template is EVM-shaped: it reads EVM contract deploys. Solana NFT (Metaplex) collection metadata does not flow through the deployed-contracts stream the same way EVM contract deploys do, so the template targets EVM chains. It is chain-parametrized via the `chain` setting across any supported EVM chain.
### Fidelity gaps
`GET /nft/{address}/metadata` returns enrichment fields this template does not source, all off-chain indexer or editorial state:
* `collection_logo` / `collection_banner_image`, off-chain CDN assets.
* `collection_category`: editorial categorisation.
* `project_url` / `discord_url` / `telegram_url` / `wiki_url`, social links.
* `possible_spam` / `verified_collection`, spam & verification heuristics from a separate pipeline.
* `synced_at` (wall-clock), this template carries on-chain `block_number` / `block_timestamp` instead.
The core on-chain fields, `token_address`, `name`, `symbol`, `contract_type`, plus `block_number` and `deployer_address`, are fully sourced.
## Migrating from the REST API
This template replaces the collection-metadata side of the NFT REST endpoints. Data Feeds are **not** 1:1 replicas of those responses, you land the underlying data in your own database and reconstruct the response shape with a query. The subsections below cover each REST endpoint: what replaces it, the field mapping (**exact** = straight from the chain, **calculated** = derived from real trades, very close, **add yourself** = off-chain signal not in the feed), and the endpoint-specific gotchas.
### GET /nft/:address/metadata
A collection's identity. Replaced directly by this template's `nft_collection_metadata` table, `name`, `symbol`, and `contract_type` land from the contract's deploy, keyed by `token_address`. Optionally add [NFT Trades](/data-feeds/templates/nft/nft-trades) for `last_sale`. The editorial layer (logo, banner, category, description, social links) and floor price are off-chain, bring your own collection directory and floor source, or drop them.
| `/nft/:address/metadata` | Data Feeds | Fidelity |
| - | - | - |
| `token_address`, `name`, `symbol`, `contract_type` | `nft_collection_metadata.*` | exact |
| `last_sale` (sale facts) | `nftTrades` | exact |
| `last_sale` USD | `nftTrades` + price feed | calculated |
| `collection_logo`, `collection_banner_image`, `collection_category`, `description`, social links | add yourself | off-chain |
| `possible_spam`, `verified_collection` | add yourself | off-chain |
| `floor_price`, `floor_price_usd`, `floor_price_currency` | add yourself | off-chain |
| `synced_at`, `created_date` | add yourself (on-chain `block_number` / `block_timestamp` carried instead) | off-chain |
The lookup (Postgres, adapt to your destination):
```sql theme={null}
SELECT token_address, name, symbol, contract_type
FROM nft_collection_metadata
WHERE token_address = lower('0x...');
```
**Gotchas**
* **`name`/`symbol` can be empty** for some ERC-1155 collections (no on-chain name), expected, not an error.
* **Backfill from the collection's deploy block**: metadata is recorded at deployment, so the deploy block must be in your indexed window. See [History & backfill](/data-feeds/concepts/history-and-backfill).
* `contract_type` may be the `NFT` fallback when a contract advertises neither EIP-165 interface; the REST endpoint made a similar best-effort call.
### POST /nft/getMultipleNFTs
Batch NFT lookup by `(token_address, token_id)`. The onchain half, ownership, mint provenance, contract type, collection identity, realized sales, is replaced by a composition of templates, with no 25-NFT batch cap.
> [!WARNING]
>
> This endpoint needs **multiple templates**, and it is *mostly a metadata product*. Run [NFT Owners by Contract](/data-feeds/templates/nft/nft-owners-by-contract) (current owner per token\_id) plus this template (collection `name` / `symbol`), [NFT Transfers](/data-feeds/templates/nft/nft-transfers) (mint provenance), and [NFT Trades](/data-feeds/templates/nft/nft-trades) (`last_sale`) against the same database. The resolved token JSON, media, rarity, and floor/listing prices are built off-chain from each token's `tokenURI` and marketplace data, pair the templates with your own metadata resolver and pricing sources, or drop those fields. If resolved metadata is the entire job, keep a metadata indexer for that layer; the templates supply the ownership and provenance to pair with it.
| `/nft/getMultipleNFTs` | Data Feeds | Fidelity |
| - | - | - |
| `token_address`, `token_id` | the lookup key | exact |
| `contract_type`, `owner_of`, `amount`, `block_number` | `nft_owners.*` (`owner_of` = `wallet_address`, `amount > 0`) | exact |
| `block_number_minted`, `minter_address` | `nft_transfers` (mint = from the zero address) | exact |
| `name`, `symbol` | `nft_collection_metadata.*` | exact |
| `token_hash` | derive (hash of contract + id) | exact |
| `last_sale` (sale facts) | `nftTrades` | exact |
| `last_sale` USD values | `nftTrades` + price feed | calculated |
| `token_uri`, `metadata`, `normalized_metadata`, `media` | add yourself (resolve token URI) | off-chain |
| `rarity_rank`, `rarity_percentage`, `rarity_label` | add yourself (rarity tool) | off-chain |
| `floor_price*`, `list_price` | add yourself (pricing/marketplace) | off-chain |
| `possible_spam`, `verified_collection`, collection editorial, `*_sync` timestamps | add yourself | off-chain |
The batch lookup (Postgres, adapt to your destination):
```sql theme={null}
SELECT o.token_address, o.token_id, o.contract_type,
o.wallet_address AS owner_of, o.amount, o.block_number,
c.name, c.symbol
FROM nft_owners o
LEFT JOIN nft_collection_metadata c ON c.token_address = o.token_address
WHERE (o.token_address, o.token_id) IN (VALUES
(lower('0x...'), '1234'),
(lower('0x...'), '5678'))
AND o.amount > 0;
```
**Gotchas**
* **Backfill each collection from its deploy block**: a token's current owner is the cumulative result of every transfer, so a late start returns stale or missing owners.
* **ERC-1155** token\_ids can have many owners, you get `(owner, amount)` rows rather than a single `owner_of`.
* `token_id` is a `uint256` stored as text, compare as strings, never as numbers.
* No batch cap and no per-call limits, the 25-NFT ceiling disappears; batch size is just the length of your `IN` list.
### Related
> [card] [NFT Owners by Contract](/data-feeds/templates/nft/nft-owners-by-contract)
>
> Current holders of a collection, pair with this metadata for a complete collection view.
> [card] [NFT Marketplace](/data-feeds/use-cases/nft-marketplace)
>
> The use case this collection metadata powers.
# NFT Owners by Contract
Source: https://docs.moralis.com/data-feeds/templates/nft/nft-owners-by-contract
Sync the current owner set for an NFT collection (every wallet holding a token_id, with live counts for ERC-1155 editions) into your own database. Mirrors the Moralis GET /nft/{address}/owners endpoint.
### Question it answers
> "Give me every current owner of NFT collection **0x…**: each `token_id`, the wallet that holds it, and how many (ERC-1155 editions)." Mirrors Moralis `GET /nft/{address}/owners`.
This is the by-collection sibling of [NFTs by Wallet](/data-feeds/templates/wallet/nfts-by-wallet): **same ingest, sorted the other way.** Each NFT transfer carries the **absolute** post-transfer holdings of both wallets, so the latest observation per `(token_address, token_id, wallet)` is the current owner. Storing the resolved owner set in your own database, keyed by collection, is the value.
### What you get
Each NFT transfer becomes **two per-wallet holding observations** (`leg = from | to`), where `amount` is the absolute count of that `token_id` held by the wallet *after* the transfer. The latest observation per `(token_address, token_id, wallet_address)` wins; keep `amount > 0` for the current owner set.
| Column | Description |
| - | - |
| `token_address` | The NFT collection (contract) |
| `token_id` | The specific NFT: `uint256`, stored as text (256-bit ids overflow numeric types) |
| `wallet_address` | The holder; the EVM zero address is excluded (mint/burn counterparty) |
| `amount` | Absolute post-transfer holding of this `token_id`: `0`/`1` for ERC-721, an arbitrary count for ERC-1155 editions |
| `contract_type` | ERC-721 / ERC-1155 discriminator |
| `leg` | `from` or `to`: which side of the transfer produced this observation |
| `block_number`, `log_index` | Recency tuple; latest wins per holding key |
| `event_ts` / `block_timestamp` | Block time |
### Source
The transform reads one per-block array, `nftTokenTransfers`, and unpivots each event into two observations using its `fromPostBalance` / `toPostBalance` fields (the from- and to-wallet's absolute count of that `token_id` after the transfer). No price or metadata join is involved.
### Destination
| Destination | Table | By-collection access |
| - | - | - |
| **ClickHouse** (first-class) | `fact_nft_owners_by_contract` | Prefix scan on `(chain_id, token_address, token_id, wallet_address, …)`; current owner via `argMax` over `FINAL` |
| **Postgres** | `nft_owner_observations` → `nft_owners` (materialized view) | Partial index `(token_address, token_id, wallet_address) WHERE amount > 0` |
| **MySQL** | `nft_owner_observations` → `nft_owners` (trigger-maintained) | PK `(token_address, token_id, wallet_address)` + `amount = 0` cleanup |
ClickHouse uses the collapsing log-table pattern (see the [templates overview](/data-feeds/templates/overview#destinations)) so chain reorganizations self-correct. The fact table is sorted collection-first, so "every owner of collection X" is a contiguous range read. Ownership is **latest-wins**: an observation is current state for its holding key, not an append-only event. Read canonical state with `FINAL` then `argMax`, never a bare `WHERE sign = 1`.
### Full schema
Below is the complete read table this template produces: one row per holding observation. Keep the columns you need and drop the rest (see [Schema & flexibility](/data-feeds/templates/overview#schema--flexibility)). `token_id` and `amount` are stored as text / wide numeric because full-range `uint256` ids and counts overflow standard numeric types.
> [accordion] ClickHouse, fact\_nft\_owners\_by\_contract
>
> ```sql theme={null}
> CREATE TABLE recipe_nft_owners_by_contract.fact_nft_owners_by_contract
> (
> vendor_event_id String,
> ingested_at DateTime64(3),
> chain_id UInt32,
> block_hash String,
> block_number UInt64,
> log_index UInt32,
> event_ts DateTime64(3),
> token_address String,
> token_id String, -- uint256, kept as text
> contract_type LowCardinality(String), -- ERC721 | ERC1155
> wallet_address String,
> amount String, -- absolute post-transfer holding of this token_id
> leg LowCardinality(String), -- from | to
> sign Int8
> )
> ENGINE = ReplicatedCollapsingMergeTree(
> '/clickhouse/tables/{database}/fact_nft_owners_by_contract', '{replica}', sign)
> PARTITION BY (chain_id, toYYYYMM(event_ts))
> ORDER BY (chain_id, token_address, token_id, wallet_address, block_number, log_index, vendor_event_id, leg);
> ```
>
> The `sign` column drives reorg collapsing: read with `FINAL` then `argMax`, or a sign-aware aggregate. A single-node setup can use `CollapsingMergeTree(sign)` without the replication path.
> [accordion] Postgres, nft\_owner\_observations + nft\_owners
>
> ```sql theme={null}
> CREATE TABLE public.nft_owner_observations (
> position BIGINT NOT NULL,
> log_index BIGINT NOT NULL,
> block_number BIGINT NOT NULL,
> block_timestamp BIGINT NOT NULL, -- unix seconds
> token_address TEXT NOT NULL,
> token_id TEXT NOT NULL, -- uint256, kept as text
> contract_type TEXT NOT NULL, -- ERC721 | ERC1155
> wallet_address TEXT NOT NULL,
> amount NUMERIC(76, 0) NOT NULL, -- absolute post-balance of this token_id
> leg TEXT NOT NULL,
> vendor_event_id TEXT NOT NULL
> );
>
> -- Recency index for the DISTINCT ON; leads with the holding key so
> -- REFRESH MATERIALIZED VIEW CONCURRENTLY avoids a sort.
> CREATE INDEX noo_owner_recency_idx
> ON public.nft_owner_observations
> (token_address, token_id, wallet_address, block_number DESC, log_index DESC);
>
> -- Current-owner surface: latest observation per (token, id, wallet).
> CREATE MATERIALIZED VIEW public.nft_owners AS
> SELECT DISTINCT ON (token_address, token_id, wallet_address)
> token_address, token_id, wallet_address, contract_type,
> amount, block_number, log_index, block_timestamp
> FROM public.nft_owner_observations
> ORDER BY token_address, token_id, wallet_address, block_number DESC, log_index DESC;
>
> CREATE UNIQUE INDEX nft_owners_pk
> ON public.nft_owners (token_address, token_id, wallet_address);
>
> -- Primary access path: current owners of a collection.
> CREATE INDEX nft_owners_by_contract_active_idx
> ON public.nft_owners (token_address, token_id, wallet_address) WHERE amount > 0;
>
> -- OPTIONAL: sibling by-wallet access path — every NFT held by a wallet.
> -- CREATE INDEX nft_owners_by_wallet_active_idx
> -- ON public.nft_owners (wallet_address, token_address, token_id) WHERE amount > 0;
> ```
>
> MySQL is the same shape with a trigger-maintained `nft_owners` state table and a `DELETE … WHERE amount = 0` cleanup. `position` is the block-level cursor used during backfill. Refresh the materialized view on a schedule with `REFRESH MATERIALIZED VIEW CONCURRENTLY nft_owners;`.
### Example reads
Current owners of a collection, latest non-zero holding per `token_id` + wallet (ClickHouse):
```sql theme={null}
SELECT token_id, wallet_address, contract_type, current_amount
FROM (
SELECT token_id,
wallet_address,
argMax(contract_type, (block_number, log_index)) AS contract_type,
argMax(amount, (block_number, log_index)) AS current_amount
FROM recipe_nft_owners_by_contract.fact_nft_owners_by_contract FINAL
WHERE chain_id = 1 AND token_address = lower('0x...')
GROUP BY token_id, wallet_address
)
WHERE current_amount != '0' AND current_amount != ''
ORDER BY token_id, wallet_address;
```
Current owners (Postgres, after refreshing the materialized view):
```sql theme={null}
REFRESH MATERIALIZED VIEW CONCURRENTLY nft_owners;
SELECT token_id, wallet_address, contract_type, amount
FROM public.nft_owners
WHERE token_address = lower('0x...') AND amount > 0
ORDER BY token_id, wallet_address;
```
Distinct holder count for a collection (Postgres):
```sql theme={null}
SELECT count(DISTINCT wallet_address)
FROM public.nft_owners
WHERE token_address = lower('0x...') AND amount > 0;
```
### Modes
Shipped defaults: **ClickHouse `hybrid`** (backfill → realtime), **Postgres / MySQL `historical`** (one-shot backfill). For live/reorg-safe ingestion, use ClickHouse (see the [overview](/data-feeds/templates/overview#modes)).
> [!NOTE]
>
> Realtime/hybrid on Postgres / MySQL is constrained because the block-level `position` cursor requires a single-column unique key. Run realtime/hybrid on **ClickHouse**; the Postgres / MySQL configs target `historical` backfill.
### Multichain
The template is chain-parametrized via the `chain` setting: point it at any supported EVM chain. NFTs on Solana are SPL tokens; if a chain emits NFT transfers under the same `nftTokenTransfers` struct, set the Solana chain variables. The `vendor_event_id` already incorporates `(token_id, amount)` on top of `log_index` to stay row-unique under Solana's repeated log indices; the owner surface it produces is identical in shape.
### Fidelity gaps
This template returns on-chain ownership only. Fields a Moralis `/nft/{address}/owners` response carries that have **no onchain source** (they need a separate metadata/indexer service) are not populated:
* `name`, `symbol`, `token_uri`, `metadata`, `normalized_metadata`: collection / token metadata (use an NFT Collection Metadata template).
* `possible_spam`, verified-collection flags: risk / curation signals.
* `block_number_minted` and historical mint provenance beyond the backfill window.
`amount` is the raw on-chain holding count, not a marketplace listing. The core access key (`token_address` → owners with `token_id`, `amount`, `contract_type`) is fully sourced from `nftTokenTransfers`.
## Migrating from the REST API
This template replaces the by-collection ownership endpoints of the Web3 API. Data Feeds are **not** 1:1 replicas of those responses: you land the underlying data in your own database and reconstruct the response shape with a query. The subsections below cover each REST endpoint: what replaces it, the field mapping (**exact** = straight from the chain, **calculated** = derived from real trades, very close, **add yourself** = off-chain signal not in the feed), and the endpoint-specific gotchas.
### GET /nft/:address/owners
Every owner of every token in a collection. Replaced by this template's owner surface (`nft_owners` on Postgres/MySQL, `argMax` over the ClickHouse fact table): one row per `(token_id, owner)` with `amount > 0`.
> [!WARNING]
>
> Reproducing the full REST response needs **three templates**, not one. Run this template plus [NFT Collection Metadata](/data-feeds/templates/nft/nft-collection-metadata) (`name` / `symbol`) and [NFT Transfers](/data-feeds/templates/nft/nft-transfers) (mint provenance; the mint is the transfer from the zero address) against the same database. The resolved token metadata is a different story entirely: `token_uri`, `metadata`, and `normalized_metadata` are derived from each token's `tokenURI` off-chain. Pair the template with your own metadata resolver, or drop those fields.
| `/nft/:address/owners` | Data Feeds | Fidelity |
| - | - | - |
| `token_address`, `token_id`, `contract_type`, `owner_of`, `amount` | `nft_owners.*` (`owner_of` = `wallet_address`) | exact |
| `block_number` | `nft_owners.block_number` | exact |
| `block_number_minted`, `minter_address` | `nft_transfers` (mint = from the zero address) | exact |
| `name`, `symbol` | `nft_collection_metadata.*` | exact |
| `token_hash` | derive (hash of contract + id) | exact |
| `last_sale` USD | `nftTrades` + price feed | calculated |
| `token_uri`, `metadata`, `normalized_metadata` | add yourself (resolve token URI) | off-chain |
| `rarity_*`, `floor_price*`, `list_price` | add yourself (rarity tool / marketplace source) | off-chain |
| `possible_spam`, `verified_collection`, `*_sync` timestamps | add yourself | off-chain |
The reconstruction query (Postgres; adapt to your destination):
```sql theme={null}
SELECT o.token_id, o.wallet_address AS owner_of, o.amount, o.contract_type,
c.name, c.symbol, o.block_number
FROM nft_owners o
LEFT JOIN nft_collection_metadata c ON c.token_address = o.token_address
WHERE o.token_address = lower('0x...') AND o.amount > 0
ORDER BY o.token_id, o.wallet_address;
```
**Gotchas**
* **Backfill from the collection's deploy block.** Ownership is current state (the cumulative result of every transfer), so a late start returns stale or missing owners. See [History & backfill](/data-feeds/concepts/history-and-backfill).
* **ERC-1155** token\_ids can have many owners, so you get a row per `(token_id, owner)`; ERC-721 has one owner per id.
* Big collections paginate heavily; keyset on `(token_id, wallet_address)` instead of offset pages.
### GET /nft/:address
Every NFT in a collection with its current owner. Same template, same tables, same joins as `/nft/:address/owners` above: the two endpoints are one read ordered differently (`ORDER BY o.token_id` for the collection listing). The field mapping is identical, plus the listing's extra enrichment fields: `media`, the collection editorial fields (logo, banner, category, social links), and `floor_price*` are all off-chain. **Add yourself** from your metadata resolver and marketplace sources, or drop them.
**Gotchas**
* The REST endpoint was mostly a metadata product; the chain only carries ownership, mint, and identity. If resolved JSON metadata and media are the entire job, keep a metadata indexer for that layer; this template supplies the ownership and provenance to pair with it.
* The REST `totalRanges` / `range` parallel-scan pagination has no equivalent: it's your table now; scan or keyset on `token_id`.
* Backfill from the collection's deploy block, as above.
### Related
> [card] [NFTs by Wallet](/data-feeds/templates/wallet/nfts-by-wallet)
>
> The same ingest, sorted by wallet: every NFT a wallet holds.
> [card] [NFT Transfers](/data-feeds/templates/nft/nft-transfers)
>
> The event-level feed behind these owner observations.
> [card] [NFT Collection Metadata](/data-feeds/templates/nft/nft-collection-metadata)
>
> The name, symbol, and token URIs this template leaves out.
> [card] [NFT Marketplace](/data-feeds/use-cases/nft-marketplace)
>
> The use case this owner surface powers.
# NFT Trades
Source: https://docs.moralis.com/data-feeds/templates/nft/nft-trades
Sync every NFT marketplace trade (seller, buyer, collection, token ID, marketplace, and raw price), re-assembled into one row per traded NFT, into your own database.
### Question it answers
> "Give me every NFT marketplace trade: for collection **0x…**, for a single `(collection, token_id)`, or for wallet **0x…** as seller or buyer."
A single sync serves all three access paths. It mirrors the on-chain subset of Moralis `GET /nft/{address}/trades` (by collection), `GET /nft/{address}/{token_id}/trades` (single token), and `GET /wallets/{address}/nfts/trades` (by wallet). It is an on-chain trade log with no off-chain enrichment: no USD price, no reliable marketplace human-name, no address labels.
### What you get
One row per **traded NFT**: a bundle/batch fill that moves several NFTs lands one row per `(trade, token_id)`, each carrying the bundle's per-item average price:
| Column | Description |
| - | - |
| `token_address` | NFT collection address |
| `token_id` | Token ID traded (`uint256`, stored as text) |
| `seller_address` | The NFT sender on the trade |
| `buyer_address` | The NFT recipient on the trade |
| `amount` | ERC-1155 quantity (`1` for ERC-721) |
| `price` | Raw price in `price_token_address` units; for bundles, the per-item average |
| `price_token_address` | Payment token; `''` means native (ETH) |
| `marketplace_address` | The marketplace contract, the canonical join key for naming |
| `marketplace` | Marketplace human name when decoded (`''` otherwise) |
| `tx_hash`, `block_number`, `log_index`, `transaction_index` | On-chain ordering and provenance |
| `event_ts` | Block time |
To collapse a bundle back to one logical trade, `GROUP BY (tx_hash, log_index)` and `groupArray(token_id)`.
### Source
The template consumes the per-block `tradeTransactions` array, which is **fully flattened**: each element is one item (an NFT transfer, a token transfer, or an internal tx) for one participant in one trade. A single sale is spread across many rows. The transform re-joins those parts into one trade: it identifies the buyer (a participant who received an NFT **and** paid), reads the seller and collection off the received-NFT row, derives the price from the buyer's native or token payment, and emits one row per received NFT.
### Destination
| Destination | Table | Read pattern |
| - | - | - |
| **ClickHouse** (first-class) | `fact_nft_trades` | Prefix scan on `(chain_id, token_address, token_id, block_number)`; `bloom_filter` skip-indexes on `seller_address` / `buyer_address`; read with `FINAL` |
| **Postgres** | `nft_trades` | Indexes on `(token_address, block_number DESC)`, `(token_address, token_id, block_number DESC)`, and seller/buyer |
| **MySQL** | `nft_trades` | Same indexes (without `DESC` on the key) |
ClickHouse uses the collapsing log-table pattern (see the [templates overview](/data-feeds/templates/overview#destinations)): every trade row in a block shares the block's hash, so a per-block reorg corrects all of that block's trades together. The fact table's sort key is collection-first, so by-collection is a prefix scan and by-`(collection, token_id)` is a tighter prefix; by-wallet is served by the bloom-filter indexes. Read canonical state with `FINAL` or a sign-aware aggregate, never a bare `WHERE sign = 1`.
### Full schema
Below is the complete read table this template produces. It's a starting point: keep the columns you need and drop the rest (see [Schema & flexibility](/data-feeds/templates/overview#schema--flexibility)). `token_id` and `price` are raw `uint256` values that exceed numeric precision, so they're stored as text / wide decimals.
> [accordion] ClickHouse, fact\_nft\_trades
>
> ```sql theme={null}
> CREATE TABLE recipe_nft_trades.fact_nft_trades
> (
> vendor_event_id String,
> ingested_at DateTime64(3),
> chain_id UInt32,
> block_hash String,
> block_number UInt64,
> event_ts DateTime64(3),
> token_address String, -- NFT collection address
> token_id String, -- uint256 big decimal, NEVER numeric
> seller_address String,
> buyer_address String,
> amount String, -- ERC-1155 quantity (1 for ERC-721)
> price String, -- raw, in price_token units
> price_token_address String, -- '' ⇒ native (ETH)
> marketplace String, -- human name when decoded ('' otherwise)
> marketplace_address String,
> tx_hash String,
> log_index Nullable(UInt32),
> transaction_index Nullable(Int32),
> sign Int8,
> -- by-wallet skip indexes: prune granules that cannot contain the wallet.
> INDEX bf_seller seller_address TYPE bloom_filter(0.01) GRANULARITY 4,
> INDEX bf_buyer buyer_address TYPE bloom_filter(0.01) GRANULARITY 4
> )
> ENGINE = ReplicatedCollapsingMergeTree(
> '/clickhouse/tables/{database}/fact_nft_trades', '{replica}', sign)
> PARTITION BY (chain_id, toYYYYMM(event_ts))
> ORDER BY (chain_id, token_address, token_id, block_number, vendor_event_id);
> ```
>
> The `sign` column drives reorg collapsing: read with `FINAL` or `sum(sign)`. A single-node setup can use `CollapsingMergeTree(sign)` without the replication path. The seller/buyer bloom-filter indexes ship enabled because by-wallet is a first-class access path here.
> [accordion] Postgres, nft\_trades
>
> ```sql theme={null}
> CREATE TABLE public.nft_trades (
> position BIGINT NOT NULL,
> log_index BIGINT,
> transaction_index BIGINT,
> block_number BIGINT NOT NULL,
> block_timestamp BIGINT NOT NULL, -- unix seconds
> tx_hash TEXT NOT NULL,
> vendor_event_id TEXT NOT NULL,
> token_address TEXT NOT NULL, -- NFT collection address
> token_id TEXT NOT NULL, -- uint256 big decimal, NEVER numeric
> seller_address TEXT NOT NULL,
> buyer_address TEXT NOT NULL,
> amount NUMERIC(76, 0) NOT NULL, -- ERC-1155 quantity (1 for ERC-721)
> price NUMERIC(76, 0) NOT NULL, -- raw, in price_token units
> price_token_address TEXT NOT NULL, -- '' ⇒ native (ETH)
> marketplace TEXT NOT NULL, -- human name when decoded ('' otherwise)
> marketplace_address TEXT NOT NULL
> );
>
> -- By-collection access (the template's primary purpose).
> CREATE INDEX IF NOT EXISTS nft_trades_token_block_idx
> ON public.nft_trades (token_address, block_number DESC);
> -- By-token-id access (single NFT sale history).
> CREATE INDEX IF NOT EXISTS nft_trades_token_id_block_idx
> ON public.nft_trades (token_address, token_id, block_number DESC);
> -- By-wallet access (either side).
> CREATE INDEX IF NOT EXISTS nft_trades_seller_block_idx
> ON public.nft_trades (seller_address, block_number DESC);
> CREATE INDEX IF NOT EXISTS nft_trades_buyer_block_idx
> ON public.nft_trades (buyer_address, block_number DESC);
> -- Block-range helper.
> CREATE INDEX IF NOT EXISTS nft_trades_block_idx
> ON public.nft_trades (block_number);
> ```
>
> MySQL is the same shape with `DECIMAL(76,0)` for `amount` / `price` and the equivalent keys. `position` is the block-level cursor used during backfill.
### Example reads
All trades of an NFT collection, newest first (ClickHouse):
```sql theme={null}
SELECT block_number, token_id, seller_address, buyer_address,
price, price_token_address, marketplace_address, tx_hash
FROM recipe_nft_trades.fact_nft_trades FINAL
WHERE chain_id = 1
AND token_address = lower('0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D')
ORDER BY block_number DESC
LIMIT 50;
```
Sale history of a single token (collection + token\_id):
```sql theme={null}
SELECT block_number, seller_address, buyer_address, price, price_token_address, tx_hash
FROM recipe_nft_trades.fact_nft_trades FINAL
WHERE chain_id = 1
AND token_address = lower('0xBC4C...')
AND token_id = '1234'
ORDER BY block_number DESC
LIMIT 50;
```
All trades involving a wallet (as seller or buyer), bloom-pruned:
```sql theme={null}
SELECT block_number, token_address, token_id, seller_address, buyer_address, price
FROM recipe_nft_trades.fact_nft_trades FINAL
WHERE chain_id = 1
AND (seller_address = lower('0x...') OR buyer_address = lower('0x...'))
ORDER BY block_number DESC
LIMIT 50;
```
### Modes
Shipped defaults: **ClickHouse `hybrid`** (backfill → realtime), **Postgres / MySQL `historical`** (one-shot backfill). For live/reorg-safe ingestion, use ClickHouse (see the [overview](/data-feeds/templates/overview#modes)).
> [!NOTE]
>
> The realtime reorg path needs a single-column `UNIQUE` on the position column, but `position` is block-level; many trades share one block. Array-expanded trade rows can only carry a composite unique, so run realtime/hybrid on **ClickHouse** (its log table corrects reorgs per-block). The Postgres / MySQL configs are intended for `historical` backfill.
### Multichain
The template is chain-parametrized: point it at any supported EVM chain or Solana. Solana marketplace trades (Magic Eden, Tensor, and others) populate the same `tradeTransactions` shape. Solana assigns the same `log_index` to multiple events in one instruction, so the trade's identity is widened with `(seller, buyer, token_address, token_id)` to keep rows distinct; the trade log it produces is identical in shape.
### Fidelity gaps
The template lands the columns the trade array carries. Fields a Moralis NFT trades endpoint surfaces that have no reliable on-chain source here are omitted:
* **USD price.** `price` is the raw amount in `price_token_address` units (native ETH when `price_token_address = ''`). Converting to USD needs a same-block Token Prices join or an external price feed, which is out of scope for this on-chain trade log.
* **Marketplace human name.** The `marketplace` field is frequently empty/unreliable on-chain and is landed as-is (`''` when absent). `marketplace_address` is always present; map it to a human name with an off-chain marketplace directory.
* **Address labels** (`seller_address_label`, `buyer_address_label`): off-chain entity tags, not on-chain data.
* **Collection metadata** (`token_name`, `token_symbol`): from the NFT contract or a metadata indexer, not the trade event (see NFT Collection Metadata).
* **Smallest-total price-token quirk.** When a buyer pays in tokens across multiple token addresses, the price token is chosen as the **smallest** summed total. This is preserved for parity with the production transformer; it is a likely upstream quirk. Native-paid trades (the common case) are unaffected.
### Related
> [card] [NFT Transfers](/data-feeds/templates/nft/nft-transfers)
>
> Every NFT movement (mints, transfers, burns), the untraded counterpart to this trade log.
> [card] [NFT Marketplace](/data-feeds/use-cases/nft-marketplace)
>
> The use case this trade feed powers.
# NFT Transfers
Source: https://docs.moralis.com/data-feeds/templates/nft/nft-transfers
Sync every ERC-721 / ERC-1155 transfer, by contract, by wallet, or for a single (contract, token_id), as a flat event log into your own database.
### Question it answers
> "Give me every NFT transfer: by contract **0x…**, by wallet **0x…**, or for a single `(contract, token_id)`."
A single template serves all three access paths. It mirrors the on-chain subset of Moralis `GET /nft/{address}/transfers` (by contract), `GET /{address}/nft/transfers` (by wallet), and `GET /nft/{address}/{token_id}/transfers` (single token). It carries no off-chain enrichment: the source array has no collection metadata or address labels (see [Fidelity gaps](#fidelity-gaps)).
### What you get
One row per NFT transfer, mapped straight from Moralis-indexed, normalized per-block onchain data:
| Column | Description |
| - | - |
| `token_address` | The NFT contract that emitted the transfer |
| `token_id` | The token id, a `uint256` big decimal stored as text (never numeric); compare as strings |
| `from_address`, `to_address` | The two sides of the transfer |
| `amount` | The ERC-1155 quantity (`1` for ERC-721) |
| `contract_type` | `ERC721` or `ERC1155` (the emitted `tokenType`) |
| `initiated_by` | The address that initiated the transfer |
| `tx_hash` | Transaction that produced the transfer |
| `block_number`, `transaction_index`, `log_index` | On-chain ordering tuple |
| `block_timestamp` | Block time |
### Source
The transform reads one per-block array and lands one row per transfer:
`nftTokenTransfers`
Fields map straight from the source struct: `tokenAddress`, `tokenId` (as a string), `fromAddress`, `toAddress`, `amount`, `tokenType` (→ `contract_type`), and `initiatedBy`. There's no price or metadata join; this is a flat event stream.
### Destination
| Destination | Table | Read pattern |
| - | - | - |
| **ClickHouse** (first-class) | `fact_nft_transfers` | Prefix scan on `(chain_id, token_address, token_id, block_number)`; by-wallet via `bloom_filter` skip indexes; read with `FINAL` or `sum(sign)` |
| **Postgres** | `nft_transfers` | Index on `(token_address, block_number DESC)`, `(token_address, token_id, block_number DESC)`, and `(from_address, …)` / `(to_address, …)` |
| **MySQL** | `nft_transfers` | Same composite indexes (ascending) |
ClickHouse uses the collapsing log-table pattern (see the [templates overview](/data-feeds/templates/overview#destinations)) so chain reorganizations self-correct: the `+1/−1` reorg pair for a row shares an identical key and collapses cleanly. The fact table's sort key is contract-first, so by-contract is a prefix scan on `token_address` and by-token-id a prefix scan on `(token_address, token_id)`. By-wallet reads are served by `bloom_filter` data-skipping indexes on `from_address` and `to_address`.
### Full schema
Below is the complete read table this template produces. Keep the columns you need and drop the rest (see [Schema & flexibility](/data-feeds/templates/overview#schema--flexibility)). `token_id` and `amount` are stored at full `uint256` width: `token_id` as text (hash-derived ENS / ERC-1155 ids routinely exceed any SQL numeric precision), `amount` as a wide decimal.
> [accordion] ClickHouse, fact\_nft\_transfers
>
> ```sql theme={null}
> CREATE TABLE recipe_nft_transfers.fact_nft_transfers
> (
> vendor_event_id String,
> ingested_at DateTime64(3),
> chain_id UInt32,
> block_hash String,
> block_number UInt64,
> event_ts DateTime64(3),
> token_address String,
> token_id String, -- uint256 big decimal, NEVER numeric
> from_address String,
> to_address String,
> amount String, -- ERC-1155 quantity (1 for ERC-721)
> contract_type LowCardinality(String), -- ERC721 | ERC1155
> initiated_by String,
> tx_hash String,
> log_index Nullable(UInt32),
> transaction_index Nullable(Int32),
> sign Int8,
> -- by-wallet skip indexes: prune granules that cannot contain the wallet.
> INDEX bf_from from_address TYPE bloom_filter(0.01) GRANULARITY 4,
> INDEX bf_to to_address TYPE bloom_filter(0.01) GRANULARITY 4
> )
> ENGINE = ReplicatedCollapsingMergeTree(
> '/clickhouse/tables/{database}/fact_nft_transfers', '{replica}', sign)
> PARTITION BY (chain_id, toYYYYMM(event_ts))
> ORDER BY (chain_id, token_address, token_id, block_number, vendor_event_id);
> ```
>
> The `sign` column drives reorg collapsing: read with `FINAL` or `sum(sign)`, never a bare `WHERE sign = 1`. A single-node setup can use `CollapsingMergeTree(sign)` without the replication path.
> [accordion] Postgres, nft\_transfers
>
> ```sql theme={null}
> CREATE TABLE public.nft_transfers (
> position BIGINT NOT NULL,
> log_index BIGINT,
> transaction_index BIGINT,
> block_number BIGINT NOT NULL,
> block_timestamp BIGINT NOT NULL, -- unix seconds
> tx_hash TEXT NOT NULL,
> vendor_event_id TEXT NOT NULL,
> token_address TEXT NOT NULL,
> token_id TEXT NOT NULL, -- uint256 big decimal, NEVER numeric
> from_address TEXT NOT NULL,
> to_address TEXT NOT NULL,
> amount NUMERIC(76, 0) NOT NULL,
> contract_type TEXT NOT NULL, -- ERC721 | ERC1155
> initiated_by TEXT NOT NULL
> );
>
> -- By-contract access (the template's primary purpose).
> CREATE INDEX IF NOT EXISTS nft_transfers_token_block_idx
> ON public.nft_transfers (token_address, block_number DESC);
> -- By-token-id access (single NFT provenance).
> CREATE INDEX IF NOT EXISTS nft_transfers_token_id_block_idx
> ON public.nft_transfers (token_address, token_id, block_number DESC);
> -- By-wallet access (either side).
> CREATE INDEX IF NOT EXISTS nft_transfers_from_block_idx
> ON public.nft_transfers (from_address, block_number DESC);
> CREATE INDEX IF NOT EXISTS nft_transfers_to_block_idx
> ON public.nft_transfers (to_address, block_number DESC);
> -- Block-range helper.
> CREATE INDEX IF NOT EXISTS nft_transfers_block_idx
> ON public.nft_transfers (block_number);
> ```
>
> MySQL is the same shape with `VARCHAR(80)` for `token_id` and equivalent ascending composite keys. `position` is the block-level cursor used during backfill.
### Example reads
All transfers of an NFT contract, newest first (ClickHouse):
```sql theme={null}
SELECT block_number, token_id, from_address, to_address, amount, contract_type, tx_hash
FROM recipe_nft_transfers.fact_nft_transfers FINAL
WHERE chain_id = 1 AND token_address = lower('0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D')
ORDER BY block_number DESC
LIMIT 50;
```
Provenance of a single token (contract + token\_id):
```sql theme={null}
SELECT block_number, from_address, to_address, amount, tx_hash
FROM recipe_nft_transfers.fact_nft_transfers FINAL
WHERE chain_id = 1 AND token_address = lower('0xBC4C...') AND token_id = '1234'
ORDER BY block_number DESC
LIMIT 50;
```
All NFT transfers involving a wallet (either side), bloom-pruned:
```sql theme={null}
SELECT block_number, token_address, token_id, from_address, to_address, amount
FROM recipe_nft_transfers.fact_nft_transfers FINAL
WHERE chain_id = 1
AND (from_address = lower('0x...') OR to_address = lower('0x...'))
ORDER BY block_number DESC
LIMIT 50;
```
### Modes
Shipped defaults: **ClickHouse `hybrid`** (backfill → realtime), **Postgres / MySQL `historical`** (one-shot backfill). For live/reorg-safe ingestion, use ClickHouse (see the [overview](/data-feeds/templates/overview#modes)).
> [!NOTE]
>
> The realtime reorg path needs a single-column `UNIQUE` on the position column, but `position` is block-level (many transfers share one block), so array-expanded transfer rows can only carry a composite unique. Run **realtime / hybrid on ClickHouse**: its log table corrects reorgs per-block via the collapsing companion table. The Postgres / MySQL shapes here are intended for `historical` backfill.
### Multichain
The template is chain-parametrized: point it at any supported EVM chain or Solana. On Solana the same `logIndex` can be assigned to multiple events in one instruction, so the event identity is widened with `(from_address, to_address, token_address, token_id, amount)` to keep rows distinct; the transfer log it produces is identical in shape.
### Fidelity gaps
The template lands only what the `nftTokenTransfers` array carries. Fields a Moralis NFT transfers endpoint surfaces that have **no onchain source** in this array are omitted:
* **Collection metadata** (`token_name`, `token_symbol`): these come from the NFT contract / a metadata indexer, not the transfer event. Out of scope for a flat transfer log; see NFT Collection Metadata for the contract-metadata pattern.
* **Address labels / entity tags** (`from_address_label`, `to_address_entity`, …): off-chain labels from a separate labelling service, not on-chain data.
* **`value`**: the native value attached to the transfer transaction isn't carried on the transfer event; omitted. `amount` (the ERC-1155 quantity) is present.
* **Pre/post NFT balances**: the template omits the balance surface to stay a flat event stream.
## Migrating from the REST API
This template replaces the wallet NFT transfers REST endpoint. Data Feeds are **not** 1:1 replicas of the old responses: you land the underlying data in your own database and reconstruct the response shape with a query. Below: what replaces the endpoint, the field mapping (**exact** = straight from the chain, **calculated** = derived from real trades, very close, **add yourself** = off-chain signal not in the feed), and the endpoint-specific gotchas.
### GET /:address/nft/transfers
A wallet's NFT transfer history. Replaced by this template's `nft_transfers` table: a wallet's transfers are the rows where it appears on either side, and the old endpoint's `contract_addresses`, `from_block`/`to_block`, and `order` parameters become plain `WHERE` / `ORDER BY` clauses.
> [!WARNING]
>
> Reproducing the full REST response needs **three templates**, not one. The transfer event carries no collection metadata or sale context. Run this template plus [NFT Collection Metadata](/data-feeds/templates/nft/nft-collection-metadata) (`token_name` / `token_symbol`) and [NFT Trades](/data-feeds/templates/nft/nft-trades) (`last_sale`) against the same database and join them.
| `/:address/nft/transfers` | Data Feeds | Fidelity |
| - | - | - |
| `token_address`, `token_id`, `contract_type` | `nft_transfers.*` | exact |
| `from_address`, `to_address`, `amount` | `nft_transfers.*` | exact |
| `operator` | `nft_transfers.initiated_by` | exact |
| `transaction_hash`, `block_number`, `block_timestamp`, `transaction_index`, `log_index` | `nft_transfers.tx_hash` / `nft_transfers.*` | exact |
| `value` (tx native value), `transaction_type` (Single/Batch) | the `nftTokenTransfers` source array, not the flat table (or `nftTrades` for sale price) | exact |
| `token_name`, `token_symbol` | `nft_collection_metadata.*` | exact |
| `last_sale` (sale facts) | `nftTrades` | exact |
| `last_sale` USD values | `nftTrades` + price feed | calculated |
| `possible_spam`, `verified_collection` | add yourself | off-chain |
| `from/to_address_label`, `*_entity`, `*_entity_logo` | add yourself | off-chain |
The reconstruction query (Postgres; adapt to your destination):
```sql theme={null}
SELECT t.*,
c.name AS token_name, c.symbol AS token_symbol,
CASE WHEN t.from_address = lower('0xWALLET') THEN 'send' ELSE 'receive' END AS direction
FROM nft_transfers t
LEFT JOIN nft_collection_metadata c ON c.token_address = t.token_address
WHERE (t.from_address = lower('0xWALLET') OR t.to_address = lower('0xWALLET'))
ORDER BY t.block_number DESC, t.log_index DESC
LIMIT 100;
```
**Gotchas**
* **Direction is yours to derive**: the feed has no `send`/`receive` flag; compare the wallet to `from_address`/`to_address` as above. The template indexes both sides, so the OR match stays fast.
* The address labels and spam/verification flags are off-chain signals with no onchain source: drop them, bring your own lists, or layer in a label source.
* `token_id` is a `uint256` stored as text; compare as strings, never as numbers.
* Backfill depth is your choice: transfers are an event list, not current state, so index only as much history as your app serves.
### Related
> [card] [NFT Trades](/data-feeds/templates/nft/nft-trades)
>
> Marketplace sales with price, the trade-priced complement to raw transfers.
> [card] [NFT Marketplace](/data-feeds/use-cases/nft-marketplace)
>
> The use case these NFT templates power.
# Data Feed Templates
Source: https://docs.moralis.com/data-feeds/templates/overview
Pre-built blueprints that reconstruct Moralis's most popular endpoints (wallet history, balances, prices, swaps, holders) as continuous syncs into your own ClickHouse, Postgres, or MySQL.
### What a template is
A **template** is a ready-made blueprint that reconstructs one popular Moralis endpoint as a continuous sync into a database you own. Instead of calling an API per request, you run the template once and the data lands, and stays current, in your own ClickHouse, Postgres, or MySQL.
> [!NOTE]
>
> **Coming from the Moralis REST API?** Each template maps to one or more REST endpoints. Start with the [migration overview](/data-feeds/migration/overview) for how the API and Data Feeds differ, then use the [endpoint list](/data-feeds/migration/endpoints) to find the field-by-field guide for the endpoint you call today.
Each template ships everything you need to run it:
> [card] Sync config
>
> The source data, the projection that shapes it, and the destination wiring.
> [card] Schema
>
> The destination DDL: tables, indexes, and materialized views.
> [card] Queries
>
> The exact reads that answer the endpoint's question.
Templates are **blueprints, not turnkey deployments**: they show the projection, schema, index layout, and reorg strategy for each access pattern. Lift the pieces you need.
### How a template works
Every template is the same three-stage pipeline:
```text theme={null}
Data Feeds source → transform (projection) → your database
```
1. **Source**: normalized per-block data from Data Feeds. One block carries arrays of every event type (token transfers, native transfers, NFT transfers, swaps, approvals, price updates, and more).
2. **Transform**: a projection that expands the arrays you care about into one row per event and shapes them into the endpoint's schema.
3. **Destination**: the rows land in your database, indexed for the access pattern the endpoint serves (by wallet, by token, by pair, …).
The same source event stream can land **different ways** for different questions: e.g. "balances by wallet" and "balances by token" are the same sync with a different sort key.
### Schema & flexibility
Every template page includes a **full schema** (the complete set of columns that access pattern can produce), but nothing about it is fixed. Templates are blueprints you shape to your needs:
* **Select the columns you want.** Start from the full wide table and keep only the fields your app reads. The projection pulls just the source fields behind the columns you keep, so trimming the schema trims the work.
* **Select the events you want.** Multi-event templates (like [Wallet History](/data-feeds/templates/wallet/wallet-history)) union several event types into one table; drop the branches you don't need.
* **Choose your keys and indexes.** The sort key and indexes are tuned for the headline access pattern; re-key for yours. Optional structures (like the by-`topic0` grouping on the [log templates](/data-feeds/templates/logs/contract-logs)) ship commented-out; enable them only when you need them.
* **Pick your destination types.** Adjust column types to fit your warehouse. The shipped DDL flags where precision matters: raw `uint256` amounts as text, USD as wide decimals.
In other words: the full schema is a **starting point, not a contract**. Take the complete shape and pare it down.
### Destinations
Templates support three destinations. **ClickHouse is the first-class path**; it's the only one that handles live, reorg-safe ingestion:
| Destination | Best for | Realtime / reorg-safe |
| - | - | - |
| **ClickHouse** | Production, large windows, live tailing | ✅ Yes (corrects chain reorganizations automatically) |
| **Postgres** | Historical backfill, analytics, smaller windows | Backfill-first |
| **MySQL** | Historical backfill, existing MySQL stacks | Backfill-first |
ClickHouse templates use a **collapsing log-table** pattern: events land in a wide table, and a companion log table carries one signed row per block. When the chain reorganizes, the log emits a counter-row and ClickHouse collapses the pair on merge, so your tables converge on canonical state without manual cleanup. Read canonical state with `FINAL` or a sign-aware aggregate, never a bare `WHERE sign = 1`.
Postgres and MySQL templates write flat, uniquely-keyed event tables and are **first-class for historical backfill**. For live/reorg-safe ingestion on these shapes, use ClickHouse.
### Modes
| Mode | What it does | Default for |
| - | - | - |
| `historical` | One-shot backfill of a block window | Postgres / MySQL |
| `realtime` | Live tail from the chain head | None |
| `hybrid` | Backfill, then a seamless handoff to realtime | ClickHouse |
### Token Prices is the connective tissue
Any "what is this worth in USD" question (a transfer's value, a portfolio's worth, a trade's notional) needs prices. The [Token Prices](/data-feeds/templates/token/token-prices) template is the shared join target across the accounting, portfolio, and trading use cases. Several templates (like [Wallet History](/data-feeds/templates/wallet/wallet-history)) also fold per-block USD values inline so common reads need no extra join.
### Template catalogue
Templates are grouped by the API product they replace, so you can start from the API you use today. ⭐ marks
the most popular endpoints.
**Coming from the REST API?** Each template page ends with a **"Migrating from the REST API"** section: the
REST endpoint(s) it replaces, the field-by-field mapping, and (because Data Feeds are not a 1:1 endpoint
swap) the exact combination of templates you need when one endpoint spans several datasets. The
[Map endpoints to templates](/data-feeds/migration/endpoints) table maps all covered endpoints in one place.
| API | Template | Answers |
| - | - | - |
| **Wallet API** | [Wallet History](/data-feeds/templates/wallet/wallet-history) ⭐ | Every event a wallet was involved in |
| | [Token Balances by Wallet](/data-feeds/templates/wallet/token-balances-by-wallet) ⭐ | Every token a wallet holds, with balance |
| | [Native Balances](/data-feeds/templates/wallet/native-balances) | Native-asset balance per wallet |
| | [NFTs by Wallet](/data-feeds/templates/wallet/nfts-by-wallet) ⭐ | Every NFT a wallet holds |
| | [Token Approvals](/data-feeds/templates/wallet/token-approvals) | Current allowances a wallet has granted |
| **Token API** | [Token Holders](/data-feeds/templates/token/token-holders) ⭐ | All non-zero holders of a token |
| | [Token Balances by Token](/data-feeds/templates/token/token-balances-by-token) | Holder balances, keyed by token |
| | [Token Transfers](/data-feeds/templates/token/token-transfers) | Every transfer of a token |
| | [Token Stats](/data-feeds/templates/token/token-stats) | Per-token transfer counters |
| | [Token Metadata](/data-feeds/templates/token/token-metadata) | Name, symbol, decimals, supply |
| **Price API** | [Token Prices](/data-feeds/templates/token/token-prices) ⭐ | USD/native mark history for a token |
| | [Pair OHLCV](/data-feeds/templates/markets/pair-ohlcv) | Candles per pool |
| **DeFi API** | [Swaps by Wallet](/data-feeds/templates/markets/swaps-by-wallet) ⭐ | Every DEX trade made by a wallet |
| | [Swaps by Token](/data-feeds/templates/markets/swaps-by-token) ⭐ | Every DEX trade touching a token |
| | [Swaps by Pair](/data-feeds/templates/markets/swaps-by-pair) | Every DEX trade on a pool/pair |
| | [Pair Reserves](/data-feeds/templates/markets/pair-reserves) | Current reserves per pool |
| **NFT API** | [NFT Trades](/data-feeds/templates/nft/nft-trades) | Marketplace trades per collection / token / wallet |
| | [NFT Transfers](/data-feeds/templates/nft/nft-transfers) | Every NFT movement |
| | [NFT Owners by Contract](/data-feeds/templates/nft/nft-owners-by-contract) | Current owners of a collection |
| | [NFT Collection Metadata](/data-feeds/templates/nft/nft-collection-metadata) | Collection-level metadata |
| **Blockchain API** | [Contract Logs](/data-feeds/templates/logs/contract-logs) | Every raw event log emitted by a contract |
| | [Logs by Event Signature](/data-feeds/templates/logs/logs-by-topic0) | One event signature (`topic0`) across all contracts |
> [!NOTE]
>
> These are blueprints, not turnkey deployments; lift the projection, schema, and queries you need. See the use cases for ready-made template bundles: [Accounting & Tax](/data-feeds/use-cases/accounting), [Portfolio Tracking](/data-feeds/use-cases/portfolio-tracking), [Token Analytics](/data-feeds/use-cases/token-analytics), [Trading & Charting](/data-feeds/use-cases/trading-charting), [NFT Marketplace](/data-feeds/use-cases/nft-marketplace), [Compliance & AML](/data-feeds/use-cases/compliance-aml), and [Onchain Event Indexing](/data-feeds/use-cases/event-indexing).
### Get started
> [card] [Run your first template](/data-feeds/migration/quickstart)
>
> Set up a sink and see template data land in your own database.
# Historical Balances
Source: https://docs.moralis.com/data-feeds/templates/token/historical-balances
Reconstruct any wallet's balance of any token at any past block, and the full holder set of a token as of a block, from a retained per-(wallet, token) balance event log in your own database.
### Question it answers
> "What was wallet **0x…**'s balance of token **0x…** at block **N**, for any past block? And who held the token back then?"
The latest-state balance templates ([Token Balances by Wallet](/data-feeds/templates/wallet/token-balances-by-wallet), [Token Holders](/data-feeds/templates/token/token-holders)) keep only the *current* balance. This template keeps **every** observation, so an as-of-block balance is a point lookup and a token's **holder set at block N** is a single query.
### What you get
Token transfers carry the **absolute** post-transfer balance of both sides (`fromPostBalance` / `toPostBalance`). Each transfer becomes two per-wallet observations, and **all** of them are retained (not just the latest). The balance as of block N is the observation with the highest `(block_number, log_index)` at or below N.
| Column | Description |
| - | - |
| `wallet_address` | The holder, leading sort key |
| `token_address` | The token contract |
| `balance` | Absolute post-transfer balance, raw `uint256` as text |
| `block_number`, `log_index` | Recency tuple, the latest at or below N wins |
| `leg` | `from` / `to`, which side of the transfer produced this observation |
| `tx_hash`, `event_ts` | The transaction and block time |
| `vendor_event_id` | Stable per-observation identity |
### Source
The transform reads one per-block array, `tokenTransfers`, and unpivots each transfer into `(from_address, from_post_balance)` and `(to_address, to_post_balance)`. Because the source supplies **absolute** post-balances, there's no running-sum reconstruction: the balance at any block is just the latest retained observation at or below it.
### Destination
| Destination | Table | As-of-block access |
| - | - | - |
| **ClickHouse** (first-class) | `fact_balance_observations` | `argMax(balance, (block_number, log_index))` over `FINAL` `WHERE block_number <= N` |
| **Postgres** | `wallet_token_balance_history` (append-only event log) | `DISTINCT ON (wallet, token) … WHERE block_number <= N ORDER BY … block_number DESC, log_index DESC` |
| **MySQL** | `wallet_token_balance_history` (append-only event log) | correlated subquery per `(wallet, token)` served by `(wallet, token, block_number, log_index)` |
ClickHouse uses the collapsing log-table pattern (see the [templates overview](/data-feeds/templates/overview#destinations)) so chain reorganizations self-correct. The fact table's sort key is wallet-first, so a wallet's balance timeline is a contiguous range read; a bloom skip index on `token_address` serves the inverse "holders of token T" access path.
### Full schema
> [accordion] ClickHouse, fact\_balance\_observations
>
> ```sql theme={null}
> CREATE TABLE recipe_historical_balance_at_block.fact_balance_observations
> (
> vendor_event_id String,
> ingested_at DateTime64(3),
> chain_id UInt32,
> block_hash String,
> block_number UInt64,
> log_index UInt32,
> event_ts DateTime64(3),
> tx_hash String,
> token_address String,
> wallet_address String,
> balance String, -- absolute post-transfer balance, raw uint256
> leg LowCardinality(String), -- 'from' | 'to'
> sign Int8,
> INDEX bf_token token_address TYPE bloom_filter(0.01) GRANULARITY 4
> )
> ENGINE = ReplicatedCollapsingMergeTree(
> '/clickhouse/tables/{database}/fact_balance_observations', '{replica}', sign)
> PARTITION BY (chain_id, toYYYYMM(event_ts))
> ORDER BY (chain_id, wallet_address, token_address, block_number, log_index, vendor_event_id, leg);
> ```
>
> Read with `FINAL` (then `argMax`) or a sign-aware aggregate, never a bare `WHERE sign = 1`. A single-node setup can use `CollapsingMergeTree(sign)` without the replication path.
> [accordion] Postgres, wallet\_token\_balance\_history
>
> ```sql theme={null}
> CREATE TABLE public.wallet_token_balance_history (
> position BIGINT NOT NULL,
> log_index BIGINT NOT NULL,
> block_number BIGINT NOT NULL,
> block_timestamp BIGINT NOT NULL, -- unix seconds
> tx_hash TEXT NOT NULL,
> token_address TEXT NOT NULL,
> wallet_address TEXT NOT NULL,
> balance NUMERIC(76, 0) NOT NULL, -- absolute post-transfer balance
> leg TEXT NOT NULL, -- 'from' | 'to'
> vendor_event_id TEXT NOT NULL,
> UNIQUE (vendor_event_id, leg)
> );
>
> -- As-of-block recency index: leads with (wallet, token) so a DISTINCT ON with a
> -- block_number cap avoids a sort and range-scans on block_number.
> CREATE INDEX wtbh_wallet_token_recency_idx
> ON public.wallet_token_balance_history
> (wallet_address, token_address, block_number DESC, log_index DESC);
> ```
>
> MySQL is the same shape with `DECIMAL(76,0)`. `position` is the block-level cursor used during backfill.
### Run it
Everything runs in **your** infrastructure: the sink writes into a database you own and you query it with plain SQL, no API and no per-call limits.
**Prerequisites**
* **Docker** and Docker Compose.
* A **Data Feeds key**, a `cm_live_…` key with `continuum:read` scope (this is *not* your Web3 API key).
> [card] [Sign up for a Data Feeds key](https://admin.moralis.com)
>
> Log in to the Moralis admin panel to create your account and generate a `cm_live_…` key.
**Start the sink**
Generate a **starter pack** for `historicalBalanceAtBlock` in the [Moralis Admin Panel](https://admin.moralis.com), pick your chain and destination database, then run it with Docker. The [quickstart](/data-feeds/migration/quickstart) walks through it end to end. Set the backfill window (`MORALIS_HISTORICAL_FROM_BLOCK`) as noted below.
> [!NOTE]
>
> **Backfill full history for correct point-in-time answers.** An as-of-block balance (or holder set) is only correct if the observation log goes back far enough, a wallet may have last moved the token long before block N. For token-scoped questions ("holders of token T at block N"), backfill from around the **token's deployment block**; for whole-wallet history, backfill from an early block. A recent-only window gives wrong historical answers. See [History & backfill](/data-feeds/concepts/history-and-backfill).
Then run the example reads below to confirm rows are landing.
### Example reads
Balance of one `(wallet, token)` as of block N (ClickHouse):
```sql theme={null}
SELECT argMax(balance, (block_number, log_index)) AS balance_at_n
FROM recipe_historical_balance_at_block.fact_balance_observations FINAL
WHERE chain_id = 1
AND wallet_address = lower('0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045')
AND token_address = lower('0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48')
AND block_number <= {N:UInt64};
```
A token's **holder set as of block N**, the historical-holders query, biggest first:
```sql theme={null}
SELECT wallet_address,
argMax(balance, (block_number, log_index)) AS balance_at_n
FROM recipe_historical_balance_at_block.fact_balance_observations FINAL
WHERE chain_id = 1
AND token_address = lower('0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48')
AND block_number <= {N:UInt64}
GROUP BY wallet_address
HAVING balance_at_n != '0' AND balance_at_n != ''
ORDER BY toFloat64OrZero(balance_at_n) DESC
LIMIT 100;
```
Postgres (as-of-block balance for a wallet, index-driven):
```sql theme={null}
SELECT DISTINCT ON (token_address)
token_address, balance
FROM public.wallet_token_balance_history
WHERE wallet_address = lower('0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045')
AND block_number <= $1
ORDER BY token_address, block_number DESC, log_index DESC;
```
### Other ways to consume this data
The sink is the way to get **this retained balance log** (`fact_balance_observations` / `wallet_token_balance_history`), recommended for point-in-time queries you own. The *same underlying data* is also available as the **raw decoded feed**, if you'd rather retain balance history yourself:
* **Your existing message clients**: stream it with **Kafka / AMQP / SQS**.
* **REST / Arrow Flight**: pull the decoded block stream directly.
Those give you the **source array** (`tokenTransfers`, with absolute post-balances) to build the history yourself, not this retained log. All of them read the one data lake into **your** infrastructure. See [What are Data Feeds?](/data-feeds/concepts/what-are-data-feeds).
### Modes
Shipped defaults: **ClickHouse `hybrid`** (backfill → realtime), **Postgres / MySQL `historical`** (one-shot backfill). For live/reorg-safe ingestion, use ClickHouse, see the [overview](/data-feeds/templates/overview#modes).
> [!NOTE]
>
> The append-only log on Postgres / MySQL isn't reorg-aware on its own. Run realtime/hybrid on **ClickHouse**, where the collapsing log table corrects reorgs per-block via `sign`; the Postgres / MySQL configs target `historical` backfill.
### Multichain
The template is chain-parametrized via the `chain` setting, point it at any supported EVM chain or **Solana**. The Solana feed's `tokenTransfers` carry the same absolute `fromPostBalance` / `toPostBalance` fields, so the template produces an identically-shaped balance history; the `vendor_event_id` already folds in `(from, to, token, amount)` to stay row-unique under Solana's repeated `logIndex`.
### Fidelity gaps
* **`balance_formatted`**: needs the token's `decimals` (contract metadata, not in `tokenTransfers`). Only the raw `balance` is emitted; divide by `10^decimals` off-stream, sourcing decimals from a [Token Metadata](/data-feeds/templates/token/token-metadata) sync.
* **No USD value**: this template lands quantities. Join a price feed at read time if you want historical USD.
* **Native balance at block**: not covered in v1; the same pattern over `nativeTransfers` post-balances would unlock it.
On-chain primitives, wallet, token, raw post-event balance, block, log index, tx hash, are fully covered.
## Migrating from the REST API
This template replaces the deprecated **historical token holders** endpoints on EVM and Solana.
> [!WARNING]
>
> Both REST endpoints below are **deprecated and sunset on July 31, 2026**. Migrate before that date.
Neither move is 1:1: the REST endpoints returned a **pre-bucketed time series**, while this template lands the retained balance log that produces it. You resolve each bucket boundary to a block, count the as-of-block holder set, and diff adjacent buckets, and a **full backfill from the token's deployment block is required**, or early buckets undercount (see the backfill note in [Run it](#run-it) and [History & backfill](/data-feeds/concepts/history-and-backfill)).
### EVM: historical token holders
```
GET /erc20/:tokenAddress/holders/historical
```
The holder-count time series becomes an aggregation over this template's balance log: the [holder set as of block N](#example-reads) query, run per bucket boundary.
> [!NOTE]
>
> **This endpoint needs more than one template.** Counts and deltas come from this template alone, but `newHoldersByAcquisition` (swap / transfer / airdrop) classifies each new holder's first inbound event, which you build from [Token Transfers](/data-feeds/templates/token/token-transfers) + [Swaps by Token](/data-feeds/templates/markets/swaps-by-token).
| REST API field | Data Feeds | Fidelity |
| - | - | - |
| `timestamp` | your chosen bucket boundary, resolved to a block | your definition |
| `totalHolders` | count of the as-of-block holder set | exact |
| `netHolderChange`, `holderPercentChange` | deltas between adjacent buckets | calculated |
| `holdersIn` / `holdersOut` (whales … shrimps) | size-tier flows on thresholds you set | your definition |
| `newHoldersByAcquisition` (swap / transfer / airdrop) | classify new holders' first inbound transfer/swap | your definition |
Holder count as of a bucket's end block (ClickHouse, repeat per bucket, or drive from a calendar):
```sql theme={null}
SELECT countIf(balance_at_n != '0' AND balance_at_n != '') AS total_holders
FROM (
SELECT wallet_address,
argMax(balance, (block_number, log_index)) AS balance_at_n
FROM recipe_historical_balance_at_block.fact_balance_observations FINAL
WHERE chain_id = 1
AND token_address = lower('0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48')
AND block_number <= {bucket_end_block:UInt64}
GROUP BY wallet_address
);
```
Gotchas:
* **Materialize, don't recompute.** Large tokens have millions of holders, compute `total_holders` per bucket on a schedule and store the small series; the deltas are then trivial.
* **No fixed `timeFrame`.** Every observation is retained, so the same log serves hourly, daily, or custom windows.
* **Tiers and acquisition are conventions you set**: a feature, not a black box, but budget time to define them.
* **Backfill from the token's deployment block**, not chain genesis, the template is token-scoped for this question.
### Solana: historical holders
```
GET /token/:network/holders/:address/historical
```
The same template, pointed at **Solana** in the Admin Panel wizard, replaces it, Solana's `tokenTransfers` carry the same absolute post-balances, so the balance log is identical in shape (see [Multichain](#multichain)). The field mapping matches the EVM table above, with the mint as `token_address`; `newHoldersByAcquisition` likewise needs [Token Transfers](/data-feeds/templates/token/token-transfers) + [Swaps by Token](/data-feeds/templates/markets/swaps-by-token) layered in.
Holder set as of a past block, the building block for each bucket (ClickHouse):
```sql theme={null}
SELECT wallet_address,
argMax(balance, (block_number, log_index)) AS balance_at_n
FROM recipe_historical_balance_at_block.fact_balance_observations FINAL
WHERE token_address = lower('') AND block_number <= {N:UInt64}
GROUP BY wallet_address
HAVING balance_at_n != '0' AND balance_at_n != '';
```
Gotchas:
* **SPL account model.** Count **owner wallets**, summing a wallet's token accounts for its per-owner balance.
* **Backfill from the mint's deployment**: a short window gives wrong historical counts.
* **Slot boundaries.** Resolve each interval boundary to a block/slot before running the as-of query.
## Related
> [card] [Token Holders](/data-feeds/templates/token/token-holders)
>
> The latest-state holder set this time-travels.
> [card] [Token Balances by Wallet](/data-feeds/templates/wallet/token-balances-by-wallet)
>
> Current balances per wallet, the latest-state sibling.
# Token Balances by Token
Source: https://docs.moralis.com/data-feeds/templates/token/token-balances-by-token
Sync the current non-zero balance of every wallet that holds a given token into your own database, the holder list behind a token, latest-wins per wallet.
> [!NOTE]
>
> **Coming from `GET /erc20/{address}/owners` or `GET /erc20/{address}/holders`?** The field-by-field migration
> for those endpoints lives on the [Token Holders](/data-feeds/templates/token/token-holders#migrating-from-the-rest-api)
> template; this page is the same balance data in its raw by-token shape.
### Question it answers
> "Give me the non-zero balance of every wallet that holds token **0x…**, largest first."
This is the by-token sort of the same balance data the public API exposes per holder, the holder list and balances for a single token. The sibling template [Token Balances by Wallet](/data-feeds/templates/wallet/token-balances-by-wallet) is the exact same data sorted the other way (wallet-first); in production you land the source once and add both read shapes.
### What you get
The template lands **one balance observation per side of every transfer**, then resolves the **latest observation per `(token, wallet)`** as the current balance. Moralis-indexed transfers carry the *absolute* post-transfer balance of both sides (`fromPostBalance` / `toPostBalance`), so no running-sum reconstruction is needed; the highest `(block_number, log_index)` observation is the truth.
| Column | Description |
| - | - |
| `token_address` | The token being held (the read key) |
| `wallet_address` | The holder |
| `balance` | Absolute balance after this transfer, raw `uint256` as text |
| `block_number`, `log_index` | Recency tuple, the latest pair wins per `(token, wallet)` |
| `event_ts` / `block_timestamp` | Block time of the observation |
| `leg` | `from` or `to`, which side of the transfer this observation came from |
| `vendor_event_id` | Stable per-observation identity (keeps the two unpivoted rows distinct) |
Each transfer yields two observations: `(from_address, from_post_balance)` and `(to_address, to_post_balance)`. The EVM zero address (mint/burn counterparty) and any side without a producer-resolved post-balance are skipped.
### Source
The transform reads one per-block array, `tokenTransfers`, and **unpivots** each transfer into the two per-wallet balance observations it carries. Balance comes straight from the transfer's `fromPostBalance` / `toPostBalance`; there is no separate balance feed or join.
### Destination
| Destination | Table | By-token read pattern |
| - | - | - |
| **ClickHouse** (first-class) | `fact_balances_by_token` | Prefix scan on `(chain_id, token_address, wallet_address, …)`; current balance via `argMax(balance, (block_number, log_index))` over `FINAL` |
| **Postgres** | `token_balances` (materialized view over `token_balance_observations`) | Partial index `(token_address, wallet_address) WHERE balance > 0` |
| **MySQL** | `token_balances` (trigger-maintained over observations) | PK `(token_address, wallet_address)` + `DELETE … WHERE balance = 0` cleanup |
ClickHouse uses the collapsing log-table pattern (see the [templates overview](/data-feeds/templates/overview#destinations)) so chain reorganizations self-correct: a reorg negates the rolled-back block's observations (`sign = -1`) and re-emits the corrected ones, and `FINAL` collapses the pair before `argMax` runs. Read canonical state with `FINAL` or a sign-aware aggregate, never a bare `WHERE sign = 1`.
On Postgres and MySQL the sink appends observations and the current-balance projection is derived: Postgres via a `DISTINCT ON (token_address, wallet_address)` materialized view, MySQL via an `AFTER INSERT` latest-wins upsert trigger plus a periodic zero-balance cleanup.
### Full schema
Below is the complete read table this template produces, the per-wallet balance observations, keyed by token. Keep the columns you need and drop the rest (see [Schema & flexibility](/data-feeds/templates/overview#schema--flexibility)). Raw `uint256` balances are stored as text in ClickHouse (they exceed numeric precision); Postgres uses an explicit `NUMERIC(76, 0)` so large raw balances don't overflow a narrower inferred type.
> [accordion] ClickHouse, fact\_balances\_by\_token
>
> ```sql theme={null}
> CREATE TABLE recipe_token_balances_by_token.fact_balances_by_token
> (
> vendor_event_id String,
> ingested_at DateTime64(3),
> chain_id UInt32,
> block_hash String,
> block_number UInt64,
> log_index UInt32,
> event_ts DateTime64(3),
> token_address String,
> wallet_address String,
> balance String, -- absolute balance after this transfer (raw uint256)
> leg LowCardinality(String), -- 'from' | 'to'
> sign Int8
> )
> ENGINE = ReplicatedCollapsingMergeTree(
> '/clickhouse/tables/{database}/fact_balances_by_token', '{replica}', sign)
> PARTITION BY (chain_id, toYYYYMM(event_ts))
> ORDER BY (chain_id, token_address, wallet_address, block_number, log_index, vendor_event_id, leg);
> ```
>
> The `leg` (`from` / `to`) keeps the two unpivoted rows of one transfer distinct; the `+1`/`−1` reorg pair for one leg shares a key and collapses. Read with `FINAL` then `argMax`, or a sign-aware aggregate. A single-node setup can use `CollapsingMergeTree(sign)` without the replication path.
> [accordion] Postgres, token\_balances (materialized view)
>
> ```sql theme={null}
> -- Observations (sink target). Append-only, keyed on the block-level position.
> CREATE TABLE public.token_balance_observations (
> position BIGINT NOT NULL,
> log_index BIGINT NOT NULL,
> block_number BIGINT NOT NULL,
> block_timestamp BIGINT NOT NULL, -- unix seconds
> token_address TEXT NOT NULL,
> wallet_address TEXT NOT NULL,
> balance NUMERIC(76, 0) NOT NULL, -- absolute balance after the transfer
> leg TEXT NOT NULL, -- 'from' | 'to'
> vendor_event_id TEXT NOT NULL
> );
>
> -- Speeds the DISTINCT ON (latest-per-key) the materialized view computes.
> CREATE INDEX IF NOT EXISTS tbo_token_wallet_recency_idx
> ON public.token_balance_observations
> (token_address, wallet_address, block_number DESC, log_index DESC);
>
> -- Current-balance projection: latest observation per (token, wallet).
> CREATE MATERIALIZED VIEW public.token_balances AS
> SELECT DISTINCT ON (token_address, wallet_address)
> token_address,
> wallet_address,
> balance,
> block_number,
> log_index,
> block_timestamp
> FROM public.token_balance_observations
> ORDER BY token_address, wallet_address, block_number DESC, log_index DESC;
>
> -- Required by REFRESH MATERIALIZED VIEW CONCURRENTLY.
> CREATE UNIQUE INDEX IF NOT EXISTS token_balances_pk
> ON public.token_balances (token_address, wallet_address);
>
> -- Active holders of a token (this template's primary access path).
> CREATE INDEX IF NOT EXISTS token_balances_by_token_active_idx
> ON public.token_balances (token_address, wallet_address)
> WHERE balance > 0;
>
> -- Sibling access path: all non-zero balances held by a wallet.
> CREATE INDEX IF NOT EXISTS token_balances_by_wallet_active_idx
> ON public.token_balances (wallet_address, token_address)
> WHERE balance > 0;
>
> -- Cleanup index: find zeroed-out positions to prune.
> CREATE INDEX IF NOT EXISTS token_balances_zero_cleanup_idx
> ON public.token_balances (token_address, wallet_address)
> WHERE balance = 0;
> ```
>
> The materialized view is the current-balance projection, refresh it on a schedule with `REFRESH MATERIALIZED VIEW CONCURRENTLY token_balances;` (the `CONCURRENTLY` form needs the unique index above and never blocks readers). MySQL is the same shape with a trigger-maintained `token_balances` table and a periodic `DELETE … WHERE balance = 0` standing in for the cleanup index.
### Example reads
All current non-zero holders of a token, largest first, `FINAL` collapses reorg `±1` pairs before `argMax` resolves the latest balance per wallet (ClickHouse):
```sql theme={null}
SELECT wallet_address,
argMax(balance, (block_number, log_index)) AS current_balance
FROM recipe_token_balances_by_token.fact_balances_by_token FINAL
WHERE chain_id = 1 AND token_address = lower('0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48')
GROUP BY wallet_address
HAVING current_balance != '0' AND current_balance != ''
ORDER BY toFloat64OrZero(current_balance) DESC
LIMIT 100;
```
Holder count for a token:
```sql theme={null}
SELECT countDistinct(wallet_address) FROM (
SELECT wallet_address,
argMax(balance, (block_number, log_index)) AS bal
FROM recipe_token_balances_by_token.fact_balances_by_token FINAL
WHERE chain_id = 1 AND token_address = lower('0xA0b8...')
GROUP BY wallet_address
HAVING bal != '0' AND bal != ''
);
```
Postgres, refresh the view, then query the partial index:
```sql theme={null}
REFRESH MATERIALIZED VIEW CONCURRENTLY token_balances;
SELECT wallet_address, balance FROM public.token_balances
WHERE token_address = lower('0xA0b8...') AND balance > 0
ORDER BY balance DESC LIMIT 100;
```
### Modes
Shipped defaults: **ClickHouse `hybrid`** (backfill → realtime), **Postgres / MySQL `historical`** (one-shot backfill). For live/reorg-safe ingestion, use ClickHouse, see the [overview](/data-feeds/templates/overview#modes).
> [!NOTE]
>
> **Postgres / MySQL are backfill-first here.** The realtime reorg path needs a single-column unique key on the position column, but the template's position is block-level, so the Postgres / MySQL configs target `historical`. The Postgres materialized view and the MySQL cleanup are also not reorg-aware on their own; under realtime you would re-derive them. ClickHouse handles reorgs automatically via `sign`, so run realtime/hybrid there.
### Multichain
The template is chain-parametrized, point it at any supported EVM chain or Solana. On Solana, the per-observation `vendor_event_id` already folds in `(from, to, token, amount)`, so each observation stays row-unique despite Solana's repeated `logIndex` within an instruction; the holder list it produces is identical in shape.
### Fidelity notes
* **Latest-wins, not a delta sum.** Balances are absolute post-transfer observations, so the current balance is purely the most recent observation per `(token, wallet)`. There is no running-sum reconstruction and no dependence on having seen every prior transfer.
* **Raw amounts only.** `balance` is the raw `uint256` (text in ClickHouse, `NUMERIC(76, 0)` in Postgres). It is not decimal-scaled and carries no USD value, divide by `10^token_decimals` for human units (fold in a decimals lookup from a Token Metadata sync), and join Token Prices if you need USD.
* **Zero address excluded.** Mint/burn counterparties (the EVM zero address) and sides without a producer-resolved post-balance are not holders and are skipped at unpivot time.
### Related
> [card] [Token Balances by Wallet](/data-feeds/templates/wallet/token-balances-by-wallet)
>
> The sibling, the same balance data sorted wallet-first.
> [card] [Token Analytics](/data-feeds/use-cases/token-analytics)
>
> The use case holder lists and balances power.
# Token Bonding Status (Solana Launchpads)
Source: https://docs.moralis.com/data-feeds/templates/token/token-bonding-status
Sync every pump.fun / Raydium LaunchLab launchpad event, created, traded, migrated, into your own database, and serve a launchpad's new / bonding / graduated token lists plus any token's bonding-curve status.
### Question it answers
> "For a Solana launchpad like **pump.fun**: which tokens just launched, which are still climbing the bonding curve, and which have graduated to a DEX, and what's a given token's bonding-curve status?"
Lands one row per **launchpad event** (`created` / `traded` / `migrated`) from the decoded `launchpadEvents` feed, and derives a per-token latest-status projection. The four deprecated pump.fun surfaces, new, bonding, graduated, and per-token status, are all reads over this one template.
### What you get
The template reads the master-block `launchpadEvents` array and lands two surfaces:
* **The launchpad event log**, keyed by exchange, one row per `created` / `traded` / `migrated` event.
* **A per-token status projection**, keyed by token, latest bonding progress, graduated flag, and graduation time.
| Column | Description |
| - | - |
| `token_address` | The launchpad token (SPL mint) |
| `exchange_address` | The launchpad program (the `:exchange` path param, e.g. pump.fun `6EF8…F6P`) |
| `launchpad_platform` | Friendly name, `pumpfun`, `raydium_launchlab` |
| `event_type` | `created` · `traded` · `migrated` (**migrated = graduated**) |
| `progress_percentage` | Bonding-curve progress 0–100 (sparse, set on trading activity) |
| `pool_address` | The DEX pool a token migrated into, populated on the `migrated` event (take `max(pool_address)`) |
| `token_name`, `token_symbol`, `token_uri` | Emitted on the `created` event only |
| `trade_direction`, `token_amount`, `native_amount` | On `traded` events, native price = `native_amount / token_amount` |
| `block_number`, `log_index`, `event_ts`, `tx_hash` | On-chain ordering + provenance |
### Source
The transform reads one per-block array, `launchpadEvents`, one row per event. `event_type` distinguishes `created` (a new token, carries name/symbol/uri), `traded` (a bonding-curve fill, carries `progress_percentage` and trade amounts), and `migrated` (graduation to a DEX pool, carries `pool_address`). On the Solana feed today the price field (`current_price`) is **not populated**, see [Fidelity gaps](#fidelity-gaps). The `exchange_address` (launchpad program) is shared by every token on a platform.
### Destination
| Destination | Tables | Access |
| - | - | - |
| **ClickHouse** (first-class) | `fact_launchpad_events` (by exchange) + `fact_token_bonding_status` (by token) | prefix scan on `(chain_id, exchange_address, block_number)` for the event log; per-token aggregate for status |
| **Postgres** | `launchpad_events` + `token_bonding_status` (materialized view) | index on `(exchange_address, block_number)`; unique on `token_address` |
| **MySQL** | `launchpad_events` + `token_bonding_status` (trigger-maintained) | same shape |
ClickHouse uses the collapsing log-table pattern so chain reorganizations self-correct. `fact_launchpad_events` is ordered for the by-exchange event log (bloom skip index on `token_address` for the by-token log); `fact_token_bonding_status` is keyed by token for the latest-state read.
### Full schema
> [accordion] ClickHouse, fact\_launchpad\_events
>
> ```sql theme={null}
> CREATE TABLE recipe_token_bonding_status.fact_launchpad_events
> (
> vendor_event_id String,
> ingested_at DateTime64(3),
> chain_id UInt32,
> block_hash String,
> block_number UInt64,
> event_ts DateTime64(3),
> token_address String,
> launchpad_platform LowCardinality(String), -- pumpfun | raydium_launchlab | …
> event_type LowCardinality(String), -- created | traded | migrated
> exchange_address String,
> initiated_by String,
> token_name String,
> token_symbol String,
> token_uri String,
> token_amount String,
> native_amount String,
> trade_direction LowCardinality(String), -- buy | sell | ''
> bonding_curve_address String,
> pool_address String, -- DEX pool (migrated events)
> current_price String,
> progress_percentage Nullable(Float64), -- 0-100, sparse
> metadata String,
> tx_hash String,
> log_index Nullable(UInt32),
> transaction_index Nullable(Int32),
> sign Int8,
> INDEX bf_token token_address TYPE bloom_filter(0.01) GRANULARITY 4
> )
> ENGINE = ReplicatedCollapsingMergeTree(
> '/clickhouse/tables/{database}/fact_launchpad_events', '{replica}', sign)
> PARTITION BY (chain_id, toYYYYMM(event_ts))
> ORDER BY (chain_id, exchange_address, block_number, vendor_event_id);
> ```
> [accordion] ClickHouse, fact\_token\_bonding\_status (per-token)
>
> ```sql theme={null}
> CREATE TABLE recipe_token_bonding_status.fact_token_bonding_status
> (
> vendor_event_id String,
> ingested_at DateTime64(3),
> chain_id UInt32,
> block_number UInt64,
> event_ts DateTime64(3),
> token_address String,
> launchpad_platform LowCardinality(String),
> exchange_address String,
> event_type LowCardinality(String),
> token_name String,
> token_symbol String,
> progress_percentage Nullable(Float64),
> current_price String,
> log_index Nullable(UInt32),
> sign Int8
> )
> ENGINE = ReplicatedCollapsingMergeTree(
> '/clickhouse/tables/{database}/fact_token_bonding_status', '{replica}', sign)
> PARTITION BY (chain_id, toYYYYMM(event_ts))
> ORDER BY (chain_id, token_address, block_number, vendor_event_id);
> ```
>
> Postgres / MySQL keep an append-only `launchpad_events` table plus a `token_bonding_status` current-state projection (a materialized view on Postgres, a trigger-maintained table on MySQL).
### Run it
Everything runs in **your** infrastructure: the sink writes into a database you own and you query it with plain SQL, no API and no per-call limits.
**Prerequisites**
* **Docker** and Docker Compose.
* A **Data Feeds key**, a `cm_live_…` key with `continuum:read` scope (this is *not* your Web3 API key).
> [card] [Sign up for a Data Feeds key](https://admin.moralis.com)
>
> Log in to the Moralis admin panel to create your account and generate a `cm_live_…` key.
**Start the sink**
Generate a **starter pack** for `tokenBondingStatus` in the [Moralis Admin Panel](https://admin.moralis.com), choose **Solana** as the chain (launchpad activity is densest on pump.fun and Raydium LaunchLab) and your destination, then run it with Docker. The [quickstart](/data-feeds/migration/quickstart) walks through it end to end.
> [!NOTE]
>
> **Backfill by use case.** The new / bonding / graduated **lists** are event feeds, run **realtime** to track launches live, no backfill needed. A per-token **status** is current state, backfill from the token's `created` event to capture its full curve. See [History & backfill](/data-feeds/concepts/history-and-backfill).
### Example reads
**New tokens** on a launchpad, the token's `created` event, newest first:
```sql theme={null}
SELECT token_address,
argMax(token_name, (block_number, log_index)) AS name,
argMax(token_symbol, (block_number, log_index)) AS symbol,
min(event_ts) AS created_at
FROM recipe_token_bonding_status.fact_launchpad_events FINAL
WHERE exchange_address = '6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P'
AND event_type = 'created'
GROUP BY token_address
ORDER BY created_at DESC
LIMIT 50;
```
**Bonding tokens**, progress \< 100, not yet graduated, closest to graduating first:
```sql theme={null}
SELECT token_address,
argMaxIf(progress_percentage, block_number, progress_percentage IS NOT NULL) AS bonding_progress
FROM recipe_token_bonding_status.fact_token_bonding_status FINAL
WHERE exchange_address = '6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P'
GROUP BY token_address
HAVING maxIf(1, event_type = 'migrated') = 0 AND bonding_progress < 100
ORDER BY bonding_progress DESC
LIMIT 50;
```
**Graduated tokens**, tokens with a `migrated` event, plus the DEX pool they migrated into (`max` grabs the non-empty `pool_address`, since a graduation can emit more than one `migrated` row):
```sql theme={null}
SELECT token_address,
minIf(event_ts, event_type = 'migrated') AS graduated_at,
max(pool_address) AS pool_address
FROM recipe_token_bonding_status.fact_launchpad_events FINAL
WHERE exchange_address = '6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P'
GROUP BY token_address
HAVING maxIf(1, event_type = 'migrated') = 1
ORDER BY graduated_at DESC
LIMIT 50;
```
**Bonding status** for one token:
```sql theme={null}
SELECT token_address AS mint,
argMaxIf(progress_percentage, (block_number, log_index),
progress_percentage IS NOT NULL) AS bonding_progress,
maxIf(1, event_type = 'migrated') = 1 AS graduated,
minIf(event_ts, event_type = 'migrated') AS graduated_at
FROM recipe_token_bonding_status.fact_token_bonding_status FINAL
WHERE token_address = {mint:String}
GROUP BY token_address;
```
### Other ways to consume this data
The sink is the way to get **these pre-shaped tables**. The *same underlying data* is also available as the **raw decoded feed**, if you'd rather shape it yourself:
* **Your existing message clients**: stream `launchpadEvents` live with **Kafka / AMQP / SQS** (great for a real-time launch feed).
* **REST / Arrow Flight**: pull the decoded Solana block stream directly.
Those give you the raw `launchpadEvents` array to project yourself, not these tables. All read the one data lake into **your** infrastructure. See [What are Data Feeds?](/data-feeds/concepts/what-are-data-feeds).
### Modes
Shipped defaults: **ClickHouse `hybrid`** (backfill → realtime), **Postgres / MySQL `historical`**. For live launch discovery use ClickHouse, see the [overview](/data-feeds/templates/overview#modes).
### Multichain
Launchpad activity is densest on **Solana** (pump.fun, Raydium LaunchLab) and **Base**; on Ethereum mainnet the `launchpadEvents` array is effectively empty. Point the template at Solana in the Admin Panel wizard for real coverage. On Solana `logIndex` isn't row-unique within an instruction, so `vendor_event_id` widens with `(tokenAddress, eventType)` to keep rows distinct.
### How much data does this consume?
`tokenBondingStatus` reads a single per-block array, `launchpadEvents`, one of the smallest slices in the feed. On **Solana mainnet**, where launchpad activity is concentrated, a continuous real-time feed measured:
| | Uncompressed bytes per month |
| - | - |
| Typical month (P50) | **\~8.7 GB** |
| Busy month (P90) | **\~15.1 GB** |
Measured 2026-08-04 against the live feed, 30 sampled partitions over 30 days, `metered` delivery. Billing is on uncompressed bytes.
**Size your allowance against the top of the band, not the middle.** Chain activity varies, and this template tracks launchpad activity specifically, which is bursty by nature: a quiet month and a memecoin frenzy are not the same month. Worked example, against a hypothetical 10 GB monthly allowance:
| If the month runs at | Against a 10 GB allowance |
| - | - |
| 8.5 GB | Within allowance, nothing extra to pay |
| 15 GB | 5 GB of overage |
Both are inside the measured range for this template, so choose an allowance that covers the busy figure and treat the typical figure as the good case.
What this figure does and does not cover:
* **Real-time only.** A historical backfill is billed separately and is usually the larger number; its size depends entirely on how far back you go.
* **Solana.** On EVM chains the `launchpadEvents` array is effectively unpopulated (see [Multichain](#multichain)), so this template reads close to nothing on Ethereum.
* **The whole slice, across every launchpad and every token.** Filtering to specific tokens, platforms, or programs happens after the data is delivered, so it does not reduce the figure. To reduce cost, narrow the **block range**, not the entity set.
* **`metered` delivery.** Under `presigned_url` you are billed for whole partitions rather than the columns you project, which is a different number.
If you want your exact scope measured before you commit to a plan, [reach out](https://admin.moralis.com/data-feeds) and we will probe it against the live feed rather than estimate it.
### Fidelity gaps
* **`name` / `symbol`** ride on the `created` event; a token seen only via `traded` events carries none until you join [Token Metadata](/data-feeds/templates/token/token-metadata) (also the source of `decimals`).
* **`progress_percentage` is sparse**: `created` events carry no curve progress (0 is coerced to null), so a freshly-created token has null progress until its first trade.
* **No price in the feed.** `current_price` lands **empty on the Solana feed today** (0 populated in live sampling). Derive the **native price** per token from `traded` events (`native_amount / token_amount`), and convert to **USD** with a SOL/USD mark (e.g. wrapped SOL from a [Token Prices](/data-feeds/templates/token/token-prices) sync). **Liquidity** (cumulative curve `native_amount`, or post-graduation [Pair Reserves](/data-feeds/templates/markets/pair-reserves)) and **FDV** (`token_metadata.total_supply` × price) are derive-or-omit.
* **`pool_address` arrives on the `migrated` event**: the DEX pool the token graduated into (verified live). A graduation can emit **more than one** `migrated` row, so take the non-empty value with `max(pool_address)` rather than `anyLast`.
* **`logo`** and other off-chain metadata aren't in the feed.
Core fields, `token_address`, `exchange_address`, `event_type`, `progress_percentage`, graduation (the `migrated` event, with `pool_address`), token name/symbol (on `created`), trade amounts, and timestamps, are sourced from `launchpadEvents`.
## Migrating from the REST API
> [!WARNING]
>
> All four Solana launchpad endpoints below are **deprecated and sunset on July 31, 2026**. This one template replaces all of them, each REST response is a read over the tables above.
The four endpoints share most of their response shape, so the common fields map once:
| REST API field (all four endpoints) | Data Feeds | Fidelity |
| - | - | - |
| `tokenAddress` / `mint` | `token_address` | exact |
| `name`, `symbol` | `token_name` / `token_symbol` on the `created` event, or [Token Metadata](/data-feeds/templates/token/token-metadata) | exact |
| `decimals` | `token_metadata.decimals` (join [Token Metadata](/data-feeds/templates/token/token-metadata)) | exact |
| `priceNative` | derive `native_amount / token_amount` from `traded` events, `currentPrice` is **not populated** on the Solana feed today | calculated |
| `priceUsd` | `priceNative` × a SOL/USD mark (wrapped SOL via [Token Prices](/data-feeds/templates/token/token-prices)) | calculated |
| `liquidity` | cumulative curve `native_amount` × price; post-graduation, [Pair Reserves](/data-feeds/templates/markets/pair-reserves) × price | calculated |
| `fullyDilutedValuation` | `token_metadata.total_supply` × price | calculated |
| `logo` | not in the feed, bring your own token list, or omit | add yourself |
In every deprecated endpoint URL, `:exchange` is the launchpad's onchain **program address** (pump.fun is `6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P`); each event carries it as `exchange_address` plus a friendly `launchpad_platform` (`pumpfun`, `raydium_launchlab`), filter on either. None of the lists have a per-call cap anymore; page with a keyset on the sort column.
### New tokens by exchange
```text theme={null}
GET /token/:network/exchange/:exchange/new
```
"New" is the set of **`created`** events on a launchpad, newest first, a view over `fact_launchpad_events`:
```sql theme={null}
CREATE VIEW new_tokens_by_exchange AS
SELECT
token_address,
exchange_address,
argMax(token_name, (block_number, log_index)) AS name,
argMax(token_symbol, (block_number, log_index)) AS symbol,
min(event_ts) AS created_at
FROM recipe_token_bonding_status.fact_launchpad_events FINAL
WHERE event_type = 'created'
GROUP BY token_address, exchange_address;
-- per launchpad: WHERE exchange_address = :exchange ORDER BY created_at DESC
```
`createdAt` maps to `min(event_ts)` over the `created` event (exact).
* Launches are an **event list**, run the template realtime for a live feed, no backfill needed; index back only to list tokens created before you started.
* A brand-new token has **no price and no curve progress** until its first trade.
### Bonding tokens by exchange
```text theme={null}
GET /token/:network/exchange/:exchange/bonding
```
"Bonding" is the set of tokens still on the curve, progress below 100, never migrated, ranked by progress:
```sql theme={null}
CREATE VIEW bonding_tokens_by_exchange AS
SELECT
token_address,
exchange_address,
argMaxIf(progress_percentage, block_number, progress_percentage IS NOT NULL) AS bonding_progress
FROM recipe_token_bonding_status.fact_token_bonding_status FINAL
GROUP BY token_address, exchange_address
HAVING maxIf(1, event_type = 'migrated') = 0 -- still bonding (not graduated)
AND bonding_progress < 100;
-- per launchpad: WHERE exchange_address = :exchange ORDER BY bonding_progress DESC
```
`bondingCurveProgress` maps to the latest non-null `progress_percentage` per token (exact).
* **Progress is carried forward**: it updates with each trade, and is null until the first trade (same as the old endpoint, which had nothing to report before curve activity).
* A token **leaves the bonding list** the moment it emits a `migrated` event; the `HAVING` clause excludes those.
### Graduated tokens by exchange
```text theme={null}
GET /token/:network/exchange/:exchange/graduated
```
Graduation is the **`migrated`** event, a token with one has left the curve for a DEX pool:
```sql theme={null}
CREATE VIEW graduated_tokens_by_exchange AS
SELECT
token_address,
exchange_address,
minIf(event_ts, event_type = 'migrated') AS graduated_at,
max(pool_address) AS pool_address -- the migrated DEX pool
FROM recipe_token_bonding_status.fact_launchpad_events FINAL
GROUP BY token_address, exchange_address
HAVING maxIf(1, event_type = 'migrated') = 1; -- has graduated
-- per launchpad: WHERE exchange_address = :exchange ORDER BY graduated_at DESC
```
`graduatedAt` maps to `minIf(event_ts, event_type = 'migrated')`, and `poolAddress`, which the old endpoint didn't even expose, is `max(pool_address)` over the token's `migrated` events (both exact).
> [!NOTE]
>
> **This one is not a 1:1 swap.** The REST response bundled prices, liquidity, and FDV, but a graduated token trades on a normal DEX pool, so price it with [Token Prices](/data-feeds/templates/token/token-prices) and read pool liquidity with [Pair Reserves](/data-feeds/templates/markets/pair-reserves), keyed on the migrated `pool_address`. Run those templates alongside this one if you serve those fields.
* `pool_address` is **only populated on `migrated` events** (verified live), and a graduation can emit more than one `migrated` row, take the non-empty value with `max(pool_address)`, not `anyLast`.
* Graduations are an event list, run realtime to catch them as they happen.
### Token bonding status
```text theme={null}
GET /token/:network/:address/bonding-status
```
The most direct migration of the set, the template's per-token projection *is* this response. `mint`, `bondingProgress`, and `graduatedAt` map to `token_address`, `bonding_progress`, and `graduated_at` (all exact). On Postgres or MySQL it's a single-row lookup on the maintained status table:
```sql theme={null}
SELECT token_address AS mint, bonding_progress, graduated, graduated_at
FROM token_bonding_status
WHERE token_address = $1;
```
On ClickHouse, use the per-token aggregate shown in [Example reads](#example-reads).
* **Status is current state**, not an event list, backfill from the token's `created` event to capture its full curve and graduation history.
* `graduated` / `graduated_at` come from the `migrated` event; both are empty until the token graduates.
### Related
> [card] [Token Metadata](/data-feeds/templates/token/token-metadata)
>
> Names, symbols, and decimals for launchpad tokens.
> [card] [Token Prices](/data-feeds/templates/token/token-prices)
>
> USD marks to layer onto bonding and graduated tokens.
# Token Holders
Source: https://docs.moralis.com/data-feeds/templates/token/token-holders
Sync the full holder list of a token, every non-zero wallet, its current balance, and a best-effort USD value, as a continuously updated table in your own database. Mirrors the Moralis GET /erc20/{address}/owners endpoint.
### Question it answers
> "Who holds token **0x…**, with their current balance and USD value? Give me the full holder list, biggest first."
Mirrors Moralis [`GET /erc20/{address}/owners`](/data-api/evm/token/holders/token-holders). Storing the holder set **pre-aggregated**, keyed by token, in your own database is the value, no per-request rebuild from raw transfers.
### What you get
Token transfers carry the **absolute** post-transfer balance of both sides of every transfer (`fromPostBalance` / `toPostBalance`). Each transfer becomes two per-wallet balance observations, and the latest observation per `(token, wallet)` is the current holding, no running-sum reconstruction. Each observation is USD-enriched in-block from the same block's price updates.
| Column | Description |
| - | - |
| `token_address` | The token contract being held |
| `wallet_address` | The holder |
| `balance` | Absolute balance after the latest transfer, raw `uint256` as text |
| `usd_price` | In-block USD spot price per **whole** token (newest-wins from the block's price updates; `0` if no same-block update) |
| `usd_value` | Best-effort holding value, `balance / 10^18 × usd_price` (see [fidelity gaps](#fidelity-gaps)) |
| `block_number`, `log_index` | Recency tuple, the latest pair wins as the current holding |
| `leg` | `from` / `to`, which side of the transfer produced this observation |
Balances are **latest-wins**: the current holding of a `(token, wallet)` is simply the observation with the highest `(block_number, log_index)`.
### Source
The transform reads one per-block array and unpivots it:
`tokenTransfers`
Each transfer yields `(from_address, from_post_balance)` and `(to_address, to_post_balance)`. The EVM zero address (mint/burn counterparty) and any side without a resolved post-balance are skipped. USD spot prices are folded in **inline** from the same block's `tokenPriceUpdates` (reversed so the chronologically-last update wins per token), no separate price join at read time.
This template is **Token Balances by Token** plus the in-block USD valuation leg.
### Destination
| Destination | Table | Read pattern |
| - | - | - |
| **ClickHouse** (first-class) | `fact_token_holders` | Prefix scan on `(chain_id, token_address, wallet_address, …)`; current holding via `argMax` over `FINAL` |
| **Postgres** | `token_holders` (materialized view over `token_holder_observations`) | Partial index `(token_address, wallet_address) WHERE balance > 0` |
| **MySQL** | `token_holders` (trigger-maintained from `token_holder_observations`) | PK `(token_address, wallet_address)` + `DELETE … WHERE balance = 0` cleanup |
ClickHouse uses the collapsing log-table pattern (see the [templates overview](/data-feeds/templates/overview#destinations)) so chain reorganizations self-correct, a reorg negates the rolled-back block's observations (`sign = -1`) and re-emits the corrected ones, and `FINAL` collapses the pair before `argMax` so the aggregate sees only canonical state. The fact table's sort key is token-first, so a token's holder set is a contiguous range read.
Postgres and MySQL keep an append-only observations table and derive the current-holder projection: Postgres as a `DISTINCT ON (token, wallet) … ORDER BY block_number DESC, log_index DESC` materialized view (refresh on a schedule), MySQL via an `AFTER INSERT` latest-wins upsert trigger with a periodic `DELETE … WHERE balance = 0` cleanup.
### Full schema
Below is the complete read table this template produces. It's a starting point, keep the columns you need and drop the rest (see [Schema & flexibility](/data-feeds/templates/overview#schema--flexibility)). Raw `uint256` balances are stored as text (they exceed numeric precision); `usd_price` is a wide decimal so a low-decimals token × price never overflows.
> [accordion] ClickHouse, fact\_token\_holders
>
> ```sql theme={null}
> CREATE TABLE recipe_token_holders.fact_token_holders
> (
> vendor_event_id String,
> ingested_at DateTime64(3),
> chain_id UInt32,
> block_hash String,
> block_number UInt64,
> log_index UInt32,
> event_ts DateTime64(3),
> token_address String,
> wallet_address String,
> balance String, -- absolute balance after this transfer (raw uint256)
> usd_price Nullable(String), -- in-block USD spot per whole token
> leg LowCardinality(String), -- 'from' | 'to'
> sign Int8
> )
> ENGINE = ReplicatedCollapsingMergeTree(
> '/clickhouse/tables/{database}/fact_token_holders', '{replica}', sign)
> PARTITION BY (chain_id, toYYYYMM(event_ts))
> ORDER BY (chain_id, token_address, wallet_address, block_number, log_index, vendor_event_id, leg);
> ```
>
> The `sign` column drives reorg collapsing, read with `FINAL` (then `argMax`) or a sign-aware aggregate, never a bare `WHERE sign = 1`. `leg` keeps the two unpivoted rows of one transfer distinct; the `+1`/`-1` reorg pair for one leg shares a key and collapses. A single-node setup can use `CollapsingMergeTree(sign)` without the replication path.
> [accordion] Postgres, token\_holders
>
> ```sql theme={null}
> -- 1. Observations (append-only sink target).
> CREATE TABLE public.token_holder_observations (
> position BIGINT NOT NULL,
> log_index BIGINT NOT NULL,
> block_number BIGINT NOT NULL,
> block_timestamp BIGINT NOT NULL, -- unix seconds
> token_address TEXT NOT NULL,
> wallet_address TEXT NOT NULL,
> balance NUMERIC(76, 0) NOT NULL, -- absolute balance after the transfer
> usd_price NUMERIC(38, 18) NOT NULL, -- in-block USD spot per whole token (0 if none)
> leg TEXT NOT NULL, -- 'from' | 'to'
> vendor_event_id TEXT NOT NULL
> );
>
> -- Speeds the DISTINCT ON (latest-per-key) the materialized view computes.
> CREATE INDEX tho_token_wallet_recency_idx
> ON public.token_holder_observations
> (token_address, wallet_address, block_number DESC, log_index DESC);
>
> -- 2. Current-holder materialized view: latest observation per (token, wallet),
> -- with the best-effort usd_value (assumes 18 decimals).
> CREATE MATERIALIZED VIEW public.token_holders AS
> SELECT DISTINCT ON (token_address, wallet_address)
> token_address,
> wallet_address,
> balance,
> usd_price,
> (balance / 1e18 * usd_price)::NUMERIC(38, 18) AS usd_value,
> block_number,
> log_index,
> block_timestamp
> FROM public.token_holder_observations
> ORDER BY token_address, wallet_address, block_number DESC, log_index DESC;
>
> -- Required by REFRESH MATERIALIZED VIEW CONCURRENTLY.
> CREATE UNIQUE INDEX token_holders_pk
> ON public.token_holders (token_address, wallet_address);
>
> -- Active holders of a token (this template's primary access path).
> CREATE INDEX token_holders_by_token_active_idx
> ON public.token_holders (token_address, wallet_address)
> WHERE balance > 0;
>
> -- OPTIONAL: sibling access path — all non-zero balances held by a wallet.
> -- CREATE INDEX token_holders_by_wallet_active_idx
> -- ON public.token_holders (wallet_address, token_address)
> -- WHERE balance > 0;
>
> -- OPTIONAL: cleanup index — find zeroed-out positions to prune.
> -- CREATE INDEX token_holders_zero_cleanup_idx
> -- ON public.token_holders (token_address, wallet_address)
> -- WHERE balance = 0;
> ```
>
> MySQL is the same shape with `DECIMAL(76,0)` / `DECIMAL(38,18)`, and replaces the materialized view with a trigger-maintained `token_holders` table. `position` is the block-level cursor used during backfill. `balance` is typed `NUMERIC(76, 0)` so the raw `uint256` survives without overflow.
### Run it
Everything runs in **your** infrastructure: the sink writes into a database you own and you query it with plain SQL, no API and no per-call limits.
**Prerequisites**
* **Docker** and Docker Compose.
* A **Data Feeds key**, a `cm_live_…` key with `continuum:read` scope (this is *not* your Web3 API key).
> [card] [Sign up for a Data Feeds key](https://admin.moralis.com)
>
> Log in to the Moralis admin panel to create your account and generate a `cm_live_…` key.
**Start the sink**
Generate a **starter pack** for `tokenHolders` in the [Moralis Admin Panel](https://admin.moralis.com), pick your chain and destination database, then run it with Docker. The [quickstart](/data-feeds/migration/quickstart) walks through it end to end. Set the backfill window (`MORALIS_HISTORICAL_FROM_BLOCK`) as noted below.
> [!NOTE]
>
> **Backfill from the token's first block for a complete holder set.** A holder list is *current state*, the latest transfer-derived balance per `(token, wallet)`, so to return **every** holder you need the token's full transfer history. The good news: that's history since the **token launched**, not chain genesis, so set `MORALIS_HISTORICAL_FROM_BLOCK` to around the token's deployment block. A recent-only window would miss holders who haven't moved the token lately. See [History & backfill](/data-feeds/concepts/history-and-backfill).
Then run the example reads below to confirm rows are landing.
### Example reads
All current non-zero holders of a token with balance and best-effort `usd_value`, `FINAL` collapses reorg `±1` pairs before `argMax` (ClickHouse). The example assumes 18 decimals; substitute the token's real decimals to be exact:
```sql theme={null}
SELECT wallet_address,
argMax(balance, (block_number, log_index)) AS current_balance,
argMax(usd_price, (block_number, log_index)) AS usd_price,
toString(toDecimal256(
(toFloat64OrZero(argMax(balance, (block_number, log_index))) / pow(10, 18))
* toFloat64OrZero(argMax(usd_price, (block_number, log_index))), 18)) AS usd_value
FROM recipe_token_holders.fact_token_holders FINAL
WHERE chain_id = 1 AND token_address = lower('0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48')
GROUP BY wallet_address
HAVING current_balance != '0' AND current_balance != ''
ORDER BY toFloat64OrZero(current_balance) DESC
LIMIT 100;
```
Holder count for a token (ClickHouse):
```sql theme={null}
SELECT countDistinct(wallet_address) FROM (
SELECT wallet_address,
argMax(balance, (block_number, log_index)) AS bal
FROM recipe_token_holders.fact_token_holders FINAL
WHERE chain_id = 1 AND token_address = lower('0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48')
GROUP BY wallet_address
HAVING bal != '0' AND bal != '');
```
The same read on Postgres after refreshing the view (the partial index serves it directly):
```sql theme={null}
REFRESH MATERIALIZED VIEW CONCURRENTLY token_holders;
SELECT wallet_address, balance, usd_price, usd_value FROM public.token_holders
WHERE token_address = lower('0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48') AND balance > 0
ORDER BY balance DESC LIMIT 100;
```
### Other ways to consume this data
The sink is the way to get **this pre-aggregated table** (`token_holders`), recommended for a holder list you own. The *same underlying data* is also available as the **raw decoded feed**, if you'd rather maintain holder state yourself:
* **Your existing message clients**: stream it with **Kafka / AMQP / SQS**.
* **REST / Arrow Flight**: pull the decoded block stream directly.
Those give you the **source array** (`tokenTransfers`, which carries absolute post-transfer balances) to compute the holder set yourself, not this pre-aggregated table. All of them read the one data lake into **your** infrastructure. See [What are Data Feeds?](/data-feeds/concepts/what-are-data-feeds).
### Modes
Shipped defaults: **ClickHouse `hybrid`** (backfill → realtime), **Postgres / MySQL `historical`** (one-shot backfill). For live/reorg-safe ingestion, use ClickHouse, see the [overview](/data-feeds/templates/overview#modes).
> [!NOTE]
>
> The Postgres materialized view and the MySQL trigger state are not reorg-aware on their own, under realtime you would have to re-derive or refresh them. Run **realtime/hybrid on ClickHouse**, where the collapsing log table corrects reorgs per-block via `sign` automatically; the Postgres/MySQL configs target `historical` backfill.
### Multichain
The template is chain-parametrized via the `chain` setting, point it at any supported EVM chain or Solana. On Solana, the event identity already includes `(from, to, token, amount)` so each observation stays row-unique despite Solana's repeated `logIndex` within an instruction; the holder set it produces is identical in shape.
### How much data does this consume?
A continuous real-time feed for this template's exact selection, `tokenTransfers` plus the inline `tokenPriceUpdates` mark, measured:
| Chain | Typical month (P50) | Busy month (P90) |
| - | - | - |
| Solana | **\~530 GB** | **\~670 GB** |
| BNB Smart Chain | **\~210 GB** | **\~285 GB** |
| Ethereum | **\~17 GB** | **\~23 GB** |
Measured 2026-07-31, 30 sampled partitions per chain, `metered` delivery. Billing is on uncompressed bytes.
**Size your allowance against the busy figure, not the typical one.** Chain activity is bursty, and the same feed can land on either side of a fixed allowance depending on the month. Three caveats:
* **Real-time only.** A historical backfill is billed separately and is usually the larger number; its size depends entirely on how far back you go.
* **Measured chains only.** Volume concentrates hard per chain (BNB Smart Chain measured over 10x Ethereum on this exact selection), so these figures do not extrapolate to unmeasured chains.
* **Filtering does not reduce it.** Restricting to specific tokens or holders happens after the data is delivered. To reduce cost, narrow the **block range**, not the entity set.
If you want your exact scope measured before you commit to a plan, [reach out](https://admin.moralis.com/data-feeds) and we will probe it against the live feed rather than estimate it.
### Fidelity gaps
The Moralis `/erc20/{address}/owners` response has fields that aren't derivable from normalized per-block data and are therefore omitted or approximated:
* **`balance_formatted`**: needs the token's `decimals`, which is contract metadata not present in `tokenTransfers`. Only the raw `balance` (uint256 string) is emitted; divide by `10^decimals` off-stream to format. Source decimals from a Token Metadata sync.
* **`usd_value`**: emitted **best-effort assuming 18 decimals** (`balance / 1e18 × usd_price`). The faithful per-token USD spot `usd_price` (same-block, newest-wins) is stored alongside, so a consumer that knows the real decimals can recompute exactly: `usd_value = balance / 10^decimals × usd_price`. Tokens with no same-block price update get `usd_price = 0` (→ `usd_value = 0`) for that observation.
* **`percentage_relative_to_total_supply`** and **`total_supply`**, there's no clean circulating/total-supply figure in the block stream (it would require summing all mints − burns since genesis or a contract `totalSupply()` read). Omitted.
* **`owner_address_label`**, **`is_contract`**, **`entity`**, **`entity_logo`**, off-chain enrichment / address-classification metadata, not on-chain block data. Omitted.
The core access key, `token_address` → holder `wallet_address` + current `balance`, is fully covered, so these gaps don't block the template.
## Migrating from the REST API
This template replaces the token-holder family of REST endpoints, the EVM Web3 API holder list and summary, and the deprecated Solana Token API holder endpoints. Data Feeds are **not** 1:1 replicas of those responses: you land the holder set in your own database and reconstruct each response shape with SQL. The subsections below cover each REST endpoint, what replaces it, the field mapping (**exact** = straight from the chain, **calculated** = derived from real DEX trades, very close, **add yourself** = off-chain signal or a definition you set), and the gotchas specific to that endpoint.
### GET /erc20/:address/owners
The per-holder list, every owner, biggest first, with balance and USD value. The most direct migration on this page: this template's `token_holders` table *is* the holder list, and the ranking becomes your `ORDER BY`.
For `balance_formatted`, `percentage_relative_to_total_supply`, and the envelope `totalSupply`, add [Token Metadata](/data-feeds/templates/token/token-metadata) (`token_metadata`) to the same database, the raw list needs only this template, the formatted fields need the join.
| `/erc20/:address/owners` | Data Feeds | Fidelity |
| - | - | - |
| `owner_address` | `token_holders.wallet_address` | exact |
| `balance` (raw) | `token_holders.balance` | exact |
| `balance_formatted` | derive: `balance / 10^decimals` (`token_metadata`) | exact |
| `usd_value` | `token_holders.usd_value` | calculated |
| `percentage_relative_to_total_supply` | derive: `balance / total_supply` (`token_metadata`) | exact |
| `totalSupply` (envelope) | `token_metadata.total_supply` | exact |
| `is_contract`, `owner_address_label`, `entity`, `entity_logo` | your own label / contract-address source | add yourself |
The reconstruction query (Postgres, adapt to your destination):
```sql theme={null}
SELECT h.wallet_address AS owner_address,
h.balance,
h.balance / power(10, m.decimals) AS balance_formatted,
h.usd_value,
h.balance / NULLIF(m.total_supply, 0) AS percentage_relative_to_total_supply
FROM token_holders h
LEFT JOIN token_metadata m ON m.token_address = h.token_address
WHERE h.token_address = lower($1)
AND h.balance > 0 -- current owners only, like the endpoint
ORDER BY h.balance DESC -- biggest first, like the endpoint
LIMIT $2 OFFSET $3;
```
**Gotchas**
* Ordering and filtering are yours: the endpoint hard-coded biggest-first and non-zero-only; with your own table you rank by `balance` or `usd_value`, set any minimum, and page with plain SQL, no per-call limit.
* The stored `usd_value` assumes 18 decimals, recompute as `balance / 10^decimals × usd_price` with real decimals from `token_metadata` for non-18-decimal tokens (see [fidelity gaps](#fidelity-gaps)).
* USD values come from real DEX trades, very close to the old endpoint, compare with a tolerance; a thinly-traded token may value at 0.
* Backfill from the token's deployment block (see [Run it](#run-it)) or the list silently misses holders who haven't moved the token lately.
### GET /erc20/:tokenAddress/holders
The **aggregate holder summary**, `totalHolders`, supply concentration, size tiers, acquisition split, and trend windows, not the per-holder list. There is no single replacement table: you compute the summary yourself over this template's holder set, which turns the black-box buckets into definitions you control.
> [!WARNING]
>
> This endpoint needs **multiple templates**, not one. Run this template plus [Token Metadata](/data-feeds/templates/token/token-metadata) (`total_supply` for the concentration percentages), and add [Token Transfers](/data-feeds/templates/token/token-transfers) if you want the `holdersByAcquisition` split (classify each holder's first inbound transfer). The `holderChange` trend windows need a holder-count series **you maintain**, snapshot the count per interval and read the deltas.
| `/erc20/:tokenAddress/holders` | Data Feeds | Fidelity |
| - | - | - |
| `totalHolders` | `COUNT(*)` over `token_holders` (`balance > 0`) | exact |
| `holderSupply.topN.supply` / `.supplyPercent` | top-N by balance vs `token_metadata.total_supply` | exact |
| `holderDistribution.{whales…shrimps}` | bucket holders by size, thresholds you set | add yourself |
| `holdersByAcquisition.{swap,transfer,airdrop}` | classify each holder's first inbound from `token_transfers` | add yourself |
| `holderChange.{5min…30d}` | holder count now vs one window ago, from your count series | calculated |
The headline numbers in one pass (Postgres, tier thresholds are illustrative, set your own):
```sql theme={null}
WITH ranked AS (
SELECT usd_value,
row_number() OVER (ORDER BY balance DESC) AS rnk,
balance / sum(balance) OVER () AS supply_share
FROM token_holders
WHERE token_address = lower($1) AND balance > 0
)
SELECT count(*) AS total_holders,
sum(supply_share) FILTER (WHERE rnk <= 10) * 100 AS top10_percent,
sum(supply_share) FILTER (WHERE rnk <= 100) * 100 AS top100_percent,
sum(supply_share) FILTER (WHERE rnk <= 500) * 100 AS top500_percent,
count(*) FILTER (WHERE usd_value >= 1000000) AS whales,
count(*) FILTER (WHERE usd_value < 100) AS shrimps
FROM ranked;
```
**Gotchas**
* The foundation is exact, the analytics are yours: holder count and concentration are deterministic SQL; the tier boundaries and acquisition rules are conventions you define, once fixed, the counts are exact.
* Materialize for large tokens, USDC has millions of holders; compute the summary on a schedule into its own table, not per request.
* Full-history backfill matters even more here: start late and you undercount holders and skew **every** aggregate, including the 30-day trend and the first-acquisition split.
* Decimals matter for USD tiering, recompute `usd_value` with real `decimals` before bucketing non-18-decimal tokens.
### Solana: GET /token/:network/holders/:address
> [!WARNING]
>
> This endpoint and `/token/:network/:address/top-holders` below are **deprecated Solana Token API endpoints sunsetting July 31, 2026**. Migrate before that date, after sunset the endpoints stop responding. This template pointed at Solana (see [Multichain](#multichain)) is the replacement for both.
The Solana holder-metrics summary, holder count and size distribution for an SPL token. Replaced by this template with `chain` set to Solana: `tokenHolders` maintains one current balance per `(mint, owner)` and you aggregate the metrics in SQL. The field mapping matches the `/erc20/:tokenAddress/holders` table above, `totalHolders` is exact, `holderDistribution` and `holdersByAcquisition` are definitions you set (the acquisition split again needs [Token Transfers](/data-feeds/templates/token/token-transfers)), and `holderChange` is calculated from a count series you maintain.
Total plus distribution tiers (Postgres, swap in your own thresholds, by `usd_value` or raw `balance`):
```sql theme={null}
SELECT count(*) AS total_holders,
count(*) FILTER (WHERE usd_value >= 1000000) AS whales,
count(*) FILTER (WHERE usd_value >= 100000 AND usd_value < 1000000) AS sharks,
count(*) FILTER (WHERE usd_value >= 10000 AND usd_value < 100000) AS dolphins,
count(*) FILTER (WHERE usd_value < 10000) AS shrimps
FROM token_holders
WHERE token_address = $1 -- base58 mint, case-sensitive: do NOT lowercase
AND balance > 0;
```
**Gotchas**
* Don't lowercase Solana addresses: EVM addresses in this template are stored lowercased, but base58 mints and owners are **case-sensitive**, match them as-is.
* SPL account model: the decoded feed resolves transfers to **owner wallets**, so `wallet_address` is the owner; one owner can hold across multiple token accounts, sum them for a per-owner total.
* Backfill from around the mint's deployment or the count silently undershoots.
### Solana: GET /token/:network/:address/top-holders
The ranked per-holder list for an SPL token, the Solana twin of `/erc20/:address/owners`, and the same direct migration: this template on Solana plus `ORDER BY balance DESC`. The field mapping matches the `/erc20/:address/owners` table above with camelCase names (`ownerAddress`, `balanceFormatted`, `usdValue`, `percentageRelativeToTotalSupply`); `isContract` (is the owner a program-owned account) is **add yourself** from your own account-type source. Formatted balance and supply percentage again need [Token Metadata](/data-feeds/templates/token/token-metadata).
```sql theme={null}
SELECT wallet_address AS owner_address,
balance,
usd_value
FROM token_holders
WHERE token_address = $1 -- base58 mint, case-sensitive: do NOT lowercase
AND balance > 0
ORDER BY balance DESC
LIMIT $2 OFFSET $3;
```
**Gotchas**
* Sunsetting **July 31, 2026** along with the holder-metrics endpoint above, plan the cutover now.
* SPL decimals vary per token, format against real `decimals` from `token_metadata`, never a fixed 18; the stored best-effort `usd_value` assumes 18.
* Same base58 case-sensitivity and owner-vs-token-account notes as above.
* USD value comes from real trades, compare with a tolerance; a thinly-traded token may value at 0.
### Related
> [card] [Token Transfers](/data-feeds/templates/token/token-transfers)
>
> The per-token movement ledger this holder set is derived from.
> [card] [Token Analytics](/data-feeds/use-cases/token-analytics)
>
> The use case holder distribution and concentration power.
# Token Metadata
Source: https://docs.moralis.com/data-feeds/templates/token/token-metadata
Sync ERC-20 token metadata (name, symbol, decimals, total supply, and deployer) captured at deploy time into your own database. Mirrors the Moralis GET /erc20/metadata endpoint.
### Question it answers
> "Give me the ERC-20 metadata (`name` / `symbol` / `decimals` / `total_supply`) for token **0x…**." Mirrors Moralis `GET /erc20/metadata`.
The template lands one observation per **TOKEN-type deployed contract** and projects it into a one-row-per-token metadata surface. Token metadata is fixed at deploy time, so there is normally exactly one row per `(chain_id, token_address)`; the latest deploy by `(block_number, transaction_index)` is canonical (defensive against a CREATE2 re-deploy at a reused address).
### What you get
One row per token contract, keyed by `token_address`:
| Column | Description |
| - | - |
| `token_address` | The deployed token contract address |
| `name` | ERC-20 token name (raw string; may contain quotes/odd characters) |
| `symbol` | ERC-20 token symbol |
| `decimals` | ERC-20 decimals; apply at read time to scale `total_supply` and any raw amounts |
| `total_supply` | Raw `uint256` supply, **no decimals applied**; divide by `10^decimals` for the human-readable value |
| `deployer_address` | Address that deployed the contract |
| `block_number`, `transaction_index` | Deploy position (the recency tiebreaker for re-deploys) |
| `block_timestamp` / `event_ts` | Deploy block time |
Token contracts are filtered to real ERC-20 deploys: a contract is kept only if its `symbol` is non-empty and ≤ 100 chars, `decimals` ≤ 50, and `deployer_address` is non-empty.
### Source
The transform reads the per-block `deployedContracts` array, filtered to entries whose `type` contains `TOKEN` (the token-contract slice of the block EVM data). Each surviving entry becomes one row. `deployedContracts` carries no log index, so `transaction_index` is the intra-block tiebreaker: one deploy per `(tx, contract)`.
### Destination
| Destination | Table | Read pattern |
| - | - | - |
| **ClickHouse** (first-class) | `fact_token_metadata` | Prefix scan on `(chain_id, token_address)`; read with `FINAL`, take latest deploy via `argMax(…, (block_number, transaction_index))` |
| **Postgres** | `token_metadata` (materialized view over `token_metadata_observations`) | Unique index on `(token_address)` |
| **MySQL** | `token_metadata` (latest-wins trigger state table over observations) | Primary key on `(token_address)` |
ClickHouse uses the collapsing log-table pattern (see the [templates overview](/data-feeds/templates/overview#destinations)) so chain reorganizations self-correct. The fact table's sort key is token-first, so a token's metadata is a point lookup. Postgres derives the current-metadata surface as a `DISTINCT ON (token_address)` materialized view; MySQL maintains it incrementally via an `AFTER INSERT` latest-wins trigger.
### Full schema
The complete read table this template produces. Keep the columns you need and drop the rest (see [Schema & flexibility](/data-feeds/templates/overview#schema--flexibility)). `total_supply` is the raw `uint256` stored as text / wide integer (it exceeds standard numeric precision); apply `decimals` at read time for the human-readable value.
> [accordion] ClickHouse, fact\_token\_metadata
>
> ```sql theme={null}
> CREATE TABLE recipe_token_metadata.fact_token_metadata
> (
> vendor_event_id String,
> ingested_at DateTime64(3),
> chain_id UInt32,
> block_hash String,
> block_number UInt64,
> transaction_index UInt32,
> event_ts DateTime64(3),
> token_address String,
> deployer_address String,
> name String,
> symbol String,
> decimals Int16,
> total_supply String, -- raw uint256, no decimals applied
> sign Int8
> )
> ENGINE = ReplicatedCollapsingMergeTree(
> '/clickhouse/tables/{database}/fact_token_metadata', '{replica}', sign)
> PARTITION BY (chain_id, toYYYYMM(event_ts))
> ORDER BY (chain_id, token_address, block_number, transaction_index, vendor_event_id);
> ```
>
> The `sign` column drives reorg collapsing: read with `FINAL` or a sign-aware aggregate, and take the latest deploy with `argMax(…, (block_number, transaction_index))`. A single-node setup can use `CollapsingMergeTree(sign)` without the replication path. Because metadata is fixed at deploy, there is normally one row per token; the latest-deploy logic only matters for a CREATE2 re-deploy at a reused address.
> [accordion] Postgres, token\_metadata
>
> ```sql theme={null}
> -- 1. Observations (sink target) — append-only, one row per deploy.
> CREATE TABLE public.token_metadata_observations (
> position BIGINT NOT NULL,
> transaction_index BIGINT,
> block_number BIGINT NOT NULL,
> block_timestamp BIGINT NOT NULL, -- unix seconds
> tx_hash TEXT NOT NULL,
> vendor_event_id TEXT NOT NULL,
> token_address TEXT NOT NULL,
> deployer_address TEXT NOT NULL,
> name TEXT NOT NULL,
> symbol TEXT NOT NULL,
> decimals SMALLINT NOT NULL,
> total_supply NUMERIC(76, 0) -- raw uint256, no decimals applied
> );
>
> -- Speeds the DISTINCT ON (latest-per-token) the materialized view computes.
> CREATE INDEX IF NOT EXISTS tmo_token_recency_idx
> ON public.token_metadata_observations
> (token_address, block_number DESC, transaction_index DESC);
>
> -- 2. Current-metadata materialized view: latest deploy per token_address.
> CREATE MATERIALIZED VIEW public.token_metadata AS
> SELECT DISTINCT ON (token_address)
> token_address,
> name,
> symbol,
> decimals,
> total_supply,
> block_number,
> deployer_address
> FROM public.token_metadata_observations
> ORDER BY token_address, block_number DESC, transaction_index DESC;
>
> -- Required by REFRESH MATERIALIZED VIEW CONCURRENTLY (one row per token).
> CREATE UNIQUE INDEX IF NOT EXISTS token_metadata_pk
> ON public.token_metadata (token_address);
>
> -- Lookup helper.
> CREATE INDEX IF NOT EXISTS token_metadata_symbol_idx
> ON public.token_metadata (symbol);
> ```
>
> Refresh the view on a schedule: `REFRESH MATERIALIZED VIEW CONCURRENTLY token_metadata;`. `total_supply` is `NUMERIC(76, 0)`: the explicit precision keeps large raw supplies from overflowing. MySQL is the same shape with `DECIMAL(65,0)` for `total_supply` and `VARCHAR(255)` for `name` / `symbol`, maintaining `token_metadata` incrementally via an `AFTER INSERT` latest-wins trigger. `position` is the block-level cursor used during backfill.
### Example reads
Metadata for one token, latest deploy wins (ClickHouse):
```sql theme={null}
SELECT
token_address,
argMax(name, (block_number, transaction_index)) AS name,
argMax(symbol, (block_number, transaction_index)) AS symbol,
argMax(decimals, (block_number, transaction_index)) AS decimals,
argMax(total_supply, (block_number, transaction_index)) AS total_supply,
argMax(deployer_address, (block_number, transaction_index)) AS deployer_address
FROM recipe_token_metadata.fact_token_metadata FINAL
WHERE chain_id = 1 AND token_address = lower('0x...')
GROUP BY token_address;
```
All tokens deployed in a block range (ClickHouse):
```sql theme={null}
SELECT token_address, name, symbol, decimals, block_number
FROM recipe_token_metadata.fact_token_metadata FINAL
WHERE chain_id = 1 AND block_number BETWEEN 19000000 AND 19001000
ORDER BY block_number, transaction_index;
```
Current metadata for one token (Postgres, after refreshing the view):
```sql theme={null}
SELECT token_address, name, symbol, decimals, total_supply
FROM public.token_metadata
WHERE token_address = lower('0x...');
```
### Modes
Shipped defaults: **ClickHouse `hybrid`** (backfill → realtime), **Postgres / MySQL `historical`** (one-shot backfill). For live/reorg-safe ingestion, use ClickHouse; see the [overview](/data-feeds/templates/overview#modes).
> [!NOTE]
>
> The Postgres / MySQL realtime reorg path needs a single-column `UNIQUE` on the position column, but `position` is block-level (one block can deploy several token contracts), so array-expanded rows can only carry a composite unique. Run realtime/hybrid on **ClickHouse**, where the collapsing log table corrects reorgs per-block. The Postgres / MySQL configs are intended for `historical` backfill; a once-off metadata census is the dominant use of this template anyway.
### Multichain
The template is chain-parametrized via the `chain` setting: point it at any supported EVM chain. The `vendor_event_id` already includes `chain_id`, `tx_hash`, `transaction_index`, and `token_address`, so rows stay unique without the Solana log-index widening other templates need. Note that SPL token metadata does not flow through `deployedContracts` the way EVM contract deploys do; this template is **EVM-shaped**.
### Fidelity gaps
The core on-chain fields (`token_address`, `name`, `symbol`, `decimals`, `total_supply`, plus `block_number` and `deployer_address`) are fully sourced. A few enrichment fields `GET /erc20/metadata` returns are **not** sourced here, as they come from off-chain or separate pipelines:
* `logo` / `thumbnail` / `logo_hash`: off-chain logo CDN assets.
* `validated` / `possible_spam` / `verified_contract`: Moralis spam & verification heuristics.
* `categories`: editorial token categorisation.
* `created_at` (wall-clock): this template carries on-chain `block_number` / `block_timestamp` instead.
Also note `total_supply` is the **raw** `uint256` with no decimals applied; divide by `10^decimals` for the human-readable supply.
## Migrating from the REST API
### `GET /erc20/metadata`: ERC-20 token metadata
This template replaces the endpoint's on-chain core: `name`, `symbol`, `decimals`, `total_supply`, and the deploy position come through exactly, with no batch cap on how many contracts you look up per query.
> [!NOTE]
>
> **Not 1:1.** `fully_diluted_valuation` needs a price join: pair this template with [Token Prices](/data-feeds/templates/token/token-prices) and multiply. The endpoint's editorial layer (`logo` / `thumbnail`, `possible_spam` / `verified_contract` / `validated` / `security_score`, `categories`, `links`, `description`) is off-chain: bring your own token list and allow/deny lists, or drop those fields. `market_cap` needs an off-chain `circulating_supply` (there is no on-chain equivalent); FDV is the on-chain-derivable alternative.
| `/erc20/metadata` | Data Feeds | Fidelity |
| - | - | - |
| `address`, `name`, `symbol`, `decimals` | `token_metadata.*` | exact |
| `total_supply` (raw) | `token_metadata.total_supply` | exact |
| `total_supply_formatted` | `total_supply / 10^decimals` | calculated |
| `block_number` (deploy) | `token_metadata.block_number` | exact |
| `created_at` (deploy time) | `token_metadata_observations.block_timestamp` (not on the `token_metadata` view) | exact |
| `fully_diluted_valuation` | `total_supply_formatted × usd_price` via [Token Prices](/data-feeds/templates/token/token-prices) | calculated |
| `market_cap` | `circulating_supply × price`; needs off-chain circulating supply | add yourself |
| `circulating_supply` | None | add yourself |
| `implementations` | match the token across the chains you index, or a multichain token list | add yourself |
| `logo`, `logo_hash`, `thumbnail` | None | add yourself |
| `possible_spam`, `verified_contract`, `validated`, `security_score` | None | add yourself |
| `categories`, `links`, `description`, `address_label` | None | add yourself |
Any set of contracts in one query, with formatted supply and FDV (Postgres):
```sql theme={null}
SELECT m.token_address AS address,
m.name, m.symbol, m.decimals,
m.total_supply,
m.total_supply / power(10, m.decimals) AS total_supply_formatted,
m.total_supply / power(10, m.decimals) * p.usd_price AS fully_diluted_valuation
FROM token_metadata m
LEFT JOIN LATERAL (
SELECT usd_price FROM token_price_updates
WHERE token_address = m.token_address ORDER BY block_number DESC LIMIT 1
) p ON true
WHERE m.token_address = ANY($1); -- lowercased addresses, no batch cap
```
* **Backfill from the deploy block.** Metadata is captured at contract deployment, so a token only appears if its deploy block is indexed; for arbitrary token lookups, run `historical` / `hybrid` over full history.
* `total_supply` is **raw and live**: no decimals applied (scale at read time), and it tracks mint/burn, so keep the feed current for an up-to-date figure.
* `created_at` isn't on the `token_metadata` view; read `block_timestamp` from `token_metadata_observations` (Postgres) or `event_ts` on the ClickHouse fact table.
* The template is **EVM-shaped**: SPL token metadata doesn't flow through `deployedContracts` (see [Multichain](#multichain)).
### Related
> [card] [Token Holders](/data-feeds/templates/token/token-holders)
>
> All non-zero holders of a token; pair with metadata for decimals and symbol.
> [card] [Token Analytics](/data-feeds/use-cases/token-analytics)
>
> The use case this metadata census powers: the decimals lookup behind every scaled amount.
# Token Prices
Source: https://docs.moralis.com/data-feeds/templates/token/token-prices
Sync a token's full USD / native mark price history (every in-block price update for each pair and protocol) as a continuous feed into your own database, with a carry-forward latest mark for valuing quiet positions.
### Question it answers
> "Give me the USD / native mark price history for token **0x…**, newest first, and the freshest mark right now so I can value a position that hasn't traded recently."
Token Prices is the **valuation join target** across Data Feeds. Any "what is this worth in USD" question (a transfer's value, a portfolio's worth, a trade's notional) joins a token's mark at a given block from this feed.
### What you get
The template lands **one row per in-block price update**: Moralis' continuous mark for each `(token, pair, protocol)` at the block it changed. A token traded across several pairs or protocols produces several marks per block; the table keeps them all, keyed for by-token lookups.
| Column | Description |
| - | - |
| `token_address` | The token the mark prices |
| `pair_address` | The pair the mark was observed on |
| `protocol` | The DEX/protocol that produced the mark |
| `usd_price` | USD mark, carried as text for full precision; cast at read time |
| `native_price` | Native-asset mark (e.g. ETH), text for full precision |
| `block_number`, `event_ts` | When the mark was set (block height and block time) |
| `tx_hash` | Transaction the price update came from |
| `chain_id` | Chain the mark belongs to |
On ClickHouse, a companion **`latest_token_price_dict`** dictionary keeps the freshest mark per `(chain_id, token_address)` for O(1) carry-forward valuation of tokens that haven't updated recently.
### Source
The transform reads one per-block array, `tokenPriceUpdates`, and lands one row per entry. Each entry is Moralis' mark for a `(token, pair, protocol)` at that block. There is no read-time join: every mark is already a row keyed by token.
### Destination
| Destination | Table | Read pattern |
| - | - | - |
| **ClickHouse** (first-class) | `fact_token_price_update` (+ `latest_token_price_dict`) | Prefix scan on `(chain_id, token_address, event_ts)`; read with `FINAL` or `sum(sign)` |
| **Postgres** | `token_price_updates` | Index on `(token_address, block_number DESC)` |
| **MySQL** | `token_price_updates` | Index on `(token_address, block_number)` |
ClickHouse uses the collapsing log-table pattern (see the [templates overview](/data-feeds/templates/overview#destinations)) so chain reorganizations self-correct. The fact table's sort key is token-first, so a token's full price history is a contiguous range read; the `latest_token_price_dict` dictionary holds the carry-forward mark for quiet positions.
### Full schema
Below is the complete read table this template produces. It's a starting point: keep the columns you need and drop the rest (see [Schema & flexibility](/data-feeds/templates/overview#schema--flexibility)). `usd_price` and `native_price` are carried as text to preserve full precision across many orders of magnitude; cast at read time.
> [accordion] ClickHouse, fact\_token\_price\_update
>
> ```sql theme={null}
> CREATE TABLE recipe_token_price_history.fact_token_price_update
> (
> vendor_event_id String,
> ingested_at DateTime64(3),
> chain_id UInt32,
> block_hash String,
> block_number UInt64,
> event_ts DateTime64(3),
> token_address String,
> pair_address String,
> protocol LowCardinality(String),
> usd_price String, -- toString(usdPrice), cast at read time
> native_price String, -- toString(nativePrice)
> sign Int8
> )
> ENGINE = ReplicatedCollapsingMergeTree(
> '/clickhouse/tables/{database}/fact_token_price_update', '{replica}', sign)
> PARTITION BY (chain_id, toYYYYMM(event_ts))
> ORDER BY (chain_id, token_address, event_ts, vendor_event_id);
>
> -- OPTIONAL (carry-forward valuation): the freshest USD mark per token, O(1).
> -- Refreshes every 30-60s, so a quiet token carries its last on-chain mark
> -- forward without a new price event. argMax over FINAL/sign=1 is reorg-correct.
> CREATE DICTIONARY recipe_token_price_history.latest_token_price_dict
> (
> chain_id UInt32,
> token_address String,
> usd_price String,
> block_number UInt64,
> event_ts DateTime64(3)
> )
> PRIMARY KEY chain_id, token_address
> SOURCE(CLICKHOUSE(
> QUERY $$
> SELECT chain_id, token_address,
> argMax(usd_price, (block_number, event_ts)) AS usd_price,
> max(block_number) AS block_number,
> max(event_ts) AS event_ts
> FROM recipe_token_price_history.fact_token_price_update FINAL
> WHERE sign = 1
> GROUP BY chain_id, token_address
> $$
> ))
> LAYOUT(COMPLEX_KEY_HASHED())
> LIFETIME(MIN 30 MAX 60);
> ```
>
> The `sign` column drives reorg collapsing: read with `FINAL` or `sum(sign)`. A single-node setup can use `CollapsingMergeTree(sign)` without the replication path. Inside the dictionary the `WHERE sign = 1` is safe (not the bare-`WHERE` anti-pattern) because `FINAL` has already collapsed the ±1 reorg pairs.
> [accordion] Postgres, token\_price\_updates
>
> ```sql theme={null}
> CREATE TABLE public.token_price_updates (
> position BIGINT NOT NULL,
> log_index BIGINT,
> transaction_index BIGINT,
> block_number BIGINT NOT NULL,
> block_timestamp BIGINT NOT NULL, -- unix seconds
> tx_hash TEXT NOT NULL,
> vendor_event_id TEXT NOT NULL,
> token_address TEXT NOT NULL,
> pair_address TEXT NOT NULL,
> protocol TEXT NOT NULL,
> usd_price NUMERIC(38, 18),
> native_price NUMERIC(38, 18)
> );
>
> -- By-token price history (the template's primary purpose).
> CREATE INDEX ON public.token_price_updates (token_address, block_number DESC);
> -- Block-range helper.
> CREATE INDEX ON public.token_price_updates (block_number);
> ```
>
> MySQL is the same shape with `DECIMAL(38,18)` for the price columns. `position` is the block-level cursor used during backfill. The explicit `NUMERIC(38,18)` precision keeps room for marks that span many orders of magnitude.
### Example reads
A token's price history, newest first (ClickHouse):
```sql theme={null}
SELECT event_ts, usd_price, native_price, pair_address, protocol
FROM recipe_token_price_history.fact_token_price_update FINAL
WHERE chain_id = 1
AND token_address = lower('0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48')
ORDER BY event_ts DESC
LIMIT 50;
```
The latest carry-forward mark via the dictionary (O(1), refreshes every 30–60s):
```sql theme={null}
SELECT dictGetOrDefault(
'recipe_token_price_history.latest_token_price_dict', 'usd_price',
tuple(1, lower('0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48')), '0'
) AS usd_price;
```
Hourly close per token (last mark in each hour bucket, sign-aware):
```sql theme={null}
SELECT toStartOfHour(event_ts) AS hour,
argMax(usd_price, (block_number, event_ts)) AS close_usd
FROM recipe_token_price_history.fact_token_price_update
WHERE chain_id = 1
AND token_address = lower('0xA0b8…')
AND sign = 1
GROUP BY hour
ORDER BY hour DESC
LIMIT 24;
```
### Modes
Shipped defaults: **ClickHouse `hybrid`** (backfill → realtime), **Postgres / MySQL `historical`** (one-shot backfill). For live/reorg-safe ingestion, use ClickHouse; see the [overview](/data-feeds/templates/overview#modes).
> [!NOTE]
>
> The realtime reorg path needs a single-column `UNIQUE` on the position column, but `position` is block-level (many price updates share one block), so the array-expanded rows can only carry a composite unique. Run realtime/hybrid on **ClickHouse**, where the collapsing log table corrects reorgs per-block. The Postgres / MySQL configs are intended for `historical` backfill.
### Multichain
The template is chain-parametrized via the `chain` setting: point it at any supported EVM chain or Solana. On Solana, the same `logIndex` can be assigned to multiple events in one instruction, so the event identity is widened with `pairAddress` (or `protocol`) to keep marks distinct; the price feed it produces is identical in shape.
### How much data does this consume?
`tokenPriceUpdates` is one of the smaller slices in the feed. A continuous real-time feed measured:
| Chain | Typical month (P50) | Busy month (P90) |
| - | - | - |
| Solana | **\~84 GB** | **\~110 GB** |
| BNB Smart Chain | **\~23 GB** | not measured |
| Base | **\~6.0 GB** | not measured |
| Polygon | **\~3.0 GB** | not measured |
| Arbitrum | **\~2.7 GB** | not measured |
| Ethereum | **\~1.3 GB** | not measured |
| Optimism | **\~0.9 GB** | not measured |
Measured 2026-07-30, `metered` delivery; Solana over 25 sampled partitions, the EVM chains over 60. Billing is on uncompressed bytes. All runs included the negligible `deployedContracts` slice.
**Size your allowance against a busy month, not a typical one.** Where only a typical figure exists, leave meaningful headroom above it rather than sizing to it — chain activity is bursty, and busy months on comparable slices have measured 30–70% above typical. Three caveats:
* **Real-time only.** A historical backfill is billed separately and is usually the larger number; its size depends entirely on how far back you go.
* **Measured chains only.** Volume concentrates hard per chain, so these figures do not extrapolate to unmeasured chains.
* **Filtering does not reduce it.** Restricting to specific tokens or venues happens after the data is delivered. To reduce cost, narrow the **block range**, not the entity set.
If you want your exact scope measured before you commit to a plan, [reach out](https://admin.moralis.com/data-feeds) and we will probe it against the live feed rather than estimate it.
### Fidelity and valuation notes
* **Precision.** `usd_price` and `native_price` are carried as strings end-to-end to preserve full precision; cast at read time (`toDecimal*` on ClickHouse, the `NUMERIC` / `DECIMAL` columns on Postgres / MySQL).
* **Multiple marks per block.** A token priced on several pairs/protocols lands one row per `(pair, protocol)` per block. Pick a venue (filter `pair_address` / `protocol`) or aggregate (`argMax`) depending on whether you want a specific venue's mark or a representative one.
* **Carry-forward staleness.** The `latest_token_price_dict` refreshes every 30–60s, so a quiet token's mark is at most \~a minute stale without needing a fresh price event, but it does not interpolate between updates.
## Migrating from the REST API
This template replaces both REST price endpoints. Their responses were **not 1:1 rows in one table**: prices, token details, and pair liquidity came bundled in a single payload, but they live in different parts of the dataset here.
> [!NOTE]
>
> Rebuilding the full REST response takes a **combination of templates**: this one for the marks, plus [Token Metadata](/data-feeds/templates/token/token-metadata) for `tokenName` / `tokenSymbol` / `tokenDecimals` and [Pair Reserves](/data-feeds/templates/markets/pair-reserves) if you need `pairTotalLiquidityUsd` (reserves × price). Join them at read time on `token_address` / `pair_address`.
Two workflow changes to plan for:
* **USD prices are calculated from DEX trades**: the same trades the REST endpoints priced from, so marks track closely, but compare with a small tolerance rather than expecting identical figures.
* **You pick the reference pair.** The REST endpoints chose one pair (typically deepest liquidity) as "the price"; this table keeps every `(pair, protocol)` mark, so you define the rule: filter by `pair_address`, or `argMax` for the newest overall.
Both endpoints returned the same shape, so one field mapping covers them:
| REST API field | Data Feeds | Fidelity |
| - | - | - |
| `tokenAddress` | `token_address` | exact |
| `usdPrice` / `usdPriceFormatted` | latest `usd_price` per token | calculated |
| `nativePrice` | latest `native_price` (a scalar, not the REST endpoint's object) | calculated |
| `pairAddress`, `exchangeName` | `pair_address`, `protocol` | exact |
| `priceLastChangedAtBlock`, `blockTimestamp` | `block_number`, `event_ts` (`block_timestamp` on Postgres / MySQL, in **seconds**, not ms) | exact |
| `tokenName`, `tokenSymbol`, `tokenDecimals` | [Token Metadata](/data-feeds/templates/token/token-metadata) template | exact |
| `24hrPercentChange`, `usdPrice24hr*` | derive: mark \~24h ago vs latest, from this table's history | calculated |
| `pairTotalLiquidityUsd` | [Pair Reserves](/data-feeds/templates/markets/pair-reserves) template (reserves × price) | calculated |
| `exchangeAddress` | not in these templates: `protocol` names the venue; bring a factory list if you need the address | add yourself |
| `tokenLogo`, `possibleSpam`, `verifiedContract`, `securityScore` | off-chain signals; bring your own token / allow / deny lists | add yourself |
### GET /erc20/:address/price: single token price
```text theme={null}
GET /erc20/:address/price
```
Replaced by the newest mark for one token in this template's table, joined to [Token Metadata](/data-feeds/templates/token/token-metadata) for the token details the endpoint bundled in. On Postgres:
```sql theme={null}
SELECT DISTINCT ON (p.token_address)
p.token_address, m.symbol, m.name, m.decimals,
p.usd_price, p.native_price, p.pair_address,
p.protocol AS exchange_name,
p.block_number AS price_last_changed_at_block,
p.block_timestamp
FROM token_price_updates p
LEFT JOIN token_metadata m ON m.token_address = p.token_address
WHERE p.token_address = lower('0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48')
ORDER BY p.token_address, p.block_number DESC; -- newest mark
```
* On ClickHouse, skip the scan for "price now": `latest_token_price_dict` is the O(1) carry-forward lookup (see [Example reads](#example-reads)).
* For "price now" you only need the feed running recently; backfill only if you want historical prices (the old `to_block` behavior) or a 24h-change window. See [History & backfill](/data-feeds/concepts/history-and-backfill).
* A token that hasn't traded recently carries an older mark; the dictionary carries it forward but does not interpolate.
### POST /erc20/prices: batch token prices
```text theme={null}
POST /erc20/prices
```
Replaced by the same newest-mark-per-token read over a set of tokens: one query, **no 100-token batch cap**. On ClickHouse:
```sql theme={null}
SELECT token_address,
argMax(usd_price, (block_number, event_ts)) AS usd_price,
argMax(native_price, (block_number, event_ts)) AS native_price,
argMax(pair_address, (block_number, event_ts)) AS pair_address,
max(block_number) AS price_last_changed_at_block
FROM recipe_token_price_history.fact_token_price_update FINAL
WHERE chain_id = 1
AND sign = 1
AND token_address IN (lower('0xA0b8…'), lower('0xC02a…'), lower('0x6B17…'))
GROUP BY token_address;
```
* The REST 24h-change fields (`24hrPercentChange`, `usdPrice24hr*`) aren't stored; derive them by comparing each token's latest mark against its mark \~24 hours earlier from this same table.
* Pin the reference pair per token (filter `pair_address` or order by your liquidity column) before `argMax`, or the "price" can flip between venues call to call.
* Tokens with no recent DEX activity return their last mark, not `null`; check `price_last_changed_at_block` if staleness matters.
### Related
> [card] [Token Transfers](/data-feeds/templates/token/token-transfers)
>
> The per-token transfer ledger you value against these marks.
> [card] [Portfolio Tracking](/data-feeds/use-cases/portfolio-tracking)
>
> Token Prices is the valuation join target behind portfolio worth.
# Token Stats
Source: https://docs.moralis.com/data-feeds/templates/token/token-stats
Maintain per-token transfer counters (how many transfers a token has had) as a continuous, reorg-safe aggregate in your own database. Replaces the removed Moralis GET /erc20/{address}/stats endpoint.
### Question it answers
> "How many transfers has token **0x…** had?" Replaces the removed Moralis `GET /erc20/{address}/stats` (`{ transfers: { total } }`).
Each ERC-20 transfer event contributes `+1` to that token's counter. The shape is intentionally compact (one counter today), but the **pattern** is the value: fold any future per-token counter (holder-count delta, daily active addresses, …) onto the same row so a single read returns the full stats block for a token.
### What you get
One aggregated row per token, keyed by `token_address`:
| Column | Description |
| - | - |
| `chain_id` | The chain the token lives on |
| `token_address` | The ERC-20 contract address (the counter key) |
| `transfers_total` | Net count of transfer events for the token (`transfers.total`) |
`transfers_total` counts every row in the source transfer array, **including mints (`from = 0x0`) and burns (`to = 0x0`)**, matching the endpoint's "transfers of the token" semantics. See [Counter semantics](#counter-semantics) to exclude mints/burns.
### Source
The transform reads one per-block array and counts it:
`tokenTransfers`
This is by definition the ERC-20 transfer event collection (NFT and native transfers are separate arrays: `nftTokenTransfers`, `nativeTransfers`), so no token-standard filter is needed. Each event contributes `+1` to `transfers_total` for its `token_address`. `block_number` / `block_timestamp` come from the block envelope.
### Destination
| Destination | Table | Read pattern |
| - | - | - |
| **ClickHouse** (first-class) | `fact_token_stats` | `ORDER BY (chain_id, token_address)`; net count via `sum(transfers_total)` or `FINAL` |
| **Postgres** | `token_stats` (materialized view over `token_transfer_events`) | Unique index `(token_address)` |
| **MySQL** | `token_stats` (trigger-maintained over `token_transfer_events`) | Primary key `(token_address)` |
ClickHouse uses a **SummingMergeTree** counter table (not the collapsing pattern most templates use): the table is keyed by `(chain_id, token_address)`, so every event for a token shares one key and the engine **sums** the per-event rows on background merges. The materialized view emits `transfers_total = sign` per event (`+1` for forward inserts, `-1` for reorg reverts), so the per-token sum is always the net count and is naturally reorg-safe.
### Full schema
Below is the complete read table this template produces. It's deliberately minimal (one counter) and is a starting point for the forward-compatible counter pattern: add more summable columns to land more per-token stats on the same row (see [Schema & flexibility](/data-feeds/templates/overview#schema--flexibility)).
> [accordion] ClickHouse, fact\_token\_stats
>
> ```sql theme={null}
> CREATE TABLE recipe_token_stats.fact_token_stats
> (
> chain_id UInt32,
> token_address String,
> transfers_total Int64
> )
> ENGINE = ReplicatedSummingMergeTree(
> '/clickhouse/tables/{database}/fact_token_stats', '{replica}')
> ORDER BY (chain_id, token_address);
> ```
>
> SummingMergeTree sums every numeric column that isn't part of the `ORDER BY` tuple, so adding a new counter is just another `Int64` / `UInt64` column plus a projection branch in the materialized view; no engine change. Read the net counter with `sum(transfers_total)` or `FINAL` (which forces the merge first); **never** a bare `WHERE sign = 1`. A single-node setup can use `SummingMergeTree()` without the replication path.
> [accordion] Postgres, token\_stats
>
> ```sql theme={null}
> -- 1. Transfer events (sink target).
> CREATE TABLE public.token_transfer_events (
> position BIGINT NOT NULL,
> log_index BIGINT NOT NULL,
> block_number BIGINT NOT NULL,
> block_timestamp BIGINT NOT NULL, -- unix seconds
> tx_hash TEXT NOT NULL,
> token_address TEXT NOT NULL,
> vendor_event_id TEXT NOT NULL
> );
>
> -- Row-uniqueness for idempotent ingestion.
> CREATE UNIQUE INDEX IF NOT EXISTS token_transfer_events_uq_event
> ON public.token_transfer_events (vendor_event_id);
>
> -- Per-token grouping index — lets the view's GROUP BY do an index scan, not a sort.
> CREATE INDEX IF NOT EXISTS token_transfer_events_token_idx
> ON public.token_transfer_events (token_address);
>
> -- 2. Per-token counter materialized view.
> CREATE MATERIALIZED VIEW public.token_stats AS
> SELECT
> token_address,
> COUNT(*)::BIGINT AS transfers_total
> FROM public.token_transfer_events
> GROUP BY token_address;
>
> CREATE UNIQUE INDEX IF NOT EXISTS token_stats_pk
> ON public.token_stats (token_address);
> ```
>
> Refresh on a schedule: `REFRESH MATERIALIZED VIEW CONCURRENTLY token_stats;`. MySQL keeps the same `token_transfer_events` table plus a trigger-maintained `token_stats` state table doing `INSERT … ON DUPLICATE KEY UPDATE transfers_total = transfers_total + 1`. Add another aggregate column to the view (Postgres) or another trigger column (MySQL) to land more counters.
### Example reads
Per-token transfer counters on chain 1, most-transferred first; `sum()` is reorg-safe (ClickHouse):
```sql theme={null}
SELECT token_address,
sum(transfers_total) AS transfers_total
FROM recipe_token_stats.fact_token_stats
WHERE chain_id = 1
GROUP BY token_address
ORDER BY transfers_total DESC
LIMIT 10;
```
A single token: this is the read that replaces `GET /erc20/{address}/stats`:
```sql theme={null}
SELECT sum(transfers_total) AS transfers_total
FROM recipe_token_stats.fact_token_stats
WHERE chain_id = 1
AND token_address = lower('0x...');
```
Same query via `FINAL` (forces the background merge first; identical result):
```sql theme={null}
SELECT token_address, transfers_total
FROM recipe_token_stats.fact_token_stats FINAL
WHERE chain_id = 1
ORDER BY transfers_total DESC
LIMIT 10;
```
### Counter semantics
`transfers_total` includes **mints and burns**, matching the endpoint's "transfers of the token" definition: every `+1` of supply movement is counted, with no `from = 0x0` / `to = 0x0` filter. The ClickHouse fact table carries only the aggregated counter, so to exclude mints/burns query the Postgres/MySQL event table (which retains per-event rows), or add `from`/`to` columns to the transform and event-table schema if you need that surface in ClickHouse:
```sql theme={null}
-- Postgres: counts excluding mints + burns (requires from/to columns on the event table).
SELECT token_address, COUNT(*) AS transfers_total
FROM public.token_transfer_events
WHERE token_address = lower('0x...')
GROUP BY token_address;
```
### Modes
Shipped defaults: **ClickHouse `hybrid`** (backfill → realtime), **Postgres / MySQL `historical`** (one-shot backfill). For live, reorg-corrected counters, use ClickHouse; see the [overview](/data-feeds/templates/overview#modes).
> [!NOTE]
>
> On Postgres / MySQL the counter **only ever increments** in `historical` mode: there is no reorg-safe row-deletion path on these destinations, and the per-event `vendor_event_id` uniqueness only guards against double-ingestion of the same canonical event. `position` is block-level and array-expanded transfer rows share it, which constrains realtime/hybrid here. Run realtime/hybrid on **ClickHouse**, which corrects reorgs per-block via signed `-1` rows.
### Multichain
The template is chain-parametrized via the `chain` setting: point it at any supported EVM chain or Solana. On Solana, every SPL token transfer contributes `+1`; the `vendor_event_id` is widened to stay unique even where a log index repeats within an instruction, so per-token counts round-trip identically in shape.
### Related
> [card] [Token Transfers](/data-feeds/templates/token/token-transfers)
>
> The per-event transfer ledger this counter is derived from.
> [card] [Token Analytics](/data-feeds/use-cases/token-analytics)
>
> The use case per-token stats power.
# Token Transfers
Source: https://docs.moralis.com/data-feeds/templates/token/token-transfers
Sync every ERC-20 token transfer, by token or by wallet, as a flat, ordered event log into your own database.
### Question it answers
> "Give me every ERC-20 transfer: all transfers of token **0x…**, or every transfer wallet **0x…** sent or received."
One flat event log of token transfers, served two ways from a single sync: **by-token** (every movement of a given token) and **by-wallet** (every transfer a wallet was on either side of). Each row is one transfer carrying exactly one token and one amount; there's no USD enrichment, because a transfer event carries no price.
### What you get
One row per transfer, from Moralis-indexed, normalized per-block onchain data:
| Column | Description |
| - | - |
| `token_address` | The transferred token's contract |
| `from_address`, `to_address` | Sender and recipient |
| `amount` | Raw `uint256` token units (not decimal-adjusted) |
| `transfer_type` | Transfer kind as emitted (`erc20`, …) |
| `initiated_by` | Address that initiated the transfer |
| `block_number`, `log_index`, `transaction_index` | On-chain ordering tuple |
| `tx_hash` | Transaction that produced the transfer |
| `block_timestamp` / `event_ts` | Block time |
### Source
The transform reads a single per-block array, `tokenTransfers`, and lands one row per transfer. Fields map straight from the source struct (`tokenAddress → token_address`, `fromAddress → from_address`, `toAddress → to_address`, `amount → amount`, `type → transfer_type`, `initiatedBy → initiated_by`).
There's no price join: transfers are unpriced, so there is no `amount_usd` column. The per-transfer `vendor_event_id` is widened beyond `(tx_hash, log_index)` so the id stays unique on Solana, where `logIndex` is not row-unique within an instruction (see [Multichain](#multichain)).
### Destination
| Destination | Table | Read pattern |
| - | - | - |
| **ClickHouse** (first-class) | `fact_token_transfers` | Prefix scan on `(chain_id, token_address, block_number)` for by-token; `bloom_filter` skip-indexes on `from_address` / `to_address` for by-wallet; read with `FINAL` or `sum(sign)` |
| **Postgres** | `token_transfers` | Index on `(token_address, block_number DESC)`; plus `(from_address, …)` and `(to_address, …)` |
| **MySQL** | `token_transfers` | Index on `(token_address, block_number)`; plus `(from_address, …)` and `(to_address, …)` |
ClickHouse uses the collapsing log-table pattern (see the [templates overview](/data-feeds/templates/overview#destinations)) so chain reorganizations self-correct: the `+1/−1` reorg pair for a row shares an identical key and collapses on merge. The fact table's sort key is token-first, so all transfers of a token are a contiguous range read; by-wallet reads are accelerated by data-skipping bloom filters rather than a second sort key.
### Full schema
Below is the complete read table this template produces. It's a starting point: keep the columns you need and drop the rest (see [Schema & flexibility](/data-feeds/templates/overview#schema--flexibility)). `amount` is stored raw (`uint256` token units) because the transfer event carries no decimals; scale by `10^token_decimals` at read time.
> [accordion] ClickHouse, fact\_token\_transfers
>
> ```sql theme={null}
> CREATE TABLE recipe_token_transfers.fact_token_transfers
> (
> vendor_event_id String,
> ingested_at DateTime64(3),
> chain_id UInt32,
> block_hash String,
> block_number UInt64,
> event_ts DateTime64(3),
> token_address String,
> from_address String,
> to_address String,
> amount String, -- raw uint256 token units
> transfer_type LowCardinality(String),
> initiated_by String,
> tx_hash String,
> log_index Nullable(UInt32),
> transaction_index Nullable(Int32),
> sign Int8,
> -- by-wallet skip indexes: prune granules that cannot contain the wallet.
> INDEX bf_from from_address TYPE bloom_filter(0.01) GRANULARITY 4,
> INDEX bf_to to_address TYPE bloom_filter(0.01) GRANULARITY 4
> )
> ENGINE = ReplicatedCollapsingMergeTree(
> '/clickhouse/tables/{database}/fact_token_transfers', '{replica}', sign)
> PARTITION BY (chain_id, toYYYYMM(event_ts))
> ORDER BY (chain_id, token_address, block_number, vendor_event_id);
> ```
>
> The `sign` column drives reorg collapsing: read with `FINAL` or `sum(sign)`, never a bare `WHERE sign = 1`. A single-node setup can use `CollapsingMergeTree(sign)` without the replication path.
> [accordion] Postgres, token\_transfers
>
> ```sql theme={null}
> CREATE TABLE public.token_transfers (
> position BIGINT NOT NULL,
> log_index BIGINT,
> transaction_index BIGINT,
> block_number BIGINT NOT NULL,
> block_timestamp BIGINT NOT NULL, -- unix seconds
> tx_hash TEXT NOT NULL,
> vendor_event_id TEXT NOT NULL,
> token_address TEXT NOT NULL,
> from_address TEXT NOT NULL,
> to_address TEXT NOT NULL,
> amount NUMERIC(76, 0) NOT NULL, -- raw uint256 token units
> transfer_type TEXT NOT NULL,
> initiated_by TEXT NOT NULL
> );
>
> -- By-token access (the template's primary purpose).
> CREATE INDEX IF NOT EXISTS token_transfers_token_block_idx
> ON public.token_transfers (token_address, block_number DESC);
> -- By-wallet access (either side).
> CREATE INDEX IF NOT EXISTS token_transfers_from_block_idx
> ON public.token_transfers (from_address, block_number DESC);
> CREATE INDEX IF NOT EXISTS token_transfers_to_block_idx
> ON public.token_transfers (to_address, block_number DESC);
> -- Block-range helper.
> CREATE INDEX IF NOT EXISTS token_transfers_block_idx
> ON public.token_transfers (block_number);
> ```
>
> MySQL is the same shape with the same indexes. `amount` uses `NUMERIC(76, 0)` so large raw `uint256` values don't overflow; `position` is the block-level cursor used during backfill.
### Example reads
All transfers of a token, newest first (ClickHouse):
```sql theme={null}
SELECT block_number, from_address, to_address, amount, transfer_type, tx_hash
FROM recipe_token_transfers.fact_token_transfers FINAL
WHERE chain_id = 1
AND token_address = lower('0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48')
ORDER BY block_number DESC
LIMIT 50;
```
All transfers involving a wallet on either side (bloom-pruned):
```sql theme={null}
SELECT block_number, token_address, from_address, to_address, amount
FROM recipe_token_transfers.fact_token_transfers FINAL
WHERE chain_id = 1
AND (from_address = lower('0x...') OR to_address = lower('0x...'))
ORDER BY block_number DESC
LIMIT 50;
```
Net amount received by a wallet for one token (sign-aware, cheaper than `FINAL`):
```sql theme={null}
SELECT
sumIf(toFloat64OrZero(amount), to_address = lower('0xwallet') AND sign = 1)
- sumIf(toFloat64OrZero(amount), to_address = lower('0xwallet') AND sign = -1)
AS received
FROM recipe_token_transfers.fact_token_transfers
WHERE chain_id = 1 AND token_address = lower('0xtoken');
```
### Modes
Shipped defaults: **ClickHouse `hybrid`** (backfill → realtime), **Postgres / MySQL `historical`** (one-shot backfill). For live/reorg-safe ingestion, use ClickHouse; see the [overview](/data-feeds/templates/overview#modes).
> [!NOTE]
>
> The realtime reorg path needs a single-column `UNIQUE` on the position column, but `position` is block-level (many transfers share one block), so array-expanded transfer rows can only carry a composite unique. Run realtime/hybrid on **ClickHouse**, where the collapsing log table corrects reorgs per-block. The Postgres / MySQL configs are intended for `historical` backfill.
### Multichain
The template is chain-parametrized via the `chain` setting: point it at any supported EVM chain or Solana. On Solana, multiple events in one instruction can share a `logIndex`, so the `vendor_event_id` is widened with `(from_address, to_address, token_address, amount)` to keep rows distinct; the transfer log it produces is identical in shape.
### How much data does this consume?
A continuous real-time feed centered on `tokenTransfers` measured:
| Chain | Typical month (P50) | Busy month (P90) |
| - | - | - |
| Solana | **\~480 GB** | **\~590 GB** |
| BNB Smart Chain | **\~210 GB** | **\~285 GB** |
| Ethereum | **\~17 GB** | **\~23 GB** |
Measured 2026-07-31, 30 sampled partitions per chain, `metered` delivery. Billing is on uncompressed bytes. The Ethereum and BNB Smart Chain runs included the small `tokenPriceUpdates` slice, so they run slightly high for a transfers-only feed; the Solana run included the `nftTokenTransfers` slice, which is negligible there.
**Size your allowance against the busy figure, not the typical one.** Chain activity is bursty, and the same feed can land on either side of a fixed allowance depending on the month. Three caveats:
* **Real-time only.** A historical backfill is billed separately and is usually the larger number; its size depends entirely on how far back you go.
* **Measured chains only.** Volume concentrates hard per chain (BNB Smart Chain measured over 10x Ethereum on the same selection), so these figures do not extrapolate to unmeasured chains.
* **Filtering does not reduce it.** Restricting to specific tokens or wallets happens after the data is delivered. To reduce cost, narrow the **block range**, not the entity set.
If you want your exact scope measured before you commit to a plan, [reach out](https://admin.moralis.com/data-feeds) and we will probe it against the live feed rather than estimate it.
### Fidelity gaps
The template lands exactly what the `tokenTransfers` array carries. Fields a transfers endpoint might surface that have **no onchain source in this array** are omitted:
* **USD value**: a transfer carries no price. Pricing requires joining the same-block price data; that's out of scope for a plain transfer log (see Token Prices for the price-join pattern).
* **Token metadata** (`symbol`, `name`, `decimals`, logo, verified/spam flags): these come from a separate token-metadata sync, not the transfer event. `amount` is therefore stored raw, not decimal-adjusted.
* **Pre/post balances**: the balance surface lives in the balances templates (Token Balances by Token / by Wallet); this transfer log stays a flat event stream.
## Migrating from the REST API
This template replaces both ERC-20 transfer REST endpoints from one sync: the same `token_transfers` table serves the by-token and by-wallet reads.
> [!NOTE]
>
> **Not 1:1.** The REST responses inlined `token_name` / `token_symbol` / `token_decimals` and a pre-scaled `value_decimal`; this template's `amount` is raw `uint256`. Pair it with [Token Metadata](/data-feeds/templates/token/token-metadata) and join on `token_address` to scale amounts and label tokens. `token_logo`, `possible_spam`, `verified_contract`, `security_score`, and the address `*_label` / `*_entity` fields are off-chain signals; add them from your own token/label lists or drop them.
Field mapping (both endpoints share it; **calculated** = derived at read time, **add yourself** = off-chain):
| REST API field | Data Feeds | Fidelity |
| - | - | - |
| `from_address`, `to_address`, token contract | `token_transfers.from_address` / `to_address` / `token_address` | exact |
| `value` (raw) | `token_transfers.amount` | exact |
| `value_decimal` | `amount / 10^decimals` (decimals via Token Metadata) | calculated |
| `transaction_hash` | `token_transfers.tx_hash` | exact |
| `block_number`, `block_timestamp`, `block_hash`, `transaction_index`, `log_index` | `token_transfers.*` | exact |
| `token_name`, `token_symbol`, `token_decimals` | join [Token Metadata](/data-feeds/templates/token/token-metadata) | exact |
| `token_logo`, `possible_spam`, `verified_contract`, `security_score` | None | add yourself |
| `from/to_address_label`, `*_entity`, `*_entity_logo` | None | add yourself |
Neither endpoint returned USD values (a transfer carries no price), so every mapped value is exact from the chain, and the feed adds two fields the API omitted: `transfer_type` and `initiated_by`.
### `GET /erc20/{address}/transfers`: transfers by token
Every transfer of one token becomes a plain by-token read of `token_transfers`, the table's primary sort, so it's a contiguous range scan:
```sql theme={null}
SELECT t.*, t.amount / power(10, m.decimals) AS value_decimal
FROM token_transfers t
LEFT JOIN token_metadata m ON m.token_address = t.token_address
WHERE t.token_address = lower('0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48')
ORDER BY t.block_number DESC, t.log_index DESC
LIMIT 100;
```
* The endpoint's `from_date` / `to_date`, `from_block` / `to_block`, and `order` params are plain `WHERE` / `ORDER BY` clauses; no fixed page size.
* High-volume tokens have enormous histories: keyset-paginate on `(block_number, log_index)`, not `OFFSET`.
* For a token's *complete* history, backfill from its deploy block (`historical` or `hybrid` mode); `realtime` alone only captures new transfers.
### `GET /{address}/erc20/transfers`: transfers by wallet
A wallet's transfers are the rows where it appears on **either side**; the template indexes both `from_address` and `to_address`, so it's one query:
```sql theme={null}
SELECT t.*,
t.amount / power(10, m.decimals) AS value_decimal,
CASE WHEN t.from_address = lower('0xwallet') THEN 'send' ELSE 'receive' END AS direction
FROM token_transfers t
LEFT JOIN token_metadata m ON m.token_address = t.token_address
WHERE (t.from_address = lower('0xwallet') OR t.to_address = lower('0xwallet'))
ORDER BY t.block_number DESC, t.log_index DESC
LIMIT 100;
```
* In each row the `token_address` is the token, not the wallet; derive direction by comparing the wallet to `from_address` / `to_address`, as above.
* The endpoint's `contract_addresses` filter becomes `AND t.token_address = ANY($tokens)`; block/date windows and `order` map the same way as by-token.
* On ClickHouse the by-wallet read is served by the `bloom_filter` skip indexes on `from_address` / `to_address` (see [Example reads](#example-reads)) rather than a second sort key.
### Related
> [card] [Token Holders](/data-feeds/templates/token/token-holders)
>
> The balance roll-up these transfers feed: all non-zero holders of a token.
> [card] [Accounting & Tax](/data-feeds/use-cases/accounting)
>
> Per-asset transfer ledgers for reconciliation, valued via Token Prices.
# Native Balances
Source: https://docs.moralis.com/data-feeds/templates/wallet/native-balances
Sync each wallet's current native-asset (ETH/MATIC/…) balance into your own database, kept current from per-block onchain data. Mirrors the Moralis GET /{address}/balance and GET /wallets/balances endpoints.
### Question it answers
> "What is wallet **0x…**'s current native-asset (ETH / MATIC / …) balance?"
Mirrors Moralis `GET /{address}/balance` and `GET /wallets/balances`. It is the native-asset analog of [Token Balances by Wallet](/data-feeds/templates/wallet/token-balances-by-wallet): each `nativeTransfers` event carries the absolute post-transfer native balance for both legs, so the latest observation per `(chain_id, wallet_address)` is the current balance, with no replaying of deltas.
### What you get
The template lands **one row per balance observation**: each native transfer is unpivoted into two observations (the `from` leg and the `to` leg), each carrying that wallet's absolute native balance immediately after the transfer. There is **no `token_address` and no `token_id`**, because the native asset is implied by the chain.
| Column | Description |
| - | - |
| `wallet_address` | The wallet whose post-transfer balance this row records |
| `balance` | Absolute native balance after the transfer (raw `uint256`, in wei) |
| `leg` | `from` or `to`: which side of the transfer produced this observation |
| `block_number` | Block the transfer landed in |
| `native_seq` | 1-based position of the transfer within the block's `nativeTransfers` array (the recency tiebreaker) |
| `transaction_index` | Informational only (not unique per native transfer) |
| `block_hash`, `event_ts` | Block hash and block time |
| `vendor_event_id` | Stable per-observation identity |
Current balance is **latest-wins**: the most recent observation by `(block_number, native_seq)` per wallet is the live balance.
### Source
The transform reads one per-block array and unpivots it:
`nativeTransfers`
Each transfer becomes two observations: `(fromAddress, fromPostBalance)` and `(toAddress, toPostBalance)`. The zero address and empty post-balances are dropped, and `toAddress` (nullable on block-reward / fee-burn legs) is coalesced before those filters apply.
### Destination
| Destination | Table | Read pattern |
| - | - | - |
| **ClickHouse** (first-class) | `fact_native_balances` | Prefix scan on `(chain_id, wallet_address, block_number, native_seq)`; current balance via `argMax` over `FINAL` |
| **Postgres** | `native_balances` (materialized view over `native_balance_observations`) | Partial index `(wallet_address) WHERE balance > 0` |
| **MySQL** | `native_balances` (trigger-maintained from `native_balance_observations`) | PK `(wallet_address)` |
ClickHouse uses the collapsing log-table pattern (see the [templates overview](/data-feeds/templates/overview#destinations)) so chain reorganizations self-correct. The fact table's sort key is wallet-first, so a wallet's observations are a contiguous range read and `argMax` picks the live balance. Postgres collapses observations into a current-balance materialized view; MySQL keeps a trigger-maintained state table.
### Full schema
Below is the complete read table this template produces: observations keyed by wallet. Keep the columns you need and drop the rest (see [Schema & flexibility](/data-feeds/templates/overview#schema--flexibility)). The raw `balance` is a `uint256` in wei and is stored as text (it exceeds numeric precision); divide by `10^18` (the native decimals) in your app to read whole units.
> [accordion] ClickHouse, fact\_native\_balances
>
> ```sql theme={null}
> CREATE TABLE recipe_native_balances.fact_native_balances
> (
> vendor_event_id String,
> ingested_at DateTime64(3),
> chain_id UInt32,
> block_hash String,
> block_number UInt64,
> transaction_index UInt32, -- informational only (not unique per native transfer)
> native_seq UInt32, -- 1-based in-block ordinal; recency tiebreaker
> event_ts DateTime64(3),
> wallet_address String,
> balance String, -- absolute post-transfer native balance, raw uint256 (wei)
> leg LowCardinality(String), -- from | to
> sign Int8
> )
> ENGINE = ReplicatedCollapsingMergeTree(
> '/clickhouse/tables/{database}/fact_native_balances', '{replica}', sign)
> PARTITION BY (chain_id, toYYYYMM(event_ts))
> ORDER BY (chain_id, wallet_address, block_number, native_seq, vendor_event_id, leg);
> ```
>
> The `sign` column drives reorg collapsing; read with `FINAL` + `argMax`, never a bare `WHERE sign = 1`. A single-node setup can use `CollapsingMergeTree(sign)` without the replication path.
> [accordion] Postgres, native\_balances
>
> ```sql theme={null}
> -- Observations (sink target).
> CREATE TABLE public.native_balance_observations (
> position BIGINT NOT NULL, -- block-level backfill cursor
> transaction_index BIGINT NOT NULL, -- informational only
> native_seq BIGINT NOT NULL, -- 1-based in-block ordinal; recency tiebreaker
> block_number BIGINT NOT NULL,
> block_timestamp BIGINT NOT NULL, -- unix seconds
> wallet_address TEXT NOT NULL,
> balance NUMERIC(76, 0) NOT NULL, -- absolute native balance (wei)
> leg TEXT NOT NULL, -- from | to
> vendor_event_id TEXT NOT NULL
> );
>
> -- Recency index for the DISTINCT ON; leads with the DISTINCT ON key so
> -- REFRESH MATERIALIZED VIEW CONCURRENTLY avoids a sort.
> CREATE INDEX nbo_wallet_recency_idx
> ON public.native_balance_observations
> (wallet_address, block_number DESC, native_seq DESC);
>
> -- Current-balance materialized view: latest observation per wallet.
> CREATE MATERIALIZED VIEW public.native_balances AS
> SELECT DISTINCT ON (wallet_address)
> wallet_address, balance, block_number, native_seq, transaction_index, block_timestamp
> FROM public.native_balance_observations
> ORDER BY wallet_address, block_number DESC, native_seq DESC;
>
> CREATE UNIQUE INDEX native_balances_pk ON public.native_balances (wallet_address);
>
> -- Active (non-zero) native balances — this template's primary access path.
> CREATE INDEX native_balances_active_idx
> ON public.native_balances (wallet_address) WHERE balance > 0;
> -- Cleanup index for zeroed wallets.
> CREATE INDEX native_balances_zero_cleanup_idx
> ON public.native_balances (wallet_address) WHERE balance = 0;
> ```
>
> MySQL is the same shape with `DECIMAL(65,0)` for `balance` and a trigger-maintained `native_balances` state table (PK `wallet_address`, plus a `DELETE … WHERE balance = 0` cleanup). `position` is the block-level cursor used during backfill. Refresh the Postgres view on a schedule: `REFRESH MATERIALIZED VIEW CONCURRENTLY native_balances;`.
### Example reads
Current native balance for a wallet (ClickHouse; `argMax` picks the latest observation):
```sql theme={null}
SELECT argMax(balance, (block_number, native_seq)) AS current_balance
FROM recipe_native_balances.fact_native_balances FINAL
WHERE chain_id = 1 AND wallet_address = lower('0x...')
GROUP BY wallet_address
HAVING current_balance != '0' AND current_balance != '';
```
All current non-zero native balances (mirrors `GET /wallets/balances`):
```sql theme={null}
SELECT wallet_address,
argMax(balance, (block_number, native_seq)) AS current_balance
FROM recipe_native_balances.fact_native_balances FINAL
WHERE chain_id = 1
GROUP BY wallet_address
HAVING current_balance != '0' AND current_balance != ''
ORDER BY wallet_address;
```
Postgres: current balance for one wallet, after a refresh:
```sql theme={null}
REFRESH MATERIALIZED VIEW CONCURRENTLY native_balances;
SELECT balance FROM public.native_balances
WHERE wallet_address = lower('0x...');
```
### Modes
Shipped defaults: **ClickHouse `hybrid`** (backfill → realtime), **Postgres / MySQL `historical`** (one-shot backfill). For live/reorg-safe ingestion, use ClickHouse; see the [overview](/data-feeds/templates/overview#modes).
> [!NOTE]
>
> The backfill cursor (`position`) is block-level, so realtime/hybrid on Postgres / MySQL is constrained by their single-column `UNIQUE` requirement. Run realtime/hybrid on ClickHouse; the Postgres / MySQL configs target `historical` backfill.
### Multichain
The template is chain-parametrized via the `chain` setting: point it at any supported EVM chain or Solana. On Solana, the `vendor_event_id` already folds in `(transactionIndex, fromAddress, toAddress, amount, 'native')`, so observations stay row-unique even where Solana repeats indices within a transaction. The balance surface it produces is identical in shape.
### Recency: why `native_seq`, not `log_index`
`nativeTransfers` carry **no `logIndex`**, and `transactionIndex` is **not unique** per transfer (a single transaction with several internal native movements reuses it). "Which post-balance is current" is therefore tiebroken by **`native_seq`**, the 1-based position of each transfer within the block's `nativeTransfers` array. It is a stable block-global ordinal emitted in canonical order and computed once in the shared transform, so ClickHouse `argMax`, Postgres `DISTINCT ON`, and the MySQL trigger all converge on the same current balance per wallet.
### Fidelity gaps
* **No USD value.** Moralis `GET /{address}/balance` can return a USD-valued balance; that needs the native-asset/USD price at the block, which is not carried on `nativeTransfers`. Join against a native-price source (e.g. the wrapped-native pair from a [Token Prices](/data-feeds/templates/token/token-prices) sync) to add it.
* **Raw wei, no decimals scaling.** `balance` is the raw `uint256` in wei; divide by `10^18` in your app to read whole native units.
## Migrating from the REST API
```
GET /:address/balance
```
This template replaces the endpoint on its own: the latest observation per wallet **is** the response's `balance`, exact and straight from the chain, with no other template required. `GET /wallets/balances` is the same read across many wallets.
Two workflow changes: you query your own table instead of calling an endpoint, and you must **backfill history first**: a wallet only has a row once it appears in a native transfer within your indexed range, so run the template `historical` or `hybrid` from an early block (see [History & backfill](/data-feeds/concepts/history-and-backfill)). Set up the sink via the [quickstart](/data-feeds/migration/quickstart), then read the current balance as shown in [Example reads](#example-reads) above.
**Field mapping**
| `/:address/balance` | Data Feeds | Fidelity |
| - | - | - |
| `balance` (raw wei) | `native_balances.balance` | exact |
| `balance_formatted` | derive: `balance / 1e18` | exact |
**Good to know**
* **Exact and single-valued.** Nothing off-chain and nothing to price here.
* **Raw wei.** Divide by `10^18` in your app for whole native units.
* **USD value is not included.** Multiply by the native asset's price, e.g. the wrapped-native pair from a [Token Prices](/data-feeds/templates/token/token-prices) sync.
* **Freshness.** Postgres / MySQL configs target one-shot `historical` state; use ClickHouse for realtime / `hybrid`.
### Related
> [card] [Token Balances by Wallet](/data-feeds/templates/wallet/token-balances-by-wallet)
>
> The ERC-20 sibling: every token a wallet holds, with balance.
> [card] [Portfolio Tracking](/data-feeds/use-cases/portfolio-tracking)
>
> Native balances are the base-asset leg of a wallet's portfolio.
# NFTs by Wallet
Source: https://docs.moralis.com/data-feeds/templates/wallet/nfts-by-wallet
Sync every NFT a wallet currently holds (collection, token ID, contract type, and balance) as a continuously updated holdings table in your own database. Mirrors the Moralis GET /{address}/nft endpoint.
### Question it answers
> "Give me every NFT wallet **0x…** currently holds. Each row is a `(collection, token_id)` it owns, with the ERC-721/ERC-1155 contract type and current balance."
Mirrors Moralis `GET /{address}/nft`. It's the NFT-keyed sibling of [Token Balances by Wallet](/data-feeds/templates/wallet/token-balances-by-wallet): the same observation/latest-wins pattern, but sourced from NFT transfers and keyed on `(wallet, token_address, token_id)` instead of `(wallet, token_address)`.
### What you get
The template lands **NFT holding observations**, then the current holding is the latest non-zero observation per `(wallet, token_address, token_id)`. Each NFT transfer carries the **absolute post-transfer holdings** of each side (`from`/`to`), so the template never has to sum a running balance; the latest observation *is* the balance.
| Column | Description |
| - | - |
| `wallet_address` | The holder (the `from` or `to` side of a transfer) |
| `token_address` | The NFT contract (collection) |
| `token_id` | The NFT identifier, a `uint256`, stored as text (it exceeds numeric precision) |
| `contract_type` | `ERC721` or `ERC1155` discriminator (from the transfer's token type) |
| `balance` | Absolute post-transfer holding of this `token_id` for this wallet (`1`/`0` for ERC-721, a count for ERC-1155) |
| `block_number`, `log_index` | Ordering tuple, the latest pair wins as the current holding |
| `event_ts` / `block_timestamp` | Block time |
The EVM zero address (`0x0000…0000`) is a mint/burn counterparty, not a holder, so it's excluded. Observations with an empty post-balance string are filtered so the balance column never receives `''`.
### Source
The transform reads one per-block array and unpivots each transfer into two per-wallet observations:
`nftTokenTransfers`
Each transfer becomes `(from_address, from_post_balance)` and `(to_address, to_post_balance)`. `from_post_balance` / `to_post_balance` are the absolute post-transfer holdings of that wallet for the given `(token_address, token_id)`, so the latest observation with a non-zero balance is a current holding.
### Destination
| Destination | Table | Read pattern |
| - | - | - |
| **ClickHouse** (first-class) | `fact_wallet_nfts` | Prefix scan on `(chain_id, wallet_address, token_address, token_id, …)`; current holding via `argMax` over `FINAL` |
| **Postgres** | `wallet_nfts` (materialized view over `wallet_nft_observations`) | Partial index `(wallet_address, token_address, token_id) WHERE balance > 0` |
| **MySQL** | `wallet_nfts` | PK `(wallet_address, token_address, token_id)` with zeroed positions cleaned up |
ClickHouse uses the collapsing log-table pattern (see the [templates overview](/data-feeds/templates/overview#destinations)) so chain reorganizations self-correct. The fact table's sort key is wallet-first, so a wallet's full holdings set is a contiguous range read; `argMax` over `(block_number, log_index)` resolves the current balance per id. On Postgres/MySQL the current-holding table is derived by keeping the latest observation per `(wallet, token_address, token_id)`.
### Full schema
Below is the complete read table this template produces. It's a starting point, keep the columns you need and drop the rest (see [Schema & flexibility](/data-feeds/templates/overview#schema--flexibility)). `token_id` is a `uint256` identifier stored as text (never numeric, ERC-1155/721 ids exceed any practical numeric precision), and `balance` is the absolute post-transfer holding.
> [accordion] ClickHouse, fact\_wallet\_nfts
>
> ```sql theme={null}
> CREATE TABLE recipe_wallet_nfts.fact_wallet_nfts
> (
> vendor_event_id String,
> ingested_at DateTime64(3),
> chain_id UInt32,
> block_hash String,
> block_number UInt64,
> log_index UInt32,
> event_ts DateTime64(3),
> token_address String,
> token_id String, -- uint256 id → String, not numeric
> contract_type LowCardinality(String), -- ERC721 | ERC1155
> wallet_address String,
> balance String, -- absolute post-transfer holding
> leg LowCardinality(String), -- from | to
> sign Int8
> )
> ENGINE = ReplicatedCollapsingMergeTree(
> '/clickhouse/tables/{database}/fact_wallet_nfts', '{replica}', sign)
> PARTITION BY (chain_id, toYYYYMM(event_ts))
> ORDER BY (chain_id, wallet_address, token_address, token_id, block_number, log_index, vendor_event_id, leg);
> ```
>
> The `sign` column drives reorg collapsing, read with `FINAL` then `argMax`, or a sign-aware aggregate, never a bare `WHERE sign = 1`. A single-node setup can use `CollapsingMergeTree(sign)` without the replication path.
> [accordion] Postgres, wallet\_nfts
>
> ```sql theme={null}
> -- 1. Observations (sink target). Latest per key wins as the current holding.
> CREATE TABLE public.wallet_nft_observations (
> position BIGINT NOT NULL,
> log_index BIGINT NOT NULL,
> block_number BIGINT NOT NULL,
> block_timestamp BIGINT NOT NULL, -- unix seconds
> token_address TEXT NOT NULL,
> token_id TEXT NOT NULL, -- uint256 id → TEXT, not numeric
> contract_type TEXT NOT NULL, -- ERC721 | ERC1155
> wallet_address TEXT NOT NULL,
> balance NUMERIC(76, 0) NOT NULL, -- absolute post-balance of the id
> leg TEXT NOT NULL,
> vendor_event_id TEXT NOT NULL
> );
>
> -- Recency index: leads with the DISTINCT ON keys so REFRESH avoids a sort.
> CREATE INDEX wno_wallet_token_id_recency_idx
> ON public.wallet_nft_observations
> (wallet_address, token_address, token_id, block_number DESC, log_index DESC);
>
> -- 2. Current-holding view: latest observation per (wallet, token, token_id).
> CREATE MATERIALIZED VIEW public.wallet_nfts AS
> SELECT DISTINCT ON (wallet_address, token_address, token_id)
> wallet_address, token_address, token_id, contract_type,
> balance, block_number, log_index, block_timestamp
> FROM public.wallet_nft_observations
> ORDER BY wallet_address, token_address, token_id, block_number DESC, log_index DESC;
>
> CREATE UNIQUE INDEX wallet_nfts_pk
> ON public.wallet_nfts (wallet_address, token_address, token_id);
>
> -- Primary access path: NFTs currently held by a wallet.
> CREATE INDEX wallet_nfts_active_idx
> ON public.wallet_nfts (wallet_address, token_address, token_id)
> WHERE balance > 0;
>
> -- Sibling access path: all current holders of a given NFT id.
> CREATE INDEX wallet_nfts_by_token_active_idx
> ON public.wallet_nfts (token_address, token_id, wallet_address)
> WHERE balance > 0;
>
> -- Cleanup index for zeroed (no-longer-held) positions.
> CREATE INDEX wallet_nfts_zero_cleanup_idx
> ON public.wallet_nfts (wallet_address, token_address, token_id)
> WHERE balance = 0;
> ```
>
> Refresh the current-holding view on a schedule with `REFRESH MATERIALIZED VIEW CONCURRENTLY wallet_nfts;`. MySQL is the same shape with a trigger-maintained `wallet_nfts` table and a `DELETE … WHERE balance = 0` cleanup. `position` is the block-level cursor used during backfill.
### Example reads
Every NFT a wallet currently holds, latest non-zero post-balance per id (ClickHouse):
```sql theme={null}
SELECT token_address, token_id, contract_type,
argMax(balance, (block_number, log_index)) AS amount
FROM recipe_wallet_nfts.fact_wallet_nfts FINAL
WHERE chain_id = 1 AND wallet_address = lower('0x...')
GROUP BY token_address, token_id, contract_type
HAVING amount != '0' AND amount != ''
ORDER BY token_address, token_id;
```
The same holdings read on Postgres (after refreshing the view):
```sql theme={null}
REFRESH MATERIALIZED VIEW CONCURRENTLY wallet_nfts;
SELECT token_address, token_id, contract_type, balance
FROM public.wallet_nfts
WHERE wallet_address = lower('0x...') AND balance > 0
ORDER BY token_address, token_id;
```
### Modes
Shipped defaults: **ClickHouse `hybrid`** (backfill → realtime), **Postgres / MySQL `historical`** (one-shot backfill). For live/reorg-safe ingestion, use ClickHouse, see the [overview](/data-feeds/templates/overview#modes).
> [!NOTE]
>
> `position` is block-level, so realtime/hybrid on Postgres/MySQL is constrained by their single-column `UNIQUE` requirement. Run realtime/hybrid on **ClickHouse**; the Postgres/MySQL configs target `historical` backfill.
### Multichain
The template is chain-parametrized via the `chain` setting, point it at any supported EVM chain or Solana. NFTs on Solana are emitted on `nftTokenTransfers` too; the `vendor_event_id` identity already includes `(from, to, token, tokenId, amount)` so each row stays unique under Solana's repeated log indices. The holdings table it produces is identical in shape.
### Fidelity gaps
`GET /{address}/nft` returns collection and metadata fields that have **no source in this per-block stream**, so they are intentionally not populated:
* `name`, `symbol`, NFT contract name/symbol. Enrich downstream from a contract-metadata table if you need them.
* `token_uri`, `metadata`, `normalized_metadata`, per-token metadata fetched from the token URI by a separate indexer; not in block data.
* `owner_of`: the API echoes the queried wallet; here it is the `wallet_address` holding key.
* `block_number_minted`, `minter_address`, `possible_spam`, `verified_collection`, `collection_logo`, `floor_price*`, `rarity*`, enrichment from separate indexers / pricing services, with no per-block source.
Core holding fields, `token_address`, `token_id`, `contract_type`, `balance`, owner (via `wallet_address`), and block coordinates, are fully populated.
## Migrating from the REST API
This template is the landing point for two wallet-NFT REST endpoints. In both cases the onchain holding is exact; the metadata, spam, and pricing layers the API bundled in are separate templates or your own sources.
### GET /:address/nft
```
GET /:address/nft
```
This template replaces it directly: one current row per `(wallet, token_address, token_id)` with a non-zero balance is exactly the holdings list the endpoint returned.
> [!NOTE]
>
> **Not 1:1**, the full response spans two templates. This template supplies the holdings; join [NFT Collection Metadata](/data-feeds/templates/nft/nft-collection-metadata) (`nft_collection_metadata`, keyed by `token_address`) for `name`/`symbol`. Token-level metadata (`token_uri`, `metadata`, media) is resolved off-chain from each token's URI and is not in any per-block feed, you fetch it yourself or layer in a metadata source.
| `/:address/nft` field | Here | Fidelity |
| - | - | - |
| `token_address`, `token_id`, `contract_type` | same columns | exact |
| `amount` | `balance` | exact |
| `owner_of` | `wallet_address` (the query key) | exact |
| `block_number` | `block_number` | exact |
| `name`, `symbol` | `nft_collection_metadata.*` | exact |
| `token_hash` | derive (hash of contract + token\_id) | exact |
| `token_uri`, `metadata`, `normalized_metadata`, `media` | resolve from the token URI | add yourself |
| `rarity_*`, `floor_price*`, `last_sale`, `list_price` | marketplace/rarity data ([NFT Trades](/data-feeds/templates/nft/nft-trades) for realized sales) | add yourself |
| `possible_spam`, `verified_collection`, collection art | your own lists / sources | add yourself |
| `block_number_minted`, `minter_address`, `*_sync` | indexer-derived | add yourself |
The endpoint response, as one query (Postgres table names; keyset pagination on `(token_address, token_id)` replaces the old cursor):
```sql theme={null}
SELECT n.token_address, n.token_id, n.contract_type,
n.balance AS amount, m.name, m.symbol
FROM wallet_nfts n
LEFT JOIN nft_collection_metadata m ON m.token_address = n.token_address
WHERE n.wallet_address = lower('0x...')
AND n.balance > 0
ORDER BY n.token_address, n.token_id
LIMIT 100;
```
Gotchas:
* **Backfill full history.** Holdings are current state, a wallet can still hold an NFT it last moved years ago, so run `historical`/`hybrid` from an early block. Only tracking specific collections? Filter to those `token_addresses` and start from each collection's first block. See [History & backfill](/data-feeds/concepts/history-and-backfill).
* **No fixed spam filter.** The old `exclude_spam` was off-chain curation; it becomes your own `WHERE` against your own lists.
* **ERC-1155 `amount` is a real count**, not always `1`, the `balance` column carries it.
* **Empty `name`/`symbol` is normal** for many ERC-1155 (and some ERC-721) collections; it isn't an error.
### GET /:address/nft/collections
```
GET /:address/nft/collections
```
There is no separate collections dataset, this endpoint is a **`GROUP BY` rollup of this template's holdings table**. If you've built the per-NFT query above, the collection list is one more query over the same tables.
> [!NOTE]
>
> **Not 1:1**, combine this template (holdings to group) with [NFT Collection Metadata](/data-feeds/templates/nft/nft-collection-metadata) for `name`/`symbol`, and optionally [NFT Trades](/data-feeds/templates/nft/nft-trades) if you want `last_sale` from realized onchain sales.
| `/:address/nft/collections` field | Here | Fidelity |
| - | - | - |
| `token_address`, `contract_type` | same columns (grouped) | exact |
| `count` | `count(*)` over held token\_ids | exact |
| `name`, `symbol` | `nft_collection_metadata.*` | exact |
| `last_sale` (sale facts) | `nft_trades` | exact |
| `last_sale` USD values | `nft_trades` + price feed | calculated |
| `possible_spam`, `verified_collection` | your own lists | add yourself |
| `collection_logo`, `collection_banner_image`, `floor_price*` | your own sources | add yourself |
The rollup:
```sql theme={null}
SELECT n.token_address, n.contract_type, m.name, m.symbol,
count(*) AS count -- token_ids held in this collection
FROM wallet_nfts n
LEFT JOIN nft_collection_metadata m ON m.token_address = n.token_address
WHERE n.wallet_address = lower('0x...')
AND n.balance > 0
GROUP BY n.token_address, n.contract_type, m.name, m.symbol
ORDER BY count DESC;
```
Gotchas:
* **ERC-1155 `count`.** `count(*)` counts distinct token\_ids (matches the old endpoint); swap in `sum(balance)` to count units instead, a one-word change.
* **Same full-history requirement** as the per-NFT endpoint: start the backfill late and the rollup silently misses collections.
* **`last_sale` USD is calculated** from real trades plus a price feed, compare with a small tolerance, not an identical figure.
* **Floor price, logo, banner are off-chain**: layer them in from your own sources keyed by `token_address`, or drop them.
### Related
> [card] [Token Balances by Wallet](/data-feeds/templates/wallet/token-balances-by-wallet)
>
> The ERC-20 sibling, same latest-wins pattern, keyed by (wallet, token).
> [card] [NFT Owners by Contract](/data-feeds/templates/nft/nft-owners-by-contract)
>
> The inverse view, all current holders of a collection.
> [card] [Portfolio Tracking](/data-feeds/use-cases/portfolio-tracking)
>
> Wallet holdings across tokens and NFTs in one owned dataset.
> [card] [NFT Marketplace](/data-feeds/use-cases/nft-marketplace)
>
> Per-wallet NFT inventory behind a marketplace.
# Token Approvals
Source: https://docs.moralis.com/data-feeds/templates/wallet/token-approvals
Sync the current ERC-20 allowances a wallet has granted, and to whom, as a continuous, reorg-safe feed into your own database. Mirrors the Moralis GET /wallets/{address}/approvals endpoint.
### Question it answers
> "What ERC-20 allowances has wallet **0x…** granted, and to whom?" Mirrors Moralis `GET /wallets/{address}/approvals`.
Each ERC-20 `Approval(owner, spender, value)` log is one approval event. The **current allowance** for an `(owner, token, spender)` triple is the latest approval by `(block_number, log_index)`, a fresh `approve` overwrites the prior allowance (latest-wins, the same machinery as the balances templates). A revoke is just `approve(spender, 0)`, so it lands as a new event whose value is `'0'`.
### What you get
One row per approval event, keyed by the approving wallet (`owner_address`). The **current** allowance for a triple is the latest event, resolved with `argMax` (ClickHouse) or a latest-wins projection (Postgres / MySQL):
| Column | Description |
| - | - |
| `owner_address` | The approving wallet (the `owner` on the `Approval` log) |
| `spender_address` | The address authorized to spend |
| `token_address` | The ERC-20 token the allowance is for |
| `value` | The raw allowance amount, stored as text (an unlimited approve is `type(uint256).max`, 78 digits) |
| `block_number`, `log_index` | On-chain ordering tuple; the latest pair per triple wins |
| `tx_hash` | Transaction that produced the approval |
| `event_ts` / `block_timestamp` | Block time |
Compare `value` against `'0'` for the revoked / non-revoked distinction; do any arbitrary-precision arithmetic in your application layer.
### Source
The transform reads a single per-block array and lands one row per approval log:
`tokenApprovals`
The struct carries `approverAddress` (→ `owner_address`), `spenderAddress`, `tokenAddress`, and `amount` (→ `value`); `block_number` and `block_timestamp` come from the block envelope.
### Destination
| Destination | Table | Read pattern |
| - | - | - |
| **ClickHouse** (first-class) | `fact_token_approvals` | Prefix scan on `(chain_id, owner_address, token_address, spender_address, …)`; current allowance via `argMax(value, (block_number, log_index))` over `FINAL` |
| **Postgres** | `token_approval_events` + `token_allowances` materialized view | Partial index `(owner_address, token_address, spender_address) WHERE value <> '0'` |
| **MySQL** | `token_approval_events` + maintained `token_allowances` state table | PK `(owner_address, token_address, spender_address)` with `value = '0'` cleanup |
ClickHouse uses the collapsing log-table pattern (see the [templates overview](/data-feeds/templates/overview#destinations)) so chain reorganizations self-correct. The fact table's sort key is owner-first, so "all allowances granted by owner Y" is a contiguous range read. Postgres keeps a flat event table plus a `token_allowances` materialized view (latest approve per triple, refreshed on a schedule); MySQL keeps the same event table plus a latest-wins state table.
### Full schema
Below is the complete read table this template produces, keep the columns you need and drop the rest (see [Schema & flexibility](/data-feeds/templates/overview#schema--flexibility)). The raw allowance `value` is stored as text on all three destinations: an unlimited approve uses `type(uint256).max` (78 digits), which overflows Postgres `NUMERIC(76,0)` and MySQL `DECIMAL(65,0)`.
> [accordion] ClickHouse, fact\_token\_approvals
>
> ```sql theme={null}
> CREATE TABLE recipe_token_approvals.fact_token_approvals
> (
> vendor_event_id String,
> ingested_at DateTime64(3),
> chain_id UInt32,
> block_hash String,
> block_number UInt64,
> log_index UInt32,
> event_ts DateTime64(3),
> tx_hash String,
> token_address String,
> owner_address String,
> spender_address String,
> value String, -- raw allowance; unlimited approve = uint256 max (78 digits)
> sign Int8
> )
> ENGINE = ReplicatedCollapsingMergeTree(
> '/clickhouse/tables/{database}/fact_token_approvals', '{replica}', sign)
> PARTITION BY (chain_id, toYYYYMM(event_ts))
> ORDER BY (chain_id, owner_address, token_address, spender_address, block_number, log_index, vendor_event_id);
> ```
>
> The `sign` column drives reorg collapsing. Read the current allowance with `argMax(value, (block_number, log_index))` over `FINAL`, never a bare `WHERE sign = 1`. A single-node setup can use `CollapsingMergeTree(sign)` without the replication path.
> [accordion] Postgres, token\_approval\_events + token\_allowances
>
> ```sql theme={null}
> -- 1. Approval events (sink target) — one row per Approval log.
> CREATE TABLE public.token_approval_events (
> position BIGINT NOT NULL,
> log_index BIGINT NOT NULL,
> block_number BIGINT NOT NULL,
> block_timestamp BIGINT NOT NULL, -- unix seconds
> tx_hash TEXT NOT NULL,
> token_address TEXT NOT NULL,
> owner_address TEXT NOT NULL,
> spender_address TEXT NOT NULL,
> value TEXT NOT NULL, -- allowance; max-uint = 78 digits
> vendor_event_id TEXT NOT NULL
> );
>
> -- Recency index leading with the DISTINCT ON keys so REFRESH avoids a sort.
> CREATE INDEX tae_owner_token_spender_recency_idx
> ON public.token_approval_events
> (owner_address, token_address, spender_address, block_number DESC, log_index DESC);
>
> -- 2. Current-allowance materialized view: latest approve per (owner, token, spender).
> CREATE MATERIALIZED VIEW public.token_allowances AS
> SELECT DISTINCT ON (owner_address, token_address, spender_address)
> owner_address, token_address, spender_address,
> value, tx_hash, block_number, log_index, block_timestamp
> FROM public.token_approval_events
> ORDER BY owner_address, token_address, spender_address, block_number DESC, log_index DESC;
>
> CREATE UNIQUE INDEX token_allowances_pk
> ON public.token_allowances (owner_address, token_address, spender_address);
>
> -- Primary access path: all live allowances granted by an owner.
> CREATE INDEX token_allowances_by_owner_active_idx
> ON public.token_allowances (owner_address, token_address, spender_address)
> WHERE value <> '0';
>
> -- Sibling access path: who can spend a given token on behalf of others.
> CREATE INDEX token_allowances_by_spender_idx
> ON public.token_allowances (spender_address, token_address);
> ```
>
> MySQL is the same shape with `VARCHAR(80)` for `value` and a trigger-maintained `token_allowances` state table doing the latest-wins upsert. `position` is the block-level cursor used during backfill.
### Example reads
All current allowances granted by an owner, latest approve per token + spender, dropping revoked (`'0'`) rows (ClickHouse):
```sql theme={null}
SELECT token_address,
spender_address,
argMax(value, (block_number, log_index)) AS current_allowance
FROM recipe_token_approvals.fact_token_approvals FINAL
WHERE chain_id = 1 AND owner_address = lower('0x...')
GROUP BY token_address, spender_address
HAVING current_allowance != '0' AND current_allowance != ''
ORDER BY token_address, spender_address;
```
Postgres, refresh the projection, then read the live allowances:
```sql theme={null}
REFRESH MATERIALIZED VIEW CONCURRENTLY token_allowances;
SELECT token_address, spender_address, value
FROM public.token_allowances
WHERE owner_address = lower('0x...') AND value <> '0'
ORDER BY token_address, spender_address;
```
### Modes
Shipped defaults: **ClickHouse `hybrid`** (backfill → realtime), **Postgres / MySQL `historical`** (one-shot backfill). For live/reorg-safe ingestion, use ClickHouse, see the [overview](/data-feeds/templates/overview#modes).
> [!NOTE]
>
> Realtime / hybrid on Postgres / MySQL is constrained: the block-level cursor means array-expanded approval rows share a `position`, which collides with the single-column `UNIQUE` requirement. Run realtime / hybrid on **ClickHouse**, which corrects reorgs per-block via the collapsing log table; the Postgres / MySQL configs target `historical` backfill.
### EVM only
`tokenApprovals` is an EVM ERC-20 `Approval` log array. SPL token delegation on Solana is a different model and is not emitted into this array.
### Fidelity gaps
On-chain primitives, owner, spender, token, raw allowance value, block, and tx hash, are fully covered. Response fields of `GET /wallets/{address}/approvals` with no on-chain source are intentionally omitted:
* `value_formatted`: needs token `decimals`; scale `value` by `10^token_decimals` using a Token Metadata sync.
* `token.name` / `token.symbol` / `token.logo` / `token.decimals`, token metadata, not in `tokenApprovals`.
* `spender.entity` / `spender.entity_logo` / `spender.address_label`, off-chain spender labelling.
## Migrating from the REST API
```
GET /wallets/:address/approvals
```
The **active allowance set**, allowance value, spender, token address, block and tx, comes from this template directly: the latest approve per `(owner, token, spender)` wins, and revokes (approve-to-zero) drop out. The rest of the endpoint's response (token metadata, wallet balance, USD figures) does not live on the `Approval` log, you rebuild it with joins.
> [!NOTE]
>
> **This endpoint needs four templates.** Data Feeds are not 1:1 endpoint replicas, to reproduce the full response, run these together and join their tables yourself (query below):
>
> * **Token Approvals** (this page), allowance, spender, token address, block / tx
> * [Token Metadata](/data-feeds/templates/token/token-metadata): `token.name`, `token.symbol`, `decimals` for `value_formatted`
> * [Token Balances by Wallet](/data-feeds/templates/wallet/token-balances-by-wallet): the wallet's current balance of each approved token
> * [Token Prices](/data-feeds/templates/token/token-prices): `usd_price`, and `usd_at_risk` derived from it
**Field mapping**, **exact** comes from the chain, **calculated** is derived from real onchain trades (very close; compare with a small tolerance), **add yourself** is an off-chain signal:
| `/wallets/:address/approvals` | Data Feeds | Fidelity |
| - | - | - |
| `value` (allowance) | `token_allowances.value` | exact |
| `value_formatted` | derive: `value / 10^decimals` | exact |
| `block_number`, `block_timestamp`, `transaction_hash` | `token_allowances.*` | exact |
| `spender.address` | `token_allowances.spender_address` | exact |
| `token.address` | `token_allowances.token_address` | exact |
| `token.name`, `token.symbol` | token metadata sync | exact |
| `token.current_balance(_formatted)` | token balances sync | exact |
| `token.usd_price` | latest price update | calculated |
| `token.usd_at_risk` | derive: `min(allowance, balance) × price` | calculated |
| `token.logo`, `possible_spam`, `verified_contract`, `address_label` | add yourself | off-chain |
| `spender.address_label`, `entity`, `entity_logo` | add yourself | off-chain |
**The join** (Postgres; table names follow each template's default schema), one view that reproduces the response, with `usd_at_risk` computed the realistic way (`min(allowance, balance) × price`, a spender can't take more than the wallet holds):
```sql theme={null}
CREATE VIEW wallet_approvals AS
SELECT
a.owner_address AS wallet_address,
a.token_address,
a.spender_address,
m.name, m.symbol,
a.value AS allowance,
a.value / power(10, m.decimals) AS value_formatted,
b.balance AS current_balance,
p.usd_price,
least(a.value, coalesce(b.balance, 0))
/ power(10, m.decimals) * p.usd_price AS usd_at_risk,
a.block_number, a.block_timestamp, a.tx_hash
FROM token_allowances a
LEFT JOIN token_metadata m ON m.token_address = a.token_address
LEFT JOIN token_balances b ON b.token_address = a.token_address
AND b.wallet_address = a.owner_address
LEFT JOIN LATERAL (
SELECT usd_price FROM token_price_updates
WHERE token_address = a.token_address ORDER BY block_number DESC LIMIT 1
) p ON true;
```
Query it per wallet with `ORDER BY usd_at_risk DESC NULLS LAST` so the riskiest approvals surface first.
**Good to know**
* **Backfill full history first.** The latest approve for a triple can sit at any past block, run `historical` / `hybrid` from an early block or you'll miss or misstate allowances ([History & backfill](/data-feeds/concepts/history-and-backfill)).
* **Unlimited approvals** show as a max-uint `value` (78 digits, stored as text). Lead with `usd_at_risk`, it caps the scary figure to what the wallet actually holds.
* **Revokes disappear automatically** (an approve to zero), so you always see the live, active set.
* **Compare USD figures with a tolerance**: prices come from real DEX trades, not the REST API's pricing.
* **Real-time is the strength here.** Stream the `tokenApprovals` feed (Kafka / AMQP / SQS) to alert the moment a risky allowance is granted, instead of polling.
### Related
> [card] [Wallet History](/data-feeds/templates/wallet/wallet-history)
>
> The full chronological event feed, approvals included alongside transfers and swaps.
> [card] [Compliance & AML](/data-feeds/use-cases/compliance-aml)
>
> Outstanding allowances are a core risk surface for wallet monitoring.
# Token Balances by Wallet
Source: https://docs.moralis.com/data-feeds/templates/wallet/token-balances-by-wallet
Sync every ERC-20 token a wallet holds, with its current non-zero balance, into your own database: a portfolio lookup that's a single prefix scan.
### Question it answers
> "Give me every token wallet **0x…** holds, with its current non-zero balance."
This is the by-wallet portfolio read. It's the same ingest as Token Balances by Token, sorted the other way: this template keys **wallet-first** so one wallet's full token holdings are a contiguous range read, while the sibling keys token-first to list a token's holders.
### What you get
The template lands **one balance observation per wallet, per transfer leg**. Each `token_transfer` carries absolute post-transfer balances (`from_post_balance` / `to_post_balance`), so every transfer becomes two observations: one for the sender, one for the receiver. The **latest observation per `(wallet, token)`** is the current balance ("latest-wins").
| Column | Description |
| - | - |
| `chain_id` | Chain identifier |
| `wallet_address` | The holder (leading sort key) |
| `token_address` | The ERC-20 contract |
| `balance` | Absolute post-transfer balance for this wallet, raw `uint256` (the latest per `(wallet, token)` is the current balance) |
| `leg` | `from` or `to`: which side of the transfer produced this observation |
| `block_number`, `log_index` | On-chain ordering tuple; picks the latest observation |
| `event_ts` | Block time |
| `vendor_event_id` | Stable per-observation identity (keeps rows unique) |
The zero address is excluded, so a token's balance going to `0` on a full transfer-out is a real observation you read as the current state, not a missing row.
### Source
The transform reads one per-block array, `tokenTransfers`, and unpivots each transfer into two per-wallet observations: `(from_address, from_post_balance)` and `(to_address, to_post_balance)`. Because the source supplies **absolute** post-balances on each transfer, there's no running-sum reconstruction: the latest observation is the balance.
### Destination
| Destination | Table | By-wallet access |
| - | - | - |
| **ClickHouse** (first-class) | `fact_balances_by_wallet` | Prefix scan on `(chain_id, wallet_address, token_address, …)`; current balance via `argMax` over `FINAL` |
| **Postgres** | `token_balances` (materialized view over `token_balance_observations`) | Partial index `(wallet_address, token_address) WHERE balance > 0` |
| **MySQL** | `token_balances` (trigger-maintained over `token_balance_observations`) | PK `(wallet_address, token_address)` + `DELETE … WHERE balance = 0` cleanup |
ClickHouse uses the collapsing log-table pattern (see the [templates overview](/data-feeds/templates/overview#destinations)) so chain reorganizations self-correct. The fact table's sort key is wallet-first, so a wallet's holdings are a contiguous range read; you collapse to the current balance per token with `argMax` over `FINAL`.
### Full schema
Below is the complete read table this template produces. It's a starting point: keep the columns you need and drop the rest (see [Schema & flexibility](/data-feeds/templates/overview#schema--flexibility)). Raw `uint256` balances are stored as text (ClickHouse) or `NUMERIC(76, 0)` (Postgres) so they never overflow.
> [accordion] ClickHouse, fact\_balances\_by\_wallet
>
> ```sql theme={null}
> CREATE TABLE recipe_token_balances_by_wallet.fact_balances_by_wallet
> (
> vendor_event_id String,
> ingested_at DateTime64(3),
> chain_id UInt32,
> block_hash String,
> block_number UInt64,
> log_index UInt32,
> event_ts DateTime64(3),
> token_address String,
> wallet_address String,
> balance String, -- absolute post-transfer balance, raw uint256
> leg LowCardinality(String), -- from | to
> sign Int8
> )
> ENGINE = ReplicatedCollapsingMergeTree(
> '/clickhouse/tables/{database}/fact_balances_by_wallet', '{replica}', sign)
> PARTITION BY (chain_id, toYYYYMM(event_ts))
> ORDER BY (chain_id, wallet_address, token_address, block_number, log_index, vendor_event_id, leg);
> ```
>
> The `sign` column drives reorg collapsing; read with `FINAL` then `argMax`, or a sign-aware aggregate, never a bare `WHERE sign = 1`. A single-node setup can use `CollapsingMergeTree(sign)` without the replication path.
> [accordion] Postgres, token\_balances
>
> ```sql theme={null}
> -- 1. Observations (sink target): one row per wallet, per transfer leg.
> CREATE TABLE public.token_balance_observations (
> position BIGINT NOT NULL,
> log_index BIGINT NOT NULL,
> block_number BIGINT NOT NULL,
> block_timestamp BIGINT NOT NULL, -- unix seconds
> token_address TEXT NOT NULL,
> wallet_address TEXT NOT NULL,
> balance NUMERIC(76, 0) NOT NULL,
> leg TEXT NOT NULL,
> vendor_event_id TEXT NOT NULL
> );
>
> -- Recency index leads with the DISTINCT ON keys so the REFRESH avoids a sort.
> CREATE INDEX tbo_token_wallet_recency_idx
> ON public.token_balance_observations
> (token_address, wallet_address, block_number DESC, log_index DESC);
>
> -- 2. Current-balance materialized view: latest observation per (token, wallet).
> CREATE MATERIALIZED VIEW public.token_balances AS
> SELECT DISTINCT ON (token_address, wallet_address)
> token_address,
> wallet_address,
> balance,
> block_number,
> log_index,
> block_timestamp
> FROM public.token_balance_observations
> ORDER BY token_address, wallet_address, block_number DESC, log_index DESC;
>
> CREATE UNIQUE INDEX token_balances_pk
> ON public.token_balances (token_address, wallet_address);
>
> -- This template's primary access path: active balances held by a wallet.
> CREATE INDEX token_balances_by_wallet_active_idx
> ON public.token_balances (wallet_address, token_address)
> WHERE balance > 0;
>
> -- Sibling access path (all non-zero holders of a token).
> CREATE INDEX token_balances_by_token_active_idx
> ON public.token_balances (token_address, wallet_address)
> WHERE balance > 0;
>
> -- Cleanup index for zeroed positions.
> CREATE INDEX token_balances_zero_cleanup_idx
> ON public.token_balances (wallet_address, token_address)
> WHERE balance = 0;
> ```
>
> Refresh the view on a schedule: `REFRESH MATERIALIZED VIEW CONCURRENTLY token_balances;`. MySQL is the same shape with a trigger-maintained `token_balances` table and a `DELETE … WHERE balance = 0` cleanup. `position` is the block-level cursor used during backfill.
### Run it
Everything runs in **your** infrastructure: the sink writes into a database you own and you query it with plain SQL, no API and no per-call limits.
**Prerequisites**
* **Docker** and Docker Compose.
* A **Data Feeds key**, a `cm_live_…` key with `continuum:read` scope (this is *not* your Web3 API key).
> [card] [Sign up for a Data Feeds key](https://admin.moralis.com)
>
> Log in to the Moralis admin panel to create your account and generate a `cm_live_…` key.
**Start the sink**
Generate a **starter pack** for `tokenBalancesByWalletAddress` in the [Moralis Admin Panel](https://admin.moralis.com), pick your chain and destination database, then run it with Docker. The [quickstart](/data-feeds/migration/quickstart) walks through it end to end. Set the backfill window (`MORALIS_HISTORICAL_FROM_BLOCK`) as noted below.
> [!NOTE]
>
> **Backfill full history for complete balances.** A balance is *current state* (the latest transfer-derived observation per `(wallet, token)`), and a wallet can still hold a token it last moved years ago. To return a wallet's *complete* holdings, backfill from an early block (`MORALIS_HISTORICAL_FROM_BLOCK=0`, or a token's deploy block if you scope to one token). A recent-only window like `tip-1000` captures only tokens that moved in that window, so balances would be incomplete. Unlike an event feed, a partial window is **not** correct here. Full-chain backfill on a busy chain is large; plan for it. See [History & backfill](/data-feeds/concepts/history-and-backfill).
Then run the example reads below to confirm rows are landing.
### Example reads
Every token a wallet holds, current non-zero balance only (ClickHouse; `argMax` over `FINAL` picks the latest observation per token):
```sql theme={null}
SELECT token_address,
argMax(balance, (block_number, log_index)) AS current_balance
FROM recipe_token_balances_by_wallet.fact_balances_by_wallet FINAL
WHERE chain_id = 1 AND wallet_address = lower('0x...')
GROUP BY token_address
HAVING current_balance != '0' AND current_balance != ''
ORDER BY token_address;
```
Postgres (after `REFRESH MATERIALIZED VIEW CONCURRENTLY token_balances;`):
```sql theme={null}
SELECT token_address, balance FROM public.token_balances
WHERE wallet_address = lower('0x...') AND balance > 0
ORDER BY balance DESC;
```
MySQL:
```sql theme={null}
SELECT token_address, balance FROM token_balances
WHERE wallet_address = LOWER('0x...') AND balance > 0
ORDER BY balance DESC;
```
### Other ways to consume this data
The sink is the way to get **this pre-shaped table** (`token_balances`), recommended for a portfolio lookup you own. The *same underlying data* is also available as the **raw decoded feed**, if you'd rather derive balances yourself:
* **Your existing message clients**: stream it with **Kafka / AMQP / SQS**.
* **REST / Arrow Flight**: pull the decoded block stream directly.
Those give you the **source array** (`tokenTransfers`, which carries absolute post-transfer balances) to compute balances yourself, not this pre-computed table. All of them read the one data lake into **your** infrastructure. See [What are Data Feeds?](/data-feeds/concepts/what-are-data-feeds).
### Modes
Shipped defaults: **ClickHouse `hybrid`** (backfill → realtime), **Postgres / MySQL `historical`** (one-shot backfill). For live/reorg-safe ingestion, use ClickHouse; see the [overview](/data-feeds/templates/overview#modes).
> [!NOTE]
>
> The backfill cursor (`position`) is block-level, so realtime/hybrid on Postgres / MySQL is constrained by their single-column `UNIQUE` requirement. Run realtime/hybrid on **ClickHouse**; the Postgres / MySQL configs target `historical` backfill.
### Multichain
The template is chain-parametrized: point it at any supported EVM chain or Solana. On Solana, the per-observation identity already folds `(from, to, token, amount)` into `vendor_event_id` so rows stay unique under Solana's repeated `logIndex`; the balances it produces are identical in shape.
### Fidelity gaps
* **Raw balances only.** `balance` is the raw `uint256` post-transfer amount; divide by `10^token_decimals` to read human units. Fold in a decimals lookup from a Token Metadata sync if you need it pre-scaled.
* **No USD value.** This template lands quantities, not dollar value. Join to a Token Prices sync at read time for portfolio valuation.
* **Latest-wins semantics.** A `(wallet, token)` row reflects the most recent transfer-derived post-balance. Direct mints/burns or rebases that emit a transfer are captured; balance changes with no transfer event are not.
## Migrating from the REST API
This template replaces the wallet-balance family of Web3 API endpoints. Data Feeds are **not** 1:1 replicas of those responses: you land the underlying data in your own database and reconstruct the response shape with a view. The subsections below cover each REST endpoint: what replaces it, the field mapping (**exact** = straight from the chain, **calculated** = derived from real DEX trades, very close, **add yourself** = off-chain signal not in the feed), and the gotchas specific to that endpoint.
### GET /wallets/:address/tokens
The enriched balances-plus-prices endpoint. Replaced by this template's `token_balances` table joined with three sibling templates for native balance, token details, and prices.
> [!WARNING]
>
> This endpoint needs **four templates**, not one. Run this template plus [Native Balances](/data-feeds/templates/wallet/native-balances) (`native_balances`), [Token Metadata](/data-feeds/templates/token/token-metadata) (`token_metadata`), and [Token Prices](/data-feeds/templates/token/token-prices) (`token_price_updates`) against the same database, then join them in one view. There is no single pre-joined template; the composition is the supported path.
| `/wallets/:address/tokens` | Data Feeds | Fidelity |
| - | - | - |
| `token_address`, `balance` (raw) | `token_balances.*` | exact |
| `balance_formatted` | derive: `balance / 10^decimals` | exact |
| `name`, `symbol`, `decimals`, `total_supply(_formatted)` | `token_metadata.*` | exact |
| `usd_price` | latest `token_price_updates.usd_price` | calculated |
| `usd_value`, `usd_price_24hr_*`, `portfolio_percentage` | derive from balance × price / price history | calculated |
| `percentage_relative_to_total_supply` | derive: `balance / total_supply` | exact |
| `native_token` + native balance | `native_balances` | exact |
| `logo`, `thumbnail`, `possible_spam`, `verified_contract`, `security_score` | add yourself | off-chain |
The reconstruction view (Postgres; adapt to your destination):
```sql theme={null}
CREATE VIEW wallet_token_balances_price AS
WITH latest_price AS (
SELECT DISTINCT ON (token_address)
token_address, usd_price
FROM token_price_updates
ORDER BY token_address, block_number DESC -- newest price per token
)
SELECT
b.wallet_address,
b.token_address,
m.symbol,
m.name,
m.decimals,
b.balance AS balance_raw,
b.balance / power(10, m.decimals) AS balance_formatted,
p.usd_price,
(b.balance / power(10, m.decimals)) * p.usd_price AS usd_value,
m.total_supply,
b.balance / NULLIF(m.total_supply, 0) AS percentage_relative_to_total_supply
FROM token_balances b
LEFT JOIN token_metadata m ON m.token_address = b.token_address
LEFT JOIN latest_price p ON p.token_address = b.token_address
WHERE b.balance > 0;
```
Finishing touches: `portfolio_percentage` is `usd_value / SUM(usd_value)` per wallet at query time; `UNION` in `native_balances` priced with the native asset's USD mark; derive 24-hour change from the price \~24h ago in `token_price_updates`.
**Gotchas**
* USD values come from real DEX trades: very close to the old endpoint, but compare with a tolerance, not bit-for-bit. A thinly-traded token may not have a price yet.
* No fixed spam filter: you get every token the wallet holds, then apply your own spam/dust rules.
* No wallet-size limit: the old endpoint caps very large wallets; your own dataset has none.
* Balances are current-state on Postgres/MySQL; use ClickHouse for real-time/hybrid.
### GET /:address/erc20
The plain ERC-20 balances endpoint (no prices, no portfolio math). Replaced by this template's `token_balances` table joined with [Token Metadata](/data-feeds/templates/token/token-metadata) for name/symbol/decimals/supply: two templates, one view, every onchain value exact.
| `/:address/erc20` | Data Feeds | Fidelity |
| - | - | - |
| `token_address`, `balance` (raw) | `token_balances.*` | exact |
| `name`, `symbol`, `decimals`, `total_supply` | `token_metadata.*` | exact |
| `total_supply_formatted`, `percentage_relative_to_total_supply` | derive from those values | exact |
| `balance_formatted` *(bonus, the REST response omits it)* | derive: `balance / 10^decimals` | exact |
| `logo`, `thumbnail`, `possible_spam`, `verified_contract`, `security_score` | add yourself | off-chain |
The view is the balances-and-prices view above minus the price join: join `token_balances` to `token_metadata`, keep `balance > 0`, and derive the formatted/supply-relative columns. The old `exclude_spam` / `exclude_unverified_contracts` filters become a `WHERE` against your own list.
**Gotchas**
* Everything onchain is exact: no pricing engine in the loop, nothing to reconcile with a tolerance.
* ERC-20 only, matching the REST endpoint. For native (ETH) balance, add [Native Balances](/data-feeds/templates/wallet/native-balances).
* No wallet-size limit: the old endpoint errors on very large wallets ("too many ERC20 token balances"); your dataset doesn't, and you get real keyset pagination on top.
### GET /wallets/:address/net-worth
The USD net-worth roll-up. There is no single replacement table; net worth is `SUM(token balance × price) + native balance × native price`, computed over the same tables as `/wallets/:address/tokens`.
> [!WARNING]
>
> This endpoint needs **four templates**: this template plus [Native Balances](/data-feeds/templates/wallet/native-balances), [Token Metadata](/data-feeds/templates/token/token-metadata), and [Token Prices](/data-feeds/templates/token/token-prices). Build the balances-and-prices view above first, then aggregate it; net worth is a `SUM` on top of that view.
| `/wallets/:address/net-worth` | Data Feeds | Fidelity |
| - | - | - |
| `native_balance`, `native_balance_formatted` | `native_balances.balance` | exact |
| `native_balance_usd` | derive: native balance × native price | calculated |
| `token_balance_usd` | `SUM(usd_value)` over the balances view | calculated |
| `networth_usd` | derive: native + token USD | calculated |
| `total_networth_usd` | derive: sum across chains | calculated |
The roll-up view (Postgres; sums the balances view above and adds the native leg):
```sql theme={null}
CREATE VIEW wallet_net_worth AS
WITH tokens AS (
SELECT wallet_address,
sum(usd_value) AS token_balance_usd -- exclude what shouldn't count (see gotchas)
FROM wallet_token_balances_price
WHERE usd_value IS NOT NULL
GROUP BY wallet_address
),
native AS (
SELECT n.wallet_address,
n.balance / 1e18 AS native_balance_formatted,
n.balance / 1e18 * p.usd_price AS native_balance_usd
FROM native_balances n
LEFT JOIN LATERAL (
SELECT usd_price FROM token_price_updates
WHERE token_address = lower('0xC02aaa39b223FE8D0A0e5C4F27eAD9083C756Cc2') -- WETH = native mark
ORDER BY block_number DESC LIMIT 1
) p ON true
)
SELECT
coalesce(t.wallet_address, n.wallet_address) AS wallet_address,
n.native_balance_formatted,
n.native_balance_usd,
coalesce(t.token_balance_usd, 0) AS token_balance_usd,
coalesce(t.token_balance_usd, 0) + coalesce(n.native_balance_usd, 0) AS networth_usd
FROM tokens t
FULL JOIN native n ON n.wallet_address = t.wallet_address;
```
**Gotchas**
* **Curating the token set is the whole game.** One spam or bogus-priced token can dominate the total. The old `exclude_spam` / `exclude_unverified_contracts` / `min_pair_side_liquidity_usd` filters become your own `WHERE` in the `tokens` CTE; here they're essential, not polish.
* Stale prices: a token that hasn't traded recently has no fresh mark. Decide whether to value it at zero, carry forward the last mark, or exclude it. Each choice moves the total.
* Cross-chain net worth: each chain is its own feed. Compute per chain and sum `networth_usd` into `total_networth_usd`.
* Compare with a tolerance: USD comes from real DEX trades, very close to the old figure, not identical.
* A missed holding silently changes the total, so full-history backfill (see the note in [Run it](#run-it)) matters even more here.
### Related
> [card] [Token Balances by Token](/data-feeds/templates/token/token-balances-by-token)
>
> The sibling: same ingest, keyed token-first to list a token's holders.
> [card] [Portfolio Tracking](/data-feeds/use-cases/portfolio-tracking)
>
> The use case this balance feed powers.
# Wallet History
Source: https://docs.moralis.com/data-feeds/templates/wallet/wallet-history
Reconstruct a wallet's full chronological event feed (every transfer, swap, NFT move, approval, and LP change, with USD value per event) as a continuous sync into your own database.
### Question it answers
> "Show me the full chronological event feed for wallet **0x…**, newest first. Each row is one event with its actual payload (counterparty, amounts, token IDs, pair address, USD value), and I can filter by event type."
A single read returns what the public API stitches together client-side from `/wallets/{address}/erc20-transfers`, `/native-transactions`, `/nfts/transfers`, `/swaps`, `/approvals`, and `/defi/positions`. Storing it **pre-stitched**, in your own database, is the value.
### What you get
The template lands **one row per wallet-bearing event**. A wallet is "involved" if it is a non-empty `from`/`to` (or owner/approver) on the event. Six event types share one wide, flat table; per-type columns are populated as relevant:
| `event_type` | Rows per event | Populated columns | USD value |
| - | - | - | - |
| `token_transfer` | 2 (from + to) | `token_address`, `amount` | ✅ inline (unscaled) |
| `native_transfer` | 2 (from + to) | `amount` | None |
| `nft_transfer` | 2 (from + to) | `token_address`, `token_id`, `amount` | None |
| `swap` | 1 (the wallet) | `pair_address`, `token_in/out_address`, `amount_in/out` | ✅ inline |
| `approval` | 1 (approver) | `spender_address`, `token_address`, `amount` | None |
| `liquidity_change` | 1 (LP owner) | `change_type`, `pair_address`, `token0/1_address`, `token0/1_amount` | ✅ inline |
Each row also carries `direction` (`sent` · `received` · `self` · `minted` · `burned`), `counterparty`, `tx_hash`, `block_number`, `block_timestamp`, and `log_index`.
### Source
The transform reads six per-block arrays and `UNION`s them into the event feed:
`tokenTransfers` · `nativeTransfers` · `nftTokenTransfers` · `tokenSwaps` · `tokenApprovals` · `pairLiquidityChanges`
USD values are computed **inline** from the same block's `tokenPriceUpdates`, with no separate price join at read time.
### Destination
| Destination | Table | Read pattern |
| - | - | - |
| **ClickHouse** (first-class) | `fact_wallet_history_full` | Prefix scan on `(chain_id, wallet_address, block_number, log_index)`; read with `FINAL` or `sum(sign)` |
| **Postgres** | `wallet_history_full` | Index on `(wallet_address, block_number DESC)` |
| **MySQL** | `wallet_history_full` | Index on `(wallet_address, block_number)` |
ClickHouse uses the collapsing log-table pattern (see the [templates overview](/data-feeds/templates/overview#destinations)) so chain reorganizations self-correct. The fact table's sort key is wallet-first, so a wallet's feed, optionally filtered by `event_type`, is a contiguous range read.
### Full schema
Below is the complete read table this template produces. It's the **full shape**: every event type's columns in one wide row. This is a starting point: keep the columns and event types you need and drop the rest (see [Schema & flexibility](/data-feeds/templates/overview#schema--flexibility)). Raw `uint256` amounts and `token_id` are stored as text (they exceed numeric precision); USD columns are wide decimals so a low-decimals token × price never overflows.
> [accordion] ClickHouse, fact\_wallet\_history\_full
>
> ```sql theme={null}
> CREATE TABLE recipe_wallet_history_full.fact_wallet_history_full
> (
> chain_id UInt32,
> wallet_address String,
> block_number UInt64,
> log_index UInt32,
> event_type LowCardinality(String), -- token_transfer | native_transfer | nft_transfer | swap | approval | liquidity_change
> vendor_event_id String,
> block_timestamp DateTime64(3),
> tx_hash String,
> transaction_index Nullable(Int32),
> direction LowCardinality(String), -- sent | received | self | minted | burned | n/a
> counterparty String,
> token_address String,
> amount String, -- raw uint256
> amount_usd Nullable(String),
> token_id String,
> pair_address String,
> token_in_address String,
> amount_in String,
> amount_in_usd Nullable(String),
> token_out_address String,
> amount_out String,
> amount_out_usd Nullable(String),
> spender_address String,
> change_type LowCardinality(String), -- mint | burn | sync | ''
> token0_address String,
> token0_amount String,
> token0_amount_usd Nullable(String),
> token1_address String,
> token1_amount String,
> token1_amount_usd Nullable(String),
> sign Int8
> )
> ENGINE = ReplicatedCollapsingMergeTree(
> '/clickhouse/tables/{database}/fact_wallet_history_full', '{replica}', sign)
> PARTITION BY (chain_id, toYYYYMM(block_timestamp))
> ORDER BY (chain_id, wallet_address, block_number, log_index, event_type, vendor_event_id);
> ```
>
> The `sign` column drives reorg collapsing; read with `FINAL` or `sum(sign)`. A single-node setup can use `CollapsingMergeTree(sign)` without the replication path.
> [accordion] Postgres, wallet\_history\_full
>
> ```sql theme={null}
> CREATE TABLE public.wallet_history_full (
> position BIGINT NOT NULL,
> chain_id BIGINT NOT NULL,
> block_number BIGINT NOT NULL,
> block_timestamp BIGINT NOT NULL, -- unix seconds
> tx_hash TEXT NOT NULL,
> log_index BIGINT NOT NULL,
> wallet_address TEXT NOT NULL,
> event_type TEXT NOT NULL,
> vendor_event_id TEXT NOT NULL,
> direction TEXT NOT NULL,
> counterparty TEXT NOT NULL,
> token_address TEXT NOT NULL,
> amount TEXT NOT NULL, -- raw uint256
> amount_usd NUMERIC(65, 18) NULL,
> token_id TEXT NOT NULL,
> pair_address TEXT NOT NULL,
> token_in_address TEXT NOT NULL,
> amount_in TEXT NOT NULL,
> amount_in_usd NUMERIC(65, 18) NULL,
> token_out_address TEXT NOT NULL,
> amount_out TEXT NOT NULL,
> amount_out_usd NUMERIC(65, 18) NULL,
> spender_address TEXT NOT NULL,
> change_type TEXT NOT NULL,
> token0_address TEXT NOT NULL,
> token0_amount TEXT NOT NULL,
> token0_amount_usd NUMERIC(65, 18) NULL,
> token1_address TEXT NOT NULL,
> token1_amount TEXT NOT NULL,
> token1_amount_usd NUMERIC(65, 18) NULL
> );
>
> -- Primary access pattern: every event for a wallet, newest first.
> CREATE INDEX ON public.wallet_history_full (chain_id, wallet_address, block_number DESC);
> -- Event-type filter within a wallet.
> CREATE INDEX ON public.wallet_history_full (chain_id, wallet_address, event_type, block_number DESC);
> ```
>
> MySQL is the same shape with `DECIMAL(65,18)` for the USD columns. `position` is the block-level cursor used during backfill.
### Run it
Everything runs in **your** infrastructure: the sink writes into a database you own and you query it with plain SQL, no API and no per-call limits.
**Prerequisites**
* **Docker** and Docker Compose.
* A **Data Feeds key**, a `cm_live_…` key with `continuum:read` scope (this is *not* your Web3 API key).
> [card] [Sign up for a Data Feeds key](https://admin.moralis.com)
>
> Log in to the Moralis admin panel to create your account and generate a `cm_live_…` key.
**Start the sink**
Generate a **starter pack** for `walletHistoryFull` in the [Moralis Admin Panel](https://admin.moralis.com), pick your chain and destination database, then run it with Docker. The [quickstart](/data-feeds/migration/quickstart) walks through it end to end. Choose the backfill window (`MORALIS_HISTORICAL_FROM_BLOCK`, e.g. `tip-1000`) as noted below.
> [!NOTE]
>
> **Size the window deliberately.** This template lands one row per event across six event types, so history adds up fast, `tip-1000` on Ethereum is roughly 3M rows. The 9-branch transform is memory-hungry: on chain-heavy windows raise the sink's ClickHouse memory ceiling (`CLICKHOUSE_MAX_MEMORY_USAGE`, default 4 GiB). See [Modes](#modes) for backfill vs realtime.
Then run the example reads below to confirm rows are landing.
### Example reads
A wallet's full feed, newest first (ClickHouse):
```sql theme={null}
SELECT block_number, log_index, event_type, direction, counterparty,
token_address, amount, amount_usd
FROM recipe_wallet_history_full.fact_wallet_history_full FINAL
WHERE chain_id = 1
AND wallet_address = lower('0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045')
ORDER BY block_number DESC, log_index DESC
LIMIT 50;
```
Only swaps and token transfers (the `event_type` filter compresses the scan further):
```sql theme={null}
SELECT block_number, event_type, token_in_address, amount_in,
token_out_address, amount_out, amount_in_usd, amount_out_usd
FROM recipe_wallet_history_full.fact_wallet_history_full FINAL
WHERE chain_id = 1
AND wallet_address = lower('0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045')
AND event_type IN ('swap', 'token_transfer')
ORDER BY block_number DESC, log_index DESC;
```
Per-event-type breakdown (sign-aware, cheaper than `FINAL`):
```sql theme={null}
SELECT event_type, sum(sign) AS events
FROM recipe_wallet_history_full.fact_wallet_history_full
WHERE chain_id = 1 AND wallet_address = lower('0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045')
GROUP BY event_type
ORDER BY events DESC;
```
### Other ways to consume this data
The sink is the way to get **this pre-shaped table** (`wallet_history_full`), recommended for a queryable history you own. The *same underlying data* is also available as the **raw decoded feed**, if you'd rather shape it yourself:
* **Your existing message clients**: stream it with **Kafka / AMQP / SQS**.
* **REST / Arrow Flight**: pull the decoded block stream directly.
Those give you the **source arrays** (`tokenTransfers`, `tokenSwaps`, …) to assemble yourself, not this pre-stitched wallet table. All of them read the one data lake into **your** infrastructure. See [What are Data Feeds?](/data-feeds/concepts/what-are-data-feeds).
### USD valuation and fidelity gaps
* **Swaps and LP changes** carry per-leg decimals, so their `*_usd` columns are true dollar values (`raw / 10^decimals × price`).
* **Token transfers** have no decimals field on the transfer event, so `amount_usd` is `raw_amount × price` (**unscaled**). Divide by `10^token_decimals` to read dollars; fold in a decimals lookup from a Token Metadata sync if you need it pre-scaled.
* **Native and NFT transfers** leave USD `NULL`: native pricing needs a separate native-price feed, and NFT pricing is out of scope (use an NFT Trades template for trade-priced data).
* **Approvals** leave USD `NULL` by design: an unlimited allowance × price is meaningless.
### Lightweight variant: transaction pointers
If you only need a wallet's **transaction list** (one pointer per `(wallet, tx)`, not the full payload), there's a slimmer variant that lands just the deduplicated pointers from the transfer arrays. Use the full feed above when you need amounts, counterparties, and USD value; use the pointer variant when you only need "which transactions touched this wallet."
### Modes
Shipped defaults: **ClickHouse `hybrid`** (backfill → realtime), **Postgres / MySQL `historical`** (one-shot backfill). For live/reorg-safe ingestion, use ClickHouse; see the [overview](/data-feeds/templates/overview#modes).
### Multichain
The template is chain-parametrized via the `chain` setting: point it at any supported EVM chain or Solana. On Solana, the event identity is widened to stay unique under Solana's repeated log indices; the wallet feed it produces is identical in shape.
### How much data does this consume?
Wallet history is one of the **largest** scopes in the feed, because it unions several transfer arrays across every wallet on the chain. On **Solana mainnet**, continuous real-time feeds measured:
| Selection | Typical month (P50) | Busy month (P90) |
| - | - | - |
| The three transfer arrays alone (`nativeTransfers`, `tokenTransfers`, `nftTokenTransfers`) | **\~1,300 GB** | **\~1,600 GB** |
| The full nine-slice wallet-history selection (adds swaps, aggregator swaps, approvals, liquidity changes, prices) | **\~1,400 GB** | **\~1,800 GB** |
| The transfer arrays **without** `nativeTransfers` | **\~480 GB** | **\~590 GB** |
Measured 2026-07-31, 30 sampled partitions per selection, `metered` delivery. Billing is on uncompressed bytes.
This template's selection sits between the first two rows. Note the third row: **`nativeTransfers` is roughly two thirds of the bill on its own** — if your use case doesn't need native (SOL/ETH) transfers, dropping that one slice is the single largest cost lever available.
**Size your allowance against the busy figure, not the typical one.** Chain activity is bursty, and the same feed can land on either side of a fixed allowance depending on the month. Three caveats:
* **Real-time only.** A historical backfill is billed separately and is usually the larger number; its size depends entirely on how far back you go.
* **Solana only.** Volume concentrates hard per chain — Solana has measured over 20x Ethereum on comparable transfer-shaped selections — so this figure does not extrapolate to other chains.
* **Filtering does not reduce it.** Restricting to specific wallets happens after the data is delivered. To reduce cost, narrow the **block range**, not the entity set.
If you want your exact scope measured before you commit to a plan, [reach out](https://admin.moralis.com/data-feeds) and we will probe it against the live feed rather than estimate it.
### Powers these use cases
> [card] [Accounting & Tax](/data-feeds/use-cases/accounting)
>
> The chronological, USD-valued event feed behind a ledger.
> [card] [Compliance & AML](/data-feeds/use-cases/compliance-aml)
>
> Full counterparty and transfer trail per address.
## Migrating from the REST API
Coming from the Web3 Data API? This template replaces the wallet-activity endpoints below. Data Feeds are **not 1:1 replicas** of REST responses (you own the table and reshape it with SQL), so each subsection states exactly what maps, what's calculated for you, and what you add yourself. For the general model see [Data Feeds vs. the REST API](/data-feeds/concepts/data-feeds-vs-the-rest-api); for the full endpoint index see the [endpoint map](/data-feeds/migration/endpoints).
### Wallet transaction history
`GET /wallets/{address}/history`
Replaced by this template's `wallet_history_full` table: the same activity, flattened to **one row per event** instead of one object per transaction, with a per-event USD value the old endpoint never had.
> [!NOTE]
>
> **Not a 1:1 swap.** The old response nests events under each transaction and layers on a decoded/curated layer. You need **this template** for the events, plus [Token Metadata](/data-feeds/templates/token/token-metadata) for token names/symbols/decimals, plus a `GROUP BY tx_hash` reshape if your UI expects the transaction-grouped shape. Transaction-level fields (gas, nonce, receipt) come from the raw `block` transaction rows; see [The `block` array](/data-feeds/concepts/the-block-array).
| `/wallets/{address}/history` | Data Feeds | Fidelity |
| - | - | - |
| `hash`, `block_number`, `block_timestamp`, `transaction_index`, `from`/`to`, `value` | `wallet_history_full.*` | exact |
| `nonce`, `gas`, `gas_price`, `input`, `receipt_*`, `transaction_fee` | raw `block` transaction row (join on `tx_hash`) | exact |
| nested transfer `value` (raw) / `value_formatted` | `amount`, `amount_in/out`, `token0/1_amount`; formatted = `amount / 10^decimals` | exact |
| per-event USD value | `amount_usd`, `amount_in/out_usd`, `token0/1_amount_usd` | calculated *(new; the endpoint had none)* |
| token `name` / `symbol` / `decimals` | `token_metadata.*` ([Token Metadata](/data-feeds/templates/token/token-metadata)) | exact |
| `direction` | `wallet_history_full.direction` | exact |
| `internal_transactions[]` | not delivered by a shipped template today | gap |
| `logs[]` (raw) / `logs[].decoded_event` | raw `block` log rows / decode from the ABI yourself | exact / add yourself |
| `category`, `summary`, `method_label` | build yourself, or omit | add yourself |
| `*_label`, `*_entity`, logos, `possible_spam`, `verified_collection` | your own label / curation source | add yourself |
To reproduce the endpoint's transaction-grouped shape, group events by `tx_hash` (Postgres):
```sql theme={null}
SELECT tx_hash,
max(block_number) AS block_number,
max(block_timestamp) AS block_timestamp,
jsonb_agg(to_jsonb(e) ORDER BY log_index) FILTER (WHERE event_type = 'token_transfer') AS erc20_transfers,
jsonb_agg(to_jsonb(e) ORDER BY log_index) FILTER (WHERE event_type = 'nft_transfer') AS nft_transfers,
jsonb_agg(to_jsonb(e) ORDER BY log_index) FILTER (WHERE event_type = 'native_transfer') AS native_transfers
FROM wallet_history_full e
WHERE wallet_address = lower($1)
GROUP BY tx_hash
ORDER BY block_number DESC
LIMIT $2;
```
**Good to know**
* The biggest migration task is the reshape: event-flat → transaction-grouped is a `GROUP BY tx_hash`. Skip it entirely if your UI prefers an event feed.
* You gain per-event USD the endpoint never provided. Compare with a tolerance, and expect `NULL`/0 for unpriced tokens.
* The decoded/categorized/labeled layer is off-chain processing, not onchain data; add it yourself or drop it.
* Only need "which transactions touched this wallet"? Use the [lightweight pointer variant](#lightweight-variant-transaction-pointers) instead of the full feed.
* No per-call limit: page a wallet's entire history with plain SQL.
### Wallet native transactions
`GET /{address}`
Replaced by this template filtered to `event_type = 'native_transfer'`: the native slice of the same event feed. Direction, date, block, and ordering filters become plain `WHERE` / `ORDER BY` clauses.
> [!NOTE]
>
> **Not a 1:1 swap for strict parity.** The REST endpoint returns *every* transaction where the wallet is `from` or `to`, including `value = 0` contract calls; native value movements alone miss those. For exact parity, and for gas/nonce/receipt fields, read the raw transaction rows from the `block` array (filter `transactionFrom` / `transactionTo` = your wallet) alongside this template. See [The `block` array](/data-feeds/concepts/the-block-array).
| `/{address}` | Data Feeds | Fidelity |
| - | - | - |
| `hash`, `nonce`, `transaction_index` | `block` array transaction row | exact |
| `from_address`, `to_address`, `value`, `input` | transaction row / `nativeTransfers` | exact |
| `gas`, `gas_price`, `receipt_*` | `block` array transaction row | exact |
| `transaction_fee` | derive: `receipt_gas_used × gas_price` | exact |
| `block_number`, `block_timestamp`, `block_hash` | block / transaction row | exact |
| `logs[]` | `block` array log rows | exact |
| `internal_transactions` | not delivered by a shipped template today | gap |
| `method_label` | decode the 4-byte selector from the ABI | add yourself |
| `from/to_address_entity`, `*_label`, `*_entity_logo` | your own label directory | add yourself |
**Good to know**
* No wallet-size cap: the old endpoint can error on very large wallets; your own table has no such limit.
* Strict parity includes `value = 0` sends, so use the block-array transaction rows when you need every transaction, not just value movements.
* Run the template `realtime` (ClickHouse recommended) for a live feed of new transactions.
### Wallet active chains
`GET /wallets/{address}/chains`
Replaced by a roll-up you build: run this template on **each chain** you cover, keep a `min`/`max` activity summary per wallet per chain, and union the results in your app.
> [!NOTE]
>
> **Not a 1:1 swap.** Data Feeds are one feed per chain. This endpoint needs this template running on every chain you want to report, plus a small cross-chain union in your application layer. A wallet active on a chain you don't index simply won't appear; that coverage is yours to set.
| `/wallets/{address}/chains` | Data Feeds | Fidelity |
| - | - | - |
| `address` | the query | exact |
| `active_chains[].chain`, `chain_id` | the indexed chains where the wallet has rows | exact |
| `first_transaction` (block, timestamp, hash) | `MIN` activity block per chain + the tx there | exact |
| `last_transaction` (block, timestamp, hash) | `MAX` activity block per chain + the tx there | exact |
Keep the per-chain read cheap with a summary view over the template's table:
```sql theme={null}
CREATE VIEW wallet_chain_activity AS
SELECT
wallet_address,
min(block_number) AS first_block,
max(block_number) AS last_block
FROM wallet_history_full
GROUP BY wallet_address;
```
**Good to know**
* First-seen needs full history; "active" and last-seen do not. Backfill each chain to an early block where you want a correct first transaction; a wallet's first activity can be genesis-era.
* Every value is exact: no prices, no off-chain data, just onchain presence and the bounding transactions.
* Stream each chain's feed to keep last-seen live as the wallet transacts.
### Wallet stats
`GET /wallets/{address}/stats`
Replaced by plain `COUNT`s: three of the five stats come straight from this template's table; the NFT holdings counts need a second template.
> [!NOTE]
>
> **Not a 1:1 swap.** You need this template **plus** [NFTs by Wallet](/data-feeds/templates/wallet/nfts-by-wallet). `transactions`, `token_transfers`, and `nft_transfers` are `event_type` counts over `wallet_history_full`; `nfts` and `collections` are counts over the wallet-NFT holdings table.
| `/wallets/{address}/stats` | Data Feeds | Fidelity |
| - | - | - |
| `nfts` | `count` over `wallet_nfts` where `balance > 0` ([NFTs by Wallet](/data-feeds/templates/wallet/nfts-by-wallet)) | exact |
| `collections` | `count(DISTINCT token_address)` over `wallet_nfts` | exact |
| `transactions.total` | `count` of the wallet's native transactions | exact |
| `nft_transfers.total` | `count` where `event_type = 'nft_transfer'` | exact |
| `token_transfers.total` | `count` where `event_type = 'token_transfer'` | exact |
```sql theme={null}
SELECT
(SELECT count(*) FROM wallet_nfts
WHERE wallet_address = $1 AND balance > 0) AS nfts,
(SELECT count(DISTINCT token_address) FROM wallet_nfts
WHERE wallet_address = $1 AND balance > 0) AS collections,
(SELECT count(*) FROM wallet_history_full
WHERE wallet_address = $1 AND event_type = 'native_transfer') AS transactions_total,
(SELECT count(*) FROM wallet_history_full
WHERE wallet_address = $1 AND event_type = 'nft_transfer') AS nft_transfers_total,
(SELECT count(*) FROM wallet_history_full
WHERE wallet_address = $1 AND event_type = 'token_transfer') AS token_transfers_total;
```
**Good to know**
* These counts are **cumulative over the wallet's life**: accurate totals need the full chain history backfilled (`historical` / `hybrid` from an early block). See [History & backfill](/data-feeds/concepts/history-and-backfill).
* For `transactions.total`, native transfers miss `value = 0` contract calls; count the raw block-array transaction rows for strict parity (same caveat as [native transactions](#wallet-native-transactions)).
* For `nfts`, decide whether you count held token IDs or sum ERC-1155 amounts. The endpoint counted token IDs.
* Serving many wallets? Materialize a per-wallet stats row and update it as events land.
# Accounting & Tax
Source: https://docs.moralis.com/data-feeds/use-cases/accounting
A Data Feeds template bundle for accounting, tax, and treasury tools: a wallet's full event feed plus per-asset transfer ledgers, valued in USD at block time, synced into your own database.
### Who it's for
Teams building **accounting, tax, bookkeeping, treasury, and audit** tooling: anything that needs a complete, valued, auditable record of what moved through a set of wallets. The goal is a ledger you own: every inflow and outflow, classified, with a USD value at the time it happened.
### The template bundle
This use case combines a small set of templates. Start with **Wallet History** as the backbone, then add the standalone transfer templates when you need per-asset ledger tables, and **Token Prices** for valuation.
| Template | Role in the ledger |
| - | - |
| [Wallet History](/data-feeds/templates/wallet/wallet-history) | The backbone: every event a wallet was involved in, in order, with inline USD value. Covers token, native, and NFT transfers, swaps, approvals, and LP changes in one feed. |
| [Token Transfers](/data-feeds/templates/token/token-transfers) | Per-token transfer ledger: every ERC-20 movement of a given token, keyed for asset-level reconciliation. |
| Native Transfers | Native-asset (gas-token) movements, including internal transfers; available within Wallet History's `native_transfer` rows. |
| [NFT Transfers](/data-feeds/templates/nft/nft-transfers) | NFT movements (collection + token ID) for inventory and disposal tracking. |
| [Token Balances by Wallet](/data-feeds/templates/wallet/token-balances-by-wallet) | Period-end token holdings per wallet: the balance-sheet snapshot, reconciled against the transfer ledger. |
| [Native Balances](/data-feeds/templates/wallet/native-balances) | Period-end native-asset (gas-token) balance per wallet. |
| [Token Prices](/data-feeds/templates/token/token-prices) | The valuation join target: USD/native marks used to value every transfer and holding at block time. |
| [Contract Logs](/data-feeds/templates/logs/contract-logs) | Raw events from contracts you can't book from decoded feeds: staking rewards, vesting, rebases, custom protocol events. Decode against the ABI to classify them as income/expense. |
| [Logs by Event Signature](/data-feeds/templates/logs/logs-by-topic0) | One event type chain-wide: e.g. capture a specific reward or distribution event across every protocol you interact with, in one feed. |
> [!NOTE]
>
> **Wallet History already contains the transfer events.** If a single, filterable event feed per wallet is enough, the backbone template alone covers accounting. Add the standalone **Token / NFT Transfers** templates when you want dedicated, per-asset tables (e.g. one table per token to reconcile against an exchange's books) rather than filtering one wide feed. Add the **log templates** when income or expense lives in events the decoded feeds don't model (staking rewards, vesting unlocks, rebases, or any custom protocol event), so nothing falls outside the books. Add the **balance templates** for the positions side: period-end holdings (the balance sheet) to reconcile against the transaction ledger.
### How the pieces fit
```text theme={null}
Wallet History ──┐
Token Transfers ──┤
Native Transfers ──┼──► transaction ledger (flows) ──┐
NFT Transfers ──┤ │
Contract Logs ──┘ (custom income/expense events) ├──► valued by ── Token Prices
│
Token Balances by Wallet ──┐ │
Native Balances ──┴─► balance-sheet (positions)┘
```
* **Wallet History** gives you the chronological, classified feed: each row already tagged `sent` / `received` / `self` / `minted` / `burned`, so debits and credits fall out of `direction`.
* **The transfer templates** give you asset-first tables for reconciliation: "every movement of token X across all tracked wallets."
* **The log templates** close the gap for income and expense that isn't a plain transfer: staking rewards, vesting unlocks, rebases, fee distributions. Decode the raw `data` against the contract ABI and classify each event into your chart of accounts.
* **Transfers are the flows; balances are the positions.** [Token Balances by Wallet](/data-feeds/templates/wallet/token-balances-by-wallet) and [Native Balances](/data-feeds/templates/wallet/native-balances) give the period-end holdings snapshot, the balance sheet, to reconcile against the transfer ledger and to value at the reporting date.
* **Token Prices** is the connective tissue: join any transfer or holding to the token's mark at its `block_number` to compute USD value at the time of the event (for the P\&L) or at period end (for the balance sheet). This is the basis every tax and accounting calculation needs.
### Valuing transfers in USD
Wallet History folds USD values inline for the event types that carry decimals (swaps, LP changes) and for token transfers as an **unscaled** product (`raw_amount × price`). For a ledger you'll typically want fully-scaled dollar values for every asset, which is a join against the Token Prices sync:
```sql theme={null}
-- Token transfers for a wallet, valued in USD at block time.
SELECT wh.block_timestamp,
wh.direction,
wh.token_address,
wh.amount,
wh.counterparty,
wh.tx_hash
FROM fact_wallet_history_full AS wh FINAL
WHERE wh.chain_id = 1
AND wh.wallet_address = lower('0x…')
AND wh.event_type = 'token_transfer'
ORDER BY wh.block_number DESC, wh.log_index DESC;
```
Pair this with the Token Prices sync (joined on token + nearest block) and a token-decimals lookup to produce a fully-scaled, dated, dollar-valued ledger.
### Notes and considerations
* **Cost basis** is a downstream calculation (FIFO/LIFO/average) your application performs over this ledger. The templates give you the valued, ordered events it needs, not the basis itself.
* **Decimals.** Scale raw `amount` values by `10^token_decimals` before reporting dollars; source decimals from a Token Metadata sync.
* **Native and NFT USD.** Wallet History leaves these `NULL`; value native movements against a native-price feed, and treat NFTs separately (cost/proceeds from trade data, not transfers).
* **Completeness for audit.** Run the ClickHouse path in `hybrid` mode so the ledger backfills history and then stays current, reorg-safe, at the chain head.
### Get started
Start with the templates in this workflow, then follow the Quickstart to run them.
> [card] [Get started](/data-feeds/migration/quickstart)
>
> Build an owned, auditable onchain ledger.
# Compliance & AML
Source: https://docs.moralis.com/data-feeds/use-cases/compliance-aml
A Data Feeds template bundle for compliance, AML, and forensics teams: a complete, ordered, auditable trail of everything an address did, plus its asset positions and risk surface, synced into your own database.
### Who it's for
Teams building **compliance, AML, transaction-monitoring, and forensics** tooling: anything that needs a complete, ordered, defensible record of what an address did and what it holds. The goal is a full audit trail you own: every event in sequence, every counterparty, the address's current and historical positions, and the standing risk it has granted, all reconstructable from Moralis-indexed, normalized per-block onchain data.
### The template bundle
This use case combines a small set of templates. Start with **Wallet History** as the chronological backbone, layer **Token Transfers** and **Swaps by Wallet** for asset-level and DEX-activity trails, **Token Balances by Wallet** and **Native Balances** for the address's full asset positions, and **Token Approvals** for the standing risk surface.
| Template | Role in the trail |
| - | - |
| [Wallet History](/data-feeds/templates/wallet/wallet-history) | The backbone: every event an address was involved in, in on-chain order, classified by `direction` and `event_type`, with USD value inline. Token, native, and NFT transfers, swaps, approvals, and LP changes in one feed. |
| [Token Transfers](/data-feeds/templates/token/token-transfers) | Asset-first movement trail: every ERC-20 transfer of a token, with `from_address` / `to_address` and the initiator, for counterparty and flow tracing. |
| [Token Balances by Wallet](/data-feeds/templates/wallet/token-balances-by-wallet) | The address's token holdings: current and historical positions per token, for net-worth, exposure, and balance-at-block snapshots. |
| [Native Balances](/data-feeds/templates/wallet/native-balances) | The address's native-asset (gas-token) position over time, for net-worth and balance-at-block snapshots. |
| [Token Approvals](/data-feeds/templates/wallet/token-approvals) | The risk surface: every allowance the address has granted, so you can compute the live exposure to each spender. |
| [Swaps by Wallet](/data-feeds/templates/markets/swaps-by-wallet) | DEX activity per address: every trade, with notional in USD, for layering/structuring detection. |
| [Contract Logs](/data-feeds/templates/logs/contract-logs) | Audit-grade completeness: every raw event log emitted by a contract of interest (mixer, bridge, sanctioned address, custom protocol), including events the decoded templates don't model. |
| [Logs by Event Signature](/data-feeds/templates/logs/logs-by-topic0) | One event signature (`topic0`) chain-wide: capture a specific event across all contracts (e.g. every interaction of a flagged signature) for screening and pattern detection. |
> [!NOTE]
>
> **Wallet History already contains the transfer, swap, and approval events.** If a single, filterable event feed per address is enough, the backbone template alone is your audit trail. Add the standalone templates when you want dedicated, differently-keyed tables: **Token Transfers** keyed by token for counterparty tracing, **Swaps by Wallet** for trade-level notional, **Token Approvals** for live-allowance reconciliation, and **Token Balances by Wallet** + **Native Balances** for current/historical position snapshots. Add the **log templates** when you need raw, decode-it-yourself completeness: events on custom or non-standard contracts that the decoded feeds don't cover, which an audit can't afford to miss.
### How the pieces fit
```text theme={null}
┌──► Token Transfers (counterparty / flow trail)
Wallet History ──────────┤
(ordered event feed) ├──► Swaps by Wallet (DEX activity / notional)
│
Token Balances ─────────┐│
Native Balances ─────────┤│
Token Approvals ─────────┤├──► your audit trail per address
│
Contract Logs ───────────┤ (raw events the decoded feeds don't model —
Logs by Signature ───────┘ custom contracts, flagged signatures)
```
* **Wallet History** is the spine: the complete, ordered, classified feed for one address. Each row is tagged `sent` / `received` / `self` / `minted` / `burned` via `direction`, and the event kind via `event_type`, so a full activity timeline falls out of one table.
* **Token Transfers** and **Swaps by Wallet** are asset-first and trade-first views of the same source events, keyed for the questions a forensics workflow asks: "who did this address transact with for token X" and "what was the USD notional of each trade."
* **Token Balances by Wallet**, **Native Balances**, and **Token Approvals** describe *state*: the address's token and native positions over time, and the standing allowances it has granted. Balances answer "what does this address hold, now or at block N"; approvals are the risk surface: an unrevoked unlimited allowance is live exposure regardless of activity.
* **The log templates** are the completeness backstop. The decoded feeds cover standard transfers, swaps, and approvals; **Contract Logs** and **Logs by Event Signature** capture *everything else* (custom protocol events, non-standard contracts, interactions with a flagged address) as raw `topic0…3` + `data` you decode against the ABI. For audit defensibility, "we indexed every event" beats "we indexed the events we had a decoder for."
### Building the per-address audit trail
The compliance question is "show me everything this address did, in order." That is the Wallet History feed, read reorg-safe with `FINAL`:
```sql theme={null}
-- Full chronological event trail for one address.
SELECT block_timestamp,
event_type,
direction,
counterparty,
token_address,
amount,
amount_usd,
tx_hash
FROM recipe_wallet_history_full.fact_wallet_history_full FINAL
WHERE chain_id = 1
AND wallet_address = lower('0x…')
ORDER BY block_number DESC, log_index DESC;
```
To assess the standing risk surface alongside the activity trail, compute the address's live allowances: the latest approval per `(token, spender)`, dropping anything revoked to zero:
```sql theme={null}
-- Live allowances the address has granted (the risk surface).
SELECT token_address,
spender_address,
argMax(value, (block_number, log_index)) AS current_allowance
FROM recipe_token_approvals.fact_token_approvals FINAL
WHERE chain_id = 1
AND owner_address = lower('0x…')
GROUP BY token_address, spender_address
HAVING current_allowance != '0' AND current_allowance != ''
ORDER BY token_address, spender_address;
```
Use `argMax` over `(block_number, log_index)` rather than a bare `WHERE sign = 1` so the read is correct under the collapsing log-table model and converges after reorgs.
### Notes and considerations
* **Read canonical state correctly.** On ClickHouse, every fact table follows the collapsing log-table pattern. Read with `FINAL` or a sign-aware aggregate (`argMax`, `sum(sign)`), never a bare `WHERE sign = 1`, so the trail stays correct across chain reorganizations.
* **Approvals are EVM-only** (ERC-20 `Approval(owner, spender, value)`). Value the *exposure*, not allowance × price. An unlimited approval is `2^256-1`, so dollar-weighting it is meaningless; treat unrevoked unlimited allowances as a categorical risk flag.
* **Chains.** Wallet History, Token Transfers, Token Balances by Wallet, Native Balances, and Swaps by Wallet are chain-parametrized across EVM and Solana; Token Approvals is EVM only.
* **Counterparty enrichment is yours.** The templates deliver the complete, ordered primitives: addresses, amounts, directions, counterparties. Sanctions screening, address labelling, and risk scoring are downstream layers your application runs over this trail.
* **Decimals and USD.** Scale raw `amount` / `value` text fields by `10^token_decimals` before reporting; source decimals from a Token Metadata sync. Wallet History folds USD inline where decimals are known (swaps, LP changes); Swaps by Wallet carries `notional_usd` per trade.
* **Completeness for audit.** Run the ClickHouse path in `hybrid` mode so the trail backfills full history and then stays current, reorg-safe, at the chain head.
* **Pairing.** For valuation across every asset, add [Token Prices](/data-feeds/templates/token/token-prices); for holder-side context on a token of interest, add [Token Holders](/data-feeds/templates/token/token-holders).
### Get started
Start with the templates in this workflow, then follow the Quickstart to run them.
> [card] [Get started](/data-feeds/migration/quickstart)
>
> Build an owned, auditable per-address trail.
# Onchain Event Indexing
Source: https://docs.moralis.com/data-feeds/use-cases/event-indexing
A Data Feeds template bundle for indexing raw event logs (every event from a contract, or one event signature across all contracts) into your own database for custom decoding and analytics.
### Who it's for
Teams that need **raw onchain events** in their own database: protocol teams indexing their own contracts, analytics platforms building chain-wide event feeds, and data teams covering **custom or non-standard events** that the decoded endpoints don't model. The output is a complete, ordered, reorg-safe log table you decode against your own ABIs.
### Raw logs vs decoded templates
Data Feeds ships two kinds of event data. Reach for raw logs when the decoded path doesn't cover what you need:
| Use… | When |
| - | - |
| **Decoded templates** (Token Transfers, Token Approvals, Swaps, NFT Transfers) | The event is a standard, already-decoded type: you want typed columns, no ABI decoding. |
| **Raw log templates** (this use case) | A custom/unsupported contract or event, or you want *every* event a contract emits, or one signature chain-wide. You'll decode `data` against your own ABI. |
### The template bundle
| Template | Role |
| - | - |
| [Contract Logs](/data-feeds/templates/logs/contract-logs) | Every raw event log emitted by a specific contract, in on-chain order. The "index my protocol's contracts" path. Optional `(contract, topic0)` grouping for high-volume contracts. |
| [Logs by Event Signature](/data-feeds/templates/logs/logs-by-topic0) | One event signature (`topic0`) across **all** contracts, chain-wide: every `Transfer`, `Approval`, `Swap`, etc. The "index one event everywhere" path. Optional `(topic0, contract)` grouping. |
### Two access patterns
```text theme={null}
Contract Logs Logs by Event Signature
key: contract_address key: topic0
"everything contract "this event across
X emitted" all contracts"
```
* **By contract**: point Contract Logs at your protocol's addresses and get a complete, ordered event log per contract. Decode in your application against the contract ABI.
* **By event signature**: point Logs by Event Signature at a `topic0` and capture that event chain-wide. Because popular signatures (`Transfer`, `Approval`) span the whole chain, scope reads to a block range. Enable the optional `(topic0, contract)` grouping when you frequently narrow to specific contracts within a signature.
### Decoding the payload
Both templates are intentionally raw: `topic0` is the event signature hash, `topic1…topic3` are the indexed parameters, and `data` is the ABI-encoded non-indexed payload as hex. Decode `data` (and interpret the indexed topics) against the event ABI in your application. Data Feeds delivers the complete, ordered, reorg-safe primitives; the decode layer stays under your control.
### Notes and considerations
* **EVM only.** Raw log extraction covers EVM event logs (`topic0…3` + `data`). Solana program logs are a different model.
* **Heavier source.** Logs come from the wide raw `block` data (all logs and transactions per block), so per-block volume is higher than the compact decoded templates. `tx_hash` is recovered by joining each log to its sibling transaction row; drop that join if you don't need it.
* **Scope popular signatures.** A chain-wide `Transfer`/`Approval` feed is large. Bound it to a block range and run the ClickHouse path for live, reorg-safe ingestion.
* **Pair with decoded templates.** Use raw logs for the long tail and custom events; use the decoded templates where a typed, ready-made shape already exists.
### Get started
Start with the templates in this workflow, then follow the Quickstart to run them.
> [card] [Get started](/data-feeds/migration/quickstart)
>
> Index any contract or event into your own infrastructure.
# NFT Marketplace
Source: https://docs.moralis.com/data-feeds/use-cases/nft-marketplace
A Data Feeds template bundle for NFT marketplaces and analytics platforms: collection trade history, current ownership, wallet inventories, and collection metadata, synced into your own database.
### Who it's for
Teams building **NFT marketplaces, collection explorers, and NFT analytics** platforms need sale history, current ownership, and per-wallet inventories without polling an API per page view. The output is your own set of tables: every marketplace trade, the live owner of every token, what each wallet holds, and the collection metadata to label it all.
### The template bundle
This use case combines a handful of templates. Start with **NFT Trades** for sale history, layer **NFT Owners by Contract** and **NFTs by Wallet** for the two ownership views, and add **NFT Collection Metadata** to label collections. Drop down to **NFT Transfers** when you need the raw movement feed under the trades.
| Template | Role in this use case |
| - | - |
| [NFT Trades](/data-feeds/templates/nft/nft-trades) | The sale feed: every marketplace trade (seller, buyer, collection, token ID, price, marketplace) by collection, by single token, or by wallet as seller/buyer. |
| [NFT Owners by Contract](/data-feeds/templates/nft/nft-owners-by-contract) | Current owners of a collection: the latest non-zero holding per `(token_id, wallet)`. The holder list and floor/holder analytics base. |
| [NFTs by Wallet](/data-feeds/templates/wallet/nfts-by-wallet) | A wallet's NFT inventory: every token a wallet currently holds, keyed by `(wallet, token_address, token_id)`. |
| [NFT Collection Metadata](/data-feeds/templates/nft/nft-collection-metadata) | Collection-level metadata (name, symbol, ERC-721/1155 type, deployer) to label collections across every other table. |
| [NFT Transfers](/data-feeds/templates/nft/nft-transfers) | The raw movement feed: every NFT transfer (mints, burns, plain sends, and the transfer legs of trades). Provenance and the substrate the ownership views are built from. |
> [!NOTE]
>
> **Trades and transfers are different feeds.** NFT Transfers is *every* movement of a token: mints, gifts, wallet-to-wallet sends, and the transfer leg of a marketplace sale. NFT Trades is the subset that settled through a marketplace, re-assembled with seller, buyer, price, and the marketplace address. Use Trades for sale history and volume; use Transfers for full provenance and to drive ownership.
### How the pieces fit
```text theme={null}
NFT Collection Metadata
(labels everything)
│
NFT Transfers ──► NFT Owners by Contract (owners of a collection)
(movements)└─► NFTs by Wallet (a wallet's inventory)
NFT Trades ─────► sale history · volume · floor / last-sale
```
* **NFT Transfers** is the substrate: every `(token_address, token_id)` movement, in on-chain order. The two ownership views are the same ingest sorted two ways: **NFT Owners by Contract** keys on `(token_address, token_id, wallet)` to answer "who owns this collection," and **NFTs by Wallet** keys on `(wallet, token_address, token_id)` to answer "what does this wallet hold."
* **NFT Trades** is the marketplace-settled subset, enriched with seller, buyer, price, and marketplace address: the feed behind sale history, volume charts, and last-sale prices.
* **NFT Collection Metadata** is the label layer: join `token_address` to attach a collection's name, symbol, and contract type to any trade, holding, or transfer row.
### Building a collection dashboard
A typical collection page needs sale history and the current holder set, labeled with collection metadata. The trades feed answers sale history and volume directly:
```sql theme={null}
-- Recent sales for a collection, newest first.
SELECT t.block_number,
t.token_id,
t.seller_address,
t.buyer_address,
t.price,
t.price_token_address,
t.marketplace_address,
t.tx_hash
FROM recipe_nft_trades.fact_nft_trades AS t FINAL
WHERE t.chain_id = 1
AND t.token_address = lower('0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D')
ORDER BY t.block_number DESC
LIMIT 50;
```
The current holder set comes from the ownership view: read the latest non-zero holding per `(token_id, wallet)` with a sign-aware aggregate over `FINAL`:
```sql theme={null}
-- Current owners of a collection (latest non-zero holding per token_id + wallet).
SELECT token_id,
wallet_address,
argMax(contract_type, (block_number, log_index)) AS contract_type,
argMax(amount, (block_number, log_index)) AS current_amount
FROM recipe_nft_owners_by_contract.fact_nft_owners_by_contract FINAL
WHERE chain_id = 1
AND token_address = lower('0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D')
GROUP BY token_id, wallet_address
HAVING current_amount != '0' AND current_amount != ''
ORDER BY token_id, wallet_address;
```
Label either result with a collection row from the metadata sync (latest deploy wins, defensive against CREATE2 re-deploys):
```sql theme={null}
SELECT token_address,
argMax(name, (block_number, transaction_index)) AS name,
argMax(symbol, (block_number, transaction_index)) AS symbol,
argMax(contract_type, (block_number, transaction_index)) AS contract_type
FROM recipe_nft_collection_metadata.fact_nft_collection_metadata FINAL
WHERE chain_id = 1
AND token_address = lower('0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D')
GROUP BY token_address;
```
### Notes and considerations
* **Read canonical state correctly.** ClickHouse templates use the collapsing log-table pattern. Read with `FINAL` or a sign-aware aggregate (`argMax` over the latest `(block_number, log_index)`), never a bare `WHERE sign = 1`, which double-counts reorged rows.
* **No off-chain enrichment.** The trade and transfer arrays carry no marketplace human-name, no USD price, and no address labels. `price` is in `price_token_address` units; value it in USD by joining a Token Prices sync, and resolve marketplace/address names in your own application.
* **Ownership = current state.** NFT Owners by Contract and NFTs by Wallet keep the *latest* holding per key; filter to non-zero amounts to drop wallets that transferred out. For full history, read NFT Transfers or NFT Trades directly.
* **ERC-721 vs ERC-1155.** `contract_type` carries the discriminator. ERC-1155 `amount` can exceed 1 per `(token_id, wallet)`; raw `uint256` amounts are stored as text. Compare against `'0'`, don't assume a single-owner-per-token model.
* **Chains.** NFT Trades, Transfers, Owners by Contract, NFTs by Wallet, and Collection Metadata are chain-parametrized: point them at any supported EVM chain or Solana. Solana marketplace trades (Magic Eden, Tensor, and others) populate the same trade shape; trade identity is widened with `(seller, buyer, token_address, token_id)` to keep rows distinct where one instruction shares a `log_index`.
* **Scale and live tailing.** Run the ClickHouse path in `hybrid` mode to backfill collection history and then stay current, reorg-safe, at the chain head. For a chain-wide view across many collections, the by-collection and by-token-id prefixes keep reads scoped.
* **Pair with other templates.** Add [Token Prices](/data-feeds/templates/token/token-prices) to value trades in USD, and [Wallet History](/data-feeds/templates/wallet/wallet-history) for a per-wallet feed that already folds NFT transfers in alongside tokens and swaps.
### Get started
Start with the templates in this workflow, then follow the Quickstart to run them.
> [card] [Get started](/data-feeds/migration/quickstart)
>
> Build NFT marketplace and analytics data into your own infrastructure.
# Portfolio Tracking
Source: https://docs.moralis.com/data-feeds/use-cases/portfolio-tracking
A Data Feeds template bundle for portfolio apps, wallets, and dashboards: every token, native asset, and NFT a wallet holds, valued in USD, synced into your own database.
### Who it's for
Teams building **portfolio apps, wallets, and dashboards** need to show what a wallet holds right now and what it's worth. The goal is a current-holdings view you own: every token balance, native-asset balance, and NFT, each marked in USD, refreshed live at the chain head.
### The template bundle
This use case combines three balance templates, one per asset class, with **Token Prices** for valuation. Each balance template is keyed by wallet, so "everything wallet Y holds" is a single prefix scan.
| Template | Role in the portfolio |
| - | - |
| [Token Balances by Wallet](/data-feeds/templates/wallet/token-balances-by-wallet) | Every ERC-20 / SPL token a wallet holds, with its current balance: the core fungible-holdings table, keyed by wallet. |
| [Native Balances](/data-feeds/templates/wallet/native-balances) | The wallet's native-asset (gas-token) balance (ETH, BNB, SOL, etc.), tracked separately from tokens. |
| [NFTs by Wallet](/data-feeds/templates/wallet/nfts-by-wallet) | Every NFT a wallet holds: collection address, token ID, and ERC-721 / ERC-1155 type. |
| [Token Prices](/data-feeds/templates/token/token-prices) | The valuation join target: the latest USD/native mark per token used to value fungible holdings. |
> [!NOTE]
>
> Balances are tracked as **post-balance observations**: each template records the holder's balance *after* every transfer it was part of, so the latest observation per `(wallet, asset)` is the current balance. No periodic re-scan of the chain is needed.
### How the pieces fit
```text theme={null}
Token Balances by Wallet ──┐
Native Balances ──┼──► current holdings ◄── valued by ── Token Prices
NFTs by Wallet ──┘ (per wallet)
```
* **The three balance templates** each unpivot every transfer into per-wallet `(from, post-balance)` and `(to, post-balance)` observations. The latest observation per `(wallet, asset)`, `argMax` over `(block_number, log_index)`, is the live holding. Token and NFT balances are keyed by `(chain_id, wallet_address, token_address[, token_id])`; native balances drop `token_address` and tiebreak on `native_seq` (native transfers carry no `log_index`).
* **Token Prices** is the connective tissue: join each fungible balance to its token's latest mark to value the holding. The template ships a carry-forward `latest_token_price_dict`, so even quiet tokens keep their last on-chain mark: a single `dictGet` per token.
### Valuing a wallet's fungible holdings
Read the current non-zero token balances for a wallet, then value each against the latest USD mark from the Token Prices sync:
```sql theme={null}
SELECT b.token_address,
b.current_balance,
dictGetOrDefault(
'recipe_token_price_history.latest_token_price_dict', 'usd_price',
tuple(b.chain_id, b.token_address), '0') AS usd_price
FROM (
SELECT chain_id,
token_address,
argMax(balance, (block_number, log_index)) AS current_balance
FROM recipe_token_balances_by_wallet.fact_balances_by_wallet FINAL
WHERE chain_id = 1 AND wallet_address = lower('0x…')
GROUP BY chain_id, token_address
HAVING current_balance != '0' AND current_balance != ''
) AS b;
```
Scale `current_balance` by `10^token_decimals` before multiplying by `usd_price` to get a fully-scaled dollar value; source decimals from a Token Metadata sync. The native balance follows the same pattern against the Native Balances fact (tiebreak on `native_seq`), valued against a native-price feed.
### Notes and considerations
* **Read canonical state.** All three balance facts and Token Prices use the collapsing log-table pattern. Read with `FINAL` (then `argMax`) or a sign-aware aggregate, never a bare `WHERE sign = 1`, or unmerged reorg counter-rows will skew balances.
* **Decimals.** Balances are raw integer strings. Scale by `10^token_decimals` before displaying or valuing; pull decimals from a Token Metadata sync.
* **Chains.** Token Balances and Token Prices are chain-parametrized (EVM + Solana); set the chain env vars per sync. NFTs by Wallet is EVM (ERC-721 / ERC-1155).
* **Native vs token.** The native asset is not an ERC-20 and is tracked by its own template. Don't expect it in the token-balances table. Value it against a native-price mark, not the token-price dictionary.
* **Pair with other templates.** Add [Wallet History](/data-feeds/templates/wallet/wallet-history) for the chronological feed behind a holding, and [Token Approvals](/data-feeds/templates/wallet/token-approvals) to surface outstanding allowances in a wallet's security view.
* **Run mode.** Run the ClickHouse path in `hybrid` mode so balances backfill history and then stay current, reorg-safe, at the chain head.
### Get started
Start with the templates in this workflow, then follow the Quickstart to run them.
> [card] [Get started](/data-feeds/migration/quickstart)
>
> Build a live, valued portfolio view on your own infrastructure.
# Token Analytics
Source: https://docs.moralis.com/data-feeds/use-cases/token-analytics
A Data Feeds template bundle for tracking a token's distribution and activity (holders, balances, transfers, transfer counters, and every DEX trade), synced into your own database.
### Who it's for
Token and project teams, growth and analytics functions, and dashboards that need a live, owned view of **a token's distribution and activity**: who holds it, how it's spread, how much it moves, and how it trades. The output is a set of token-keyed tables in your own warehouse: the holder list and its balances, the full transfer log, per-token counters, and every DEX trade touching the token.
### The template bundle
All of these templates read the same Moralis-indexed, normalized per-block onchain data and key by token, so they compose into one token-centric view.
| Template | Role in the analytics view |
| - | - |
| [Token Holders](/data-feeds/templates/token/token-holders) | The holder list: every non-zero holder with their current balance and a best-effort USD value, derived from the absolute post-transfer balances. The "who owns it" leg. |
| [Token Balances by Token](/data-feeds/templates/token/token-balances-by-token) | The same holder balances without the in-block USD valuation: the lean distribution table when you don't need price enrichment. |
| [Token Stats](/data-feeds/templates/token/token-stats) | Per-token transfer counters: a reorg-safe rollup row per token, queried as one row for the full stats block. |
| [Token Transfers](/data-feeds/templates/token/token-transfers) | The flat transfer log: one row per ERC-20 transfer of the token, the raw activity feed every counter and balance derives from. |
| [Swaps by Token](/data-feeds/templates/markets/swaps-by-token) | Every DEX trade that touched the token, direct pool fills and aggregator-routed trades, USD-enriched in-block for volume and notional. |
> [!NOTE]
>
> **Token Holders is Token Balances by Token plus the USD valuation leg.** If you only need the distribution table (addresses and balances), run Token Balances by Token alone. Add Token Holders when you want the in-block USD spot price and `usd_value` folded onto each holding.
### How the pieces fit
```text theme={null}
Token Transfers ──┬──► Token Stats (per-token transfer counters)
├──► Token Balances by Token (latest balance per wallet)
└──► Token Holders (balances + in-block USD value)
Swaps by Token ──────► trade + volume feed (every DEX fill, USD-enriched)
```
* **Token Transfers** is the activity backbone: every movement of the token, one row each. It carries each side's absolute post-transfer balance, which is what makes the balance and holder views a latest-observation lookup rather than a running sum.
* **Token Stats** folds the transfer stream into a per-token counter row: the cheap, always-current "how many transfers" answer, and the pattern to extend with any future per-token metric.
* **Token Balances by Token** and **Token Holders** project the same transfers into the current balance per `(token, wallet)`; Token Holders adds the in-block USD spot price and best-effort `usd_value`.
* **Swaps by Token** is the market leg: trading activity and USD volume, separate from raw transfers, so you can split "moved" from "traded."
### Distribution + activity in one read
A token dashboard usually wants the headline numbers together: holder count, top holders, transfer count, and recent trading volume. Each comes from its own template's token-keyed table, read with `FINAL` or a sign-aware aggregate so reorgs are corrected.
**Top holders with USD value** (Token Holders: `FINAL` collapses reorg `±1` pairs before `argMax`):
```sql theme={null}
SELECT wallet_address,
argMax(balance, (block_number, log_index)) AS current_balance,
argMax(usd_price, (block_number, log_index)) AS usd_price
FROM recipe_token_holders.fact_token_holders FINAL
WHERE chain_id = 1 AND token_address = lower('0xA0b8...')
GROUP BY wallet_address
HAVING current_balance != '0' AND current_balance != ''
ORDER BY toFloat64OrZero(current_balance) DESC
LIMIT 100;
```
**Total transfer count** (Token Stats: `sum` is reorg-safe, the reverted block's `-1` rows cancel the original `+1`):
```sql theme={null}
SELECT sum(transfers_total) AS transfers_total
FROM recipe_token_stats.fact_token_stats
WHERE chain_id = 1 AND token_address = lower('0xA0b8...');
```
**24h DEX volume** (Swaps by Token: sign-aware, cheaper than `FINAL`):
```sql theme={null}
SELECT sumIf(toFloat64OrZero(notional_usd), sign = 1)
- sumIf(toFloat64OrZero(notional_usd), sign = -1) AS volume_usd
FROM recipe_swaps_by_token.fact_swaps_by_token
WHERE chain_id = 1
AND token_address = lower('0xA0b8...')
AND event_ts >= now() - INTERVAL 1 DAY;
```
Holder count is the same Token Holders table wrapped in a `count()` over the non-zero `argMax` balances; the raw activity behind any of these numbers is a scan of `recipe_token_transfers.fact_token_transfers` filtered to the token.
### Notes and considerations
* **Read canonical state correctly.** On ClickHouse, read with `FINAL` or a sign-aware aggregate (`sum`, `sumIf … sign`), never a bare `WHERE sign = 1`. The collapsing/summing log tables converge on canonical state on merge; a bare sign filter sees uncollapsed reorg rows.
* **Balances are observations, not deltas.** Token Holders and Token Balances by Token rely on the absolute `fromPostBalance` / `toPostBalance` carried on each transfer, so the current holding is just the latest observation per `(token, wallet)`: no reconstruction. The EVM zero address (mint/burn counterparty) is skipped.
* **Decimals and USD.** Token Holders' `usd_value` is a best-effort in-block mark using a fixed scale; for precise reporting, scale raw amounts by `10^token_decimals` from a Token Metadata sync and value against a Token Prices feed.
* **EVM + Solana.** These templates are chain-parametrized; set the Solana chain env vars to run the same shapes against Solana, where the event ids stay row-unique despite repeated `logIndex` within an instruction.
* **Run mode and scale.** Run the ClickHouse path in `hybrid` mode to backfill history and then tail the chain head, reorg-safe. A high-volume token's transfer and swap tables are large; scope chain-wide reads to a block or time range, and lean on the token-first sort key for prefix scans.
* **Pair with other templates.** Add [Token Prices](/data-feeds/templates/token/token-prices) for precise valuation and price history, and [Token Metadata](/data-feeds/templates/token/token-metadata) for decimals, name, and symbol on your dashboard.
### Get started
Start with the templates in this workflow, then follow the Quickstart to run them.
> [card] [Get started](/data-feeds/migration/quickstart)
>
> Track a token's holders, transfers, and trading in your own database.
# Trading & Charting
Source: https://docs.moralis.com/data-feeds/use-cases/trading-charting
A Data Feeds template bundle for trading terminals, charting UIs, and bots: every DEX trade per pool and per token, candles, live reserves, and USD marks, synced into your own database.
### Who it's for
Teams building **trading terminals, charting UIs, market-data backends, and trading bots** need live, owned market data keyed by pool/pair or by token. The goal is your own market-data store: every fill on a pool, every trade touching a token, OHLCV candles, current pool reserves, and a USD mark for every asset, all reorg-safe and current at the chain head.
### The template bundle
This use case combines the markets templates. **Swaps by Pair** is the trade backbone (one row per fill); **Pair OHLCV** is a downstream aggregation of that same trade ingest; **Swaps by Token** re-keys the trades for token-centric views; **Pair Reserves** and **Token Prices** add live state and valuation.
| Template | Role in the terminal |
| - | - |
| [Swaps by Pair](/data-feeds/templates/markets/swaps-by-pair) | The trade backbone: every fill on a pool/pair (direct pool fills and aggregator-routed trades), one row per trade, USD-enriched in-block. The "trade tape" for a pool. |
| [Swaps by Token](/data-feeds/templates/markets/swaps-by-token) | The same trades re-keyed by token: every trade that touched token X, found under either side of the pair. The token-centric tape. |
| [Pair OHLCV](/data-feeds/templates/markets/pair-ohlcv) | Time-bucketed open/high/low/close + volume + trade count per pool, built by aggregating the swap ingest into candles. |
| [Pair Reserves](/data-feeds/templates/markets/pair-reserves) | Current `reserve0` / `reserve1` per pool, read from each swap's pool post-balances: live depth without a running sum. |
| [Token Prices](/data-feeds/templates/token/token-prices) | USD/native mark history per token, plus a latest-mark dictionary for carry-forward valuation of quiet positions. |
> [!NOTE]
>
> **Swaps by Pair, Swaps by Token, and Pair OHLCV share one trade projection.** They are the same trade ingest shaped three ways: one row per fill keyed by pool, the same fills re-keyed by token, and those fills bucketed into candles. Pick the keys your screens read; you don't need all three if one access pattern covers your UI.
### How the pieces fit
```text theme={null}
┌──► Swaps by Pair (trade tape, by pool)
trade fills ────────┼──► Swaps by Token (trade tape, by token)
└──► Pair OHLCV (candles, by pool)
pool post-balances ──► Pair Reserves (live depth, by pool)
price updates ──► Token Prices (USD/native marks, by token)
```
* **The swap templates** all draw from the same normalized in-block trade events, direct pool fills (`tokenSwaps`) and aggregator-routed trades (`aggregateTokenSwaps`), so every fill lands exactly once. Key by pool for a pool's tape, by token for a token's tape.
* **Pair OHLCV** is a downstream aggregation of that ingest: the same trades land, then a candle surface buckets them per `(pool, hour)`. "Price" per fill is the bought-leg in-block USD mark; `volume` is summed notional; `trades` is the count.
* **Pair Reserves** reads the pool's absolute `token0PostBalance` / `token1PostBalance` from each swap, so current reserves are simply the latest observation per pair: live depth without reconstructing a running sum.
* **Token Prices** is the connective tissue for valuation: join any trade, balance, or position to the token's mark, and use the latest-mark dictionary to value quiet positions with no fresh update.
### Building a pool overview
A trading terminal's pool screen wants the live tape, the candles, the current depth, and a mark: each from its own template, keyed by the same pool. Read ClickHouse with `FINAL` or a sign-aware aggregate so reorg `±1` pairs collapse before you aggregate; never a bare `WHERE sign = 1`.
The trade tape for a pool, newest first:
```sql theme={null}
SELECT event_ts, side, source_kind,
token0_address, token1_address,
amount0, amount1, notional_usd, protocol
FROM recipe_swaps_by_pair.fact_swaps_by_pair FINAL
WHERE chain_id = 1
AND pool_address = lower('0x88e6A0c2dDD26FEEb64F039a2c41296FcB3f5640')
ORDER BY event_ts DESC
LIMIT 50;
```
The hourly candles backing the chart (fast sign-aware accelerator):
```sql theme={null}
SELECT bucket_start, open, high, low, close, volume, trades
FROM recipe_pair_ohlcv.candles
WHERE chain_id = 1
AND pool_address = lower('0x88e6A0c2dDD26FEEb64F039a2c41296FcB3f5640')
ORDER BY bucket_start DESC
LIMIT 24;
```
The current depth (latest reserves; `FINAL` collapses reorg pairs before `argMax`):
```sql theme={null}
SELECT pair_address,
argMax(reserve0, (block_number, log_index)) AS reserve0,
argMax(reserve1, (block_number, log_index)) AS reserve1
FROM recipe_pair_reserves.fact_pair_reserves FINAL
WHERE chain_id = 1
AND pair_address = lower('0x88e6A0c2dDD26FEEb64F039a2c41296FcB3f5640')
GROUP BY pair_address;
```
And the latest USD mark for either side, via the Token Prices dictionary (O(1), refreshes every 30–60s, no fresh trade required):
```sql theme={null}
SELECT dictGetOrDefault(
'recipe_token_price_history.latest_token_price_dict', 'usd_price',
tuple(1, lower('0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2')), '0'
) AS usd_price;
```
For a token's market overview across all its pools, swap `fact_swaps_by_pair` for `recipe_swaps_by_token.fact_swaps_by_token` keyed on `token_address`.
### Notes and considerations
* **EVM + Solana.** The trade, candle, reserve, and price templates are chain-parametrized. On Solana, repeated `logIndex` within one instruction means the pool-fill `vendor_event_id` should be widened (e.g. with the token addresses/amounts) to keep rows distinct; the candle math is chain-agnostic.
* **One trade, two pool addresses.** A fill observed both as a direct pool fill (`pairAddress`) and as part of an aggregator route (`aggregatorAddress`) appears under both; they are distinct events by design. `source_kind` (`pool_fill` vs `aggregator`) tells them apart.
* **USD is in-block only.** Trades, candles, and notional are enriched from same-block `tokenPriceUpdates`. No cross-block carry-forward. Illiquid or brand-new tokens with no in-block mark leave `price_usd` / `notional_usd` `NULL` (and produce candle gaps for that hour). For valuing quiet positions, use the Token Prices latest-mark dictionary, which carries the last on-chain mark forward.
* **OHLCV is fixed 1-hour and trade-reconstructed.** Candles are built from on-chain swap fills, so they can differ slightly from a DEX's own reported OHLC. For other intervals, re-bucket the trade ingest. Use `candles` for the fast accelerator and `candles_exact` (over `fact_swaps FINAL`) when post-reorg precision on high/low matters; `volume` and `trades` are sign-weighted and always exact.
* **Reserves need an in-window swap.** Current reserves come from swap post-balances, so a pool appears only if it had at least one swap with resolved post-balances in the ingested window. Quiet pools have unchanged reserves by definition. Widen the window to pick them up.
* **Run ClickHouse in `hybrid` for live terminals.** It backfills history then hands off to a seamless, reorg-safe realtime tail at the chain head. Postgres/MySQL are first-class for historical backfill; the trade templates expand many rows per block, so live/reorg-safe ingestion is ClickHouse-only.
* **Pair with other bundles.** Add [Swaps by Wallet](/data-feeds/templates/markets/swaps-by-wallet) for per-user trade history, or see [Token Analytics](/data-feeds/use-cases/token-analytics) and [Portfolio Tracking](/data-feeds/use-cases/portfolio-tracking) for adjacent template bundles.
### Get started
Start with the templates in this workflow, then follow the Quickstart to run them.
> [card] [Get started](/data-feeds/migration/quickstart)
>
> Build a live, owned market-data backend.
# Get Your API Key
Source: https://docs.moralis.com/get-started/get-your-api-key
Learn how to get your Moralis API Key
To start using Moralis products, you’ll need an API key to authenticate your requests.
Follow this quick guide to create your account and retrieve your API key - then you'll be ready to make your [first request](/data-api/first-request).
## 1. Create Your Account
Create your **Moralis account** by visiting the [Moralis Dashboard](https://admin.moralis.com/register).

> [!TIP]
>
> Moralis doesn't have a self-serve free plan. To try it before you subscribe, request a free trial and the team will reach out.
>
> Request a free trial
## 2. Navigate to Data APIs
Once registered, navigate to the [Data APIs section](https://admin.moralis.com/data-api) in the dashboard.

## 3. Copy Your API Key
Click the **copy** icon next to your API key to add it to your clipboard.

## 4. Manage API keys (optional)
You can also manage your keys from the **API Keys** section - including creating new keys or rotating existing ones.

That's it - you're now ready to make your [first API request](/data-api/first-request)
# Global API Reference
Source: https://docs.moralis.com/get-started/global-api-reference
This is a single, consolidated quick-reference catalog of the Moralis Data API endpoints.
A unified API to fetch balances, transfers, DeFi positions, PnL, NFTs, and fully decoded wallet activity across multiple chains.
### EVM Wallet API
A comprehensive suite of wallet-focused endpoints: balances, history, DeFi positions, PnL, approvals, and identity resolution.
| Endpoint | Description |
| :- | :- |
| [Wallet History](/data-api/evm/wallet/wallet-history) | Complete decoded activity feed for a wallet. |
| [Wallet Transactions](/data-api/evm/wallet/wallet-transactions) | Raw transaction list for a wallet. |
| [Decoded Transactions](/data-api/evm/wallet/decoded-transactions) | Human-readable transaction data and summaries. |
| [Token Balances](/data-api/evm/wallet/token-balances) | Current ERC-20 holdings for a wallet. |
| [Token Balances (Legacy)](/data-api/evm/wallet/token-balances-legacy) | Legacy token balance endpoint. |
| [Token Transfers](/data-api/evm/wallet/token-transfers) | ERC-20 transfer history for a wallet. |
| [Native Balance](/data-api/evm/wallet/native-balance) | Native currency balance for a wallet. |
| [Native Balances (Batch)](/data-api/evm/wallet/native-balances-batch) | Native balances for multiple wallets. |
| [NFT Balances](/data-api/evm/wallet/nft-balances) | Current NFT holdings for a wallet. |
| [NFT Collections](/data-api/evm/wallet/nft-collections) | NFT collections held by a wallet. |
| [NFT Transfers](/data-api/evm/wallet/nft-transfers) | NFT transfer history for a wallet. |
| [NFT Trades](/data-api/evm/wallet/nft-trades-by-wallet) | NFT trade history for a wallet. |
| [Net Worth](/data-api/evm/wallet/net-worth) | Total wallet value in USD. |
| [Wallet P\&L](/data-api/evm/wallet/wallet-pnl) | Profit / loss calculated per token. |
| [Wallet P\&L Summary](/data-api/evm/wallet/wallet-pnl-summary) | Aggregated profit / loss summary. |
| [Wallet Stats](/data-api/evm/wallet/wallet-stats) | General wallet statistics. |
| [Wallet Swaps](/data-api/evm/wallet/wallet-swaps) | DEX swap history for a wallet. |
| [Approvals](/data-api/evm/wallet/approvals) | Token approval / allowance data for a wallet. |
| [Chain Activity](/data-api/evm/wallet/chain-activity) | Multi-chain activity summary for a wallet. |
| [Wallet Protocols](/data-api/evm/wallet/wallet-protocols) | Summary of DeFi protocols used by a wallet. |
| [Wallet Positions](/data-api/evm/wallet/wallet-positions) | DeFi positions per protocol. |
| [Detailed Positions](/data-api/evm/wallet/detailed-positions) | Enhanced DeFi position breakdown. |
| [ENS Lookup](/data-api/evm/wallet/ens-lookup) | Resolve an ENS name to an address. |
| [Resolve Address](/data-api/evm/wallet/resolve-address) | Reverse-resolve an address to an ENS name. |
### EVM Token API
The most powerful Token API in Web3 — fetch, analyse, and monitor ERC-20 tokens across multiple chains, covering prices, balances, transfers, liquidity, holders, volume, profitability, and advanced safety signals.
#### Prices
| Endpoint | Description |
| :- | :- |
| [Token Price](/data-api/evm/token/prices/token-price) | Get real-time and historical price for a token. |
| [Token Prices (Batch)](/data-api/evm/token/prices/token-prices-batch) | Get prices for multiple tokens in one call. |
| [OHLC Candlesticks](/data-api/evm/token/prices/ohlc) | Get historical OHLC (Open-High-Low-Close) data. |
#### Transfers
| Endpoint | Description |
| :- | :- |
| [Token Transfers](/data-api/evm/token/transfers/token-transfers) | Get transfer history by wallet or token contract. |
#### Metadata
| Endpoint | Description |
| :- | :- |
| [Token Metadata](/data-api/evm/token/metadata/token-metadata) | Get token details including name, symbol, and logo. |
| [Token Score](/data-api/evm/token/metadata/token-score) | Get safety / quality score for a token. |
| [Token Score Timeseries](/data-api/evm/token/metadata/token-score-timeseries) | Historical token score data over time. |
#### Pairs & Swaps
| Endpoint | Description |
| :- | :- |
| [Token Pairs](/data-api/evm/token/swaps/token-pairs) | Get DEX trading pairs, reserves, and liquidity data. |
| [Pair Stats](/data-api/evm/token/swaps/pair-stats) | Get stats for a specific DEX pair. |
| [Pair Swaps](/data-api/evm/token/swaps/pair-swaps) | Get recent swaps for a specific pair. |
| [Token Swaps](/data-api/evm/token/swaps/token-swaps) | Get swap history for a token. |
#### Holders
| Endpoint | Description |
| :- | :- |
| [Token Holders](/data-api/evm/token/holders/token-holders) | Get current holders of a token. |
| [Token Holder Stats](/data-api/evm/token/holders/token-holder-stats) | Get holder distribution and statistics. |
#### Discovery
| Endpoint | Description |
| :- | :- |
| [Token Categories](/data-api/evm/token/discovery/token-categories) | Get available token categories. |
#### Signals
| Endpoint | Description |
| :- | :- |
| [Top Traders](/data-api/evm/token/signals/top-traders) | Get top profitable traders for a token. |
### EVM NFT API
Everything needed to build NFT experiences: metadata, ownership, transfers, sales, rarity, floor prices, and marketplace activity.
#### Collections
| Endpoint | Description |
| :- | :- |
| [NFT Collections by Wallet](/data-api/evm/nft/collections/nft-collections-by-wallet) | Get NFT collections held by a wallet. |
| [NFTs by Collection](/data-api/evm/nft/collections/nfts-by-collection) | Get all NFTs in a collection. |
| [NFTs by Wallet](/data-api/evm/nft/collections/nfts-by-wallet) | Get all NFTs owned by a wallet. |
#### Metadata
| Endpoint | Description |
| :- | :- |
| [NFT Metadata](/data-api/evm/nft/metadata/nft-metadata) | Get metadata for a specific NFT. |
| [NFT Metadata (Batch)](/data-api/evm/nft/metadata/nft-metadata-batch) | Get metadata for multiple NFTs. |
| [Collection Metadata](/data-api/evm/nft/metadata/collection-metadata) | Get collection-level metadata. |
| [Collection Metadata (Batch)](/data-api/evm/nft/metadata/collection-metadata-batch) | Get metadata for multiple collections. |
| [Collection Stats](/data-api/evm/nft/metadata/collection-stats) | Get statistics for a collection. |
#### Ownership
| Endpoint | Description |
| :- | :- |
| [Owners by Contract](/data-api/evm/nft/ownership/owners-by-contract) | List all owners of a collection. |
| [Owners by Token ID](/data-api/evm/nft/ownership/owners-by-token-id) | Get owner(s) of a specific NFT. |
#### Prices
| Endpoint | Description |
| :- | :- |
| [Collection Floor Price](/data-api/evm/nft/prices/collection-floor-price) | Current floor price for a collection. |
| [Floor Price by Token ID](/data-api/evm/nft/prices/floor) | Floor price for a specific token. |
| [Historical Floor Price](/data-api/evm/nft/prices/historical-floor-price) | Floor price history for a collection. |
| [Sale Price by Contract](/data-api/evm/nft/prices/sale-price-by-contract) | Last sale prices for a collection. |
| [Sale Price by Token ID](/data-api/evm/nft/prices/sale-price-by-token-id) | Last sale price for a specific NFT. |
#### Trades
| Endpoint | Description |
| :- | :- |
| [Collection Trades](/data-api/evm/nft/trades/collection-trades) | Recent sales for a collection. |
| [Trades by Token ID](/data-api/evm/nft/trades/trades-by-token-id) | Trade history for a specific NFT. |
#### Transfers
| Endpoint | Description |
| :- | :- |
| [Collection Transfers](/data-api/evm/nft/transfers/collection-transfers) | Transfer history for a collection. |
| [Token ID Transfers](/data-api/evm/nft/transfers/token-id-transfers) | Transfer history for a specific NFT. |
#### Traits
| Endpoint | Description |
| :- | :- |
| [NFTs by Traits](/data-api/evm/nft/traits/nfts-by-traits) | Filter NFTs by trait values. |
| [Traits by Collection](/data-api/evm/nft/traits/traits-by-collection) | Get all traits for a collection. |
| [Traits by Collection (Paginated)](/data-api/evm/nft/traits/traits-by-collection-paginated) | Paginated trait data for a collection. |
#### Utilities
| Endpoint | Description |
| :- | :- |
| [Resync NFT Metadata](/data-api/evm/nft/utilities/resync-nft-metadata) | Trigger a metadata refresh for an NFT. |
| [Resync NFT Traits](/data-api/evm/nft/utilities/resync-nft-traits) | Trigger a traits refresh for a collection. |
### EVM DeFi API
Track DeFi positions, balances, rewards, and protocol interactions with enriched, protocol-aware data.
| Endpoint | Description |
| :- | :- |
| [Wallet Protocols](/data-api/evm/defi/wallet-protocols) | Summary of protocols used by a wallet. |
| [Wallet Positions](/data-api/evm/defi/wallet-positions) | Detailed positions per protocol. |
| [Detailed Positions](/data-api/evm/defi/wallet-positions-detailed) | Enhanced position breakdown. |
### EVM Price API
Dedicated APIs to fetch comprehensive historical and real-time token and NFT price data.
| Endpoint | Description |
| :- | :- |
| [Token Price](/data-api/evm/price/token-price) | Get real-time price for a token. |
| [Token Prices (Batch)](/data-api/evm/price/token-prices-batch) | Get prices for multiple tokens. |
| [OHLC Candlesticks](/data-api/evm/price/ohlc) | Get historical OHLC data. |
| [Collection Floor Price](/data-api/evm/price/collection-floor-price) | Current floor price for an NFT collection. |
| [Timeseries Floor Price](/data-api/evm/price/timeseries-floor-price) | Historical floor price data. |
| [Token ID Floor Price](/data-api/evm/price/token-id-floor-price) | Floor price for a specific token ID. |
| [Sale Prices by Collection](/data-api/evm/price/sale-prices-by-collection) | Sale prices for NFTs in a collection. |
| [Sale Price by Token ID](/data-api/evm/price/sale-price-by-token-id) | Last sale price for a specific NFT. |
### EVM Blockchain API
Core block-level data, logs, and internal transactions for EVM chains.
| Endpoint | Description |
| :- | :- |
| [Address Transactions](/data-api/evm/blockchain/address-transactions) | Get transactions for an address. |
| [Address Transactions (Decoded)](/data-api/evm/blockchain/address-transactions-decoded) | Get decoded transactions for an address. |
| [Block by Hash](/data-api/evm/blockchain/block-by-hash) | Retrieve a block by its hash. |
| [Block by Date](/data-api/evm/blockchain/block-by-date) | Retrieve the closest block to a given date. |
| [Latest Block](/data-api/evm/blockchain/latest-block) | Get the latest block number. |
| [Transaction by Hash](/data-api/evm/blockchain/transaction-by-hash) | Get a transaction by its hash. |
| [Transaction by Hash (Decoded)](/data-api/evm/blockchain/transaction-by-hash-decoded) | Get a decoded transaction by its hash. |
### Solana API
#### Solana Wallet API
| Endpoint | Description |
| :- | :- |
| [Native Balance](/data-api/solana/wallet/native-balance) | Get the native SOL balance for a wallet. |
| [Token Balances](/data-api/solana/wallet/token-balances) | Get SPL token balances for a wallet. |
| [Wallet Swaps](/data-api/solana/wallet/wallet-swaps) | Get swap transactions for a wallet. |
| [Wallet Portfolio](/data-api/solana/wallet/portfolio) | Get complete portfolio overview for a wallet. |
| [NFT Balances](/data-api/solana/wallet/nft-balances) | Get NFT balances for a wallet. |
#### Solana Token API
**Metadata & Scores**
| Endpoint | Description |
| :- | :- |
| [Token Metadata](/data-api/solana/token/token-metadata) | Get metadata for an SPL token. |
| [Token Metadata (Batch)](/data-api/solana/token/token-metadata-batch) | Get metadata for multiple SPL tokens. |
| [Token Score](/data-api/solana/token/token-score) | Get safety / quality score for a token. |
| [Token Score Timeseries](/data-api/solana/token/token-score-timeseries) | Historical token score data. |
**Prices**
| Endpoint | Description |
| :- | :- |
| [Token Price](/data-api/solana/token/prices/token-price) | Get real-time price for a Solana token. |
| [Token Prices (Batch)](/data-api/solana/token/prices/token-prices-batch) | Get prices for multiple Solana tokens. |
| [OHLC Candlesticks](/data-api/solana/token/prices/ohlc) | Get OHLC price data for a Solana token. |
**Pairs & Swaps**
| Endpoint | Description |
| :- | :- |
| [Token Pairs](/data-api/solana/token/pairs/token-pairs) | Get DEX pairs for a Solana token. |
| [Pair Stats](/data-api/solana/token/pairs/pair-stats) | Get stats for a specific pair. |
| [Pair Swaps](/data-api/solana/token/pairs/pair-swaps) | Get recent swaps for a pair. |
| [Token Swaps](/data-api/solana/token/swaps/token-swaps) | Get swap history for a token. |
| [Wallet Swaps](/data-api/solana/token/swaps/wallet-swaps) | Get swap history for a wallet. |
**Market Metrics**
| Endpoint | Description |
| :- | :- |
| [Token Analytics](/data-api/solana/token/market-metrics/token-analytics) | Get market analytics for a token. |
| [Token Analytics (Batch)](/data-api/solana/token/market-metrics/token-analytics-batch) | Get analytics for multiple tokens. |
| [Token Analytics Timeseries](/data-api/solana/token/market-metrics/token-analytics-timeseries) | Historical analytics data. |
**Discovery**
| Endpoint | Description |
| :- | :- |
| [Token Search](/data-api/solana/token/search-and-discovery/token-search) | Search for Solana tokens by name or symbol. |
#### Solana NFT API
| Endpoint | Description |
| :- | :- |
| [NFT Metadata](/data-api/solana/nft/nft-metadata) | Get metadata for a Solana NFT. |
#### Solana Price API
| Endpoint | Description |
| :- | :- |
| [Token Price](/data-api/solana/price/token-price) | Get real-time price for a Solana token. |
| [Token Prices (Batch)](/data-api/solana/price/token-prices-batch) | Get prices for multiple Solana tokens. |
| [OHLC Candlesticks](/data-api/solana/price/ohlc) | Get OHLC price data for a Solana token. |
### Universal API
Cross-chain data covering token analytics, entity data, and market metrics.
#### Token API
| Endpoint | Description |
| :- | :- |
| [Token Analytics](/data-api/universal/token/analytics/token-analytics) | Get cross-chain analytics for a token. |
| [Token Analytics (Multi)](/data-api/universal/token/analytics/token-analytics-multi) | Get analytics for multiple tokens. |
| [Token Analytics Timeseries](/data-api/universal/token/analytics/token-analytics-timeseries) | Historical cross-chain analytics. |
| [Token Score](/data-api/universal/token/score/token-score) | Get cross-chain safety / quality score. |
| [Token Score Timeseries](/data-api/universal/token/score/token-score-timeseries) | Historical token score data. |
| [Token Search](/data-api/universal/token/search/token-search) | Search tokens across all chains. |
| [Trending Tokens](/data-api/universal/token/trending-tokens) | Get currently trending tokens. |
#### Entity API
| Endpoint | Description |
| :- | :- |
| [Entity Search](/data-api/universal/entity/endpoints/entity-search) | Search for known entities (exchanges, protocols, etc.). |
| [Entity by ID](/data-api/universal/entity/endpoints/entity-by-id) | Get entity details by ID. |
| [Entity by Category](/data-api/universal/entity/endpoints/entity-by-category) | Get entities filtered by category. |
| [Entity Categories](/data-api/universal/entity/endpoints/entity-categories) | List all entity categories. |
### Streams API
Real-time blockchain event streaming via webhooks. Create and manage streams that push decoded blockchain data to your backend.
#### Stream Management
| Endpoint | Description |
| :- | :- |
| [Create Stream](/streams/api-reference/streams/create-streams) | Create a new stream. |
| [Get Streams](/streams/api-reference/streams/get-streams) | List all streams. |
| [Get Stream by ID](/streams/api-reference/streams/get-stream-by-id) | Get a specific stream. |
| [Update Stream](/streams/api-reference/streams/update-stream) | Update stream configuration. |
| [Update Stream Status](/streams/api-reference/streams/update-stream-status) | Pause or resume a stream. |
| [Delete Stream](/streams/api-reference/streams/delete-stream) | Delete a stream. |
| [Duplicate Stream](/streams/api-reference/streams/duplicate-stream) | Clone an existing stream. |
#### Address Management
| Endpoint | Description |
| :- | :- |
| [Add Address](/streams/api-reference/streams/add-address-to-stream) | Add an address to a stream. |
| [Get Addresses](/streams/api-reference/streams/get-addresses-by-stream) | List addresses on a stream. |
| [Replace Address](/streams/api-reference/streams/replace-address-on-stream) | Replace an address on a stream. |
| [Delete Address](/streams/api-reference/streams/delete-address-from-stream) | Remove an address from a stream. |
#### History & Replay
| Endpoint | Description |
| :- | :- |
| [Get History](/streams/api-reference/history/get-history) | Get webhook delivery history. |
| [Get Logs](/streams/api-reference/history/get-logs) | Get stream processing logs. |
| [Replay History](/streams/api-reference/history/replay-history) | Replay missed webhook deliveries. |
#### Project Settings
| Endpoint | Description |
| :- | :- |
| [Get Project Settings](/streams/api-reference/project/get-project-settings) | Get current project settings. |
| [Set Project Settings](/streams/api-reference/project/set-project-settings) | Update project settings. |
#### Statistics
| Endpoint | Description |
| :- | :- |
| [Get Stats](/streams/api-reference/stats/get-stats) | Get global stream statistics. |
| [Get Stats by Stream](/streams/api-reference/stats/get-stats-by-stream) | Get statistics for a specific stream. |
#### Webhook Data
| Endpoint | Description |
| :- | :- |
| [Get Webhook Data by Block](/streams/api-reference/streams/get-webhook-data-by-block-number) | Get webhook payload for a specific block. |
| [Send Webhook Data by Block](/streams/api-reference/streams/send-webhook-data-by-block-number) | Manually trigger webhook for a block. |
# Pricing
Source: https://docs.moralis.com/get-started/pricing
Moralis plans, compute units and rate limits. There is no self-serve free plan; request a free trial from the team on this page.
All Moralis plans come with generous monthly request limits. The number of included requests depends on your plan - see the [product pricing page](https://moralis.com/pricing) for details.
Moralis uses **Compute Units (CUs)** as a standard way to measure and bill for usage across all products - including [Data API](/data-api/overview), [Streams](/streams/overview), and [RPC Nodes](/rpc-nodes/overview).
CUs provide a unified way to account for **computational complexity** across every product, so usage is metered consistently regardless of which product you're using.
## Plan Overview
| Plan | Price | CUs Included | RPS | RPC Nodes | Archive Data |
| - | - | - | - | - | - |
| Starter | \$149/mo | 2,000,000/mo | 40 | 5 | Yes |
| Pro | \$249/mo | 100,000,000/mo | 80 | 20 | Yes |
| Business | \$749/mo | 500,000,000/mo | 200 | Unlimited | Yes |
| Enterprise | Custom | Custom | Custom | Unlimited | Yes |
Prices shown are for monthly billing. Annual billing is also available - see the [pricing page](https://moralis.com/pricing) for current rates.
[View all plans](https://moralis.com/pricing)
## Free Trial
Moralis doesn't have a self-serve free plan. If you want to try Moralis before you subscribe, request a free trial with the form below and the team will reach out to set you up.
## What is a Compute Unit?
A **Compute Unit (CU)** represents the relative computational cost of a request, task, or operation within the Moralis platform. Simple operations consume fewer CUs, while more complex or resource-intensive ones consume more.
For example:
* A basic wallet balance check may consume a small number of CUs.
* A multi-chain portfolio aggregation, or a high-frequency stream of on-chain events, may consume significantly more.
CUs ensure you're only billed for the resources you actually use - and that high-load workloads are fairly metered across the system.
## CU Cost
Each product applies CU-based billing differently. Generally:
* **CUs are deducted from your plan’s included quota**.
* **Usage beyond your quota is billed as overage**, at the per-million rate for your plan.
### Overage Rates
| Plan | Overage Rate |
| - | - |
| Starter | \$11.25 per million CUs |
| Pro | \$5 per million CUs |
| Business | \$4 per million CUs |
| Enterprise | Custom |
Overage applies once you exceed the CUs included in your plan. Higher plans carry a lower per-million rate, so sustained overage is usually a signal to upgrade.
Visit the individual pricing pages to see how CUs apply to each product:
* [Data API Pricing](/data-api/pricing)
* [Streams Pricing](/streams/pricing)
* [Nodes Pricing](/rpc-nodes/pricing)
## Dynamic Endpoints
Some API endpoints have **dynamic CU costs** that scale based on the scope of the request. Instead of a fixed cost per call, these endpoints charge a base CU amount multiplied by a variable factor such as the number of chains, wallets, or addresses involved.
For example:
* An endpoint costing **50 CUs per chain** that queries 3 chains will consume **150 CUs** total.
* An endpoint costing **250 CUs per chain** that queries 5 chains will consume **1,250 CUs** total.
Dynamic endpoints are clearly marked on their respective documentation pages. You can find CU costs for all endpoints on the individual product pricing pages listed above.
## RPS Throughput
Rate limits are enforced as **requests per second (RPS)**, separately from CU consumption. CUs meter how much you use, RPS caps how fast you can call.
Each plan defines a maximum request rate, evaluated over a rolling 4-second window. This allows short bursts as long as your total request count stays within the limit across that window. Exceeding it returns a **429 Too Many Requests** response.
See [Rate Limits](/data-api/resources/rate-limits) for the full breakdown.
Different products may apply throughput differently. Check the respective documentation for details.
# Quickstart Guides
Source: https://docs.moralis.com/get-started/quickstart-guides
Get up and running with Moralis APIs and services.
Choose a product to get started:
> [card] [Data API](/data-api/quickstart)
>
> Query blockchain data across 30+ chains with a unified API.
> [card] [Streams](/streams/quickstart)
>
> Receive real-time blockchain events via webhooks.
> [card] [RPC Nodes](/rpc-nodes/overview)
>
> Connect to blockchain nodes with reliable RPC endpoints.
> [card] [Data Feeds](/data-feeds/overview)
>
> Build custom indexes with SQL-based queries (Early Access).
> [card] [Auth API](/auth-api/overview)
>
> Authenticate users with wallet signatures.
# Supported Chains
Source: https://docs.moralis.com/get-started/supported-chains
Overview of all blockchain networks supported by Moralis across Data APIs, Streams and RPC.
### Supported ChainsMoralis supports a wide range of EVM and non-EVM blockchain networks across its product stack, including Data APIs, Streams, and RPC nodes.This page provides a **high-level view of chain coverage across Moralis**, helping you quickly understand:- Which chains are actively supported
- Which products are available per chain
- Where coverage may differ between productsUse the selector below to filter the table by product.⚠️**Moonbeam and Moonriver are deprecated.** Both chains stopped
producing new blocks on August 1, 2026, and Moralis support is removed on
**September 25, 2026**, following Moonbeam's network
relaunch on Base. GLMR and MOVR are now ERC-20 tokens on Base, so migrate to
the `base` chain parameter and export any history you still need
before that date. See the
[deprecation notice](/changelog#moonbeam-moonriver-and-lisk-support-ends-september-25-2026) for contract addresses and
details.⚠️**Lisk is deprecated.** Moralis support for Lisk (
`0x46f`) is removed on **September 25, 2026**,
ahead of the Lisk Chain wind-down. Migrate to the `eth` or
`base` chain parameter and export any history you still need
before that date. See the
[deprecation notice](/changelog#moonbeam-moonriver-and-lisk-support-ends-september-25-2026)
for the full timeline.
Showing chain
.
\
Chain Name
\
Type
\
Chain ID
\
Data API
\
Streams
\
Datashare
\
RPC Nodes
\
Auth API
\
For product-specific details, see the dedicated supported-chains pages below\.Related pages:- [Data API Supported Chains](/data-api/supported-chains)
- [Streams Supported Chains](/streams/supported-chains)
- [RPC Node Supported Chains](/rpc-nodes/supported-chains)
# How to Authenticate Users with Coinbase Wallet
Source: https://docs.moralis.com/get-started/tutorials/auth-api/authenticate-users-with-coinbase-wallet
This tutorial will teach you how to add secure Web3 Moralis authentication to your NextJS application by walking you through creating a full-stack Web3 authentication solution using the popular NextJS framework.
## Before Starting
You can start this tutorial if you already have a NextJS dapp with [MetaMask sign-in](/get-started/tutorials/auth-api/authenticate-users-with-meta-mask) functionality.
## Configuring the Coinbase Wallet Connector
1. Open the `pages/signin.jsx` file and add `CoinbaseWalletConnector` as a connector to `connectAsync()`:
```javascript theme={null}
import { CoinbaseWalletConnector } from 'wagmi/connectors/coinbaseWallet'
import { signIn } from 'next-auth/react'
import { useAccount, useConnect, useSignMessage, useDisconnect } from 'wagmi'
import { useRouter } from 'next/router'
import { useAuthRequestChallengeEvm } from '@moralisweb3/next'
function SignIn() {
const { connectAsync } = useConnect()
const { disconnectAsync } = useDisconnect()
const { isConnected } = useAccount()
const { signMessageAsync } = useSignMessage()
const { push } = useRouter()
const { requestChallengeAsync } = useAuthRequestChallengeEvm()
const handleAuth = async () => {
if (isConnected) {
await disconnectAsync()
}
const { account, chain } = await connectAsync({
connector: new CoinbaseWalletConnector({
options: {
appName: 'amazing.finance',
},
}),
})
const userData = { address: account, chain: chain.id, network: 'evm' }
const { message } = await requestChallengeAsync(userData)
const signature = await signMessageAsync({ message })
// redirect user after success authentication to '/user' page
const { url } = await signIn('moralis-auth', {
message,
signature,
redirect: false,
callbackUrl: '/user',
})
/**
* instead of using signIn(..., redirect: "/user")
* we get the url from callback and push it to the router to avoid page refreshing
*/
push(url)
}
return (
Web3 Authentication
)
}
export default SignIn
```
## Testing the Coinbase Wallet Connector
Visit [`http://localhost:3000/signin`](http://localhost:3000/signin) to test authentication.
1. Click on `Authenticate via Coinbase Wallet`
2. Connect Coinbase Wallet
3. Sign the message
4. After successful authentication, you will be redirected to the `/user` page
5. Visit [`http://localhost:3000/user`](http://localhost:3000/user) to test the user session's functionality:
* When a user is authenticated, we show the user's info on the page.
* When a user is not authenticated, we redirect to the `/signin` page.
* When a user is authenticated, we show the user's info on the page, even refreshing after the page. ([***`Explanation: After Web3 wallet authentication, the next-auth library creates a session cookie with an encrypted JWT [JWE] stored inside. It contains session info [such as an address and signed message] in the user's browser.`***](https://jwt.io/introduction))
# How to Authenticate Users with Magic.Link
Source: https://docs.moralis.com/get-started/tutorials/auth-api/authenticate-users-with-magic-link
This tutorial will teach you how to add secure Web3 Moralis authentication to your NextJS application by walking you through the task of creating a full-stack Web3 authentication solution using the popular NextJS framework.
## Before Starting
You can start this tutorial if you already have a NextJS dapp with [MetaMask sign-in](/get-started/tutorials/auth-api/authenticate-users-with-meta-mask) functionality.
## Installing the Magic Connector
[WAGMI Magic Connector](https://www.npmjs.com/package/@everipedia/wagmi-magic-connector) - the easiest way to add [Magic.Link authentication](https://magic.link/auth) for dapps using [wagmi](https://wagmi.sh/):
```bash npm2yarn theme={null}
npm install @everipedia/wagmi-magic-connector
```
## Configuring the Magic Connector
1. Open the`pages/signin.jsx` file and add `MagicConnector` as a connector to the `useConnect()` hook:
```javascript theme={null}
import { MagicAuthConnector } from "@everipedia/wagmi-magic-connector";
import { signIn } from "next-auth/react";
import { useAccount, useConnect, useSignMessage, useDisconnect } from "wagmi";
import { useRouter } from "next/router";
import { useAuthRequestChallengeEvm } from "@moralisweb3/next";
function SignIn() {
const { connectAsync } = useConnect({
connector: new MagicAuthConnector({
options: {
apiKey: "YOUR_MAGIC_LINK_API_KEY", //required
},
}),
});
const { disconnectAsync } = useDisconnect();
const { isConnected } = useAccount();
const { signMessageAsync } = useSignMessage();
const { requestChallengeAsync } = useAuthRequestChallengeEvm();
const { push } = useRouter();
const handleAuth = async () => {
if (isConnected) {
await disconnectAsync();
}
const { account } = await connectAsync();
const { message } = await requestChallengeAsync({
address: account,
chainId: "0x1",
});
const signature = await signMessageAsync({ message });
// redirect user after success authentication to '/user' page
const { url } = await signIn("moralis-auth", {
message,
signature,
redirect: false,
callbackUrl: "/user",
});
/**
* instead of using signIn(..., redirect: "/user")
* we get the url from callback and push it to the router to avoid page refreshing
*/
push(url);
};
return (
Web3 Authentication
);
}
export default SignIn;
```
## Testing the WalletConnect Connector
Visit [`http://localhost:3000/signin`](http://localhost:3000/signin) to test authentication.
1. Click on `Authenticate via Magic.Link`
2. Enter your email
3. Verify the login from your email
4. After successful authentication, you will be redirected to the `/user` page
5. Visit [`http://localhost:3000/user`](http://localhost:3000/user) to test the user session's functionality:
* When a user is authenticated, we show the user's info on the page.
* When a user is not authenticated, we redirect to the `/signin` page.
* When a user is authenticated, we show the user's info on the page, even refreshing after the page. ([***`Explanation: After Web3 wallet authentication, the next-auth library creates a session cookie with an encrypted JWT [JWE] stored inside. It contains session info [such as an address and signed message] in the user's browser.`***](https://jwt.io/introduction))
# How to Authenticate Users with MetaMask
Source: https://docs.moralis.com/get-started/tutorials/auth-api/authenticate-users-with-meta-mask
## Introduction
This tutorial demonstrates how to create a NextJS application that allows users to log in using their Web3 wallets.
After Web3 wallet authentication, the [**next-auth**](https://next-auth.js.org/) library creates a session cookie with an encrypted [**JWT**](https://jwt.io/introduction) (**JWE**) stored inside. It contains session info (such as an address, signed message, and expiration time) in the user's browser. It's a secure way to store users' info without a database, and it's impossible to read/modify the **JWT** without a [secret key](https://next-auth.js.org/configuration/options#secret).
Once the user is logged in, they will be able to visit a page that displays all their user data.
You can find the repository with the final code [here](https://github.com/MoralisWeb3/demo-apps/tree/main/nextjs_moralis_auth).
> [!NOTE]
>
> You can find the final dapp with implemented style on our [GitHub](https://github.com/MoralisWeb3/Moralis-JS-SDK/tree/beta/demos/nextjs).
## Prerequisites
1. Create a [Moralis account](https://www.moralis.io).
2. Install and set up [Visual Studio](https://code.visualstudio.com/).
3. Create your NextJS dapp (you can create it using [**create-next-app**](https://nextjs.org/docs/api-reference/create-next-app) or follow the **NextJS dapp** tutorial).
## Install the Required Dependencies
1. Install `moralis` and `@moralisweb3/next` (if not installed) and `next-auth`dependencies:
```bash npm2yarn theme={null}
npm install moralis @moralisweb3/next next-auth
```
2. To implement authentication using a Web3 wallet (e.g., MetaMask), we need to use a Web3 library. For the tutorial, we will use [wagmi](https://wagmi.sh/docs/getting-started). So, install the `wagmi` dependency:
```bash npm2yarn theme={null}
npm install wagmi viem
```
3. Add new environment variables in your `.env.local` file in the app root:
* **APP\_DOMAIN**: RFC 4501 DNS authority that is requesting the signing.
* **MORALIS\_API\_KEY**: You can get it [here](https://admin.moralis.com/account/profile).
* **NEXTAUTH\_URL**: Your app address. In the development stage, use [`http://localhost:3000`](http://localhost:3000).
* **NEXTAUTH\_SECRET**: Used for encrypting JWT tokens of users. You can put any value here or generate it on [`https://generate-secret.now.sh/32`](https://generate-secret.now.sh/32). Here's an `.env.local` example:
```text .env.local theme={null}
APP_DOMAIN=amazing.finance
MORALIS_API_KEY=xxxx
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=7197b3e8dbee5ea6274cab37245eec212
```
> [!WARNING]
>
> Keep your `NEXTAUTH_SECRET` value in secret to prevent security problems.\
> \
> Every time you modify the `.env.local` file, you need to restart your dapp.
## Wrapping App with `WagmiConfig` and `SessionProvider`
4. Create the `pages/_app.jsx` file. We need to wrap our pages with `WagmiConfig` ([docs](https://wagmi.sh/docs/WagmiConfig)) and `SessionProvider` ([docs](https://next-auth.js.org/getting-started/client#sessionprovider)):
```javascript theme={null}
import { createConfig, configureChains, WagmiConfig } from "wagmi";
import { publicProvider } from "wagmi/providers/public";
import { SessionProvider } from "next-auth/react";
import { mainnet } from "wagmi/chains";
const { publicClient, webSocketPublicClient } = configureChains(
[mainnet],
[publicProvider()]
);
const config = createConfig({
autoConnect: true,
publicClient,
webSocketPublicClient,
});
function MyApp({ Component, pageProps }) {
return (
);
}
export default MyApp;
```
> [!NOTE]
>
> NextJS uses the `App` component to initialize pages. You can override it and control the page initialization. Check out the [NextJS docs](https://nextjs.org/docs/advanced-features/custom-app).
## Configure Next-Auth and MoralisNextAuth
5. Create a new file, `pages/api/auth/[...nextauth].js`, with the following content:
> [tab] Tab
>
> ```javascript Javascript theme={null}
> import NextAuth from "next-auth";
> import { MoralisNextAuthProvider } from "@moralisweb3/next";
>
> export default NextAuth({
> providers: [MoralisNextAuthProvider()],
> // adding user info to the user session object
> callbacks: {
> async jwt({ token, user }) {
> if (user) {
> token.user = user;
> }
> return token;
> },
> async session({ session, token }) {
> session.user = token.user;
> return session;
> },
> },
> });
> ```
> [tab] Tab
>
> ```typescript theme={null}
> import NextAuth from "next-auth";
> import { MoralisNextAuthProvider } from "@moralisweb3/next";
>
> export default NextAuth({
> providers: [MoralisNextAuthProvider()],
> // adding user info to the user session object
> callbacks: {
> async jwt({ token, user }) {
> if (user) {
> token.user = user;
> }
> return token;
> },
> async session({ session, token }) {
> (session as { user: unknown }).user = token.user;
> return session;
> },
> },
> });
> ```
6. Add an authenticating config to the `pages/api/moralis/[...moralis].ts`:
```javascript theme={null}
import { MoralisNextApi } from "@moralisweb3/next";
export default MoralisNextApi({
apiKey: process.env.MORALIS_API_KEY,
authentication: {
domain: "amazing.dapp",
uri: process.env.NEXTAUTH_URL,
timeout: 120,
},
});
```
## Create Sign-In Page
7. Create a new page file, `pages/signin.jsx`, with the following content:
```javascript theme={null}
function SignIn() {
return (
);
}
export default SignIn;
```
## Secure Authentication after Signing and Verifying the Signed Message
10. Return to the `pages/signin.jsx` file. Let's add the `next-auth` authentication:
```javascript theme={null}
import { MetaMaskConnector } from "wagmi/connectors/metaMask";
import { signIn } from "next-auth/react";
import { useAccount, useConnect, useSignMessage, useDisconnect } from "wagmi";
import { useRouter } from "next/router";
import { useAuthRequestChallengeEvm } from "@moralisweb3/next";
function SignIn() {
const { connectAsync } = useConnect();
const { disconnectAsync } = useDisconnect();
const { isConnected } = useAccount();
const { signMessageAsync } = useSignMessage();
const { requestChallengeAsync } = useAuthRequestChallengeEvm();
const { push } = useRouter();
const handleAuth = async () => {
if (isConnected) {
await disconnectAsync();
}
const { account, chain } = await connectAsync({
connector: new MetaMaskConnector(),
});
const { message } = await requestChallengeAsync({
address: account,
chainId: chain.id,
});
const signature = await signMessageAsync({ message });
// redirect user after success authentication to '/user' page
const { url } = await signIn("moralis-auth", {
message,
signature,
redirect: false,
callbackUrl: "/user",
});
/**
* instead of using signIn(..., redirect: "/user")
* we get the url from callback and push it to the router to avoid page refreshing
*/
push(url);
};
return (
Web3 Authentication
);
}
export default SignIn;
```
## Showing the User Profile
11. Let's create a user page, `pages/user.jsx`, with the following content:
```javascript theme={null}
import { getSession, signOut } from "next-auth/react";
// gets a prop from getServerSideProps
function User({ user }) {
return (
User session:
{JSON.stringify(user, null, 2)}
);
}
export async function getServerSideProps(context) {
const session = await getSession(context);
// redirect if not authenticated
if (!session) {
return {
redirect: {
destination: "/signin",
permanent: false,
},
};
}
return {
props: { user: session.user },
};
}
export default User;
```
## Testing the MetaMask Wallet Connector
Visit [`http://localhost:3000/signin`](http://localhost:3000/signin`) to test the authentication.
1. Click on the `Authenticate via Metamask` button:
2. Connect the MetaMask wallet
3. Sign the message
4. After successful authentication, you will be redirected to the `/user` page
5. Visit [`http://localhost:3000/user`](http://localhost:3000/user`) to test the user session functionality:
* When a user authenticates, we show the user's info on the page.
* When a user is not authenticated, we redirect to the `/signin` page.
* When a user is authenticated, we show the user's info on the page, even refreshing after the page.
* (**Explanation:** [*****`After Web3 wallet authentication, the next-auth library creates a session cookie with an encrypted JWT (JWE) stored inside. It contains session info [such as an address and signed message] in the user's browser.)`*****](https://jwt.io/introduction)
*
# How to Authenticate Users with MetaMask using Angular
Source: https://docs.moralis.com/get-started/tutorials/auth-api/authenticate-users-with-meta-mask-using-angular
Learn how Moralis authentication works and see how to add secure authentication to your Angular dapp. This tutorial covers how to create full-stack Web3 authentication using the popular Angular framework.
## Introduction
This tutorial demonstrates how to create an Angular application that allows users to log in using their Web3 wallets.
After Web3 wallet authentication, the server creates a session cookie with a signed [JWT](https://jwt.io/introduction) stored inside. It contains session info (such as an address, signed message) in the user's browser.
Once the user is logged in, they will be able to visit a page that displays all their user data.
## Prerequisites
1. Follow the Your First Dapp - Angular tutorial to set up your Angular dapp and server
## Install the Required Dependencies
To implement authentication using a Web3 wallet (e.g., MetaMask), we will use a Web3 library. For the tutorial, we will use [@wagmi/core](https://github.com/wagmi-dev/wagmi/tree/main/packages/core).
1. Install `@wagmi/core`, `@wagmi/connectors`, `viem@2.x`, and `axios` dependencies.
```bash npm2yarn theme={null}
npm install @wagmi/core @wagmi/connectors viem@2.x
```
2. Generate an environment file for our Angular app:
```bash npm2yarn theme={null}
ng generate environments
```
3. Open `src/environments/environment.ts` and `src/environments/environment.prod.ts` - add a variable of `SERVER_URL` for our server.
```typescript theme={null}
export const environment = {
SERVER_URL: "http://localhost:3000",
};
```
4. We will generate two components (pages) - `/signin` (to authenticate) and `/user` (to show the user profile):
```shell theme={null}
ng generate component signin
ng generate component user
```
5. Open `src/app/app.routes.ts`, add these two components as routes:
```typescript theme={null}
import { SigninComponent } from "./signin/signin.component";
import { UserComponent } from "./user/user.component";
const routes: Routes = [
{ path: "signin", component: SigninComponent },
{ path: "user", component: UserComponent },
];
```
## Initial Setup
We will do an initial setup of our `/signin` and `/user` pages to make sure they work before integrating with our server.
1. Open `src/app/signin/signin.component.html` and replace the contents with:
```typescript theme={null}
Web3 Authentication
```
2. Open `src/app/signin/signin.component.ts` and add an empty `handleAuth` function below `ngOnInit(): void {}`:
```typescript theme={null}
ngOnInit(): void {}
async handleAuth() {}
```
3. Run `npm run start` and open [`http://localhost:4200/signin`](http://localhost:4200/signin) in your browser. It should look like:
4. Import `NgIf` in `src/app/user/user.component.ts`:
```typescript theme={null}
import { Component } from "@angular/core";
import { NgIf } from "@angular/common"; // Import NgIf
@Component({
selector: "app-user",
standalone: true,
imports: [NgIf], // Include NgIf in the imports array
templateUrl: "./user.component.html",
styleUrls: ["./user.component.css"],
})
export class UserComponent {}
```
5. Open `src/app/user/user.component.html` and replace the contents with:
```typescript theme={null}
User session:
{{ session }}
```
6. Open `src/app/user/user.component.ts` and add the variable we used above and an empty `signOut()` function:
```typescript theme={null}
session = '';
ngOnInit(): void {}
async signOut() {}
```
## Server Setup
Now we will update our server's `index.js` for the code we need for authentication. In this demo, cookies will be used for the user data.
1. Install the required dependencies for our server:
```shell theme={null}
npm install cookie-parser jsonwebtoken dotenv
```
2. Create a file called `.env` in your server's root directory (where `package.json` is):
* **APP\_DOMAIN**: RFC 4501 DNS authority that is requesting the signing.
* **MORALIS\_API\_KEY**: You can get it [here](https://admin.moralis.com/account/profile).
* **ANGULAR\_URL**: Your app address. By default Angular uses [`http://localhost:4200`](http://localhost:4200/).
* **AUTH\_SECRET**: Used for signing JWT tokens of users. You can put any value here or generate it on [`https://generate-secret.now.sh/32`](https://generate-secret.now.sh/32). Here's an `.env` example:
```
APP_DOMAIN=localhost
MORALIS_API_KEY=xxxx
ANGULAR_URL=http://localhost:4200
AUTH_SECRET=1234
```
3. Open `index.js`. We will create a `/request-message` endpoint for making requests to `Moralis.Auth` to generate a unique message (Angular will use this endpoint on the `/signin` page):
```javascript theme={null}
// to use our .env variables
require("dotenv").config();
// for our server's method of setting a user session
const cookieParser = require("cookie-parser");
const jwt = require("jsonwebtoken");
const config = {
domain: process.env.APP_DOMAIN,
statement: "Please sign this message to confirm your identity.",
uri: process.env.ANGULAR_URL,
timeout: 60,
};
app.post("/request-message", async (req, res) => {
const { address, chain } = req.body;
try {
const message = await Moralis.Auth.requestMessage({
address,
chain,
...config,
});
res.status(200).json(message);
} catch (error) {
res.status(400).json({ error: error.message });
console.error(error);
}
});
```
4. We will create a `/verify` endpoint for verifying the signed message from the user. After the user successfully verifies, they will be redirected to the `/user` page where their info will be displayed.
```javascript theme={null}
app.post("/verify", async (req, res) => {
try {
const { message, signature } = req.body;
const { address, profileId } = (
await Moralis.Auth.verify({
message,
signature,
networkType: "evm",
})
).raw;
const user = { address, profileId, signature };
// create JWT token
const token = jwt.sign(user, process.env.AUTH_SECRET);
// set JWT cookie
res.cookie("jwt", token, {
httpOnly: true,
});
res.status(200).json(user);
} catch (error) {
res.status(400).json({ error: error.message });
console.error(error);
}
});
```
5. We will create an `/authenticate` endpoint for checking the JWT cookie we previously set to allow the user access to the `/user` page:
```javascript theme={null}
app.get("/authenticate", async (req, res) => {
const token = req.cookies.jwt;
if (!token) return res.sendStatus(403); // if the user did not send a jwt token, they are unauthorized
try {
const data = jwt.verify(token, process.env.AUTH_SECRET);
res.json(data);
} catch {
return res.sendStatus(403);
}
});
```
6. Lastly we will create a `/logout` endpoint for removing the cookie.
```javascript theme={null}
app.get("/logout", async (req, res) => {
try {
res.clearCookie("jwt");
return res.sendStatus(200);
} catch {
return res.sendStatus(403);
}
});
```
Your final `index.js` should look like this:
```javascript theme={null}
const Moralis = require("moralis").default;
const express = require("express");
const cors = require("cors");
const cookieParser = require("cookie-parser");
const jwt = require("jsonwebtoken");
require("dotenv").config();
const app = express();
const port = 3000;
app.use(express.json());
app.use(cookieParser());
// allow access to Angular app domain
app.use(
cors({
origin: process.env.ANGULAR_URL,
credentials: true,
})
);
const config = {
domain: process.env.APP_DOMAIN,
statement: "Please sign this message to confirm your identity.",
uri: process.env.ANGULAR_URL,
timeout: 60,
};
// request message to be signed by client
app.post("/request-message", async (req, res) => {
const { address, chain } = req.body;
try {
const message = await Moralis.Auth.requestMessage({
address,
chain,
...config,
});
res.status(200).json(message);
} catch (error) {
res.status(400).json({ error: error.message });
console.error(error);
}
});
// verify message signed by client
app.post("/verify", async (req, res) => {
try {
const { message, signature } = req.body;
const { address, profileId } = (
await Moralis.Auth.verify({
message,
signature,
networkType: "evm",
})
).raw;
const user = { address, profileId, signature };
// create JWT token
const token = jwt.sign(user, process.env.AUTH_SECRET);
// set JWT cookie
res.cookie("jwt", token, {
httpOnly: true,
});
res.status(200).json(user);
} catch (error) {
res.status(400).json({ error: error.message });
console.error(error);
}
});
// verify JWT cookie to allow access
app.get("/authenticate", async (req, res) => {
const token = req.cookies.jwt;
if (!token) return res.sendStatus(403); // if the user did not send a jwt token, they are unauthorized
try {
const data = jwt.verify(token, process.env.AUTH_SECRET);
res.json(data);
} catch {
return res.sendStatus(403);
}
});
// remove JWT cookie
app.get("/logout", async (req, res) => {
try {
res.clearCookie("jwt");
return res.sendStatus(200);
} catch {
return res.sendStatus(403);
}
});
const startServer = async () => {
await Moralis.start({
apiKey: process.env.MORALIS_API_KEY,
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
};
startServer();
```
7. Run `npm run start` to make sure your server runs without immediate errors.
```shell theme={null}
node index.js
```
## Bringing It All Together
Now we will finish setting up our Angular pages to integrate with our server.
1. Open `src/app/signin/signin.component.ts`. Add our required imports:
```typescript theme={null}
import { Component } from "@angular/core";
// for navigating to other routes
import { Router } from "@angular/router";
// for making HTTP requests
import axios from "axios";
import {
connect,
disconnect,
getAccount,
injected,
signMessage,
} from "@wagmi/core";
import { http, createConfig } from "@wagmi/core";
import { mainnet, sepolia } from "@wagmi/core/chains";
import { environment } from "../../environments/environment";
```
2. Add this code to set up the Wagmi client:
```typescript theme={null}
export const config = createConfig({
chains: [mainnet, sepolia],
transports: {
[mainnet.id]: http(),
[sepolia.id]: http(),
},
});
```
3. Replace our empty `handleAuth()` function with the following:
```typescript theme={null}
async handleAuth() {
const { isConnected } = getAccount(config);
if (isConnected) await disconnect(config); //disconnects the web3 provider if it's already active
const provider = await connect(config, { connector: injected() }); // enabling the web3 provider metamask
const userData = {
address: provider.accounts[0],
chain: provider.chainId,
};
const { data } = await axios.post(
`${environment.SERVER_URL}/request-message`,
userData
);
const message = data.message;
const signature = await signMessage(config, { message });
await axios.post(
`${environment.SERVER_URL}/verify`,
{
message,
signature,
},
{ withCredentials: true } // set cookie from Express server
);
// redirect to /user
this.router.navigateByUrl('/user');
}
```
4. The full `signin.component.ts` should look like:
```typescript theme={null}
import { Component } from "@angular/core";
// for navigating to other routes
import { Router } from "@angular/router";
// for making HTTP requests
import axios from "axios";
import {
connect,
disconnect,
getAccount,
injected,
signMessage,
} from "@wagmi/core";
import { http, createConfig } from "@wagmi/core";
import { mainnet, sepolia } from "@wagmi/core/chains";
import { environment } from "../../environments/environment";
export const config = createConfig({
chains: [mainnet, sepolia],
transports: {
[mainnet.id]: http(),
[sepolia.id]: http(),
},
});
@Component({
selector: "app-signin",
standalone: true,
imports: [],
templateUrl: "./signin.component.html",
styleUrl: "./signin.component.css",
})
export class SigninComponent {
constructor(private router: Router) {}
ngOnInit(): void {}
async handleAuth() {
const { isConnected } = getAccount(config);
if (isConnected) await disconnect(config); //disconnects the web3 provider if it's already active
const provider = await connect(config, { connector: injected() }); // enabling the web3 provider metamask
const userData = {
address: provider.accounts[0],
chain: provider.chainId,
};
const { data } = await axios.post(
`${environment.SERVER_URL}/request-message`,
userData
);
const message = data.message;
const signature = await signMessage(config, { message });
await axios.post(
`${environment.SERVER_URL}/verify`,
{
message,
signature,
},
{ withCredentials: true } // set cookie from Express server
);
// redirect to /user
this.router.navigateByUrl("/user");
}
}
```
5. Open `src/app/user/user.component.ts`. Add our required imports:
```typescript theme={null}
import { Router } from "@angular/router";
import axios from "axios";
import { environment } from "../../environments/environment";
```
6. Replace `ngOnInit(): void {}` with:
```typescript theme={null}
async ngOnInit() {
try {
const { data } = await axios.get(
`${environment.SERVER_URL}/authenticate`,
{
withCredentials: true,
}
);
const { iat, ...authData } = data; // remove unimportant iat value
this.session = JSON.stringify(authData, null, 2); // format to be displayed nicely
} catch (err) {
// if user does not have a "session" token, redirect to /signin
this.router.navigateByUrl('/signin');
}
}
```
7. Replace our empty `signOut()` function with the following:
```typescript theme={null}
async signOut() {
await axios.get(`${environment.SERVER_URL}/logout`, {
withCredentials: true,
});
this.router.navigateByUrl('/signin');
}
```
8. The full `user.component.ts` should look like:
```typescript theme={null}
import { Component } from "@angular/core";
import { NgIf } from "@angular/common"; // Import NgIf
import { Router } from "@angular/router";
import axios from "axios";
import { environment } from "../../environments/environment";
@Component({
selector: "app-user",
standalone: true,
imports: [NgIf], // Include NgIf in the imports array
templateUrl: "./user.component.html",
styleUrls: ["./user.component.css"],
})
export class UserComponent {
constructor(private router: Router) {}
session = "";
async ngOnInit() {
try {
const { data } = await axios.get(
`${environment.SERVER_URL}/authenticate`,
{
withCredentials: true,
}
);
const { iat, ...authData } = data; // remove unimportant iat value
this.session = JSON.stringify(authData, null, 2); // format to be displayed nicely
} catch (err) {
// if user does not have a "session" token, redirect to /signin
this.router.navigateByUrl("/signin");
}
}
async signOut() {
await axios.get(`${environment.SERVER_URL}/logout`, {
withCredentials: true,
});
this.router.navigateByUrl("/signin");
}
}
```
If you get errors related to default imports, open your `tsconfig.app.json` file and add `"allowSyntheticDefaultImports": true` under `compilerOptions`:
```json theme={null}
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"outDir": "./out-tsc/app",
"types": []
}
```
## Testing the MetaMask Wallet Connector
Visit [`http://localhost:4200/signin`](http://localhost:4200/signin) to test the authentication.
1. Click on the `Authenticate via MetaMask` button
2. Connect the MetaMask wallet and sign the message
3. After successful authentication, you will be redirected to the `/user` page
* When a user authenticates, we show the user's info on the page.
* When a user is not authenticated, we redirect to the `/signin` page.
* When a user is authenticated, we show the user's info on the page, even refreshing after the page.
# How to Authenticate Users with MetaMask using Python and Django
Source: https://docs.moralis.com/get-started/tutorials/auth-api/authenticate-users-with-meta-mask-using-python-and-django
This tutorial will teach you how Moralis authentication works and demonstrates how to add secure authentication to your Django application by walking you through creating a full-stack Web3 authentication stack using the popular Django web framework.
## Introduction
In this tutorial, we show you how to create a full-stack Django app that allows users to log in using their Web3 wallets, and Django will create a session associated with the individual user. Once logged in, the user can visit a page that displays all their user data.
You can find the repository with the final code [here](https://github.com/MoralisWeb3/demo-apps/tree/main/django_moralis_auth).
## Prerequisites
1. Create a [Moralis account](https://admin.moralis.com/login).
2. Install Python 3 (in case you don't already have it). In this tutorial, we used Python 3.10 on a Windows system.
3. Basic Django knowledge ([Django documentation](https://docs.djangoproject.com/en/dev/intro/tutorial01/)).
## Installing Required Dependencies
1. Create a virtual environment if needed: `python3 -m venv django_web3_auth_env`.
2. Install `django` and `requests` dependencies. Django version 4.1 was used for this tutorial:
* `django_web3_auth_env\Scripts>pip3.10.exe install django`.
* `django_web3_auth_env\Scripts>pip3.10.exe install requests`.\
(These commands, for example, `pip3.10.exe install django`, are meant to be executed in that specific **Scripts** folder from that virtual environment.)
## Creating a Django Project and App
1. Create the Django project:
* `django_web3_auth_env\Scripts\django-admin startproject moralis_auth` and `django-admin` will be found in the `Scripts` folder: `django_web3_auth_env\Scripts\django-admin.exe`.
2. Create the Django app:
* `django_web3_auth_env\Scripts\python.exe manage.py startapp web3_auth`.
* You can move that newly created app folder named `web3_auth` into the same folder where the `moralis_auth` project is in - the same folder where `manage.py` is located.
3. Run database migrations:
* `django_web3_auth_env\Scripts\python.exe manage.py migrate`. Here, you will have to use the complete path that points to the Python executable in the newly created virtual environment.
4. Create a **super user** (it can be used in the Django admin interface); it is optional:
* `django_web3_auth_env\Scripts\python.exe manage.py createsuperuser`. Here, you will have to use the complete path that points to the Python executable in the new created virtual environment.
## Edit `moralis_auth` Project Settings
1. Add the newly created app named `web3_auth` to the list of installed apps in `settings.py` at the end of the `INSTALLED_APPS` list:
```python settings.py theme={null}
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'web3_auth'
]
```
2. Include URLs from the newly created app in the new project (here, we also added the URLs from `django.contrib.auth.urls` to be able to use the log-out functionality):
```python urls.py theme={null}
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('web3_auth/', include('web3_auth.urls')),
path('auth/', include('django.contrib.auth.urls')),
]
```
## Creating the Main *web3\_auth* Application (`urls.py`, `views.py`, and Templates)
1. The contents for `urls.py` (you will have to create this file):
```python urls.py theme={null}
from django.urls import path
from . import views
urlpatterns = [
path('moralis_auth', views.moralis_auth, name='moralis_auth'),
path('request_message', views.request_message, name='request_message'),
path('my_profile', views.my_profile, name='my_profile'),
path('verify_message', views.verify_message, name='verify_message')
]
```
* `moralis_auth` will contain the data from where a user can authenticate.
* `request_message` will make a request to the Moralis Auth API for a message to be signed.
* `my_profile` will show current profile info for a user when authenticated.
* `verify_message` will be used to verify a message that was signed.
2. The contents for `views.py` (you will need to set your Web3 API key on line nine \[`API_KEY = 'WEB3_API_KEY_HERE'`]):
```python views.py theme={null}
import json
import requests
from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from datetime import datetime, timedelta, timezone
API_KEY = 'WEB3_API_KEY_HERE'
# this is a check to make sure the API key was set
# you have to set the API key only in line 9 above
# you don't have to change the next line
if API_KEY == 'WEB3_API_KEY_HERE':
print("API key is not set")
raise SystemExit
def moralis_auth(request):
return render(request, 'login.html', {})
def my_profile(request):
return render(request, 'profile.html', {})
def request_message(request):
data = json.loads(request.body)
print(data)
#setting request expiration time to 1 minute after the present->
present = datetime.now(timezone.utc)
present_plus_one_m = present + timedelta(minutes=1)
expirationTime = str(present_plus_one_m.isoformat())
expirationTime = str(expirationTime[:-6]) + 'Z'
REQUEST_URL = 'https://authapi.moralis.io/challenge/request/evm'
request_object = {
"domain": "defi.finance",
"chainId": 1,
"address": data['address'],
"statement": "Please confirm",
"uri": "https://defi.finance/",
"expirationTime": expirationTime,
"notBefore": "2020-01-01T00:00:00.000Z",
"timeout": 15
}
x = requests.post(
REQUEST_URL,
json=request_object,
headers={'X-API-KEY': API_KEY})
return JsonResponse(json.loads(x.text))
def verify_message(request):
data = json.loads(request.body)
print(data)
REQUEST_URL = 'https://authapi.moralis.io/challenge/verify/evm'
x = requests.post(
REQUEST_URL,
json=data,
headers={'X-API-KEY': API_KEY})
print(json.loads(x.text))
print(x.status_code)
if x.status_code == 201:
# user can authenticate
eth_address=json.loads(x.text).get('address')
print("eth address", eth_address)
try:
user = User.objects.get(username=eth_address)
except User.DoesNotExist:
user = User(username=eth_address)
user.is_staff = False
user.is_superuser = False
user.save()
if user is not None:
if user.is_active:
login(request, user)
request.session['auth_info'] = data
request.session['verified_data'] = json.loads(x.text)
return JsonResponse({'user': user.username})
else:
return JsonResponse({'error': 'account disabled'})
else:
return JsonResponse(json.loads(x.text))
```
Here we have a view for the main authentication: `moralis_auth`; one view to display the profile info: `my_profile`; and two views specific to authentication: `request_message` and `verify_message`. Furthermore, `verify_message` will request a message from the Moralis Auth API that will be signed with MetaMask, and `verify_message` will validate the received signature and create a user when the validation succeeds. After that, a session is created for that user, and we can add additional info in that session, such as the data that was used specifically for authentication.
3. Templates (you will have to create a folder named templates):
* `login.html`, this template contains all the JavaScript code required to sign a message with MetaMask:
```html login.html theme={null}
Moralis Auth Django Demo
{% if user.is_authenticated %}
{% else %}
{% endif %}
```
* `profile.html`, this template only shows current info associated with an authenticated user:
```html profile.html theme={null}
Moralis Auth Django Profile Page Demo
{% if user.is_authenticated %}
Eth address: {{ user.username }}
Session auth info
{% for key,value in request.session.auth_info.items %}
{{key}}
{{ value }}
{% endfor %}
Verified user info
{% for key,value in request.session.verified_data.items %}
```
## Starting the Application
* `django_web3_auth_env\Scripts\python.exe manage.py runserver 1000` (this will start a local server on port **1000**).
After the application starts, this is how it should look when you access `http://127.0.0.1:1000/web3_auth/moralis_auth`
This will show when clicking on the above "login" button
After the message is signed and the authentication is successful, you can see the complete profile page:
# How to Authenticate Users with MetaMask using React
Source: https://docs.moralis.com/get-started/tutorials/auth-api/authenticate-users-with-meta-mask-using-react
Learn how Moralis authentication works and see how to add secure authentication to your React dapp. This tutorial covers how to create full-stack Web3 authentication using the popular React framework.
## Introduction
This tutorial demonstrates how to create a React app that allows users to log in using their Web3 wallets.
After Web3 wallet authentication, the server creates a session cookie with a signed [JWT](https://jwt.io/introduction) stored inside. It contains session info (such as an address, signed message) in the user's browser.
Once the user is logged in, they will be able to visit a page that displays all their user data.
## Prerequisites
1. Follow the Your First Dapp - React tutorial to set up your React dapp and server
## Install the Required Dependencies
To implement authentication using a Web3 wallet (e.g., MetaMask), we will use a Web3 library. For the tutorial, we will use [wagmi](https://wagmi.sh).
1. Install `wagmi` and `viem` in your React app:
```bash npm2yarn theme={null}
npm install wagmi viem
```
## Initial Setup
First we will add an environment variable that will be used when calling our API.
1. Create a file called `.env` in the root of your react project (where `package.json` is) and add:
```sh theme={null}
REACT_APP_SERVER_URL=http://localhost:4000
```
Next we will add the providers required for `wagmi`.
2. Open `src/App.js` and add our required imports:
```javascript theme={null}
import { createConfig, configureChains, WagmiConfig } from "wagmi";
import { publicProvider } from "wagmi/providers/public";
import { mainnet } from "wagmi/chains";
import Signin from "./signin";
import User from "./user";
```
3. We will add the client and providers, and update the routes for our `/signin` component (to be set up next):
```javascript theme={null}
const { publicClient, webSocketPublicClient } = configureChains(
[mainnet],
[publicProvider()]
);
const config = createConfig({
autoConnect: true,
publicClient,
webSocketPublicClient,
});
const router = createBrowserRouter([
{
path: "/signin",
element: ,
},
{
path: "/user",
element: ,
},
{
path: "/",
element:
Home Component
,
},
]);
function App() {
return (
);
}
export default App;
```
# Your full App.js file should look like this
```javascript theme={null}
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import { createConfig, configureChains, WagmiConfig } from "wagmi";
import { publicProvider } from "wagmi/providers/public";
import { mainnet } from "wagmi/chains";
import Signin from "./signin";
import User from "./user";
const { publicClient, webSocketPublicClient } = configureChains(
[mainnet],
[publicProvider()]
);
const config = createConfig({
autoConnect: true,
publicClient,
webSocketPublicClient,
});
const router = createBrowserRouter([
{
path: "/signin",
element: ,
},
{
path: "/user",
element: ,
},
{
path: "/",
element:
Home Component
,
},
]);
function App() {
return (
);
}
export default App;
```
## Server Setup
Back in our server directory we will update our server's `index.js` for the code we need for authentication. In this demo, cookies will be used for the user data.
1. Install the required dependencies for our server:
```shell theme={null}
npm install cookie-parser jsonwebtoken dotenv
```
2. Create a file called `.env` in your server's root directory (where `package.json` is):
* **APP\_DOMAIN**: RFC 4501 DNS authority that is requesting the signing.
* **MORALIS\_API\_KEY**: You can get it [here](https://admin.moralis.com/account/profile).
* **REACT\_URL**: Your app address. By default React uses [`http://localhost:3000`](http://localhost:3000).
* **AUTH\_SECRET**: Used for signing JWT tokens of users. You can put any value here or generate it on [`https://generate-secret.now.sh/32`](https://generate-secret.now.sh/32).
```
APP_DOMAIN=amazing.finance
MORALIS_API_KEY=xxxx
REACT_URL=http://localhost:3000
AUTH_SECRET=1234
```
3. Open `index.js`. We will create a `/request-message` endpoint for making requests to `Moralis.Auth` to generate a unique message (React will use this endpoint on the `/signin` page):
```javascript theme={null}
// to use our .env variables
require("dotenv").config();
app.use(express.json());
// for our server's method of setting a user session
const cookieParser = require("cookie-parser");
const jwt = require("jsonwebtoken");
const config = {
domain: process.env.APP_DOMAIN,
statement: "Please sign this message to confirm your identity.",
uri: process.env.REACT_URL,
timeout: 60,
};
app.post("/request-message", async (req, res) => {
const { address, chain, network } = req.body;
try {
const message = await Moralis.Auth.requestMessage({
address,
chain,
...config,
});
res.status(200).json(message);
} catch (error) {
res.status(400).json({ error: error.message });
console.error(error);
}
});
```
4. We will create a `/verify` endpoint for verifying the signed message from the user. After the user successfully verifies, they will be redirected to the `/user` page where their info will be displayed:
```javascript theme={null}
app.post("/verify", async (req, res) => {
try {
const { message, signature } = req.body;
const { address, profileId } = (
await Moralis.Auth.verify({
message,
signature,
networkType: "evm",
})
).raw;
const user = { address, profileId, signature };
// create JWT token
const token = jwt.sign(user, process.env.AUTH_SECRET);
// set JWT cookie
res.cookie("jwt", token, {
httpOnly: true,
});
res.status(200).json(user);
} catch (error) {
res.status(400).json({ error: error.message });
console.error(error);
}
});
```
5. We will create an `/authenticate` endpoint for checking the JWT cookie we previously set to allow the user access to the `/user` page:
```javascript theme={null}
app.get("/authenticate", async (req, res) => {
const token = req.cookies.jwt;
if (!token) return res.sendStatus(403); // if the user did not send a jwt token, they are unauthorized
try {
const data = jwt.verify(token, process.env.AUTH_SECRET);
res.json(data);
} catch {
return res.sendStatus(403);
}
});
```
6. Lastly we will create a `/logout` endpoint for removing the cookie:
```javascript theme={null}
app.get("/logout", async (req, res) => {
try {
res.clearCookie("jwt");
return res.sendStatus(200);
} catch {
return res.sendStatus(403);
}
});
```
Your final `index.js` should look like this:
```javascript theme={null}
const Moralis = require("moralis").default;
const express = require("express");
const cors = require("cors");
const cookieParser = require("cookie-parser");
const jwt = require("jsonwebtoken");
// to use our .env variables
require("dotenv").config();
const app = express();
const port = 4000;
app.use(express.json());
app.use(cookieParser());
// allow access to React app domain
app.use(
cors({
origin: "http://localhost:3000",
credentials: true,
})
);
const config = {
domain: process.env.APP_DOMAIN,
statement: "Please sign this message to confirm your identity.",
uri: process.env.REACT_URL,
timeout: 60,
};
// request message to be signed by client
app.post("/request-message", async (req, res) => {
const { address, chain, network } = req.body;
try {
const message = await Moralis.Auth.requestMessage({
address,
chain,
...config,
});
res.status(200).json(message);
} catch (error) {
res.status(400).json({ error: error.message });
console.error(error);
}
});
app.post("/verify", async (req, res) => {
try {
const { message, signature } = req.body;
const { address, profileId } = (
await Moralis.Auth.verify({
message,
signature,
networkType: "evm",
})
).raw;
const user = { address, profileId, signature };
// create JWT token
const token = jwt.sign(user, process.env.AUTH_SECRET);
// set JWT cookie
res.cookie("jwt", token, {
httpOnly: true,
});
res.status(200).json(user);
} catch (error) {
res.status(400).json({ error: error.message });
console.error(error);
}
});
app.get("/authenticate", async (req, res) => {
const token = req.cookies.jwt;
if (!token) return res.sendStatus(403); // if the user did not send a jwt token, they are unauthorized
try {
const data = jwt.verify(token, process.env.AUTH_SECRET);
res.json(data);
} catch {
return res.sendStatus(403);
}
});
app.get("/logout", async (req, res) => {
try {
res.clearCookie("jwt");
return res.sendStatus(200);
} catch {
return res.sendStatus(403);
}
});
const startServer = async () => {
await Moralis.start({
apiKey: process.env.MORALIS_API_KEY,
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
};
startServer();
```
## Bringing It All Together
Now we will finish setting up our React pages to integrate with our server.
1. In `src`, create a file called `signin.jsx` and add:
```javascript theme={null}
import { useNavigate } from "react-router-dom";
import { useAccount, useConnect, useSignMessage, useDisconnect } from "wagmi";
import { InjectedConnector } from "wagmi/connectors/injected";
import axios from "axios";
export default function SignIn() {
const navigate = useNavigate();
const { connectAsync } = useConnect();
const { disconnectAsync } = useDisconnect();
const { isConnected } = useAccount();
const { signMessageAsync } = useSignMessage();
const handleAuth = async () => {
//disconnects the web3 provider if it's already active
if (isConnected) {
await disconnectAsync();
}
// enabling the web3 provider metamask
const { account } = await connectAsync({
connector: new InjectedConnector(),
});
const userData = { address: account, chain: 1 };
// making a post request to our 'request-message' endpoint
const { data } = await axios.post(
`${process.env.REACT_APP_SERVER_URL}/request-message`,
userData,
{
headers: {
"content-type": "application/json",
},
}
);
const message = data.message;
// signing the received message via metamask
const signature = await signMessageAsync({ message });
await axios.post(
`${process.env.REACT_APP_SERVER_URL}/verify`,
{
message,
signature,
},
{ withCredentials: true } // set cookie from Express server
);
// redirect to /user
navigate("/user");
};
return (
Web3 Authentication
);
}
```
2. Inside `src`, create a new file called `user.jsx` and add:
```js theme={null}
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
export default function User() {
const navigate = useNavigate();
const [session, setSession] = useState({});
useEffect(() => {
axios(`${process.env.REACT_APP_SERVER_URL}/authenticate`, {
withCredentials: true,
})
.then(({ data }) => {
const { iat, ...authData } = data; // remove unimportant iat value
setSession(authData);
})
.catch((err) => {
navigate("/signin");
});
}, []);
async function signOut() {
await axios(`${process.env.REACT_APP_SERVER_URL}/logout`, {
withCredentials: true,
});
navigate("/signin");
}
return (
User session:
{JSON.stringify(session, null, 2)}
);
}
```
## Testing the MetaMask Wallet Connector
In your teminal run `npm run start` and visit [`http://localhost:3000/signin`](http://localhost:3000/signin) to test the authentication.
1. Click on the `Authenticate via MetaMask` button
2. Connect the MetaMask wallet and sign the message
3. After successful authentication, you will be redirected to the `/user` page
* When a user authenticates, we show the user's info on the page.
* When a user is not authenticated, we redirect to the `/signin` page.
* When a user is authenticated, we show the user's info on the page, even refreshing after the page.
# How to Authenticate Users with Particle Network
Source: https://docs.moralis.com/get-started/tutorials/auth-api/authenticate-users-with-particle-network
## What is Particle Network?
> [!TIP]
>
> Check the Particle Network [documentation website](https://docs.particle.network/) to get more information.
**Particle Network** is the Intent-Centric, Modular Access Layer of Web3. With Particle's [Smart Wallet-as-a-Service](https://blog.particle.network/announcing-our-smart-wallet-as-a-service-modular-stack-upgrading-waas-with-erc-4337/), developers can curate unparalleled user experience through modular and customizable EOA/AA embedded wallet components. By utilizing MPC-TSS for key management, Particle can streamline onboarding via familiar Web2 accounts—such as Google accounts, email addresses, and phone numbers.
## Prerequisites
### Next.js Dapp with MetaMask Sign-In
Before you begin this tutorial, make sure you have set up a Next.js decentralized application (Dapp) that includes MetaMask sign-in functionality. If you haven't integrated MetaMask sign-in yet, refer to the guide [How to Authenticate Users with MetaMask](/get-started/tutorials/auth-api/authenticate-users-with-meta-mask).
### Install Dependencies
To prepare for this tutorial, you'll need to install the following dependencies for Particle Connect:
* **@particle-network/connect-react-ui**: This package provides React UI components for Particle Connect. You can install it using npm or yarn.
```bash theme={null}
npm install @particle-network/connect-react-ui
```
or
```bash theme={null}
yarn add @particle-network/connect-react-ui
```
* **@particle-network/connect**: This package is essential for integrating Particle Connect into your Dapp. Install it using npm or yarn.
```bash theme={null}
npm install @particle-network/connect
```
or
```bash theme={null}
yarn add @particle-network/connect
```
* **@particle-network/chains**: This optional dependency is leveraged for handling blockchain chains within Particle Connect. You can install it using npm or yarn.
```bash theme={null}
npm install @particle-network/chains
```
or
```bash theme={null}
yarn add @particle-network/chains
```
With these prerequisites organized, you'll be fully prepared to smoothly integrate Particle Connect into your Next.js Dapp.
## Configure Particle Connect
Open the `pages/signin.jsx` file and restructure your code as shown below. This code utilizes Particle Connect's components and hooks for handling the connection process and wallet interactions.
```javascript theme={null}
import { useRouter } from 'next/router';
import { useEffect } from 'react';
import { useAccount, ConnectButton, useConnectKit, ModalProvider } from '@particle-network/connect-react-ui';
import { useAuthRequestChallengeEvm } from '@moralisweb3/next';
import { signIn } from 'next-auth/react';
import { Ethereum } from '@particle-network/chains';
import { evmWallets } from '@particle-network/connect';
import '@particle-network/connect-react-ui/dist/index.css';
export default function SignIn() {
const { requestChallengeAsync } = useAuthRequestChallengeEvm();
const { push } = useRouter();
const account = useAccount();
const connect = useConnectKit();
useEffect(() => {
if (account) {
(async () => {
const { message } = await requestChallengeAsync({
address: account,
chainId: '0x1',
});
const signature = await connect.particle.evm.personalSign(`0x${Buffer.from(message).toString('hex')}`); // Conversion to hex, then signing with connected Particle account (whether that be through Particle Auth or otherwise)
const result = await signIn("moralis-auth", {
message,
signature,
redirect: false,
callbackUrl: '/user',
});
if (result && result.url) {
push(result.url);
}
})();
}
}, [account]);
return (
Web3 Authentication
);
}
```
## Test Particle Connect
To test the authentication process with Particle Connect, follow these steps:
1. **Visit Sign-In Page**: Go to [`http://localhost:3000/signin`](http://localhost:3000/signin).
2. **Connect Wallet**: Click the "Connect Wallet" button to initiate the login process. You can choose to log in through Particle Auth or a supported Web3 (EVM) wallet.
3. **Select Sign-In Method**: Choose your preferred sign-in method from the options provided.
4. **Successful Authentication**: After successful authentication, you will be automatically redirected to the `/user` page.
5. **Test User Session**: Visit [`http://localhost:3000/user`](http://localhost:3000/user) to test the functionality of the user session:
* When a user is authenticated, their information will be displayed on the page.
* If a user is not authenticated, they will be redirected to the `/signin` page.
* Even after refreshing the page, the user's information will still be displayed. (***`Explanation: After Web3 wallet authentication, the next-auth library creates a session cookie with an encrypted [JWT] containing session information, stored in the user's browser.`***)
# How to Authenticate Users with Phantom Wallet
Source: https://docs.moralis.com/get-started/tutorials/auth-api/authenticate-users-with-phantom-wallet
This tutorial covers how to create full-stack Web3 authentication for the Phantom wallet, using the popular NextJS framework.
## Introduction
This tutorial shows you how to create a NextJS application that lets users log in using their Phantom wallet.
After Web3 wallet authentication, the [**next-auth**](https://next-auth.js.org/) library creates a session cookie with an encrypted [**JWT**](https://jwt.io/introduction) (**JWE**) stored inside. It contains session info (such as an address, signed message, and expiration time) in the user's browser. It's a secure way to store users' info without a database, and it's impossible to read/modify the **JWT** without a [secret key](https://next-auth.js.org/configuration/options#secret).
Once the user is logged in, they will be able to visit a page that displays all their user data.
> [!NOTE]
>
> You can find the final dapp with implemented style on our [GitHub](https://github.com/JohnVersus/nextjs_solana_auth_api/tree/moralisweb3-next-client-auth).
## Prerequisites
1. Create a [Moralis account](https://www.moralis.io).
2. Install and set up [Visual Studio](https://code.visualstudio.com/).
3. Create your NextJS dapp (you can create it using [**create-next-app**](https://nextjs.org/docs/api-reference/create-next-app) or follow the **NextJS dapp** tutorial).
## Install the Required Dependencies
1. Install `@moralisweb3/next` (if not installed), `next-auth` and `@web3uikit/core` dependencies:
```bash npm2yarn theme={null}
npm install @moralisweb3/next next-auth @web3uikit/core
```
2. To process data like the signature of a Solana Web3 wallet (e.g., Phantom), we need the `bs58` package to encode and decode data from the wallet. Let's install the `bs58` package:
```bash npm2yarn theme={null}
npm install bs58
```
3. Add new environment variables in your `.env.local` file in the app root:
* **APP\_DOMAIN**: RFC 4501 DNS authority that is requesting the signing.
* **MORALIS\_API\_KEY**: You can get it [here](https://admin.moralis.com/account/profile).
* **NEXTAUTH\_URL**: Your app address. In the development stage, use [`http://localhost:3000`](http://localhost:3000).
* **NEXTAUTH\_SECRET**: Used for encrypting JWT tokens of users. You can put any value here or generate it on [`https://generate-secret.now.sh/32`](https://generate-secret.now.sh/32). Here's an `.env.local` example:
```text .env.local theme={null}
APP_DOMAIN=amazing.finance
MORALIS_API_KEY=xxxx
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=7197b3e8dbee5ea6274cab37245eec212
```
> [!NOTE]
>
> Keep your `NEXTAUTH_SECRET` value in secret to prevent security problems.\
> \
> Every time you modify the `.env.local` file, you need to restart your dapp.
## Wrapping App with `SessionProvider`
4. Create the `pages/_app.jsx` file. We need to wrap our pages with `SessionProvider` ([docs](https://next-auth.js.org/getting-started/client#sessionprovider)):
```javascript theme={null}
import "../styles/globals.css";
import { SessionProvider } from "next-auth/react";
function MyApp({ Component, pageProps }) {
return (
);
}
export default MyApp;
```
> [!NOTE]
>
> NextJS uses the `App` component to initialize pages. You can override it and control the page initialization. Check out the [NextJS docs](https://nextjs.org/docs/advanced-features/custom-app).
## Configure Next-Auth and MoralisNextAuth
5. Create a new file, `pages/api/auth/[...nextauth].ts`, with the following content:
> [tab] Tab
>
> ```typescript theme={null}
> import NextAuth from "next-auth";
> import { MoralisNextAuthProvider } from "@moralisweb3/next";
>
> export default NextAuth({
> providers: [MoralisNextAuthProvider()],
> // adding user info to the user session object
> callbacks: {
> async jwt({ token, user }) {
> if (user) {
> token.user = user;
> }
> return token;
> },
> async session({ session, token }) {
> (session as { user: unknown }).user = token.user;
> return session;
> },
> },
> });
> ```
> [tab] Tab
>
> ```javascript Javascript theme={null}
> import NextAuth from "next-auth";
> import { MoralisNextAuthProvider } from "@moralisweb3/next";
>
> export default NextAuth({
> providers: [MoralisNextAuthProvider()],
> // adding user info to the user session object
> callbacks: {
> async jwt({ token, user }) {
> if (user) {
> token.user = user;
> }
> return token;
> },
> async session({ session, token }) {
> session.user = token.user;
> return session;
> },
> },
> });
> ```
6. Add an authenticating config to the `pages/api/moralis/[...moralis].ts`:
> [tab] Tab
>
> ```typescript [...moralis].ts theme={null}
> import { MoralisNextApi } from "@moralisweb3/next";
>
> const DATE = new Date();
> const FUTUREDATE = new Date(DATE);
> FUTUREDATE.setDate(FUTUREDATE.getDate() + 1);
>
> const { MORALIS_API_KEY, APP_DOMAIN, NEXTAUTH_URL } = process.env;
>
> if (!MORALIS_API_KEY || !APP_DOMAIN || !NEXTAUTH_URL) {
> throw new Error(
> "Missing env variables. Please add the required env variables."
> );
> }
>
> export default MoralisNextApi({
> apiKey: MORALIS_API_KEY,
> authentication: {
> timeout: 120,
> domain: APP_DOMAIN,
> uri: NEXTAUTH_URL,
> expirationTime: FUTUREDATE.toISOString(),
> statement: "Sign message to authenticate.",
> },
> });
> ```
> [tab] Tab
>
> ```typescript [...moralis].js theme={null}
> import { MoralisNextApi } from "@moralisweb3/next";
>
> const DATE = new Date();
> const FUTUREDATE = new Date(DATE);
> FUTUREDATE.setDate(FUTUREDATE.getDate() + 1);
>
> const { MORALIS_API_KEY, APP_DOMAIN, NEXTAUTH_URL } = process.env;
>
> if (!MORALIS_API_KEY || !APP_DOMAIN || !NEXTAUTH_URL) {
> throw new Error(
> "Missing env variables. Please add the required env variables."
> );
> }
>
> export default MoralisNextApi({
> apiKey: MORALIS_API_KEY,
> authentication: {
> timeout: 120,
> domain: APP_DOMAIN,
> uri: NEXTAUTH_URL,
> expirationTime: FUTUREDATE.toISOString(),
> statement: "Sign message to authenticate.",
> },
> });
> ```
## Create Wallet Component
7. Create a new file under `app/components/loginBtn/phantomBtn.tsx`:
> [tab] Tab
>
> ```typescript phantomBtn.tsx theme={null}
> import React from "react";
> import { Button } from "@web3uikit/core";
> import { signIn } from "next-auth/react";
> import base58 from "bs58";
> import { useAuthRequestChallengeSolana } from "@moralisweb3/next";
>
> export default function PhantomBtn() {
> const { requestChallengeAsync, error } = useAuthRequestChallengeSolana();
> const authenticate = async () => {
> // @ts-ignore
> const provider = window.phantom?.solana;
> const resp = await provider.connect();
> const address = resp.publicKey.toString();
> const chain = "devnet";
> const account = {
> address: address,
> chain: chain,
> network: "solana",
> };
> // const message = "Sign to provide access to app";
> const challenge = await requestChallengeAsync({
> address,
> network: "devnet",
> });
> const encodedMessage = new TextEncoder().encode(challenge?.message);
> const signedMessage = await provider.signMessage(encodedMessage, "utf8");
> const signature = base58.encode(signedMessage.signature);
> try {
> const authResponse = await signIn("moralis-auth", {
> message: challenge?.message,
> signature,
> network: "Solana",
> redirect: false,
> });
> if (authResponse?.error) {
> throw new Error(authResponse.error);
> }
> } catch (e) {
> return;
> }
> };
>
> return (
>