Get Transactions
Query transactions on the Aptos blockchain with various filtering options.
Available Endpoints​
GET /transactions
- Get recent transactionsGET /transactions/by_hash/{txn_hash}
- Get transaction by hashGET /transactions/by_version/{txn_version}
- Get transaction by versionGET /accounts/{address}/transactions
- Get account transactions
When to Use These Methods​
Transaction queries are essential for:
- Transaction History - Display user transaction history
- Transaction Details - Get full transaction information
- Block Explorers - Build transaction search functionality
- Activity Monitoring - Track on-chain activity
Implementation Examples​
- TypeScript
- Python
- Rust
import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";
const config = new AptosConfig({
network: Network.MAINNET,
fullnode: "https://api-aptos-mainnet.n.dwellir.com/v1/YOUR_API_KEY",
});
const aptos = new Aptos(config);
// Get transaction by hash
async function getTransactionByHash(txnHash: string) {
try {
const transaction = await aptos.getTransactionByHash({
transactionHash: txnHash
});
return {
hash: transaction.hash,
sender: transaction.sender,
success: transaction.success,
version: transaction.version,
gasUsed: transaction.gas_used,
gasUnitPrice: transaction.gas_unit_price,
timestamp: transaction.timestamp,
payload: transaction.payload,
events: transaction.events,
changes: transaction.changes,
};
} catch (error) {
if (error.status === 404) {
return null; // Transaction not found
}
throw error;
}
}
// Get transaction by version
async function getTransactionByVersion(version: number) {
const transaction = await aptos.getTransactionByVersion({
ledgerVersion: version
});
return transaction;
}
// Get account transactions with pagination
async function getAccountTransactions(
address: string,
limit: number = 25,
start?: number
) {
const transactions = await aptos.getTransactions({
options: {
where: {
account_address: { _eq: address },
},
limit,
offset: start,
},
});
return transactions;
}
// Get recent transactions
async function getRecentTransactions(limit: number = 10) {
const response = await fetch(
`https://api-aptos-mainnet.n.dwellir.com/v1/YOUR_API_KEY/transactions?limit=${limit}`,
{ headers: { 'Accept': 'application/json' } }
);
return response.json();
}
// Search transactions with filters
async function searchTransactions(filters: {
sender?: string;
receiver?: string;
functionName?: string;
startTime?: number;
endTime?: number;
minAmount?: number;
maxAmount?: number;
}) {
const transactions = await aptos.getTransactions({
options: {
where: {
...(filters.sender && { sender: { _eq: filters.sender } }),
...(filters.startTime && {
timestamp: { _gte: filters.startTime * 1000000 }
}),
...(filters.endTime && {
timestamp: { _lte: filters.endTime * 1000000 }
}),
},
orderBy: [{ timestamp: "desc" }],
},
});
// Additional client-side filtering
return transactions.filter(txn => {
if (filters.functionName && !txn.payload?.function?.includes(filters.functionName)) {
return false;
}
return true;
});
}
from aptos_sdk.client import RestClient
from aptos_sdk.account_address import AccountAddress
from typing import Optional, List, Dict
import time
client = RestClient("https://api-aptos-mainnet.n.dwellir.com/v1/YOUR_API_KEY")
def get_transaction_by_hash(txn_hash: str) -> Optional[Dict]:
"""Get transaction details by hash"""
try:
transaction = client.get_transaction_by_hash(txn_hash)
return {
"hash": transaction["hash"],
"sender": transaction["sender"],
"success": transaction["success"],
"version": transaction["version"],
"gas_used": transaction["gas_used"],
"gas_unit_price": transaction["gas_unit_price"],
"timestamp": transaction["timestamp"],
"payload": transaction["payload"],
"events": transaction["events"],
"changes": transaction.get("changes", [])
}
except Exception as e:
if "404" in str(e):
return None
raise e
def get_transaction_by_version(version: int) -> Dict:
"""Get transaction by version number"""
return client.get_transaction_by_version(version)
def get_account_transactions(
address: str,
limit: int = 25,
start: Optional[int] = None
) -> List[Dict]:
"""Get transactions for a specific account"""
account_addr = AccountAddress.from_str(address)
transactions = client.get_account_transactions(
account_addr,
limit=limit,
start=start
)
return transactions
def get_recent_transactions(limit: int = 10) -> List[Dict]:
"""Get most recent transactions"""
import requests
response = requests.get(
f"https://api-aptos-mainnet.n.dwellir.com/v1/YOUR_API_KEY/transactions",
params={"limit": limit},
headers={"Accept": "application/json"}
)
return response.json()
def search_transactions_by_function(
function_id: str,
limit: int = 100
) -> List[Dict]:
"""Search transactions by function"""
all_transactions = get_recent_transactions(limit)
matching = []
for txn in all_transactions:
if txn.get("payload", {}).get("function") == function_id:
matching.append(txn)
return matching
def get_transaction_events(txn_hash: str, event_type: Optional[str] = None):
"""Get events from a transaction"""
transaction = get_transaction_by_hash(txn_hash)
if not transaction:
return []
events = transaction.get("events", [])
if event_type:
events = [e for e in events if event_type in e["type"]]
return events
def monitor_account_activity(address: str, callback, interval: int = 5):
"""Monitor an account for new transactions"""
last_version = None
while True:
transactions = get_account_transactions(address, limit=10)
if transactions:
current_version = int(transactions[0]["version"])
if last_version and current_version > last_version:
# New transactions detected
new_txns = [
txn for txn in transactions
if int(txn["version"]) > last_version
]
for txn in new_txns:
callback(txn)
last_version = current_version
time.sleep(interval)
use aptos_sdk::rest_client::Client;
use aptos_sdk::types::{
account_address::AccountAddress,
transaction::Transaction,
};
use std::str::FromStr;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new(
"https://api-aptos-mainnet.n.dwellir.com/v1/YOUR_API_KEY"
.parse()?
);
// Get transaction by hash
async fn get_transaction_by_hash(
client: &Client,
hash: &str,
) -> Result<Option<Transaction>, Box<dyn std::error::Error>> {
match client.get_transaction_by_hash(hash).await {
Ok(txn) => Ok(Some(txn)),
Err(e) if e.to_string().contains("404") => Ok(None),
Err(e) => Err(e.into()),
}
}
// Get account transactions
async fn get_account_transactions(
client: &Client,
address: AccountAddress,
limit: u16,
) -> Result<Vec<Transaction>, Box<dyn std::error::Error>> {
let transactions = client.get_account_transactions(
address,
None,
Some(limit),
).await?;
Ok(transactions)
}
Ok(())
}
Common Use Cases​
1. Transaction History Display​
Build a transaction history UI:
interface TransactionSummary {
hash: string;
type: string;
status: "success" | "failed";
timestamp: Date;
from: string;
to?: string;
amount?: string;
gasUsed: string;
gasCost: string;
}
async function getTransactionHistory(
address: string,
page: number = 1,
pageSize: number = 20
): Promise<{
transactions: TransactionSummary[];
hasMore: boolean;
}> {
const start = (page - 1) * pageSize;
const transactions = await getAccountTransactions(address, pageSize + 1, start);
const hasMore = transactions.length > pageSize;
const displayTxns = transactions.slice(0, pageSize);
const summaries: TransactionSummary[] = await Promise.all(
displayTxns.map(async (txn) => {
const summary: TransactionSummary = {
hash: txn.hash,
type: getTransactionType(txn),
status: txn.success ? "success" : "failed",
timestamp: new Date(parseInt(txn.timestamp) / 1000),
from: txn.sender,
gasUsed: txn.gas_used,
gasCost: (BigInt(txn.gas_used) * BigInt(txn.gas_unit_price)).toString(),
};
// Extract transfer details if applicable
if (txn.payload?.function === "0x1::aptos_account::transfer") {
summary.to = txn.payload.arguments[0];
summary.amount = txn.payload.arguments[1];
}
return summary;
})
);
return { transactions: summaries, hasMore };
}
function getTransactionType(txn: any): string {
const func = txn.payload?.function;
if (!func) return "Unknown";
if (func.includes("transfer")) return "Transfer";
if (func.includes("mint")) return "Mint";
if (func.includes("burn")) return "Burn";
if (func.includes("swap")) return "Swap";
if (func.includes("stake")) return "Stake";
return func.split("::").pop() || "Contract Call";
}
2. Transaction Receipt​
Generate detailed transaction receipts:
async function getTransactionReceipt(txnHash: string) {
const txn = await getTransactionByHash(txnHash);
if (!txn) {
throw new Error("Transaction not found");
}
const receipt = {
// Basic info
transactionHash: txn.hash,
status: txn.success ? "Success" : "Failed",
blockVersion: txn.version,
timestamp: new Date(parseInt(txn.timestamp) / 1000),
// Participants
from: txn.sender,
to: extractRecipient(txn),
// Execution details
function: txn.payload?.function || "N/A",
arguments: txn.payload?.arguments || [],
typeArguments: txn.payload?.type_arguments || [],
// Gas details
gasUsed: txn.gas_used,
gasUnitPrice: txn.gas_unit_price,
totalGasCost: (BigInt(txn.gas_used) * BigInt(txn.gas_unit_price)).toString(),
maxGasAmount: txn.max_gas_amount,
// Results
vmStatus: txn.vm_status,
events: txn.events.map(e => ({
type: e.type,
data: e.data,
sequenceNumber: e.sequence_number,
})),
// State changes
changesCount: txn.changes?.length || 0,
changes: summarizeChanges(txn.changes || []),
};
return receipt;
}
function extractRecipient(txn: any): string | null {
// For transfers
if (txn.payload?.function?.includes("transfer")) {
return txn.payload.arguments[0];
}
// Check events for recipient
const transferEvent = txn.events?.find(
(e: any) => e.type.includes("CoinTransferEvent")
);
return transferEvent?.data?.to || null;
}
function summarizeChanges(changes: any[]): any {
const summary = {
resourcesCreated: 0,
resourcesModified: 0,
resourcesDeleted: 0,
modules: [],
coinBalances: [],
};
for (const change of changes) {
if (change.type === "write_resource") {
if (!change.data.old_value) {
summary.resourcesCreated++;
} else if (!change.data.data) {
summary.resourcesDeleted++;
} else {
summary.resourcesModified++;
}
// Track coin balance changes
if (change.data.type.includes("CoinStore")) {
summary.coinBalances.push({
address: change.address,
coinType: change.data.type,
newBalance: change.data.data?.coin?.value,
});
}
} else if (change.type === "write_module") {
summary.modules.push(change.data.module);
}
}
return summary;
}
3. Transaction Analytics​
Analyze transaction patterns:
async function analyzeTransactionActivity(
address: string,
days: number = 30
): Promise<any> {
const endTime = Date.now();
const startTime = endTime - (days * 24 * 60 * 60 * 1000);
// Get all transactions in period
const allTransactions = [];
let start = 0;
const batchSize = 100;
while (true) {
const batch = await getAccountTransactions(address, batchSize, start);
const inPeriod = batch.filter(txn => {
const txnTime = parseInt(txn.timestamp) / 1000;
return txnTime >= startTime && txnTime <= endTime;
});
allTransactions.push(...inPeriod);
if (batch.length < batchSize || inPeriod.length < batch.length) {
break;
}
start += batchSize;
}
// Analyze patterns
const analysis = {
totalTransactions: allTransactions.length,
successfulTransactions: allTransactions.filter(t => t.success).length,
failedTransactions: allTransactions.filter(t => !t.success).length,
// Gas analysis
totalGasUsed: allTransactions.reduce(
(sum, t) => sum + BigInt(t.gas_used),
0n
).toString(),
averageGasUsed: Math.floor(
allTransactions.reduce((sum, t) => sum + parseInt(t.gas_used), 0) /
allTransactions.length
),
// Activity by day
activityByDay: new Map<string, number>(),
// Most used functions
functionCalls: new Map<string, number>(),
// Interaction addresses
uniqueInteractions: new Set<string>(),
};
// Process each transaction
for (const txn of allTransactions) {
// Activity by day
const date = new Date(parseInt(txn.timestamp) / 1000)
.toISOString()
.split('T')[0];
analysis.activityByDay.set(
date,
(analysis.activityByDay.get(date) || 0) + 1
);
// Function calls
const func = txn.payload?.function;
if (func) {
analysis.functionCalls.set(
func,
(analysis.functionCalls.get(func) || 0) + 1
);
}
// Track interactions
const recipient = extractRecipient(txn);
if (recipient) {
analysis.uniqueInteractions.add(recipient);
}
}
return {
...analysis,
activityByDay: Object.fromEntries(analysis.activityByDay),
functionCalls: Object.fromEntries(analysis.functionCalls),
uniqueInteractionsCount: analysis.uniqueInteractions.size,
};
}
4. Real-time Transaction Monitoring​
Monitor transactions in real-time:
class TransactionMonitor {
private lastVersion: bigint | null = null;
private pollInterval: number = 2000; // 2 seconds
private isRunning: boolean = false;
async start(
address: string,
onNewTransaction: (txn: any) => void
) {
this.isRunning = true;
while (this.isRunning) {
try {
const transactions = await getAccountTransactions(address, 10);
if (transactions.length > 0) {
const latestVersion = BigInt(transactions[0].version);
if (this.lastVersion === null) {
// First run - initialize
this.lastVersion = latestVersion;
} else if (latestVersion > this.lastVersion) {
// New transactions detected
const newTxns = transactions.filter(
txn => BigInt(txn.version) > this.lastVersion!
);
for (const txn of newTxns.reverse()) {
onNewTransaction(txn);
}
this.lastVersion = latestVersion;
}
}
} catch (error) {
console.error("Monitor error:", error);
}
await new Promise(resolve => setTimeout(resolve, this.pollInterval));
}
}
stop() {
this.isRunning = false;
}
}
// Usage
const monitor = new TransactionMonitor();
monitor.start("0x1", (txn) => {
console.log("New transaction:", txn.hash);
console.log("Type:", getTransactionType(txn));
console.log("Success:", txn.success);
});
Performance Optimization​
Transaction Caching​
class TransactionCache {
private cache = new Map<string, any>();
private maxSize = 1000;
get(hash: string): any | null {
return this.cache.get(hash) || null;
}
set(hash: string, transaction: any) {
// Implement LRU if needed
if (this.cache.size >= this.maxSize) {
const firstKey = this.cache.keys().next().value;
this.cache.delete(firstKey);
}
this.cache.set(hash, transaction);
}
async getTransaction(hash: string): Promise<any> {
// Check cache first
const cached = this.get(hash);
if (cached) {
return cached;
}
// Fetch from network
const transaction = await getTransactionByHash(hash);
if (transaction) {
this.set(hash, transaction);
}
return transaction;
}
}
Need help? Contact our support team or check the Aptos documentation.