api.ts•3.06 kB
import { Connection, PublicKey } from '@solana/web3.js';
export interface TransactionHistoryOptions {
limit?: number;
before?: string;
until?: string;
types?: string[];
minContextSlot?: number;
}
export interface TransactionData {
signature: string;
slot: number;
timestamp: number;
err: any;
memo: string | null;
blockTime: number;
type: string;
fee: number;
status: string;
}
export class TransactionHelperApi {
/**
* Helper function to fetch transaction history using Helius API directly
* @param connection - Solana connection object containing the API key
* @param address - The address to get transaction history for
* @param options - Query parameters
* @returns Array of transaction data from Helius
*/
async getTransactionHistory(
connection: Connection,
address: string,
options: TransactionHistoryOptions = {}
): Promise<TransactionData[]> {
try {
// Build query parameters
const queryParams: Record<string, string> = {};
if (options.limit) {
queryParams.limit = options.limit.toString();
}
if (options.before) {
queryParams.before = options.before;
}
if (options.until) {
queryParams.until = options.until;
}
if (options.types && options.types.length > 0) {
queryParams.type = options.types.join(',');
}
if (options.minContextSlot) {
queryParams.minContextSlot = options.minContextSlot.toString();
}
// Convert params to URL query string
const queryString = Object.entries(queryParams)
.map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
.join('&');
// Extract API key from the RPC endpoint
const rpcUrl = connection.rpcEndpoint;
const apiKey = rpcUrl.split('api-key=')[1];
if (!apiKey) {
throw new Error('Missing Helius API key in connection endpoint');
}
// Build the URL
const url = `https://api.helius.xyz/v0/addresses/${address}/transactions?api-key=${apiKey}${queryString ? `&${queryString}` : ''}`;
// Fetch data from Helius API
const response = await fetch(url);
if (!response.ok) {
if (response.status === 429) {
throw new Error("Helius API rate limit exceeded");
}
const errorText = await response.text();
throw new Error(`Helius API error: ${response.status} ${errorText}`);
}
const data = await response.json();
// Map the response to our expected format
return data.map((tx: any) => ({
signature: tx.signature,
slot: tx.slot,
timestamp: tx.timestamp,
err: tx.err,
memo: tx.memo || null,
blockTime: tx.timestamp,
type: tx.type || 'Unknown',
fee: tx.fee || 0,
status: tx.err ? 'Failed' : 'Success'
}));
} catch (error) {
console.error('Error in getTransactionHistory:', error);
throw error;
}
}
}