@moralisweb3/next
v2.27.2
Published
Moralis Evm and Solana Hooks for NextJS
Downloads
2,250
Keywords
Readme
@moralisweb3/next
Moralis Hooks for your NextJS project
This project is a thin NextJS wrapper around Moralis, to easily call functionalities and display data. It serves as a proxy, to allow users to access Moralis APIs in client-side.
Please check the official documentation of Moralis for all the functionalities of Moralis.
🚀 Quick start
1. Install Dependencies
Make sure to have next
, next-auth
, react
and react-dom
installed as dependencies, then install @moralisweb3/next
In short:
npm install @moralisweb3/next next next-auth react react-dom
or
yarn add @moralisweb3/next next next-auth react react-dom
2. Create environment variables file
Add a new file .env.local
in project's root and provide a new variable with Moralis API key:
MORALIS_API_KEY= ***
3. Create API route
To use Moralis APIs in your NextJs project create a file pages/api/moralis/[...moralis].ts
with following code:
import { MoralisNextApi } from "@moralisweb3/next";
export default MoralisNextApi({ apiKey: process.env.MORALIS_API_KEY });
You can provide a configuration object to the MoralisNextApi
.
⭐️ Star us
If this "@moralisweb3/next" library helps you build your dapps faster - please star this project, every star makes us very happy!
🤝 Need help
If you need help with setting up the boilerplate or have other questions - don't hesitate to write in our community forum and we will check asap. Forum link. The best thing about this SDK is the super active community ready to help at any time! We help each other.
🧭 Table of Contents
- 🚀 Quick start
- ⭐️ Star us
- 🤝 Need help
- 🧭 Table of Contents
- 🔐 Authentication and Session Management with NextAuth
- ✨ Hook Usage Examples
- ⚙️ Hook Advanced Config
- Authentication Api Hooks
- Evm Api Hooks
- useEvmWeb3ApiVersion
- useEvmRunContractFunction
- useEvmEndpointWeights
- useEvmWalletTransactionsVerbose
- useEvmWalletTransactions
- useEvmTransactionVerbose
- useEvmTransaction
- useEvmInternalTransactions
- useEvmWalletTokenTransfers
- useEvmWalletTokenBalances
- useEvmTokenTransfers
- useEvmTokenPrice
- useEvmTokenMetadata
- useEvmTokenMetadataBySymbol
- useEvmTokenAllowance
- useEvmErc20Transfers
- useEvmErc20Mints
- useEvmErc20Burns
- useEvmErc20Approvals
- useEvmResolveENSDomain
- useEvmResolveDomain
- useEvmResolveAddress
- useEvmSyncNFTContract
- useEvmSearchNFTs
- useEvmReSyncMetadata
- useEvmWalletNFTTransfers
- useEvmWalletNFTs
- useEvmWalletNFTCollections
- useEvmNFTTransfers
- useEvmNFTTransfersFromToBlock
- useEvmNFTTransfersByBlock
- useEvmNFTTrades
- useEvmNFTTokenIdOwners
- useEvmNFTOwners
- useEvmNFTMetadata
- useEvmNFTLowestPrice
- useEvmNFTContractTransfers
- useEvmNFTContractMetadata
- useEvmMultipleNFTs
- useEvmContractNFTs
- useEvmUploadFolder
- useEvmContractLogs
- useEvmContractEvents
- useEvmPairReserves
- useEvmPairAddress
- useEvmDateToBlock
- useEvmBlock
- useEvmNativeBalancesForAddresses
- useEvmNativeBalance
- Solana Api Hooks
- 🧙♂️ Community
🔐 Authentication and Session Management with NextAuth
The @moralisweb3/next
library provides first class tools for web3 authentication. Using the NextAuth.js and our custom MoralisNextAuthProvider()
you can implement web3 authentication you can create web3 authentication for any web3 wallet.
Please follow Sign In with MetaMask Tutorial for NextJS.
✨ Hook Usage Examples
import { useEvmWalletTokenBalances } from '@moralisweb3/next'
const App = () => {
const { data: balance, error, fetch, isFetching } = useEvmWalletTokenBalances({ address: '0x...' })
if (isFetching) return <div>Fetching/Refreshing balance…</div>
if (error) return <div>{JSON.stringify(error, null, 2)}</div>
return (
<>
<button onClick={fetch}>Refetch Balance</button>
<div>{JSON.stringify(balance, null, 2)}</div>
</>
)
}
Basically, there are three options how to fetch data with @moralisweb3/next
hooks:
1. Provide params directly to the hook
In case all required params for the hook are defined you can provide them directly to the hook params. Data fetching in this case will be triggered automatically:
import { useEvmWalletTokenBalances } from '@moralisweb3/next'
const App = () => {
const { data: balance } = useEvmWalletTokenBalances({ address: '0x...' })
return (
<div>{JSON.stringify(balance, null, 2)}</div>
)
}
2. Provide params to the fetch()
Sometimes you need to fetch data somewhere in your code or even fetch it twice with different variables. You can provide params to the fetch()
function:
import { useState } from 'react';
import { useEvmNativeBalance } from '@moralisweb3/next'
import { EvmChain } from 'moralis/common-evm-utils';
const App = () => {
const { fetch } = useEvmNativeBalance();
const [ethBalance, setEthBalance] = useState('');
const [bnbBalance, setBnbBalance] = useState('');
const fetchBalanceForEthereum = async () => {
const response = await fetch({ address: '0x...', chain: EvmChain.ETHEREUM });
if (response?.balance) {
setEthBalance(response.balance.ether);
}
};
const fetchBalanceForBsc = async () => {
const response = await fetch({ address: '0x...', chain: EvmChain.BSC });
if (response?.balance) {
setBnbBalance(response.balance.ether);
}
};
return (
<div>
<button onClick={fetchBalanceForEthereum}>Fetch Balance For Ethereum</button>
<button onClick={fetchBalanceForBsc}>Fetch Balance For BSC</button>
<p>Ethereum Balance: {ethBalance} Ether</p>
<p>Binance Balance: {bnbBalance} BNB</p>
</div>
)
}
3. Disable Auto Data Fetching
To disable auto data fetching after your component has been mounted you can set revalidateOnMount = false
. Example:
import { useEvmWalletTokenBalances } from '@moralisweb3/next'
const App = () => {
const { data: balance, fetch } = useEvmWalletTokenBalances({ address: '0x...' }, { revalidateOnMount: false })
return (
<>
<button onClick={fetch}>Fetch Balance Manually</button>
<div>{JSON.stringify(balance, null, 2)}</div>
</>
)
}
⚙️ Hook Advanced Config
The @moralisweb3/next
hooks use SWR for a better developer experience. You can provide config object to the hooks as it's shown bellow:
const { data } = useEvmWalletTokenBalances({ address: '0x...' }, { revalidateOnFocus: true })
Authentication Api Hooks
useAuthRequestChallengeSolana()
The back channel challenge containing the id to store on the api and the message to be signed by the user
Params:
{
address: SolAddressish;
network: SolNetworkish;
expirationTime?: DateInput;
notBefore?: DateInput;
};
Response:
{ id: string; message: string; profileId: string };
useAuthRequestChallengeEvm()
The back channel challenge containing the id to store on the api and the message to be signed by the user
Params:
{
address: EvmAddressish;
chainId: EvmChainish;
expirationTime?: DateInput;
notBefore?: DateInput;
};
Response:
{ id: string; message: string; profileId: string };
Evm Api Hooks
useEvmWeb3ApiVersion()
Get the current version of the Moralis Web3 API.
useEvmRunContractFunction()
Run a given function of a contract ABI and retrieve readonly data.
useEvmEndpointWeights()
Get the endpoint price list for rate limits and cost.
useEvmWalletTransactionsVerbose()
Get native transactions ordered by block number in descending order.
useEvmWalletTransactions()
Get native transactions ordered by block number in descending order.
useEvmTransactionVerbose()
Get the contents of a transaction by the given transaction hash.
useEvmTransaction()
Get the contents of a transaction by the given transaction hash.
useEvmInternalTransactions()
Get native transactions ordered by block number in descending order.
useEvmWalletTokenTransfers()
Get ERC20 token transactions ordered by block number in descending order.
useEvmWalletTokenBalances()
Get token balances for a specific wallet address.
useEvmTokenTransfers()
Get ERC20 token transactions from a contract ordered by block number in descending order.
useEvmTokenPrice()
Get the token price denominated in the blockchains native token and USD.
useEvmTokenMetadata()
Get the metadata for a given token contract address (name, symbol, decimals, logo).
useEvmTokenMetadataBySymbol()
Get metadata for a list of token symbols (name, symbol, decimals, logo).
useEvmTokenAllowance()
Get the amount which the spender is allowed to withdraw on behalf of the owner.
useEvmErc20Transfers()
Get the amount which the spender is allowed to withdraw on behalf of the owner.
useEvmErc20Mints()
Get the amount which the spender is allowed to withdraw on behalf of the owner.
useEvmErc20Burns()
Get the amount which the spender is allowed to withdraw on behalf of the owner.
useEvmErc20Approvals()
Get the amount which the spender is allowed to withdraw on behalf of the owner.
useEvmResolveENSDomain()
Resolve a specific ENS domain to its address.
useEvmResolveDomain()
Resolve an Unstoppable domain and get the address.
useEvmResolveAddress()
Resolve an ETH address and find the ENS name.
useEvmSyncNFTContract()
Initiates a sync of a previously non synced Contract.
useEvmSearchNFTs()
Get NFTs that match a given metadata search query.
useEvmReSyncMetadata()
ReSync the metadata for an NFT
- The metadata flag will request a the NFT's metadata from the already existing token_uri
- The uri(default) flag will fetch the latest token_uri from the given NFT address. In sync mode the metadata will also be fetched
- The sync mode will make the endpoint synchronous so it will wait for the task to be completed before responding
- The async mode(default) will make the endpoint asynchronous so we will wait for the task to be completed before responding
useEvmWalletNFTTransfers()
Get transfers of NFTs given the wallet and other parameters.
useEvmWalletNFTs()
Get NFTs owned by a given address.
- The response will include status [SYNCED/SYNCING] based on the contracts being indexed.
- Use the token_address param to get results for a specific contract only
- Note results will include all indexed NFTs
- Any request which includes the token_address param will start the indexing process for that NFT collection the very first time it is requested.
useEvmWalletNFTCollections()
Get NFT collections owned by a given wallet address.
useEvmNFTTransfers()
Get transfers of an NFT given a contract address and token ID.
useEvmNFTTransfersFromToBlock()
Get transfers of NFTs from a block number to a block number.
useEvmNFTTransfersByBlock()
Get transfers of NFTs given a block number or block hash.
useEvmNFTTrades()
Get trades of NFTs for a given contract and marketplace.
useEvmNFTTokenIdOwners()
Get owners of a specific NFT given the contract address and token ID.
- Requests for contract addresses not yet indexed will automatically start the indexing process for that NFT collection
useEvmNFTOwners()
Get owners of NFTs for a given contract.
- Requests for contract addresses not yet indexed will automatically start the indexing process for that NFT collection.
useEvmNFTMetadata()
Get NFT data, including metadata (where available), for the given NFT token ID and contract address.
- Requests for contract addresses not yet indexed will automatically start the indexing process for that NFT collection
useEvmNFTLowestPrice()
Get the lowest executed price for an NFT contract for the last x days (only trades paid in ETH).
useEvmNFTContractTransfers()
Get transfers of NFTs for a given contract and other parameters.
useEvmNFTContractMetadata()
Get the collection / contract level metadata for a given contract (name, symbol, base token uri).
- Requests for contract addresses not yet indexed will automatically start the indexing process for that NFT collection
useEvmMultipleNFTs()
Get NFTs for a given contract address, including metadata for all NFTs (where available).
- Results are limited to 100 per page by default
- Requests for contract addresses not yet indexed will automatically start the indexing process for that NFT collection.
useEvmContractNFTs()
Get NFTs for a given contract address, including metadata for all NFTs (where available).
- Results are limited to 100 per page by default
- Requests for contract addresses not yet indexed will automatically start the indexing process for that NFT collection.
useEvmUploadFolder()
Upload multiple files to IPFS and place them in a folder directory.
useEvmContractLogs()
Get the logs for a contract.
useEvmContractEvents()
Get events for a contract ordered by block number in descending order.
useEvmPairReserves()
Get the liquidity reserves for a given pair address. Only Uniswap V2 based exchanges supported at the moment.
useEvmPairAddress()
Fetch the pair data of the provided token0+token1 combination. The token0 and token1 options are interchangable (ie. there is no different outcome in "token0=WETH and token1=USDT" or "token0=USDT and token1=WETH")
useEvmDateToBlock()
Get the closest block given the date.
useEvmBlock()
Get the contents of a block given the block hash.
useEvmNativeBalancesForAddresses()
Get the native balances for a set of specific addresses
useEvmNativeBalance()
Get the native balance for a specific wallet address.
Solana Api Hooks
useSolTokenPrice()
Gets the token price (usd and native) for a given contract address and network
useSolNFTMetadata()
Gets the contract level metadata (mint, standard, name, symbol, metaplex) for the given network and contract
useSolSPL()
Gets token balances owned by the given network and address
useSolPortfolio()
Gets the portfolio of the given network and address
useSolNFTs()
Gets NFTs owned by the given network and address
useSolBalance()
Gets native balance owned by the given network and address