# Build Time Optimization Plan

**Current Build Time**: 1 minute 51 seconds (111s)
**Target Build Time**: <10 seconds
**Files**: 49 TypeScript files
**Dependencies**: 187MB node_modules

## 🎯 Performance Analysis

### Current Bottlenecks
1. **TypeScript Compilation**: 110.24s user time (96% of total)
2. **Source Maps**: Enabled (adds overhead)
3. **Strict Mode**: All strict checks enabled (slower compilation)
4. **Declaration Files**: Generating .d.ts for all files
5. **No Incremental Builds**: Rebuilds everything every time
6. **Package Manager**: npm (slower than alternatives)

### Quick Wins vs Long-term Solutions

| Solution | Time Savings | Effort | Compatibility |
|----------|--------------|--------|---------------|
| **Incremental Builds** | 80-90% (after first) | Low | ✅ Perfect |
| **Switch to pnpm** | 20-30% | Low | ✅ Perfect |
| **Switch to Bun** | 50-70% | Low | ⚠️ Good |
| **SWC Instead of TSC** | 40-60% | Medium | ⚠️ Good |
| **Project References** | 30-50% | High | ✅ Perfect |
| **Disable Source Maps** | 10-20% | Low | ✅ Perfect |

---

## 🚀 TIER 1: Quick Wins (Implement Immediately)

### 1. Enable TypeScript Incremental Builds

**Impact**: 🔥🔥🔥 **80-90% faster rebuilds** (after first build)
**Effort**: ⭐ **5 minutes**

**Implementation**:

```json
// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "commonjs",
    "declaration": true,
    "outDir": "./dist",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "sourceMap": true,

    // ✅ Add these for incremental builds
    "incremental": true,
    "tsBuildInfoFile": "./dist/.tsbuildinfo"
  },
  "include": ["utils/**/*"],
  "exclude": ["node_modules", "**/*.spec.ts", "**/*.bak"]
}
```

**Expected Result**:
- First build: ~111s (same)
- Subsequent builds: ~10-15s (90% faster!)

**Git Ignore**:
```bash
# Add to .gitignore
dist/.tsbuildinfo
```

---

### 2. Switch to pnpm (npm Alternative)

**Impact**: 🔥🔥 **20-30% faster installs and builds**
**Effort**: ⭐ **10 minutes**

**Why pnpm?**
- 2-3x faster than npm
- Efficient disk space usage (symlinks)
- Strict dependency resolution
- Drop-in npm replacement

**Installation**:
```bash
# Install pnpm globally
npm install -g pnpm

# Or via Homebrew (macOS)
brew install pnpm
```

**Migration**:
```bash
# 1. Remove npm artifacts
rm -rf node_modules package-lock.json

# 2. Install with pnpm
pnpm install

# 3. Update scripts (optional - pnpm understands npm scripts)
# No changes needed to package.json!

# 4. Build with pnpm
pnpm run build
```

**Update package.json** (optional):
```json
{
  "scripts": {
    "build": "tsc -p tsconfig.json",
    "build:fast": "tsc -p tsconfig.json --incremental"
  },
  "packageManager": "pnpm@9.0.0"
}
```

**Expected Result**:
- Install time: 45s → 15s
- Build time: 111s → 75-85s

---

### 3. Optimize TypeScript Compiler Options

**Impact**: 🔥 **10-20% faster**
**Effort**: ⭐ **2 minutes**

```json
// tsconfig.json - Production optimizations
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "commonjs",
    "declaration": true,
    "outDir": "./dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,

    // ✅ Performance optimizations
    "incremental": true,
    "tsBuildInfoFile": "./dist/.tsbuildinfo",
    "skipLibCheck": true,           // ✅ Already enabled
    "skipDefaultLibCheck": true,     // ✅ Add this

    // ✅ Conditional strict mode (dev vs prod)
    "strict": true,

    // ⚠️ Optional: Disable source maps for production
    // "sourceMap": false,  // Uncomment for 10-15% speed boost
    "sourceMap": true,     // Keep for development

    // ✅ Faster module resolution
    "moduleResolution": "node",
    "resolveJsonModule": true,

    "lib": ["ES2022", "DOM"]
  },
  "include": ["utils/**/*"],
  "exclude": ["node_modules", "**/*.spec.ts", "**/*.bak", "**/*.test.ts"]
}
```

**Create Separate Configs**:

```json
// tsconfig.prod.json - Fast production builds
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "sourceMap": false,        // No source maps
    "removeComments": true,     // Strip comments
    "declaration": true,        // Keep .d.ts files
    "declarationMap": false     // No .d.ts.map files
  }
}
```

```json
// tsconfig.dev.json - Development with all features
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "sourceMap": true,
    "removeComments": false,
    "declaration": true,
    "declarationMap": true
  }
}
```

**Update package.json**:
```json
{
  "scripts": {
    "build": "tsc -p tsconfig.prod.json",
    "build:dev": "tsc -p tsconfig.dev.json",
    "build:watch": "tsc -p tsconfig.dev.json --watch"
  }
}
```

---

## 🔥 TIER 2: Moderate Improvements (Implement This Week)

### 4. Switch to Bun Runtime (Fastest Option)

**Impact**: 🔥🔥🔥 **50-70% faster than npm**
**Effort**: ⭐⭐ **15 minutes**
**Compatibility**: ⚠️ **95% (minor edge cases)**

**Why Bun?**
- 10-100x faster than npm/pnpm
- Built-in TypeScript support
- Drop-in Node.js replacement
- Ultra-fast package manager

**Installation**:
```bash
# macOS/Linux
curl -fsSL https://bun.sh/install | bash

# Or via Homebrew
brew install oven-sh/bun/bun
```

**Migration**:
```bash
# 1. Remove existing artifacts
rm -rf node_modules package-lock.json pnpm-lock.yaml

# 2. Install with Bun
bun install

# 3. Build with Bun
bun run build

# Or use Bun's native TypeScript compilation (even faster!)
bun build utils/index.ts --outdir dist --target node
```

**Update package.json for Bun**:
```json
{
  "scripts": {
    "build": "tsc -p tsconfig.prod.json",
    "build:bun": "bun build utils/index.ts --outdir dist --target node --format cjs --sourcemap",
    "build:fast": "bun run build",
    "dev": "bun --watch utils/index.ts"
  },
  "packageManager": "bun@1.0.0"
}
```

**Expected Result**:
- Install time: 45s → 3-5s (10x faster!)
- Build time: 111s → 30-45s (2-3x faster!)

**Compatibility Notes**:
- ✅ Works with TypeScript
- ✅ Works with viem, ethers, Solana
- ⚠️ Some native modules may need Node.js
- ⚠️ Test thoroughly before production

---

### 5. Use SWC Instead of TypeScript Compiler

**Impact**: 🔥🔥🔥 **40-60% faster compilation**
**Effort**: ⭐⭐ **20 minutes**

**Why SWC?**
- 20-70x faster than tsc (written in Rust)
- Drop-in TypeScript compiler replacement
- Used by Next.js, Vite, etc.

**Installation**:
```bash
pnpm add -D @swc/core @swc/cli
```

**Configuration**:
```json
// .swcrc
{
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "tsx": false,
      "decorators": false,
      "dynamicImport": true
    },
    "target": "es2022",
    "loose": false,
    "externalHelpers": false,
    "keepClassNames": true
  },
  "module": {
    "type": "commonjs",
    "strict": false,
    "strictMode": true,
    "lazy": false,
    "noInterop": false
  },
  "sourceMaps": true
}
```

**Update package.json**:
```json
{
  "scripts": {
    "build": "tsc -p tsconfig.prod.json",
    "build:swc": "swc utils -d dist --config-file .swcrc && tsc --emitDeclarationOnly",
    "build:fast": "pnpm run build:swc"
  }
}
```

**Expected Result**:
- Build time: 111s → 40-60s (2x faster!)

**Trade-offs**:
- ⚠️ Still need tsc for .d.ts files
- ⚠️ Different error messages
- ✅ Production builds are identical

---

### 6. Implement Build Caching

**Impact**: 🔥🔥 **30-50% faster CI/CD builds**
**Effort**: ⭐⭐ **15 minutes**

**For Local Development**:
```bash
# Install turbo (build system with caching)
pnpm add -D turbo
```

```json
// turbo.json
{
  "$schema": "https://turbo.build/schema.json",
  "pipeline": {
    "build": {
      "outputs": ["dist/**"],
      "cache": true
    }
  }
}
```

**Update package.json**:
```json
{
  "scripts": {
    "build": "turbo run build",
    "build:nocache": "turbo run build --force"
  }
}
```

**For GitHub Actions**:
```yaml
# .github/workflows/build.yml
- name: Cache TypeScript build
  uses: actions/cache@v3
  with:
    path: |
      dist
      .tsbuildinfo
    key: ${{ runner.os }}-build-${{ hashFiles('utils/**/*.ts') }}
    restore-keys: |
      ${{ runner.os }}-build-
```

---

## 🎯 TIER 3: Advanced Optimizations (Long-term)

### 7. TypeScript Project References

**Impact**: 🔥🔥 **30-50% faster for large projects**
**Effort**: ⭐⭐⭐ **2 hours**
**Best For**: Monorepos or modular projects

**Split into Multiple Projects**:

```
packages/
├── core/
│   ├── tsconfig.json
│   └── utils/
├── evm/
│   ├── tsconfig.json
│   └── utils/
├── svm/
│   ├── tsconfig.json
│   └── utils/
└── tsconfig.json (root)
```

```json
// Root tsconfig.json
{
  "files": [],
  "references": [
    { "path": "./core" },
    { "path": "./evm" },
    { "path": "./svm" }
  ]
}
```

```json
// packages/core/tsconfig.json
{
  "compilerOptions": {
    "composite": true,
    "outDir": "dist",
    "rootDir": "utils"
  }
}
```

**Build**:
```bash
tsc --build tsconfig.json
```

**Benefits**:
- Parallel compilation
- Only rebuilds changed projects
- Better dependency management

---

### 8. Parallelize TypeScript Compilation

**Impact**: 🔥 **15-25% faster on multi-core systems**
**Effort**: ⭐⭐ **10 minutes**

```bash
# Install fork-ts-checker-webpack-plugin alternative
pnpm add -D concurrently npm-run-all
```

**Split Compilation**:
```json
// package.json
{
  "scripts": {
    "build:core": "tsc -p tsconfig.core.json",
    "build:evm": "tsc -p tsconfig.evm.json",
    "build:svm": "tsc -p tsconfig.svm.json",
    "build": "run-p build:*"  // Parallel execution
  }
}
```

---

### 9. Use esbuild for Development

**Impact**: 🔥🔥🔥 **10-100x faster dev builds**
**Effort**: ⭐⭐ **20 minutes**
**Best For**: Development only (still use tsc for production)

```bash
pnpm add -D esbuild esbuild-register
```

```json
// package.json
{
  "scripts": {
    "build": "tsc -p tsconfig.prod.json",
    "build:dev": "esbuild utils/index.ts --bundle --platform=node --outfile=dist/index.js --sourcemap",
    "dev": "esbuild utils/index.ts --bundle --platform=node --outfile=dist/index.js --watch"
  }
}
```

**Expected Result**:
- Dev build: 111s → 2-5s (20-50x faster!)
- Production: Still use tsc for type checking

---

## 📊 RECOMMENDED IMPLEMENTATION PLAN

### Week 1 - Quick Wins (Immediate 80% improvement)

```bash
# Day 1 - Enable incremental builds (5 min)
# Update tsconfig.json with incremental: true
git add tsconfig.json && git commit -m "feat: enable incremental builds"

# Day 1 - Switch to pnpm (10 min)
npm install -g pnpm
rm -rf node_modules package-lock.json
pnpm install
git add pnpm-lock.yaml && git commit -m "feat: migrate to pnpm"

# Day 2 - Optimize compiler options (5 min)
# Create tsconfig.prod.json
git add tsconfig.prod.json && git commit -m "feat: optimize prod build config"
```

**Expected Results**:
- First build: ~111s
- Incremental builds: ~10-15s
- Install time: ~15s

### Week 2 - Moderate Improvements (Additional 50% improvement)

```bash
# Option A: Try Bun (fastest)
brew install oven-sh/bun/bun
bun install
bun run build

# Option B: Try SWC (most compatible)
pnpm add -D @swc/core @swc/cli
# Create .swcrc
pnpm run build:swc
```

**Expected Results**:
- Bun: 30-45s total build time
- SWC: 40-60s total build time

### Week 3+ - Advanced (If needed)

- Implement project references
- Add build caching for CI/CD
- Consider esbuild for development

---

## 🎯 TARGET BENCHMARKS

| Scenario | Current | Target | Method |
|----------|---------|--------|--------|
| **Clean Build** | 111s | 40-60s | pnpm + SWC |
| **Incremental Build** | 111s | 5-10s | incremental: true |
| **Install** | 45s | 5-10s | pnpm or Bun |
| **Dev Build** | 111s | 2-5s | esbuild |
| **CI/CD Build** | 111s | 30s | Cache + pnpm + SWC |

---

## 💡 IMMEDIATE ACTION ITEMS

### Implement Right Now (< 10 minutes):

1. **Enable Incremental Builds**:
```bash
# Add to tsconfig.json:
"incremental": true,
"tsBuildInfoFile": "./dist/.tsbuildinfo"
```

2. **Switch to pnpm**:
```bash
npm install -g pnpm
rm -rf node_modules package-lock.json
pnpm install
```

3. **Create Optimized Config**:
```bash
# Copy tsconfig.json to tsconfig.prod.json
# Set sourceMap: false in prod config
# Update build script to use tsconfig.prod.json
```

**After these 3 changes**:
- First build: ~80-90s (20% faster)
- Incremental builds: ~8-12s (90% faster!)
- This solves 95% of the problem for daily development

---

## 🔬 TESTING & VERIFICATION

```bash
# Benchmark current build
time npm run build

# After implementing changes
time pnpm run build

# Test incremental build
touch utils/vm.ts
time pnpm run build  # Should be ~10s

# Verify output
npm run build && node -e "require('./dist/index.js')"
```

---

## 📝 NOTES

### Don't Do This:
- ❌ Disable strict mode (loses type safety)
- ❌ Remove all source maps (makes debugging impossible)
- ❌ Skip type checking completely (defeats purpose of TypeScript)

### Do This Instead:
- ✅ Use incremental builds
- ✅ Optimize for development vs production
- ✅ Cache aggressively
- ✅ Use faster tools (pnpm, Bun, SWC)

---

## 🎓 SUMMARY

**Best Bang for Buck** (Implement first):
1. ⭐⭐⭐ Incremental builds (90% faster rebuilds)
2. ⭐⭐⭐ Switch to pnpm (30% faster overall)
3. ⭐⭐ Optimize compiler options (15% faster)

**For Maximum Speed** (If build time is critical):
4. ⭐⭐⭐ Switch to Bun (70% faster than npm)
5. ⭐⭐⭐ Use SWC instead of tsc (50% faster compilation)

**Expected Final Results**:
- Clean build: 40-60s (50% improvement)
- Incremental build: 5-10s (95% improvement)
- Daily development: Much faster!

Start with the Quick Wins (Week 1), measure improvements, then decide if you need more optimization.
