This tutorial uses the alchemy_getAssetTransfers endpoint.
A few reasons for why you'd want to get address transaction history by an address:
- Displaying your a user’s full transaction history
- Querying an address's transactions filtered by smart contract interactions
- Analyzing a user's historical profit and loss
Regardless of the different types of transaction history, you want to look up, this process can be extremely burdensome for developers to stitch together without the Alchemy Transfers API
In this tutorial, we’ll be using Alchemy’s Transfers API to fetch all transactions sent from and sent to addresses you care about to create a complete picture of a user's transaction history.
When using the Transfers API for querying a user’s full on-chain history, it's important to have a few key parameters on hand.
fromAddress: the address we want to see transaction information originating fromtoAddress: the address we want to see for recipient-based transactionsfromBlock: the starting time range we want to fetch transactions over (defaults tolatest)toBlock: the ending time range we want to fetch transactions over (defaults tolatest)category: the type of transfer events we care about, in our case we want to see all transactions so we can simply let the param use its default argument of ["external", "internal", "token"]
For transaction information that originates from your target sender address, use the fromAddress parameter within the Transfers API. For recipient-based transactions, use the toAddress parameter.
If you want to get transactions that have a specific from and to address, you can specify the fromAddress and toAddress in your request.
For a no-code view of the API request check out the composer tool
Fetch
You can easily interact with Alchemy's Transfers API using simple fetch requests. No additional dependencies required with Node.js 18+.
No installation needed - fetch is built into Node.js 18 and higher:
1. Create a file.
In your current directory, create a new file called tx-history-from-fetch.js
Use your favorite file browser, code editor, or just directly in the terminal using the touch command like this:
touch tx-history-from-fetch.js2. Write script!
Copy and paste the following code snippet into your new file: tx-history-from-fetch.js
// Replace with your Alchemy API Key
const apiKey = "demo";
const baseURL = `https://eth-mainnet.g.alchemy.com/v2/${apiKey}`;
async function getTransactionHistory() {
try {
const data = {
jsonrpc: "2.0",
id: 0,
method: "alchemy_getAssetTransfers",
params: [{
fromBlock: "0x0",
fromAddress: "0x5c43B1eD97e52d009611D89b74fA829FE4ac56b1",
category: ["external", "internal", "erc20", "erc721", "erc1155"]
}]
};
const response = await fetch(baseURL, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
} catch (error) {
console.error('Error:', error);
}
}
getTransactionHistory();3. Run script!
Now, on your command line, you can execute the script by calling:
node tx-history-from-fetch.jsNode-Fetch
If you're using node-fetch a lightweight, common module that brings the Fetch API to Node.js and allows us to make our HTTP requests, here's a code snipper for the request you'd make!
1. Create a file.
In your current directory, create a new file called tx-history-from-fetch.js using your favorite file browser, code editor, or just directly in the terminal using the touch command like this:
touch tx-history-from-fetch.js2. Write script!
Copy and paste in the following code snippet into your new file: tx-history-from-fetch.js
let data = JSON.stringify({
"jsonrpc": "2.0",
"id": 0,
"method": "alchemy_getAssetTransfers",
"params": [
{
"fromBlock": "0x0",
"fromAddress": "0x5c43B1eD97e52d009611D89b74fA829FE4ac56b1",
}
]
});
var requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: data,
redirect: 'follow'
};
const apiKey = "demo"
const baseURL = `https://eth-mainnet.g.alchemy.com/v2/${apiKey}`;
const fetchURL = `${baseURL}`;
fetch(fetchURL, requestOptions)
.then(response => response.json())
.then(response => JSON.stringify(response, null, 2))
.then(result => console.log(result))
.catch(error => console.log('error', error));3. Run script!
node tx-history-from-fetch.jsAxios
If you're using Javascript axios, a promise-based HTTP client for the browser and Node.js which allows us to make a raw request to the Alchemy API, here's a code snipper for the request you'd make!
1. Create a file.
In your current directory, create a new file called tx-history-from-axios.js using your favorite file browser, code editor, or just directly in the terminal using the touch command.
touch tx-history-from-axios.js2. Write script!
Copy and paste the following code snippet into your new file: tx-history-from-axios.js
import axios from 'axios';
let data = JSON.stringify({
"jsonrpc": "2.0",
"id": 0,
"method": "alchemy_getAssetTransfers",
"params": [
{
"fromBlock": "0x0",
"fromAddress": "0x5c43B1eD97e52d009611D89b74fA829FE4ac56b1",
}
]
});
var requestOptions = {
method: 'post',
headers: { 'Content-Type': 'application/json' },
data: data,
};
const apiKey = "demo"
const baseURL = `https://eth-mainnet.g.alchemy.com/v2/${apiKey}`;
const axiosURL = `${baseURL}`;
axios(axiosURL, requestOptions)
.then(response => console.log(JSON.stringify(response.data, null, 2)))
.catch(error => console.log(error));3. Run script!
Now, on your command line, you can execute the script by calling:
node tx-history-from-axios.js*For a no-code view of the API request check out the composer tool
JavaScript with Fetch (Recommended)
Using native fetch allows us to efficiently interact with Alchemy's endpoints and make JSON-RPC requests.
Ensure you are inside your project folder and type the following command in the terminal:
# No installation needed - fetch is built-in to Node.js 18+ and browsers1. Create a file
In your current directory, create a new file called transaction-history-script.js
Use your favorite file browser, code editor, or just directly in the terminal using the touch command like this:
touch transaction-history-script.js2. Write script!
Copy and paste in the following code snippet into your new file:
// transaction-history.js
const main = async () => {
// Replace with your Alchemy API key
const apiKey = "<-- ALCHEMY APP API KEY -->";
const requestBody = {
jsonrpc: "2.0",
id: 0,
method: "alchemy_getAssetTransfers",
params: [
{
fromBlock: "0x0",
toAddress: "0x5c43B1eD97e52d009611D89b74fA829FE4ac56b1",
category: ["external", "internal", "erc20", "erc721", "erc1155"],
}
]
};
try {
const response = await fetch(`https://eth-mainnet.g.alchemy.com/v2/${apiKey}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody)
});
const data = await response.json();
console.log('Transaction history:', data.result);
} catch (error) {
console.error('Error:', error);
}
};
main();3. Run script!
Now, on your command line, you can execute the script by calling:
node transaction-history.jsNode-Fetch
If you're using node-fetch a lightweight, common module that brings the Fetch API to Node.js and allows us to make our HTTP requests, here's a code snipper for the request you'd make!
1. Create a file.
In your current directory, create a new file called fetch-transfers-to-script.js using your favorite file browser, code editor, or just directly in the terminal using the touch command like this:
touch fetch-transfers-to-script.js2. Write script!
Copy and paste in the following code snippet into your new file: fetch-transfers-to-script.js
let data = JSON.stringify({
"jsonrpc": "2.0",
"id": 0,
"method": "alchemy_getAssetTransfers",
"params": [
{
"fromBlock": "0x0",
"toAddress": "0x5c43B1eD97e52d009611D89b74fA829FE4ac56b1",
}
]
});
var requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: data,
redirect: 'follow'
};
const apiKey = "demo"
const baseURL = `https://eth-mainnet.g.alchemy.com/v2/${apiKey}`;
const fetchURL = `${baseURL}`;
fetch(fetchURL, requestOptions)
.then(response => response.json())
.then(response => JSON.stringify(response, null, 2))
.then(result => console.log(result))
.catch(error => console.log('error', error));3. Run script!
Now, on your command line, you can execute the script by calling:
node fetch-transfers-from-script.jsAxios
If you're using Javascript axios, a promise-based HTTP client for the browser and Node.js which allows us to make a raw request to the Alchemy API, here's a code snipper for the request you'd make!
1. Create a file.
In your current directory, create a new file called axios-transfers-to-script.js using your favorite file browser, code editor, or just directly in the terminal using the touch command.
touch axios-transfers-to-script.js2. Write script!
Copy and paste the following code snippet into your new file: axios-transfers-to-script.js
import axios from 'axios';
let data = JSON.stringify({
"jsonrpc": "2.0",
"id": 0,
"method": "alchemy_getAssetTransfers",
"params": [
{
"fromBlock": "0x0",
"toAddress": "0x5c43B1eD97e52d009611D89b74fA829FE4ac56b1",
}
]
});
var requestOptions = {
method: 'post',
headers: { 'Content-Type': 'application/json' },
data: data,
};
const apiKey = "demo"
const baseURL = `https://eth-mainnet.g.alchemy.com/v2/${apiKey}`;
const axiosURL = `${baseURL}`;
axios(axiosURL, requestOptions)
.then(response => console.log(JSON.stringify(response.data, null, 2)))
.catch(error => console.log(error));3. Run script!
Now, on your command line, you can execute the script by calling:
node axios-transfers-to-script.jsNow that we have made a query and can see the response, let's learn how to handle it. If you feel like jumping ahead and grabbing some pre-built code, choose a repo that matches your preferred library.
Parsing with Modern Web3 Library Responses
Parsing with Node-Fetch Responses
Parsing with Axios Responses
Without parsing the response, we have a console log that looks as follows.
{
"transfers": [
{
"blockNum": "0xb7389b",
"hash": "0xfde2a5157eda40b90514751f74e3c7314f452a41890b19a342ee147f5336dfd6",
"from": "0x5c43b1ed97e52d009611d89b74fa829fe4ac56b1",
"to": "0xe9b29ae1b4da8ba5b1de76bfe775fbc5e25bc69a",
"value": 0.245,
"erc721TokenId": null,
"erc1155Metadata": null,
"tokenId": null,
"asset": "ETH",
"category": "external",
"rawContract": {}
},
{
"blockNum": "0xcf5dea",
"hash": "0x701f837467ae3112d787ddedf8051c4996ea82914f7a7735cb3db2d805799286",
"from": "0x5c43b1ed97e52d009611d89b74fa829fe4ac56b1",
"to": "0x92560c178ce069cc014138ed3c2f5221ba71f58a",
"value": 152.89962568845024,
"erc721TokenId": null,
"erc1155Metadata": null,
"tokenId": null,
"asset": "ENS",
"category": "token",
"rawContract": {}
},
{
"blockNum": "0xd14898",
"hash": "0x2f5d93a9db65548eb43794aa43698acd653e6b2df35c6028b8599a234f2c6dc0",
"from": "0x5c43b1ed97e52d009611d89b74fa829fe4ac56b1",
"to": "0x83abecf7204d5afc1bea5df734f085f2535a9976",
"value": 27579.060635486854,
"erc721TokenId": null,
"erc1155Metadata": null,
"tokenId": null,
"asset": "PEOPLE",
"category": "token",
"rawContract": {}
}
]
}Understanding API Response
-
blockNum: the block number where a transaction event occurred, inhex -
hash: the transaction hash of a transaction -
from: where the transaction originated from -
to: where ETH or another asset was transferred to -
value: the amount of ETH transferred -
erc721TokenId: the ERC721 token ID.nullif not an ERC721 token transfer. -
erc1155Metadata: a list of objects containing the ERC1155tokenIdandvalue.nullif not an ERC1155 transfer -
tokenId: the token ID for ERC721 tokens or other NFT token standards -
asset:ETHor the token's symbol.nullif not defined in the contract and not available from other sources. -
rawContractvalue: raw transfer value denominated in the relevant Ethereum tokenaddress: Ethereum token contract addressdecimal: contract decimal
Two of the many different response objects you may be interested in parsing are: asset and value.
Let's walk through an example that parses the returned JSON object.
Whether we're querying via alchemy web3, axios, or node-fetch, we'll need to save the queried response object into a constant.
Saving response objects with Modern Web3 Libraries
// Using fetch for alchemy_getAssetTransfers API
const response = await fetch(`https://eth-mainnet.g.alchemy.com/v2/${apiKey}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'alchemy_getAssetTransfers',
params: [{
fromBlock: "0x0",
toAddress: "0x5c43B1eD97e52d009611D89b74fA829FE4ac56b1",
category: ["external", "internal", "erc20", "erc721", "erc1155"]
}]
})
});
const res = await response.json();Saving response objects with Node-Fetch
// Node-Fetch
fetch(fetchURL, requestOptions)
.then((res) => {
return res.json()
})
.then((jsonResponse) => {
//Print token name / asset value
for (const events of jsonResponse.result.transfers) {
console.log("Token Transfer: ", events.value, " ", events.asset);
}
})
.catch((err) => {
// handle error
console.error(err);
});Saving response objects with Axios
// Axios
const res = await axios(axiosURL, requestOptions);With our queried response object saved as a constant, we can now index through the transfers. In particular, the steps we take are:
- Loop through all transfers in the result
- Print each element's
valueandassetfield
// Print token asset name and its associated value
for (const events of res.data.result.transfers) {
console.log("Token Transfer: ", events.value, " ", events.asset);
}If you followed along, your response should look like the following:
Token Transfer: 0.5 ETH
Token Transfer: 0.27 ETH
Token Transfer: 9.90384 ETH
Token Transfer: 0.07024968 ETH
Token Transfer: 0.000447494250654841 ETH
Token Transfer: null null
Token Transfer: 0.075 ETH
Token Transfer: 0.003 ETH
Token Transfer: null BURN
Token Transfer: 54 DAI
Token Transfer: 12.5 GTC
Token Transfer: 2 GTC
Token Transfer: 0.42 ETH
........
Token Transfer: 0.588 WETH
Token Transfer: null null
Token Transfer: null null
Token Transfer: 2.3313024 ETH
Token Transfer: 0.0633910153108353 ETH
Token Transfer: 0.0335 ETH
Token Transfer: 2 GTCAnd that's it! You've now learned how to fetch transaction history for address on Ethereum. For more, check out the tutorial below:
Integrating Historical Transaction Data into your dApp
If you enjoyed this tutorial for getting address transaction history on Ethereum, give us a tweet @Alchemy! (Or give the author @crypt0zeke a shoutout!)
Don't forget to join our Discord server to meet other blockchain devs, builders, and entrepreneurs!
