npm package: @pioneer-platform/e2e-transfer-tokens
Description: Comprehensive end-to-end testing for ERC20 token transfers with USDT, USDC, and FOX tokens on Ethereum.
Latest version: 1.1.50

# E2E Token Transfer Test Suite

Comprehensive end-to-end testing for ERC20 token transfers with USDT, USDC, and FOX tokens on Ethereum.

## Features

### 1. **Fresh Balance Validation**
- Forces fresh balance updates before building transactions
- Validates balance data is accurate and up-to-date
- Checks balance sufficiency before attempting transfers

### 2. **Transaction Building**
- Builds proper ERC20 transfer transactions
- Validates transaction structure and encoding
- Verifies correct contract addresses and function selectors

### 3. **Transaction Insight API (`/insight`)**
- Calls Pioneer's `/insight` API endpoint before signing
- Validates gas estimation with 20% buffer
- Compares recommended vs. unsigned transaction parameters
- Provides security analysis and warnings

### 4. **Verbose Test Output**
- Step-by-step progress logging
- Detailed validation at each stage
- Clear pass/fail indicators
- Comprehensive error reporting

## Supported Tokens

### USDT (Tether USD)
- **Contract**: `0xdac17f958d2ee523a2206206994597c13d831ec7`
- **Decimals**: 6
- **Min Amount**: 1.0 USDT
- **Chain**: Ethereum Mainnet

### USDC (USD Coin)
- **Contract**: `0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48`
- **Decimals**: 6
- **Min Amount**: 1.0 USDC
- **Chain**: Ethereum Mainnet

### FOX (ShapeShift Token)
- **Contract**: `0xc770eefad204b5180df6a14ee197d99d808ee52d`
- **Decimals**: 18
- **Min Amount**: 10.0 FOX
- **Chain**: Ethereum Mainnet

## Usage

### Test All Tokens (Default)

```bash
bun run test
```

### Test Specific Token by Symbol

```bash
TEST_TOKEN=USDT bun run test
TEST_TOKEN=USDC bun run test
TEST_TOKEN=FOX bun run test
```

### Test Custom Token by Contract Address

```bash
# Via environment variable
TEST_TOKEN=0xFDFfB411C4A70AA7C95D5C981a6Fb4Da867e1111 bun run test

# Via command line argument
bun run test 0xFDFfB411C4A70AA7C95D5C981a6Fb4Da867e1111
```

### Debug Mode

```bash
bun run test-debug
```

## Environment Variables

Required in your `.env` file:

```bash
# KeepKey API Key
KEEPKEY_API_KEY=your_key_here

# Test destination address
FAUCET_ETH_ADDRESS=0x658DE0443259a1027caA976ef9a42E6982037A03

# Optional: Test specific token
TEST_TOKEN=USDT  # or USDC, FOX
```

## Custom Token Lookup

When you provide a contract address (0x followed by 40 hex characters) instead of a token symbol, the test will:

1. **Detect Contract Address**: Automatically recognizes the 0x address format
2. **Call Pioneer API via SDK**: Uses `app.pioneer.LookupTokenMetadata()` to fetch token data
3. **Fetch Metadata**: Retrieves token name, symbol, decimals from the blockchain
4. **Check Balance**: If you have a balance, it will be fetched and displayed
5. **Build Transaction**: Creates a test transfer transaction if balance exists

### Example: Testing a Custom Token

```bash
# Test the custom token at address 0xFDFfB411C4A70AA7C95D5C981a6Fb4Da867e1111
bun run test 0xFDFfB411C4A70AA7C95D5C981a6Fb4Da867e1111
```

**Expected Output:**
```
🔎 LOOKING UP CUSTOM TOKEN: 0xFDFfB411C4A70AA7C95D5C981a6Fb4Da867e1111
🔍 Looking up custom token contract: 0xFDFfB411C4A70AA7C95D5C981a6Fb4Da867e1111
Using address for balance check: 0x...
Calling Pioneer API via SDK
Payload: { networkId: 'eip155:1', contractAddress: '0xFDFfB411C4A70AA7C95D5C981a6Fb4Da867e1111', userAddress: '0x...' }
✅ Custom token found:
   Name: Token Name
   Symbol: SYMBOL
   Decimals: 18
   Contract: 0xfdffb411c4a70aa7c95d5c981a6fb4da867e1111
   CAIP: eip155:1/erc20:0xfdffb411c4a70aa7c95d5c981a6fb4da867e1111
   Balance: 1234.56 SYMBOL
```

If the token is not found or the contract is invalid, you'll see:
```
❌ Failed to lookup custom token at address: 0x...
   Make sure the contract address is valid and implements ERC20
```

## Test Flow

### Step 0: Custom Token Lookup (if contract address provided)
- Validates contract address format (0x + 40 hex chars)
- Calls Pioneer API via SDK: `app.pioneer.LookupTokenMetadata()`
- Fetches token name, symbol, decimals from blockchain
- Checks user's balance if address available
- Builds token configuration for testing

### Step 1: Set Asset Context
- Sets the asset context to the specific token CAIP
- Example: `eip155:1/erc20:0xdac17f958d2ee523a2206206994597c13d831ec7` (USDT)

### Step 2: Force Fresh Balance Update
- Calls `app.getBalance()` to sync latest balances
- Ensures balance data is current before building transaction

### Step 3: Balance Validation
- Finds token balance from synchronized balances
- Validates balance is sufficient for transfer
- Displays balance, address, and USD value

### Step 4: Build Transaction
- Builds ERC20 transfer transaction with:
  - Recipient address
  - Amount in token units
  - Fee level (1-5, 5=fastest)
- Returns unsigned transaction ready for validation

### Step 5: ERC20 Transaction Validation
- **Contract Address**: Verifies `to` field matches token contract
- **Value Field**: Confirms `value` is `0x0` (ETH value should be zero)
- **Data Field**: Validates starts with `0xa9059cbb` (ERC20 transfer function selector)
- **Data Structure**: Ensures proper encoding of recipient and amount

### Step 6: Get Transaction Insight
- Calls Pioneer `/insight` API endpoint
- Sends unsigned transaction for analysis
- Retrieves recommended parameters and warnings

### Step 7: Insight Response Validation
- **Gas Limit**: Validates gas estimation is present and reasonable
- **Gas Price/Fees**: Checks EIP1559 fees or legacy gas price
- **Addresses**: Confirms `from` and `to` match unsigned transaction
- **Data**: Verifies transaction data is preserved
- **Warnings**: Displays any security warnings or recommendations

### Step 8: Compare Recommended vs Unsigned
- Compares gas limit between unsigned tx and insight recommendation
- Warns if insight recommends higher gas limit
- Displays difference if gas limits don't match

## Validation Functions

### `validateERC20Transaction(unsignedTx, contractAddress, symbol)`

Validates that a transaction is properly formatted as an ERC20 transfer:

```typescript
// Checks performed:
- data field is not empty (has ERC20 calldata)
- to address matches token contract address
- value field is 0x0 (no ETH being sent)
- data starts with 0xa9059cbb (transfer function selector)
```

### `validateTxInsight(insight, tokenConfig, unsignedTx)`

Validates the `/insight` API response:

```typescript
// Checks performed:
- insight.data exists
- recommended parameters exist
- gas limit is present
- gas price or EIP1559 fees are present
- addresses match (to, from)
- transaction data matches
- warnings are logged
```

## Output Example

```
🏁 Starting E2E Token Transfer Test Suite
🕐 Start time: 2025-10-26T...

🔬 ===== DRY RUN MODE ENABLED =====
   Testing token transfer validation
   Will NOT sign or broadcast transactions
   Safe to run with real funds
=====================================

📋 Testing all tokens: USDT, USDC, FOX

================================================
🪙 TESTING TOKEN: USDT (Tether USD)
================================================

📍 STEP 1: Setting Asset Context
   CAIP: eip155:1/erc20:0xdac17f958d2ee523a2206206994597c13d831ec7
✅ Asset context set to: eip155:1/erc20:0xdac17f958d2ee523a2206206994597c13d831ec7

🔄 STEP 2: Forcing Fresh Balance Update
   Blockchain: eip155:1
✅ Balances synced for eip155:1

💰 STEP 3: Balance Validation
   Found 1 balance(s) for USDT
   Balance 1:
     CAIP: eip155:1/erc20:0xdac17f958d2ee523a2206206994597c13d831ec7
     Amount: 10.5 USDT
     Address: 0x...
     Value: $10.50
✅ Current USDT balance: 10.5

🔧 STEP 4: Building Transaction
   Send Payload:
     CAIP: eip155:1/erc20:0xdac17f958d2ee523a2206206994597c13d831ec7
     To: 0x658DE0443259a1027caA976ef9a42E6982037A03
     Amount: 1 USDT
     Fee Level: 5
✅ Transaction built successfully
   Transaction Details:
     From: 0x...
     To: 0xdac17f958d2ee523a2206206994597c13d831ec7
     Value: 0x0
     Data: 0xa9059cbb000000000000000000000000658de0443259a1027caa976ef9a42...
     ChainId: 0x1
     Nonce: 42
     Gas Limit: 0x10000

✅ STEP 5: ERC20 Transaction Validation
🔍 ===== ERC20 TRANSACTION VALIDATION (USDT) =====
✅ USDT transaction validation passed
   Contract: 0xdac17f958d2ee523a2206206994597c13d831ec7
   Data: 0xa9059cbb000000000000000000000000658de0443259a102...
   Value: 0x0
========================================

🔍 STEP 6: Getting Transaction Insight from /insight API
✅ Transaction insight retrieved

✅ STEP 7: Insight Response Validation
🔍 ===== TRANSACTION INSIGHT VALIDATION (USDT) =====
✅ EIP1559 fees validated
   maxFeePerGas: 0x2540be400
   maxPriorityFeePerGas: 0x3b9aca00
✅ USDT transaction insight validated
   Gas Limit: 0x12000
   To: 0xdac17f958d2ee523a2206206994597c13d831ec7
   From: 0x...
   Data: 0xa9059cbb000000000000000000000000658de0443259a102...
========================================

📊 STEP 8: Comparing Recommended vs Unsigned Transaction
⚠️  Insight recommends HIGHER gas limit:
   Unsigned: 65536
   Recommended: 73728
   Difference: +8192

================================================
✅ USDT TEST COMPLETED SUCCESSFULLY
   All validations passed:
   ✓ Asset context set correctly
   ✓ Balance updated and validated
   ✓ Transaction built successfully
   ✓ ERC20 encoding validated
   ✓ Transaction insight retrieved
   ✓ Insight parameters validated
================================================

[Tests continue for USDC and FOX...]

========================================
✅ ALL TOKEN TESTS COMPLETED
   Tokens tested: 3
   All validations passed
========================================
```

## Integration with Pioneer Stack

This test suite integrates with:

1. **Pioneer SDK** (`@pioneer-platform/pioneer-sdk`)
   - Transaction building via `app.buildTx()`
   - Balance syncing via `app.getBalance()`
   - Asset context management via `app.setAssetContext()`

2. **Pioneer Server** (`services/pioneer-server`)
   - Transaction insight via `/insight` endpoint
   - Gas estimation with 20% buffer
   - EIP1559 fee data retrieval

3. **Pioneer CAIP** (`@pioneer-platform/pioneer-caip`)
   - CAIP identifier formatting
   - Network ID conversions

## Error Handling

The test suite fails fast and provides clear error messages:

```
❌ TEST FAILED: Error: Asset context mismatch!
   Expected: eip155:1/erc20:0xdac17f958d2ee523a2206206994597c13d831ec7
   Got: eip155:1/slip44:60
```

All validation failures throw errors with context for debugging.

## Development Mode

Always runs in **DRY_RUN_MODE** by default:
- Builds transactions but does NOT sign or broadcast
- Safe to run with real wallet and funds
- Validates all steps except actual on-chain execution

To enable live transactions (NOT RECOMMENDED for automated testing):
1. Set `DRY_RUN_MODE = false` in `index.ts`
2. Ensure you have sufficient ETH for gas fees
3. Ensure you have sufficient token balance

## Common Issues

### No Balance Found
```
⚠️  No USDT balance found, skipping...
```
**Solution**: Ensure your KeepKey has USDT balance on Ethereum mainnet.

### Balance Below Minimum
```
⚠️  USDT balance (0.5) below minimum (1.0), skipping...
```
**Solution**: Transfer more tokens to meet minimum test amount.

### Pioneer Server Not Running
```
❌ Failed to get transaction insight: connect ECONNREFUSED 127.0.0.1:9001
```
**Solution**: Start Pioneer server with `make start` in pioneer directory.

## Future Enhancements

- [ ] Add tests for Polygon tokens (USDC, USDT on Polygon)
- [ ] Test token approvals (ERC20 approve function)
- [ ] Add slippage checking for DEX token swaps
- [ ] Integrate security scanning (Harpie, WalletGuard)
- [ ] Add performance benchmarking
- [ ] Test multi-sig token transfers