Step-By-Step: Fetching Token Transaction Data

Supercharge your DeFi & Web3 project with the Portals API Token Transaction Endpoints.

August 5, 2024

Whether you're tracking token movements, analyzing trading patterns, or integrating transaction data into your DeFi application, this endpoint provides valuable insights into token activity. This guide demonstrates how to use the Token Transactions endpoint in the Portals API to retrieve recent transaction data for specific tokens across multiple networks. These endpoints cover platform tokens only.

What is the Portals API?


Imagine a user-friendly DeFi API with straightforward endpoints delivering comprehensive data, with which a single query can fetch balances across all networks, or returns every single asset associated with a DeFi platform. That's the Portals API. In a single integration, the API allows you to inject your app with coverage of thousands of tokens & DeFi assets across 9 EVMs & hundreds of protocols from Aave to Yearn and everything in between.

And the best part? Most devs can start building with Portals API in under 30 minutes!

Let's get started.

Example API Response


Before we dive into the implementation details, let's take a look at what you'll get when you successfully call the Token Transaction endpoint.

Here's an example of the JSON response:

[json]
{
   "withdraws": [
       {
           "amounts": [
               {
                   "symbol": "steCRV",
                   "amount": "82.808",
                   "amountUsd": "323069.49"
               }
           ],
           "transactionHash": "0xeb9fea1c7aaa69e7e936b13ef1877e605e4aa2e4436f6b63c05f96ece6db3cbe",
           "time": "2024-08-07T16:48:47.000Z"
       }
   ],
   "deposits": [
           "amounts": [
               {
                   "key": "ethereum:0x06325440d014e39736583c165c2963ba99faf14e",
                   "symbol": "steCRV",
                   "amount": "1.06757610215469417",
                   "amountUsd": "4165.052553700089353100953537567508"
               }
           ],
           "transactionHash": "0xe76cf805a56c65effc0fab01d82fb92bdefe4a0c82a8c1be6f1a562d201d83c7",
           "time": "2024-08-07T09:48:59.000Z"
       }
   ],
   "swaps": [
       {
           "inputAmount": "331.178",
           "inputToken": "ETH",
           "outputAmount": "331.659",
           "outputToken": "stETH",
           "transactionHash": "0x249a3c017454480c6d09ecd06260658d85fe1487a6c153ca83e2026d6209c33e",
           "time": "2024-08-07T17:35:11.000Z"
       }
   ]
}
[/json]

API Endpoint Details

Method: GET
Base URL: https://api.portals.fi/v2/tokens/transactions
Purpose: Returns a list of withdrawals, deposits, and swaps for a specified platform token over the last 24 hours.
Swagger Documentation: Supported Controller getTokenHistory


Making API Requests

‣Request Parameters

To fetch historical token data, you'll need to provide the following parameters:


‣Token Identification

The API requires tokens to be identified using a specific format: [network]:[address].

For example: ethereum:0x06325440D014e39736583c165C2963BA99fAf14E

This format allows you to specify both the network and the token address in a single parameter.


Setting Up Your Environment


First, let's set up a TypeScript project. If you don't have TypeScript installed, you can do so by running:

[bash]
npm install -g typescript
[/bash]


Next, create a new directory for your project and initialize a new Node.js project:

[bash]
mkdir token-transactions
cd token-transactions
npm init -y
[/bash]


Now, install Axios and TypeScript:

[bash]
npm install axios
npm install --save-dev typescript @types/node @types/axios
[/bash]


Create a tsconfig.json file in the root directory to configure TypeScript:

[json]
{
 "compilerOptions": {
   "target": "ES6",
   "module": "commonjs",
   "strict": true,
   "esModuleInterop": true,
   "skipLibCheck": true,
   "forceConsistentCasingInFileNames": true
 },
 "include": ["src"]
}
[/json]


Passing the API Key


The Portals API requires authentication via an API key. Here's how you can pass the API key using Axios:

1) Obtain your API key from the Portals API dashboard.
2) Store the API key in an environment variable:
  - Install the dotenv package: npm install dotenv
  - Create a .env file in the root of your project and add your API key:
 
[bash]
PORTALS_API_KEY=your_api_key_here
[/bash]


Writing the TypeScript


Create a file named fetchTokenTransactions.ts in the src directory and add the following code:

[ts]
import axios from 'axios';
import * as dotenv from "dotenv";

dotenv.config();

const BASE_URL = 'https://api.portals.fi/v2/tokens/transactions';

interface TokenAmount {
  key: string;
  symbol: string;
  amount: string;
  amountUsd: string;
}

interface Transaction {
  amounts: TokenAmount[];
  transactionHash: string;
  timestamp: string;
}

interface SwapTransaction {
  inputAmount: string;
  inputToken: string;
  outputAmount: string;
  outputToken: string;
  transactionHash: string;
  timestamp: string;
}

interface TokenTransactions {
  withdraws: Transaction[];
  deposits: Transaction[];
  swaps: SwapTransaction[];
}

const API_KEY = process.env.PORTALS_API_KEY;
const axiosInstance = axios.create({

async function fetchTokenTransactions(tokenId: string): Promise<TokenTransactions> {
  try {
    const response = await axiosInstance.get(BASE_URL, {
      params: { id: tokenId }
    });
    return response.data;
  } catch (error) {
    console.error(`Error fetching token transactions: ${error}`);
    throw error;
  }
}

// Example usage
const main = async () => {
  const tokenId = 'ethereum:0x06325440D014e39736583c165C2963BA99fAf14E'; // steCRV token
  try {
    const transactions = await fetchTokenTransactions(tokenId);
    console.log('Token Transactions:', JSON.stringify(transactions, null, 2));
  } catch (error) {
    console.error('Error in main function:', error);
  }
};

main();


[/ts]

Running the Script


To run the script, compile it to JavaScript using TypeScript and then execute it with Node.js:

[bash]
tsc
node dist/fetchTokenTransactions.js
[/bash]

You should see an output with the transactions of the specified token.


Understanding the Response


A successful API call returns a JSON object containing transaction data for the specified token. The response includes three main categories of transactions: withdrawals, deposits, and swaps.

Here's a breakdown of the response structure:

withdraws & deposits: Arrays of transactions, each containing,
amounts: Array of token amounts involved in the transaction
transactionHash: Unique identifier for the blockchain transaction
timestamp: Unix timestamp of the transaction

swaps: Array of swap transactions, each containing,
inputAmount & inputToken: Amount and identifier of the input token
outputAmount & outputToken: Amount and identifier of the output token
transactionHash: Unique identifier for the blockchain transaction
timestamp: Unix timestamp of the transaction


Congratulations!

The Token Transactions endpoint provides valuable insights into recent token activity, including withdrawals, deposits, and swaps. By following these guidelines and best practices, you can effectively integrate this functionality into your DeFi applications, ensuring efficient and reliable access to critical transaction data.

Still having trouble? Looking for more possibilities?
Join like-minded developers and API users on our official Discord.

Stay tuned for more tutorials on how to leverage the power of DeFi with the Portals API!