# Altitrace ## Get started Hello world! ## Web Application The Altitrace web application delivers a sophisticated interface for HyperEVM transaction simulation and analysis. Built with **Next.js 15** and modern React patterns, the application provides comprehensive tools for developers, auditors, and power users working with HyperEVM transactions. ### Architecture & Technology Stack **Frontend Framework** utilizing Next.js 15 with App Router for optimal performance and SEO, React 18 with modern hooks and concurrent features, TypeScript for comprehensive type safety, and Tailwind CSS with custom design system components. **State Management** through Zustand for lightweight, predictable state management, React Hook Form for robust form handling and validation, and LRU caching for optimal performance with frequently accessed data. **Visualization & Analytics** featuring Recharts for interactive gas usage and performance charts, Lucide React for consistent iconography throughout the interface, custom call trace tree components for execution flow visualization, and enhanced event display with automatic ABI decoding. **Developer Experience** enhancements include ABI import functionality with automatic function detection, smart block input with latest/number/tag support, transaction form builder with parameter validation, and comprehensive error boundaries with detailed diagnostics. ### Key Capabilities **Transaction Simulation Interface** provides intuitive transaction building with ABI integration, real-time parameter validation and error checking, support for complex transaction bundles and dependencies, comprehensive gas analysis with visual breakdowns, and detailed execution results with trace visualization. **Advanced Debugging Tools** offer step-through execution traces with call frame trees, enhanced event displays with automatic parameter decoding, gas usage heatmaps for performance optimization, storage and state change visualization, and comprehensive error analysis with actionable suggestions. **Visual Analytics** include interactive charts for gas usage patterns, call depth and complexity analysis, asset flow visualization for token transfers, performance comparison tools for optimization, and comprehensive reporting with export capabilities. ### Accessing the Web App Once you have Altitrace running locally: ```bash # Start the development servers bun run dev # Web app will be available at: http://localhost:3000 ``` For production deployments, the web app is typically available at your domain's root or `/app` path. ### Interface Overview #### Navigation * **Dashboard**: Overview of recent simulations and quick actions * **Simulator**: Main transaction simulation interface * **Debugger**: Advanced debugging tools and trace analysis * **History**: Past simulation results and saved scenarios * **Settings**: Configuration and preferences #### Main Simulation Interface The primary simulation interface consists of: 1. **Transaction Builder**: Form to construct transactions 2. **Results Panel**: Simulation output and analysis 3. **Trace Viewer**: Detailed execution traces 4. **Gas Analysis**: Gas usage breakdown and optimization ### Using the Simulator #### Basic Transaction Simulation 1. **Select Transaction Type**: * Simple transfer * Contract interaction * Contract deployment * Multi-call bundle 2. **Fill Transaction Details**: ``` From Address: 0x742d35Cc6634C0532925a3b8D86C4F5e573F7d5B To Address: 0xA0b86a33E6441a8F9d6f4c13f8a39c3A7a4e8c Value: 1.0 ETH Gas Limit: Auto-estimate ``` 3. **Configure Simulation**: * Block number (latest, specific, or custom) * Trace options (memory, storage, return data) * Debug level (basic, detailed, full) 4. **Run Simulation**: Click "Simulate" to execute #### Contract Interaction For contract calls, the interface provides: * **ABI Input**: Paste or upload contract ABI * **Function Selection**: Dropdown of available functions * **Parameter Input**: Type-safe parameter forms * **Encoding Preview**: See the encoded calldata #### Advanced Features ##### Batch Simulation Simulate multiple transactions in sequence: 1. Click "Add Transaction" to create a batch 2. Configure each transaction in the sequence 3. Set dependencies and ordering 4. Run the entire batch ##### State Forking Simulate against different network states: 1. Select "Fork from Block" 2. Choose block number or use latest 3. Optionally modify account balances 4. Run simulations against forked state ##### Custom Scenarios Save and reuse common simulation scenarios: 1. Configure your transaction 2. Click "Save Scenario" 3. Name and tag for easy retrieval 4. Load scenarios from the sidebar ### Debugging Tools #### Execution Trace Viewer The trace viewer provides: * **Step-by-step execution**: Navigate through each EVM operation * **Stack visualization**: See the EVM stack at each step * **Memory inspection**: View memory state changes * **Storage monitoring**: Track storage slot modifications * **Gas tracking**: Monitor gas consumption per operation #### Error Analysis When transactions fail: * **Error highlighting**: Failed operations are highlighted * **Revert reasons**: Clear explanation of failure causes * **Stack traces**: Full execution path to the error * **Suggestions**: Recommendations for fixing issues #### Performance Analysis * **Gas heatmap**: Visual representation of gas usage * **Optimization hints**: Suggestions for gas reduction * **Comparison tools**: Compare different implementation approaches * **Bottleneck identification**: Find expensive operations ### Export and Sharing #### Export Formats * **JSON**: Complete simulation data for programmatic use * **CSV**: Tabular data for spreadsheet analysis * **PDF Report**: Formatted report with visualizations * **Markdown**: Documentation-ready format #### Sharing Features * **Shareable URLs**: Direct links to simulation results * **Team Workspaces**: Collaborative simulation environments * **Comment System**: Add notes and observations * **Version History**: Track changes to scenarios ### Keyboard Shortcuts * **Ctrl/Cmd + Enter**: Run simulation * **Ctrl/Cmd + S**: Save current scenario * **Ctrl/Cmd + D**: Duplicate transaction * **F5**: Refresh with latest block * **Esc**: Clear current simulation * **?**: Show all shortcuts ### Mobile Experience The web app is fully responsive: * **Touch-friendly**: Optimized for touch interactions * **Adaptive layout**: Interface adjusts to screen size * **Gesture support**: Swipe navigation and pinch-to-zoom * **Offline capability**: View cached results without network ### Integration with Development Workflow #### Browser Extension Install the Altitrace browser extension for: * **One-click simulation**: Simulate transactions from any dApp * **Transaction interception**: Preview transactions before signing * **Quick debugging**: Instant access to simulation tools #### Development Tools * **DevTools integration**: Simulation data in browser DevTools * **Console commands**: Command-line access to simulation API * **Network monitoring**: Track simulation requests and responses ### Settings and Configuration #### Network Settings * **RPC endpoint**: Configure HyperEVM node connection * **Chain ID**: Set network identifier * **Default gas**: Set default gas limits and prices #### UI Preferences * **Theme**: Light, dark, or auto mode * **Language**: Interface localization * **Notifications**: Configure alert preferences * **Layout**: Customize panel arrangement #### Performance Settings * **Trace depth**: Limit trace detail for performance * **Cache settings**: Configure result caching * **Batch size**: Set maximum batch transaction count ### Next Steps ## generateAccessList Generates an access list for a transaction to optimize gas usage. ### Usage :::code-group ```typescript [example.ts] import { client } from './config' const accessList = await client.generateAccessList({ // [!code focus:7] from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data: '0xa9059cbb0000000000000000000000001234567890123456789012345678901234567890000000000000000000000000000000000000000000000000000000000000000a' }) console.log('Access List:', accessList.accessList) console.log('Gas Used:', accessList.gasUsed) ``` ```typescript [config.ts] import { AltitraceClient } from '@altitrace/sdk' export const client = new AltitraceClient({ baseUrl: 'http://localhost:8080/v1' }) ``` ::: #### With Gas Comparison ```typescript // Compare gas usage with and without access list const comparison = await client.compareAccessList() .call({ from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data: '0xa9059cbb...' }) .atBlock('latest') .execute() console.log('Without access list:', comparison.withoutAccessList.gasUsed) console.log('With access list:', comparison.withAccessList.gasUsed) console.log('Gas saved:', comparison.gasSaved) console.log('Savings:', comparison.percentageSaved.toFixed(2) + '%') ``` ### Builder Pattern For complex access list generation. ```typescript const accessList = await client.accessList() .call({ from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data: '0xa9059cbb...' }) .atBlock('0x1234567') .execute() // Use the access list in simulation const result = await client.simulateCallWithAccessList( { from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data: '0xa9059cbb...' }, accessList.accessList ) ``` ### Returns `ExtendedAccessListResponse` The access list response with helper methods. ### Parameters #### call * **Type:** `TransactionCall` The transaction call to analyze. ```typescript const accessList = await client.generateAccessList({ from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', // [!code focus] to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data: '0x095ea7b3...' }) ``` #### options.block (optional) * **Type:** `string | number | bigint` * **Default:** `'latest'` The block to generate the access list against. ```typescript const accessList = await client.generateAccessList( { /* transaction */ }, { block: '0x1234567' } // [!code focus] ) ``` ### Access List Format ```typescript interface AccessList { address: string storageKeys: string[] }[] ``` Example access list: ```typescript [ { address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', storageKeys: [ '0x0000000000000000000000000000000000000000000000000000000000000001', '0x0000000000000000000000000000000000000000000000000000000000000002' ] }, { address: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', storageKeys: [] } ] ``` ### Gas Optimization Access lists reduce gas costs by pre-declaring storage slots. ```typescript // EIP-2930 transaction with access list const optimizedCall = { from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data: '0xa9059cbb...', accessList: [ { address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', storageKeys: ['0x0', '0x1'] } ] } // Simulate with access list const result = await client.simulateCall(optimizedCall) console.log('Optimized gas:', result.getTotalGasUsed()) ``` ### Error Handling ```typescript try { const accessList = await client.generateAccessList({ from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0xInvalidContract', data: '0xa9059cbb...' }) } catch (error) { if (accessList.error) { console.error('Access list generation failed:', accessList.error) } } ``` ### Types ```typescript interface ExtendedAccessListResponse { accessList: AccessList gasUsed: string error?: string | null // Helper methods hasError(): boolean getGasUsed(): bigint getFormattedAccessList(): FormattedAccessList[] getTotalStorageKeys(): number } interface AccessListComparisonResult { withAccessList: ExtendedAccessListResponse withoutAccessList: ExtendedSimulationResult gasSaved: bigint percentageSaved: number isWorthUsing(): boolean } ``` ## Client Setup Configure the Altitrace client for your environment. ### Creating a Client :::code-group ```typescript [basic.ts] import { AltitraceClient } from '@altitrace/sdk' // Default client (localhost) const client = new AltitraceClient() // Custom endpoint const client = new AltitraceClient({ baseUrl: 'http://localhost:8080/v1' }) ``` ```typescript [production.ts] import { AltitraceClient } from '@altitrace/sdk' const client = new AltitraceClient({ baseUrl: 'https://altitrace.reachaltitude.xyz/v1', timeout: 60_000, maxRetries: 3, debug: false }) ``` ```typescript [authenticated.ts] import { AltitraceClient } from '@altitrace/sdk' const client = new AltitraceClient({ baseUrl: 'https://api.example.com/v1', apiKey: process.env.ALTITRACE_API_KEY, headers: { 'X-Custom-Header': 'value' } }) ``` ::: ### Configuration Options ```typescript interface AltitraceClientConfig { // API endpoint URL baseUrl?: string // Request timeout in milliseconds timeout?: number // Number of retry attempts maxRetries?: number // API key for authentication apiKey?: string // Enable debug logging debug?: boolean // Custom headers headers?: Record // Retry configuration retryConfig?: { retryDelay?: number shouldRetry?: (error: any) => boolean } } ``` ### Default Values ```typescript { baseUrl: 'http://localhost:8080/v1', timeout: 30_000, maxRetries: 3, debug: false, retryConfig: { retryDelay: 1000 } } ``` ### Environment Variables The client supports configuration via environment variables: ```bash # API endpoint ALTITRACE_API_URL=https://altitrace.reachaltitude.xyz/v1 # API key ALTITRACE_API_KEY=your-api-key # Debug mode ALTITRACE_DEBUG=true ``` ```typescript const client = new AltitraceClient({ baseUrl: process.env.ALTITRACE_API_URL, apiKey: process.env.ALTITRACE_API_KEY, debug: process.env.ALTITRACE_DEBUG === 'true' }) ``` ### Client Methods #### Direct Access ```typescript // Simulation const result = await client.simulateCall({ from: '0x...', to: '0x...', data: '0x...' }) // Tracing const trace = await client.traceCall({ from: '0x...', to: '0x...', data: '0x...' }) // Access List const accessList = await client.generateAccessList({ from: '0x...', to: '0x...', data: '0x...' }) ``` #### Builder Pattern ```typescript // Simulation builder const result = await client.simulate() .call({ /* transaction */ }) .withAssetChanges(true) .execute() // Trace builder const trace = await client.trace() .call({ /* transaction */ }) .withCallTracer() .execute() // Access list builder const accessList = await client.accessList() .call({ /* transaction */ }) .atBlock('latest') .execute() ``` #### Sub-clients ```typescript // Direct access to specialized clients const simulation = client.simulation const tracing = client.tracing const accessLists = client.accessLists ``` ### Health Check ```typescript // Check API status const health = await client.healthCheck() console.log('Status:', health.status) console.log('Version:', health.version) console.log('Uptime:', health.uptime) ``` ## Getting Started Altitrace SDK for HyperEVM transaction simulation and tracing. ### Installation ```bash bun add @altitrace/sdk ``` ### Usage :::code-group ```typescript [example.ts] import { AltitraceClient } from '@altitrace/sdk' const client = new AltitraceClient({ baseUrl: 'https://api.altitrace.reachaltitude.xyz/v1' }) const result = await client.simulate().call({ from: '0xA79C12BCf11133af01b6B20f16F8AafAECdEBC93', to: '0x3aD2674e162A3bdA4be608C75d52f4B18C729193', value: '0x40000', }).atBlock(12026976).execute() console.log('Gas used:', result.getTotalGasUsed()) console.log('Success:', result.isSuccess()) ``` ```typescript [config.ts] import { AltitraceClient } from '@altitrace/sdk' // Local development export const localClient = new AltitraceClient({ baseUrl: 'http://localhost:8080/v1', debug: true }) // Production export const productionClient = new AltitraceClient({ baseUrl: 'https://api.altitrace.reachaltitude.xyz/v1', timeout: 60_000, maxRetries: 3 }) ``` ::: ### Core Features #### Simulation Simulate transactions to predict execution results and gas usage. ```typescript const result = await client.simulateCall({ from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data: '0x095ea7b30000000000000000000000007a250d5630b4cf539739df2c5dacb4c659f2488d0000000000000000000000000000000000000000000000000000000000000064' }) ``` #### Tracing Analyze transaction execution with multiple trace types. ```typescript const trace = await client.traceCall({ from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data: '0x70a08231000000000000000000000000742d35cc6634c0532925a3b844bc9e7595f06e8c' }, { callTracer: true, prestateTracer: true }) ``` #### Access Lists Generate optimized access lists for EIP-2930 transactions. ```typescript const accessList = await client.generateAccessList({ from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data: '0xa9059cbb0000000000000000000000001234567890123456789012345678901234567890000000000000000000000000000000000000000000000000000000000000000a' }) console.log('Access List:', accessList.accessList) console.log('Gas Used:', accessList.gasUsed) ``` ### Builder Pattern API For complex simulations, use the builder pattern. ```typescript const result = await client.simulate() .call({ from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data: '0x70a08231000000000000000000000000742d35cc6634c0532925a3b844bc9e7595f06e8c' }) .forAccount('0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c') .withAssetChanges(true) .atBlock('latest') .execute() ``` ### Batch Operations Process multiple simulations efficiently. ```typescript const results = await client.simulateBatchAPI([ { params: { calls: [{ from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data: '0x70a08231000000000000000000000000742d35cc6634c0532925a3b844bc9e7595f06e8c' }], blockNumber: '0x1234567' }, options: null }, { params: { calls: [{ from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0xdAC17F958D2ee523a2206206994597C13D831ec7', data: '0x70a08231000000000000000000000000742d35cc6634c0532925a3b844bc9e7595f06e8c' }], blockNumber: '0x1234567' }, options: null } ]) ``` ## Installation Install the Altitrace SDK in your project. ### Package Manager :::code-group ```bash [bun] bun add @altitrace/sdk ``` ```bash [npm] npm install @altitrace/sdk ``` ```bash [yarn] yarn add @altitrace/sdk ``` ```bash [pnpm] pnpm add @altitrace/sdk ``` ::: ### Requirements * Node.js 18+ or Bun * TypeScript 5.0+ (recommended) ### Verify Installation ```typescript import { AltitraceClient } from '@altitrace/sdk' const client = new AltitraceClient() const health = await client.healthCheck() console.log('Status:', health.status) ``` ### TypeScript Configuration The SDK includes TypeScript definitions. For optimal type safety: ```json [tsconfig.json] { "compilerOptions": { "strict": true, "esModuleInterop": true, "skipLibCheck": true, "moduleResolution": "bundler" } } ``` ## simulateCall Simulates a new message call without creating a transaction on the blockchain. ### Usage :::code-group ```typescript [example.ts] import { client } from './config' const result = await client.simulateCall({ // [!code focus:7] from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data: '0xa9059cbb0000000000000000000000001234567890123456789012345678901234567890000000000000000000000000000000000000000000000000000000000000000a', gas: '0xD6D8' }) ``` ```typescript [config.ts] import { AltitraceClient } from '@altitrace/sdk' export const client = new AltitraceClient({ baseUrl: 'http://localhost:8080/v1' }) ``` ::: #### Checking Balances ```typescript const result = await client.simulateCall({ to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC data: '0x70a08231000000000000000000000000742d35cc6634c0532925a3b844bc9e7595f06e8c' // balanceOf }) if (result.isSuccess()) { const balance = BigInt(result.calls[0].returnData) console.log('USDC Balance:', (Number(balance) / 1e6).toFixed(6)) } ``` #### Simulating Transfers ```typescript const result = await client.simulateCall({ from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC data: '0xa9059cbb0000000000000000000000001234567890123456789012345678901234567890000000000000000000000000000000000000000000000000000000000000000a' // transfer 10 USDC }) console.log('Transfer simulation:', result.isSuccess() ? 'Success' : 'Failed') console.log('Gas estimate:', result.getTotalGasUsed()) ``` ### Builder Pattern For more complex simulations, use the builder pattern. ```typescript const result = await client.simulate() .call({ from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data: '0xa9059cbb0000000000000000000000001234567890123456789012345678901234567890000000000000000000000000000000000000000000000000000000000000000a' }) .forAccount('0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c') .withAssetChanges(true) .withValidation(true) .atBlock('latest') .execute() // Asset changes tracking if (result.assetChanges) { const summary = result.getAssetChangesSummary() summary.forEach(change => { console.log(`${change.symbol}: ${change.netChange} (${change.type})`) }) } ``` ### Returns `ExtendedSimulationResult` The simulation result with helper methods. ### Parameters #### call * **Type:** `TransactionCall` The transaction call to simulate. ```typescript const result = await client.simulateCall({ from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', // [!code focus] to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data: '0x095ea7b3...' }) ``` #### options.blockTag (optional) * **Type:** `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` * **Default:** `'latest'` The block tag to simulate against. ```typescript const result = await client.simulateCall( { /* transaction */ }, { blockTag: 'safe' } // [!code focus] ) ``` #### options.validation (optional) * **Type:** `boolean` * **Default:** `true` Enable or disable EVM validation. ```typescript const result = await client.simulateCall( { /* transaction */ }, { validation: false } // [!code focus] ) ``` #### options.traceAssetChanges (optional) * **Type:** `boolean` * **Default:** `false` Track token balance changes. Requires `account` parameter. ```typescript const result = await client.simulateCall( { /* transaction */ }, { account: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', traceAssetChanges: true // [!code focus] } ) ``` ### State Overrides Modify account states before simulation. ```typescript const result = await client.simulate() .call({ from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data: '0xa9059cbb...' }) .withStateOverrides([{ address: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', balance: '0x1bc16d674ec80000', // 2 ETH nonce: 10 }, { address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', code: '0x608060405...', // Override bytecode storage: { '0x0': '0x1234' // Set storage slot } }]) .execute() ``` ### Block Overrides Modify block parameters for simulation. ```typescript const result = await client.simulate() .call({ /* transaction */ }) .withBlockOverrides({ timestamp: Math.floor(Date.now() / 1000) + 3600, number: '0x1234567', baseFeePerGas: '0x3b9aca00', gasLimit: '0x1c9c380' // 30M gas }) .execute() ``` ### Batch Simulations #### Sequential Batch ```typescript const config = { simulations: [ { params: { calls: [{ from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data: '0x70a08231...' }] }, options: null }, { params: { calls: [{ from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0xdAC17F958D2ee523a2206206994597C13D831ec7', data: '0x70a08231...' }] }, options: null } ], stopOnFailure: true } const batch = await client.simulateBatch(config) console.log(`Success: ${batch.successCount}/${batch.results.length}`) ``` #### Batch API ```typescript const results = await client.simulateBatchAPI([ { params: { calls: [{ /* transaction 1 */ }], blockNumber: '0x1234567' }, options: null }, { params: { calls: [{ /* transaction 2 */ }], blockNumber: '0x1234567' }, options: null } ]) results.forEach((result, i) => { console.log(`Simulation ${i + 1}:`, result.isSuccess() ? 'Success' : 'Failed') }) ``` ### Error Handling ```typescript import { AltitraceApiError, ValidationError } from '@altitrace/sdk' try { const result = await client.simulateCall({ to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data: '0xa9059cbb...' }) if (result.isFailed()) { const errors = result.getErrors() errors.forEach(error => { console.error(`Error: ${error.reason} (${error.errorType})`) }) } } catch (error) { if (error instanceof ValidationError) { console.error('Invalid input:', error.message) } else if (error instanceof AltitraceApiError) { console.error('API error:', error.code, error.message) } } ``` ### Types ```typescript interface TransactionCall { from?: string | null to?: string | null data?: string | null value?: string | null gas?: string | null accessList?: AccessList | null } interface ExtendedSimulationResult { simulationId: string status: 'success' | 'reverted' | 'failed' blockNumber: string gasUsed: string blockGasUsed: string calls: CallResult[] assetChanges?: AssetChange[] | null // Helper methods isSuccess(): boolean isFailed(): boolean getTotalGasUsed(): bigint getCallGasUsed(callIndex: number): bigint getErrors(): CallError[] getAssetChangesSummary(): AssetChangeSummary[] getDecodedEvents(): DecodedEvent[] getLogCount(): number } ``` ## traceCall Analyze transaction execution with detailed traces. ### Usage :::code-group ```typescript [example.ts] import { client } from './config' const trace = await client.traceCall({ // [!code focus:7] from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data: '0xa9059cbb0000000000000000000000001234567890123456789012345678901234567890000000000000000000000000000000000000000000000000000000000000000a' }, { callTracer: true }) ``` ```typescript [config.ts] import { AltitraceClient } from '@altitrace/sdk' export const client = new AltitraceClient({ baseUrl: 'http://localhost:8080/v1' }) ``` ::: #### Call Hierarchy Analysis ```typescript const trace = await client.traceCall({ from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D', // Uniswap Router data: '0x38ed1739...', // swapExactTokensForTokens value: '0x0' }, { callTracer: true, prestateTracer: true }) // Analyze call tree if (trace.callTracer) { console.log('Main call:', trace.callTracer.type) console.log('Gas used:', trace.callTracer.gasUsed) console.log('Sub-calls:', trace.callTracer.calls?.length || 0) } ``` #### State Changes Tracking ```typescript const trace = await client.traceCall({ from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data: '0xa9059cbb...' }, { prestateTracer: true }) // Check state changes if (trace.prestateTracer) { Object.entries(trace.prestateTracer).forEach(([address, state]) => { console.log(`Account ${address}:`) if ('balance' in state) console.log(` Balance: ${state.balance}`) if ('nonce' in state) console.log(` Nonce: ${state.nonce}`) }) } ``` ### Builder Pattern For complex traces with multiple tracers. ```typescript const trace = await client.trace() .call({ from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data: '0xa9059cbb...' }) .withCallTracer({ onlyTopCall: false, withLogs: true }) .withPrestateTracer({ diffMode: true }) .with4ByteTracer() .withStructLogger({ disableMemory: true }) .atBlock('latest') .execute() // Access all trace results console.log('Has call trace:', !!trace.callTracer) console.log('Has state trace:', !!trace.prestateTracer) console.log('Has struct logs:', !!trace.structLogger) console.log('Has 4byte data:', !!trace['4byteTracer']) ``` ### Returns `ExtendedTracerResponse` The trace results with all enabled tracers. ### Parameters #### call * **Type:** `TransactionCall` The transaction call to trace. ```typescript const trace = await client.traceCall({ from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', // [!code focus] to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data: '0x095ea7b3...' }) ``` #### options.block (optional) * **Type:** `string | number` * **Default:** `'latest'` The block to trace against. ```typescript const trace = await client.traceCall( { /* transaction */ }, { block: '0x1234567' } // [!code focus] ) ``` #### options.callTracer (optional) * **Type:** `boolean` * **Default:** `false` Enable call hierarchy tracing. ```typescript const trace = await client.traceCall( { /* transaction */ }, { callTracer: true } // [!code focus] ) ``` #### options.prestateTracer (optional) * **Type:** `boolean` * **Default:** `false` Enable state change tracing. ```typescript const trace = await client.traceCall( { /* transaction */ }, { prestateTracer: true } // [!code focus] ) ``` #### options.structLogger (optional) * **Type:** `boolean` * **Default:** `false` Enable opcode-level tracing. ```typescript const trace = await client.traceCall( { /* transaction */ }, { structLogger: true } // [!code focus] ) ``` #### options.fourByteTracer (optional) * **Type:** `boolean` * **Default:** `false` Enable function signature tracking. ```typescript const trace = await client.traceCall( { /* transaction */ }, { fourByteTracer: true } // [!code focus] ) ``` ### Trace Transaction Trace an executed transaction by hash. ```typescript const trace = await client.traceTransaction( '0xbc4a51bbcbe7550446c151d0d53ee14d5318188e2af1726e28a481b075fc7b4c', { callTracer: true, prestateTracer: true, structLogger: true, fourByteTracer: true } ) // Access transaction receipt if (trace.receipt) { console.log('Status:', trace.receipt.status) console.log('Gas used:', trace.receipt.gasUsed) console.log('Logs:', trace.receipt.logsCount) } ``` ### Trace Multiple Calls Trace multiple calls with cumulative state changes. ```typescript const traces = await client.traceCallMany( [ { transactions: [{ from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data: '0x095ea7b3...' // approve }] }, { transactions: [{ from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D', data: '0x38ed1739...' // swap }] } ], { stateContext: { blockNumber: '0x1234567', transactionIndex: -1 }, callTracer: true } ) traces.forEach((trace, i) => { console.log(`Bundle ${i + 1}:`, trace[0]?.callTracer?.gasUsed) }) ``` ### Tracer Configurations #### Call Tracer ```typescript const trace = await client.trace() .call({ /* transaction */ }) .withCallTracer({ onlyTopCall: false, // Include internal calls withLogs: true // Include event logs }) .execute() // Analyze call hierarchy function analyzeCallTree(call: CallFrame, depth = 0) { console.log(' '.repeat(depth) + `${call.type} to ${call.to}`) console.log(' '.repeat(depth) + `Gas: ${call.gasUsed}/${call.gas}`) call.calls?.forEach(subcall => analyzeCallTree(subcall, depth + 1)) } if (trace.callTracer) { analyzeCallTree(trace.callTracer) } ``` #### Prestate Tracer ```typescript const trace = await client.trace() .call({ /* transaction */ }) .withPrestateTracer({ diffMode: true, // Show before/after disableCode: false, // Include bytecode disableStorage: false // Include storage }) .execute() // Analyze state changes if (trace.prestateTracer && 'pre' in trace.prestateTracer) { const { pre, post } = trace.prestateTracer Object.keys(post).forEach(address => { if (!pre[address]) { console.log(`New account: ${address}`) } else { // Compare balances const preBalance = BigInt(pre[address].balance || '0') const postBalance = BigInt(post[address].balance || '0') if (preBalance !== postBalance) { console.log(`Balance change for ${address}:`) console.log(` ${preBalance} -> ${postBalance}`) } } }) } ``` #### Struct Logger ```typescript const trace = await client.trace() .call({ /* transaction */ }) .withStructLogger({ cleanStructLogs: true, disableMemory: true, // Save memory disableReturnData: false, disableStack: false, disableStorage: false }) .execute() // Analyze opcodes if (trace.structLogger?.structLogs) { const storageOps = trace.structLogger.structLogs.filter( log => log.op === 'SSTORE' || log.op === 'SLOAD' ) console.log(`Storage operations: ${storageOps.length}`) storageOps.forEach(op => { console.log(`${op.op} at pc=${op.pc}, gas=${op.gas}`) }) } ``` ### State Overrides Modify state before tracing. ```typescript const trace = await client.trace() .call({ from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data: '0xa9059cbb...' }) .withStateOverrides({ '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c': { balance: '0x1bc16d674ec80000', // 2 ETH nonce: 10 } }) .withCallTracer() .execute() ``` ### Types ```typescript interface ExtendedTracerResponse { callTracer?: CallTraceResponse | null prestateTracer?: PrestateTraceResponse | null structLogger?: StructLogResponse | null '4byteTracer'?: FourByteResponse | null receipt?: TransactionReceiptInfo | null // Helper methods hasCallTrace(): boolean hasPrestateTrace(): boolean hasStructLogs(): boolean has4ByteTrace(): boolean getGasUsed(): bigint getErrors(): string[] } interface CallFrame { type: 'CALL' | 'DELEGATECALL' | 'STATICCALL' | 'CREATE' | 'CREATE2' from: string to?: string value?: string gas: string gasUsed: string input: string output?: string error?: string revertReason?: string calls?: CallFrame[] logs?: LogEntry[] } interface StructLog { pc: number op: string gas: number gasCost: number depth: number stack?: string[] memory?: string[] storage?: Record refund?: number error?: string } ``` ## Transaction Building Build and simulate transactions with the Altitrace SDK. ### Transaction Format ```typescript interface TransactionCall { from?: string | null // Sender address to?: string | null // Recipient (null for contract creation) data?: string | null // Transaction data value?: string | null // ETH value in wei (hex) gas?: string | null // Gas limit (hex) accessList?: AccessList | null // EIP-2930 access list } ``` ### Basic Examples #### ETH Transfer ```typescript const ethTransfer: TransactionCall = { from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0x1234567890123456789012345678901234567890', value: '0xde0b6b3a7640000', // 1 ETH gas: '0x5208' // 21000 gas } const result = await client.simulateCall(ethTransfer) console.log('Gas used:', result.getTotalGasUsed()) ``` #### ERC-20 Transfer ```typescript const tokenTransfer: TransactionCall = { from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC data: '0xa9059cbb' + // transfer(address,uint256) '0000000000000000000000001234567890123456789012345678901234567890' + // to '0000000000000000000000000000000000000000000000000000000000000064' // 100 USDC } const result = await client.simulateCall(tokenTransfer) ``` #### Contract Deployment ```typescript const deployment: TransactionCall = { from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', data: '0x608060405234801561001057600080fd5b50...', // bytecode gas: '0x3d0900' // 4M gas } const result = await client.simulateCall(deployment) if (result.isSuccess()) { console.log('Contract deployed at:', result.calls[0].address) } ``` ### Using Viem Integrate with viem for encoding and decoding. ```typescript import { encodeFunctionData, parseAbi, parseEther } from 'viem' // Encode function call const data = encodeFunctionData({ abi: parseAbi(['function transfer(address to, uint256 amount)']), functionName: 'transfer', args: ['0x1234567890123456789012345678901234567890', parseEther('1')] }) const transaction: TransactionCall = { from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data } const result = await client.simulateCall(transaction) ``` #### Decoding Results ```typescript import { decodeAbiParameters, parseAbi } from 'viem' const result = await client.simulateCall({ to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data: encodeFunctionData({ abi: parseAbi(['function balanceOf(address) view returns (uint256)']), functionName: 'balanceOf', args: ['0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c'] }) }) if (result.isSuccess()) { const [balance] = decodeAbiParameters( parseAbi(['uint256']), result.calls[0].returnData ) console.log('Balance:', balance) } ``` ### Gas Estimation Estimate gas by simulating first. ```typescript // Simulate to get gas estimate const simulation = await client.simulateCall({ from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data: '0xa9059cbb...' }) if (simulation.isSuccess()) { const gasUsed = simulation.getTotalGasUsed() console.log('Estimated gas:', gasUsed) } ``` ### Multicall Pattern ```typescript import { encodeFunctionData, parseAbi } from 'viem' const multicallAbi = parseAbi([ 'function multicall(bytes[] calldata data) returns (bytes[] memory results)' ]) // Batch multiple calls const calls = [ encodeFunctionData({ abi: parseAbi(['function approve(address spender, uint256 amount)']), functionName: 'approve', args: ['0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D', parseEther('100')] }), encodeFunctionData({ abi: parseAbi(['function transfer(address to, uint256 amount)']), functionName: 'transfer', args: ['0x1234567890123456789012345678901234567890', parseEther('10')] }) ] const multicallTx: TransactionCall = { from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0x5BA1e12693Dc8F9c48aAD8770482f4739bEeD696', // Multicall3 data: encodeFunctionData({ abi: multicallAbi, functionName: 'multicall', args: [calls] }) } const result = await client.simulateCall(multicallTx) ``` ### Common Patterns #### Safe Transfer ```typescript // Check balance before transfer const balanceCheck = await client.simulateCall({ to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data: encodeFunctionData({ abi: parseAbi(['function balanceOf(address) view returns (uint256)']), functionName: 'balanceOf', args: ['0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c'] }) }) if (balanceCheck.isSuccess()) { const [balance] = decodeAbiParameters( parseAbi(['uint256']), balanceCheck.calls[0].returnData ) const transferAmount = parseEther('10') if (balance >= transferAmount) { // Proceed with transfer const transfer = await client.simulateCall({ from: '0x742d35Cc6634C0532925a3b844Bc9e7595f06e8c', to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data: encodeFunctionData({ abi: parseAbi(['function transfer(address to, uint256 amount)']), functionName: 'transfer', args: ['0x1234567890123456789012345678901234567890', transferAmount] }) }) } } ``` #### Transaction Validation ```typescript import { isAddress, isHex } from 'viem' function validateTransaction(tx: TransactionCall): boolean { if (tx.from && !isAddress(tx.from)) return false if (tx.to && !isAddress(tx.to)) return false if (tx.data && !isHex(tx.data)) return false if (tx.value && !isHex(tx.value)) return false if (tx.gas && !isHex(tx.gas)) return false return true } ``` ## What is Altitrace? Altitrace is a comprehensive **HyperEVM transaction simulation platform** developed by **Altitude Labs** for the [Hyperliquid Hackathon](https://taikai.network/en/hl-hackathon-organizers/hackathons/hl-hackathon/overview). The platform serves as essential infrastructure for the HyperEVM ecosystem, enabling developers, DeFi protocols, and users to simulate, debug, and optimize their transactions before execution on-chain. ### Hackathon Bounty Alignment Altitrace directly addresses the **HyperEVM Transaction Simulator** bounty requirements by providing a complete simulation platform with: **Transaction Simulation Engine** featuring 100% accurate gas usage breakdown, real-time state simulation against current HyperEVM network state, historical simulation support against past blockchain states, and full control over transaction inputs and execution context. **Advanced Simulation Features** including state overrides for modifying contract storage and balances, account impersonation for testing without private keys, bundle simulations for testing chained interdependent transactions, and access list generation for gas efficiency optimization. **Transaction Analysis & Insights** providing detailed ERC-20/ERC-721 token flow analysis, granular gas usage breakdown by operation, human-readable event logs and state changes, clear actionable error messages for failed transactions, and complete step-by-step transaction execution details. **Developer Integration** through a comprehensive REST API for programmatic access, TypeScript SDK with strong typing, and extensive API documentation with integration guides. **User Interface** featuring an intuitive web dashboard for manual transaction simulation, visual transaction builder for constructing complex transactions, clear presentation of simulation results and insights, and shareable results for collaborative debugging. ### Technical Architecture Altitrace implements a modern **Turborepo** monorepo structure with three tightly integrated packages: **`packages/api`** houses a high-performance Rust API server built with Actix Web, featuring comprehensive OpenAPI documentation, advanced simulation capabilities with multiple trace modes, direct HyperEVM RPC integration through Alloy, Redis caching for performance optimization, and structured error handling with detailed diagnostics. **`packages/sdk`** provides a strongly-typed TypeScript SDK with modular architecture, dedicated clients for simulation, tracing, and access list generation, comprehensive request builders and utility functions, seamless viem integration for enhanced EVM tooling, automatic OpenAPI type generation, and extensive example implementations. **`packages/frontend`** delivers a modern React application built with Next.js, featuring sophisticated transaction simulation interfaces, real-time visual analytics and gas analysis, ABI import and function building capabilities, advanced trace visualization with call frame trees, responsive design for desktop and mobile usage, and comprehensive state management with Zustand. ### Core Capabilities The platform provides **Transaction Simulation** with accurate execution against live or historical HyperEVM states, comprehensive gas analysis with breakdown by operation, detailed event log decoding and state change tracking, support for complex transaction bundles with dependency analysis, and advanced error handling with actionable diagnostic information. **State Control Features** enable complete account state overrides including balances and storage, contract code modification for testing bug fixes, block environment overrides for timestamp and number manipulation, access list optimization for gas efficiency improvements, and account impersonation for testing without private key requirements. **Developer Experience** enhancements include comprehensive TypeScript support with zero `any` types, seamless viem integration for enhanced EVM tooling, modular SDK architecture for flexible integration, extensive documentation with practical examples, and automated OpenAPI type generation for API consistency. ### Getting Started Ready to explore the platform? Begin with our [installation guide](/installation) for local development setup, review the [API documentation](/api) for programmatic integration, explore the [SDK documentation](/sdk) for TypeScript development, or try the [web application](/webapp) for interactive simulation testing. ## Why Altitrace? Transaction simulation is critical for modern DeFi development, but existing solutions often fall short when working with HyperEVM. Altitrace fills this gap with purpose-built tooling. ### The Problem #### Existing Limitations * **Generic Solutions**: Most simulators are built for EVM mainnet, missing HyperEVM-specific features * **Poor Developer Experience**: Weak typing, unclear APIs, and limited debugging capabilities * **Incomplete Analysis**: Surface-level results without detailed trace analysis * **Fragmented Tooling**: Different tools for simulation, debugging, and analysis #### HyperEVM Challenges * Network-specific optimizations and features * Different gas mechanics and pricing * Unique transaction patterns and flows * Limited existing tooling ecosystem ### The Altitrace Solution #### 🎢 HyperEVM Native Built specifically for HyperEVM with deep understanding of network mechanics, gas pricing, and unique features. #### 🛠️ Developer First * **Strong TypeScript Support**: Never use `any` - precise types throughout * **Viem Integration**: Leverage the best EVM tooling ecosystem * **Clear APIs**: Intuitive interfaces that make sense * **Comprehensive Documentation**: Examples, guides, and references #### 🔍 Complete Analysis * **Detailed Traces**: Full EVM execution traces with step-by-step analysis * **Storage Diffs**: See exactly what state changes occur * **Gas Breakdown**: Understand where gas is consumed * **Error Analysis**: Clear insights into transaction failures #### 📦 Unified Platform * **API**: Programmatic access for integrations * **SDK**: Type-safe client library * **Web UI**: Visual interface for manual analysis * **All-in-One**: Everything you need in a single platform ### Use Cases #### For DeFi Protocols * Test complex transaction bundles before execution * Optimize gas usage across multi-step operations * Debug failed transactions in development * Simulate edge cases and error conditions #### For dApp Developers * Integrate simulation into frontend workflows * Provide users with transaction previews * Debug smart contract interactions * Optimize user experience with gas estimates #### For Traders & Power Users * Simulate MEV strategies before execution * Test arbitrage opportunities * Analyze complex DeFi operations * Debug failed transactions ### Technical Advantages #### Performance * Fast simulation with optimized HyperEVM integration * Efficient batch processing for multiple scenarios * Minimal latency for real-time use cases #### Reliability * Accurate results matching actual HyperEVM execution * Comprehensive error handling and reporting * Robust API with proper retry and timeout handling #### Extensibility * Plugin architecture for custom analysis * Open-source foundation for community contributions * Clear interfaces for third-party integrations Ready to experience the difference? [Get started with Altitrace](/installation) today. ## Configuration ### Environment Variables ```bash # .env file HYPEREVM_RPC_URL=http://localhost:8545 HYPEREVM_CHAIN_ID=1337 # API Configuration API_PORT=8080 API_HOST=0.0.0.0 API_CORS_ORIGINS=* # Redis Configuration REDIS_URL=redis://localhost:6379 REDIS_DB=0 # Logging RUST_LOG=info DEBUG=altitrace:* # Performance MAX_CONCURRENT_REQUESTS=100 REQUEST_TIMEOUT=30000 ``` ### API Configuration ```toml # packages/api/config/default.toml [server] host = "0.0.0.0" port = 8080 cors_origins = ["*"] [hyperevm] rpc_url = "http://localhost:8545" chain_id = 1337 gas_limit = 30000000 [redis] url = "redis://localhost:6379" db = 0 max_connections = 10 [tracing] level = "info" format = "json" ``` ### SDK Configuration ```typescript import { AltitraceClient } from '@altitrace/sdk' const client = new AltitraceClient({ baseUrl: 'http://localhost:8080/v1', timeout: 30000, retries: 3, retryDelay: 1000, // Authentication apiKey: process.env.ALTITRACE_API_KEY, // Debug options debug: process.env.NODE_ENV === 'development', validateResponses: true, // Custom headers headers: { 'User-Agent': 'MyApp/1.0.0' } }) ``` ### Frontend Configuration ```typescript // packages/frontend/next.config.js const nextConfig = { env: { ALTITRACE_API_URL: process.env.ALTITRACE_API_URL || 'http://localhost:8080', HYPEREVM_RPC_URL: process.env.HYPEREVM_RPC_URL || 'http://localhost:8545', }, async rewrites() { return [ { source: '/api/:path*', destination: `${process.env.ALTITRACE_API_URL}/:path*` } ] } } ``` ### Production Configuration #### Docker Environment ```yaml # docker-compose.yml version: '3.8' services: api: environment: - HYPEREVM_RPC_URL=https://rpc.hyperevm.org - REDIS_URL=redis://redis:6379 - RUST_LOG=warn - API_PORT=8080 frontend: environment: - ALTITRACE_API_URL=http://api:8080 - NODE_ENV=production ``` #### Systemd Service ```ini # /etc/systemd/system/altitrace-api.service [Unit] Description=Altitrace API Server After=network.target [Service] Type=simple User=altitrace WorkingDirectory=/opt/altitrace/packages/api ExecStart=/usr/local/bin/altitrace-api Restart=always RestartSec=5 Environment=HYPEREVM_RPC_URL=https://rpc.hyperevm.org Environment=REDIS_URL=redis://localhost:6379 Environment=RUST_LOG=info [Install] WantedBy=multi-user.target ``` ### Performance Tuning #### API Server ```toml [performance] max_concurrent_requests = 200 request_timeout = 60000 worker_threads = 4 [cache] simulation_ttl = 300 # 5 minutes trace_ttl = 1800 # 30 minutes access_list_ttl = 600 # 10 minutes ``` #### Redis Optimization ```bash # redis.conf maxmemory 2gb maxmemory-policy allkeys-lru tcp-keepalive 60 timeout 300 ``` #### Database Connection Pool ```toml [database] max_connections = 20 min_connections = 5 connection_timeout = 5000 idle_timeout = 600000 ``` ### Security Configuration #### CORS Settings ```toml [cors] origins = ["https://app.altitrace.com", "https://docs.altitrace.com"] methods = ["GET", "POST", "PUT", "DELETE"] headers = ["Content-Type", "Authorization"] credentials = true ``` #### Rate Limiting ```toml [rate_limit] requests_per_minute = 60 burst_size = 10 whitelist = ["127.0.0.1", "10.0.0.0/8"] ``` #### Authentication ```toml [auth] jwt_secret = "your-secret-key" token_expiry = 3600 require_api_key = true ``` ### Monitoring #### Logging Configuration ```toml [logging] level = "info" format = "json" output = "stdout" [logging.fields] timestamp = true request_id = true user_agent = true ip_address = true ``` #### Metrics Export ```toml [metrics] enabled = true endpoint = "/metrics" interval = 30 [tracing.jaeger] enabled = true endpoint = "http://jaeger:14268" service_name = "altitrace-api" ``` ### Troubleshooting #### Common Issues ```bash # Check configuration altitrace-api --check-config # Validate environment altitrace-api --validate-env # Test connections curl http://localhost:8080/v1/status/healthcheck ``` #### Debug Mode ```bash # Enable debug logging RUST_LOG=debug altitrace-api # SDK debug mode DEBUG=altitrace:* npm start ``` ## Installation Get Altitrace running in minutes. ### Prerequisites * **Node.js 18+** and **Bun 1.2.7+** * **Rust toolchain** (see rust-toolchain.toml) * **Redis** (or use our docker-compose) * **HyperEVM node** with [nanoreth](https://github.com/hl-archive-node/nanoreth) for trace support ### Quick Start ```bash # Clone and setup git clone https://github.com/altitude-dev/altitrace.git cd altitrace bun install # Start Redis (if not installed) docker compose up -d redis # Configure environment cp .env.example .env # Edit .env with your HyperEVM RPC URL # Run everything bun run dev ``` This starts: * API server on [http://localhost:8080](http://localhost:8080) * Frontend on [http://localhost:3000](http://localhost:3000) * SDK in watch mode ### Verify Installation ```bash # Check API health curl http://localhost:8080/v1/status/healthcheck # Access Swagger UI open http://localhost:8080/v1/openapi/docs # Open web interface open http://localhost:3000 ``` ### Configuration Create a `.env` file in the root directory: ```env # HyperEVM RPC Configuration HYPEREVM_RPC_URL=http://localhost:8545 HYPEREVM_CHAIN_ID=1337 # API Configuration API_PORT=8080 API_HOST=0.0.0.0 # Optional: Enable debug logging DEBUG=altitrace:* ``` ### Next Steps * 📚 [Learn about the API](/api) - Understand the REST and RPC endpoints * 🛠️ [Explore the SDK](/sdk) - Integrate Altitrace into your applications * 🖥️ [Try the Web UI](/webapp) - Use the visual interface for manual simulations * ⚙️ [Advanced Configuration](/installation/configuration) - Customize your setup ### Getting Help Need assistance? Here are your options: * 💬 [GitHub Discussions](https://github.com/altitude-dev/altitrace/discussions) - Community support * 🐛 [GitHub Issues](https://github.com/altitude-dev/altitrace/issues) - Bug reports and features * 📚 [Documentation](/introduction) - Comprehensive guides and references ### Troubleshooting Common issues and solutions: #### Connection Issues ```bash # Check HyperEVM node connectivity curl -X POST -H "Content-Type: application/json" \ --data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' \ http://localhost:8545 ``` #### Port Conflicts If ports 3000 or 8080 are in use, update your `.env` file: ```env API_PORT=8081 FRONTEND_PORT=3001 ``` #### Permission Issues Ensure your user has permission to bind to the configured ports, or run with appropriate privileges. ## Authentication The Altitrace API implements a flexible authentication system through TOML configuration files, supporting both development and production deployment scenarios. ### Configuration Authentication is managed through environment-specific TOML configuration files in `packages/api/config/`: **Development (`dev.toml`)** - typically runs without authentication: ```toml [api] auth_token = "" # Empty string disables authentication rate_limit_requests = 100 rate_limit_duration = 60 ``` **Production (`prod.toml`)** - should always configure authentication: ```toml [api] auth_token = "your_secure_production_token_here" rate_limit_requests = 1000 rate_limit_duration = 60 ``` **Test (`test.toml`)** - uses predefined tokens for automated testing: ```toml [api] auth_token = "test_token_for_automated_testing" rate_limit_requests = 100 rate_limit_duration = 60 ``` ### Authentication Methods When authentication is enabled, the API supports two header formats: #### Bearer Token ```http Authorization: Bearer your_api_token_here ``` #### API Key ```http X-API-Key: your_api_token_here ``` ### Request Examples **With Bearer Token:** ```bash curl -X POST "http://localhost:8080/v1/simulate" \ -H "Authorization: Bearer your_api_token_here" \ -H "Content-Type: application/json" \ -d '{"params": {"calls": [...]}}' ``` **With API Key:** ```bash curl -X POST "http://localhost:8080/v1/simulate" \ -H "X-API-Key: your_api_token_here" \ -H "Content-Type: application/json" \ -d '{"params": {"calls": [...]}}' ``` ### SDK Integration ```typescript import { AltitraceClient } from '@altitrace/sdk' // Bearer token authentication const client = new AltitraceClient({ baseUrl: 'http://localhost:8080/v1', headers: { 'Authorization': 'Bearer your_api_token_here' } }) // API key authentication const clientWithApiKey = new AltitraceClient({ baseUrl: 'http://localhost:8080/v1', headers: { 'X-API-Key': 'your_api_token_here' } }) ``` ### Error Responses **Missing Authentication:** ```json { "success": false, "error": { "code": "AUTHENTICATION_REQUIRED", "message": "Authentication token required for this endpoint", "suggestion": "Include 'Authorization: Bearer ' or 'X-API-Key: ' header" } } ``` **Invalid Authentication:** ```json { "success": false, "error": { "code": "AUTHENTICATION_INVALID", "message": "Invalid or expired authentication token", "suggestion": "Verify your API token and ensure it matches the server configuration" } } ``` ### Rate Limiting Authentication integrates with rate limiting. Configured limits apply per environment: ```toml [api] rate_limit_requests = 1000 # Requests per duration window rate_limit_duration = 60 # Duration window in seconds ``` ### CORS Configuration Cross-origin resource sharing is configurable per environment: ```toml [api.cors] allowed_origins = ["https://altitrace.com"] allowed_methods = ["GET", "POST", "PUT", "DELETE", "OPTIONS"] allowed_headers = ["accept", "content-type", "authorization", "x-api-key"] allow_credentials = true max_age = 86400 ``` ## API Reference The Altitrace API provides programmatic access to HyperEVM transaction simulation and debugging capabilities. Built with **Rust and Actix Web**, the API offers high-performance REST endpoints with comprehensive OpenAPI documentation and automatic type generation. ### Base URL ``` http://localhost:8080/v1 ``` ### Interactive Documentation The API features a **Swagger UI** interface for interactive testing and exploration: ``` http://localhost:8080/v1/openapi/docs ``` This interactive documentation provides complete API schema definitions, request/response examples, parameter validation, and the ability to test endpoints directly from your browser. The OpenAPI specification is automatically generated from the Rust code, ensuring documentation stays synchronized with implementation. ### Configuration The API uses **TOML configuration files** located in `packages/api/config/` for environment-specific settings: * `dev.toml` - Development configuration with permissive CORS and no authentication * `prod.toml` - Production configuration with restricted origins and optional auth tokens * `test.toml` - Test configuration optimized for automated testing #### Authentication Authentication is configured through the `auth_token` field in the TOML configuration: ```toml [api] auth_token = "your_secret_token_here" rate_limit_requests = 1000 rate_limit_duration = 60 ``` When an auth token is configured, requests must include the `Authorization: Bearer ` header or `X-API-Key: ` header. #### Rate Limiting The API implements configurable rate limiting per IP address: ```toml [api] rate_limit_requests = 1000 # requests per duration window rate_limit_duration = 60 # duration window in seconds ``` #### CORS Configuration Cross-origin resource sharing is fully configurable per environment: ```toml [api.cors] allowed_origins = ["https://altitrace.com", "https://www.altitrace.com"] allowed_methods = ["GET", "POST", "PUT", "DELETE", "OPTIONS"] allowed_headers = ["accept", "content-type", "authorization", "x-api-key"] allow_credentials = true max_age = 86400 ``` #### Redis Caching The API uses Redis for performance optimization and caching: ```toml [redis] url = "redis://localhost:6379" ``` ### REST Endpoints #### Health Check ```http GET /health ``` Returns the API health status and version information. **Response:** ```json { "status": "ok", "version": "1.0.0", "network": "hyperevm", "uptime": 3600 } ``` #### Simulate Transaction ```http POST /simulate ``` Simulates a transaction without executing it on-chain. **Request Body:** ```json { "transaction": { "from": "0x742d35Cc6634C0532925a3b8D86C4F5e573F7d5B", "to": "0xA0b86a33E6441a8F9d6f4c13f8a39c3A7a4e8c", "value": "0x0", "data": "0xa9059cbb...", "gas": "0x5208" }, "blockNumber": "latest", "traceConfig": { "enableMemory": true, "enableReturnData": true, "enableStorage": true } } ``` **Response:** ```json { "success": true, "result": { "gasUsed": "0x5208", "gasLimit": "0x5208", "logs": [], "returnValue": "0x", "trace": { "steps": [], "storageChanges": {}, "memoryChanges": [] } } } ``` #### Batch Simulation ```http POST /simulate/batch ``` Simulates multiple transactions in sequence. **Request Body:** ```json { "transactions": [ { "from": "0x742d35Cc6634C0532925a3b8D86C4F5e573F7d5B", "to": "0xA0b86a33E6441a8F9d6f4c13f8a39c3A7a4e8c", "data": "0xa9059cbb..." } ], "blockNumber": "latest" } ``` ### SDK Integration The [TypeScript SDK](/sdk) provides a type-safe client for this API: ```typescript import { AltitraceClient } from '@altitrace/sdk' const client = new AltitraceClient({ apiUrl: 'http://localhost:8080/api/v1' }) const result = await client.simulate({ transaction: { from: '0x742d35Cc6634C0532925a3b8D86C4F5e573F7d5B', to: '0xA0b86a33E6441a8F9d6f4c13f8a39c3A7a4e8c', data: '0xa9059cbb...' } }) ``` ### Next Steps * 🔐 [Authentication](/api/authentication) - Secure your API access * 📊 [Simulation Endpoints](/api/simulation) - Detailed simulation API reference * 🔗 [Transaction Endpoints](/api/transactions) - Detailed transaction API reference ## Simulation Endpoints The simulation endpoints provide core transaction simulation capabilities for HyperEVM, enabling developers to test transactions, analyze gas usage, and debug execution flows before on-chain execution. ### Single Transaction Simulation #### `POST /simulate` Simulates a single transaction against the current or specified HyperEVM state with detailed execution analysis. **Request:** ```json { "params": { "calls": [{ "from": "0x742d35Cc6634C0532925a3b8D86C4F5e573F7d5B", "to": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "data": "0xa9059cbb...", "gas": "0x7a120" }], "blockTag": "latest", "validation": true }, "options": { "stateOverrides": [{ "address": "0x742d35Cc6634C0532925a3b8D86C4F5e573F7d5B", "balance": "0x1bc16d674ec80000" }] } } ``` **Response:** ```json { "success": true, "data": { "simulationId": "sim_01234567-89ab-cdef-0123-456789abcdef", "status": "success", "gasUsed": "0x5208", "calls": [{ "callIndex": 0, "status": "success", "returnData": "0x01", "gasUsed": "0x5208", "logs": [{ "address": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"], "data": "0x0000000000000000000000000000000000000000000000000000000000989680", "decoded": { "name": "Transfer", "summary": "Transfer 10.0 USDC from 0x742d... to 0x742d..." } }] }] } } ``` ### Batch Transaction Simulation #### `POST /simulate/batch` Simulates multiple independent transactions in parallel, each receiving separate analysis. **Request:** ```json [ { "params": { "calls": [{"from": "0x742d...", "to": "0xA0b8...", "data": "0xa905..."}], "blockTag": "latest" } }, { "params": { "calls": [{"from": "0x8ba1...", "to": "0x1f98...", "data": "0x70a0..."}], "blockNumber": "0x123abc" } } ] ``` **Response:** ```json { "success": true, "data": [ {"simulationId": "sim_123...", "status": "success", "gasUsed": "0x5208"}, {"simulationId": "sim_456...", "status": "success", "gasUsed": "0x7530"} ] } ``` ### State and Block Overrides Modify account states and block environment for testing different scenarios. #### State Overrides ```json { "options": { "stateOverrides": [{ "address": "0x742d35Cc6634C0532925a3b8D86C4F5e573F7d5B", "balance": "0x1bc16d674ec80000", "storage": {"0x0": "0x1"}, "code": "0x608060405234801561001057600080fd5b50" }] } } ``` #### Block Overrides ```json { "options": { "blockOverrides": { "number": "0x123456", "time": 1700000000, "baseFee": "0x3b9aca00", "gasLimit": 30000000 } } } ``` ### Advanced Features #### Asset Change Tracking Track ERC-20/ERC-721 token balance changes: ```json { "params": { "calls": [...], "account": "0x742d35Cc6634C0532925a3b8D86C4F5e573F7d5B", "traceAssetChanges": true, "traceTransfers": true } } ``` #### Validation Control ```json { "params": { "validation": false // Disable validation for relaxed execution } } ``` ### SDK Integration ```typescript import { createClient } from '@altitrace/sdk' const client = createClient.local() // Single simulation const result = await client.simulation.simulate({ params: { calls: [{ from: '0x742d35Cc6634C0532925a3b8D86C4F5e573F7d5B', to: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', data: '0xa9059cbb...' }] } }) // Batch simulation const batchResults = await client.simulation.simulateBatch([ { params: { calls: [...] } }, { params: { calls: [...] } } ]) ``` ## Transaction endpoints The transaction endpoints provide comprehensive analysis capabilities for transactions, including access list generation, detailed execution traces, and multi-level debugging information. ### Access List Generation Generate optimized access lists for transactions to reduce gas costs through EIP-2930 pre-declaration of storage slots and addresses. #### `POST /simulate/access-list` Analyzes transaction execution to identify all accessed storage locations and addresses, returning an optimized access list. ```json { "params": { "from": "0x742d35Cc6634C0532925a3b8D86C4F5e573F7d5B", "to": "0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984", "data": "0xa9059cbb..." }, "block": "latest" } ``` **Response:** ```json { "success": true, "data": { "accessList": [ { "address": "0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984", "storageKeys": ["0x0000000000000000000000000000000000000000000000000000000000000001"] } ], "gasUsed": "0x5208" } } ``` ### Transaction Tracing #### `POST /trace/tx` Traces an existing transaction by hash with comprehensive execution analysis. ```json { "transactionHash": "0xbc4a51bbcbe7550446c151d0d53ee14d5318188e2af1726e28a481b075fc7b4c", "tracerConfig": { "callTracer": { "withLogs": true }, "prestateTracer": { "diffMode": true }, "4byteTracer": true } } ``` #### `POST /trace/call` Traces a hypothetical transaction call without on-chain execution. ```json { "call": { "from": "0x742d35Cc6634C0532925a3b8D86C4F5e573F7d5B", "to": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "data": "0x70a08231..." }, "tracerConfig": { "callTracer": { "withLogs": true } } } ``` #### `POST /trace/call-many` Traces multiple calls sequentially with cumulative state changes, useful for transaction bundle analysis. ```json { "bundles": [{ "transactions": [ { "from": "0x742d...", "to": "0x1f98...", "data": "0xa905..." }, { "from": "0x742d...", "to": "0xA0b8...", "data": "0x095e..." } ] }], "tracerConfig": { "callTracer": { "withLogs": true } } } ``` ### Tracer Types The API supports multiple tracer types that can be used individually or combined for comprehensive analysis. The Call tracer is used by default. #### Call Tracer Provides hierarchical transaction execution analysis with call structure, gas usage, and sub-call relationships. ```typescript interface CallTracerConfig { onlyTopCall?: boolean // Trace only top-level call withLogs?: boolean // Include event logs } ``` **Response includes:** * Hierarchical call structure with gas tracking * Input/output data for each call * Event logs and revert reasons * Call depth and execution flow #### Prestate Tracer Captures account states before and after execution for state change analysis. ```typescript interface PrestateTracerConfig { diffMode?: boolean // Show before/after state differences disableCode?: boolean // Exclude contract code from results disableStorage?: boolean // Exclude storage from results } ``` **Default mode:** Returns all accounts touched during execution **Diff mode:** Shows precise state changes with before/after values #### Struct Logger Provides detailed opcode-level execution traces for deep debugging. ```typescript interface StructLoggerConfig { cleanStructLogs?: boolean // Remove redundant information disableMemory?: boolean // Exclude memory from traces disableStack?: boolean // Exclude stack from traces disableStorage?: boolean // Exclude storage from traces cleanStructLogs?: boolean // Avoid returning every opcode execution step } ``` **Response includes:** * Step-by-step opcode execution * Stack, memory, and storage states * Gas consumption per operation * Execution errors and context #### 4-Byte Tracer Analyzes function signatures and call patterns throughout execution. ```json { "totalIdentifiers": 3, "identifiers": { "0xa9059cbb": { "count": 2, "dataSize": 128 }, "0x70a08231": { "count": 1, "dataSize": 32 } } } ``` ### Advanced Features #### State and Block Overrides All trace endpoints support state modifications for testing scenarios: ```json { "stateOverrides": { "0x742d35Cc6634C0532925a3b8D86C4F5e573F7d5B": { "balance": "0x1bc16d674ec80000", "storage": { "0x0": "0x1" } } }, "blockOverrides": { "number": "0x123456", "time": 1700000000, "baseFee": "0x3b9aca00" } } ``` #### Multi-Tracer Analysis Combine multiple tracers in a single request for comprehensive debugging: ```json { "tracerConfig": { "callTracer": { "withLogs": true }, "prestateTracer": { "diffMode": true }, "structLogger": { "cleanStructLogs": true }, "4byteTracer": true } } ``` ### Error Handling Trace endpoints return structured errors with actionable information: ```json { "success": false, "error": { "code": "SIMULATION_EXECUTION_FAILED", "message": "Transaction execution reverted", "details": { "revertReason": "ERC20: transfer amount exceeds balance", "contractAddress": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" }, "suggestion": "Check account balance before attempting transfer" } } ``` Common error codes include: * `VALIDATION_ERROR` - Invalid request parameters * `SIMULATION_EXECUTION_FAILED` - Transaction execution issues * `STATE_ACCESS_ERROR` - Blockchain state access problems * `INSUFFICIENT_GAS` - Gas limit too low ### SDK Integration The TypeScript SDK provides convenient access to all tracing functionality: ```typescript import { createClient } from '@altitrace/sdk' const client = createClient.local() // Generate access list const accessList = await client.accessList.create({ params: { from: '0x742d...', to: '0x1f98...', data: '0xa905...' } }) // Trace existing transaction const trace = await client.trace.traceTransaction({ transactionHash: '0xbc4a51bb...', tracerConfig: { callTracer: { withLogs: true } } }) // Trace hypothetical call const callTrace = await client.trace.traceCall({ call: { from: '0x742d...', to: '0xA0b8...', data: '0x70a0...' }, tracerConfig: { callTracer: { withLogs: true } } }) ```