Skip to main content

Get Transactions

Query transactions on the Aptos blockchain with various filtering options.

Available Endpoints​

  • GET /transactions - Get recent transactions
  • GET /transactions/by_hash/{txn_hash} - Get transaction by hash
  • GET /transactions/by_version/{txn_version} - Get transaction by version
  • GET /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​

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;
});
}

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.