hadv / hadv/ethaura

Implement Transaction Simulation for Enhanced Wallet Security

Open
#140 0 comments 0 reactions 0 assignees View on GitHub
⛨ security enhancement UI/UX
Dominant language
JavaScript
Stars
2
Forks
0
PR merge metrics
No merged PRs in 30d

Description

## Overview

Transaction simulation is a critical security feature that allows users to preview the exact outcomes of a transaction before signing. This protects users from phishing attacks, malicious dApps, scam tokens, and unexpected transaction behavior.

## Background

Current state: EthAura has basic transaction validation (`validateUserOperation`) but lacks pre-execution simulation that shows users:
- What assets they're sending vs receiving
- State changes (balance changes, approval changes)
- Potential risks and warnings
- Whether the transaction will succeed or fail

## Why Transaction Simulation is Important

### Security Benefits
1. **Phishing Protection**: Detect when a "token claim" is actually draining the wallet
2. **Scam Token Detection**: Identify tokens with malicious transfer logic (honeypots)
3. **Approval Attack Prevention**: Warn when granting unlimited token approvals to suspicious contracts
4. **Slippage Protection**: Preview actual swap outcomes before execution
5. **Failed Transaction Prevention**: Avoid wasting gas on transactions that will revert

### User Experience Benefits
1. **Confidence**: Users see exactly what will happen before signing
2. **Transparency**: Clear breakdown of asset movements
3. **Education**: Help users understand complex transactions
4. **Recovery Prevention**: Catch mistakes before they're on-chain

## Proposed Implementation

### Phase 1: Basic On-Chain Simulation (MVP)

Use ERC-4337 EntryPoint's built-in simulation capabilities:

```javascript
// Use EntryPointSimulations contract for validation
import { simulateValidation, simulateHandleOp } from './userOpSimulation'

async function simulateUserOperation(userOp) {
// 1. Validate the UserOp will be accepted
const validationResult = await simulateValidation(userOp, entryPointAddress)

// 2. Simulate the full execution
const executionResult = await simulateHandleOp(
userOp,
targetAddress,
targetCallData,
entryPointAddress
)

return {
willSucceed: executionResult.targetSuccess,
gasUsed: executionResult.paid,
validationData: validationResult,
}
}
```

**Tasks:**
- [ ] Implement `simulateValidation()` wrapper using EntryPointSimulations
- [ ] Implement `simulateHandleOp()` for full execution simulation
- [ ] Add eth_call with state override for simulation
- [ ] Parse simulation results into user-friendly format
- [ ] Show simulation results before asking for passkey signature

### Phase 2: Balance Change Preview

Track state changes during simulation:

```javascript
const simulationResult = {
balanceChanges: [
{ token: 'ETH', symbol: 'ETH', before: '1.5', after: '1.4', change: '-0.1' },
{ token: '0xA0b8...', symbol: 'USDC', before: '0', after: '150.5', change: '+150.5' },
],
approvalChanges: [
{ token: 'USDC', spender: '0x68b...', allowance: '1000', warning: false },
],
riskLevel: 'low', // low, medium, high, critical
warnings: [],
}
```

**Tasks:**
- [ ] Implement balance diff tracking (before vs after simulation)
- [ ] Track ERC20/ERC721 approval changes
- [ ] Display balance changes in confirmation screen
- [ ] Color-code gains (green) and losses (red)

### Phase 3: Risk Assessment & Warnings

Analyze transactions for common attack patterns:

| Risk Type | Detection Method | Warning |
|-----------|------------------|----------|
| Unlimited approval | `allowance == MAX_UINT256` | "Granting unlimited access to your tokens" |
| New/unverified contract | No source on Etherscan | "Interacting with unverified contract" |
| Draining transaction | Sends assets, receives nothing | "This transaction sends assets but receives nothing" |
| Honeypot token | Transfer fails in simulation | "Token may prevent selling" |
| Large price impact | > 10% deviation from quote | "High price impact detected" |
| First-time interaction | Never interacted with contract | "First time interacting with this dApp" |

**Tasks:**
- [ ] Implement approval pattern detection
- [ ] Check contract verification status
- [ ] Analyze asset flow (in vs out)
- [ ] Detect suspicious transfer patterns
- [ ] Display warnings with severity levels
- [ ] Allow user to proceed with acknowledgment

### Phase 4: External Simulation API Integration (Optional)

Consider integrating with specialized simulation services for enhanced detection:

| Service | Features | Cost |
|---------|----------|------|
| **Tenderly** | Full trace, state diffs, gas profiling | Freemium |
| **Blowfish** | Security-focused, phishing detection | API key |
| **Blockaid** | ML-based threat detection | Enterprise |
| **Alchemy Transact** | Simple simulation API | Freemium |

**Tasks:**
- [ ] Evaluate simulation API providers
- [ ] Implement Tenderly integration (recommended for MVP)
- [ ] Add fallback to on-chain simulation if API fails
- [ ] Handle rate limiting and caching

## UI/UX Design

### Confirmation Screen Enhancement

The SwapConfirmationScreen already has a placeholder for transaction simulation. Update it to show:

```
┌─────────────────────────────────────┐
│ Transaction Simulation │
├─────────────────────────────────────┤
│ │
│ 📊 Balance Changes │
│ ┌─────────────────────────────────┐│
│ │ ETH 1.5 → 1.4 (-0.1) ││
│ │ USDC 0 → 150.5 (+150.5) ││
│ └─────────────────────────────────┘│
│ │
│ ⚠️ Warnings │
│ • First time interacting with │
│ this contract │
│ │
│ ✅ Simulation Status: Success │
│ Estimated Gas: 150,000 │
│ │
└─────────────────────────────────────┘
```

### Transaction States

1. **Loading**: "Simulating transaction..."
2. **Success**: Green checkmark, show changes
3. **Warning**: Yellow banner with warnings
4. **Blocked**: Red banner, prevent execution for critical risks
5. **Failed**: Show revert reason, don't allow execution

## Technical Implementation Details

### Files to Create

1. **`frontend/src/lib/transactionSimulator.js`**
- Core simulation logic
- Balance diff tracking
- Risk assessment

2. **`frontend/src/components/SimulationResults.jsx`**
- Display component for simulation results
- Balance change visualization
- Warning display

3. **`frontend/src/components/SimulationWarning.jsx`**
- Risk warning banners
- Acknowledgment checkbox for warnings

### Files to Modify

1. **`frontend/src/screens/SwapConfirmationScreen.jsx`**
- Integrate simulation results display
- Replace placeholder with actual simulation

2. **`frontend/src/components/TransactionSender.jsx`**
- Add simulation before signing
- Show simulation modal/screen

3. **`frontend/src/lib/bundlerClient.js`**
- Add simulation methods

### EntryPoint Simulation Contract

Ethaura already has EntryPointSimulations in the lib:
- `lib/account-abstraction/contracts/core/EntryPointSimulations.sol`
- Test utilities: `lib/account-abstraction/test/UserOp.ts` (`simulateValidation`, `simulateHandleOp`)

These can be ported to the frontend:

```javascript
// State override approach for simulation
const stateOverride = {
[entryPointAddress]: {
code: EntryPointSimulationsJson.deployedBytecode
}
}

const result = await provider.send('eth_call', [tx, 'latest', stateOverride])
```

## Acceptance Criteria

### Phase 1 (MVP)
- [ ] UserOperation is simulated before passkey prompt
- [ ] User sees if transaction will succeed or fail
- [ ] Revert reason is shown if simulation fails
- [ ] Gas estimate is displayed

### Phase 2
- [ ] Balance changes (ETH + tokens) are displayed
- [ ] Approval changes are tracked and displayed
- [ ] Changes are color-coded (green=gain, red=loss)

### Phase 3
- [ ] Risk warnings are shown for suspicious patterns
- [ ] Unlimited approvals are flagged
- [ ] Unverified contracts are flagged
- [ ] User can acknowledge warnings and proceed

### Phase 4 (Optional)
- [ ] External simulation API integrated
- [ ] Fallback to on-chain simulation
- [ ] Advanced threat detection

## Resources

### ERC-4337 Simulation
- [EntryPointSimulations Contract](https://github.com/eth-infinitism/account-abstraction/blob/develop/contracts/core/EntryPointSimulations.sol)
- [ERC-4337 Bundler Simulation](https://docs.erc4337.io/index.html)

### Simulation APIs
- [Tenderly Transaction Simulator](https://docs.tenderly.co/simulations/quickstart)
- [Tenderly SDK](https://github.com/Tenderly/tenderly-sdk)
- [Alchemy Transact API](https://www.alchemy.com/overviews/how-to-choose-a-transaction-simulation-provider)

### Security Research
- [Wallet Security Browser Extensions](https://www.coingecko.com/learn/security-browser-extensions-crypto)
- [Web3 Security Stack](https://www.coinbase.com/blog/a-developers-guide-to-the-web3-security-stack)

## Priority

**High** - Transaction simulation is a critical security feature that protects users from:
- Phishing attacks
- Malicious dApps
- Scam tokens
- Failed transactions (wasted gas)

## Labels

`security`, `enhancement`, `frontend`, `ux`

## Related Issues

- #102 - Phase 4: Security & UX Enhancements (parent feature)
- #114 - Swap Confirmation Screen (has placeholder for simulation)
- #135 - Swap Confirmation Screen PR (placeholder implemented)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.