# Token Lifecycle Simulator

A powerful Node.js simulator for modeling token lifecycles, vesting schedules, AMM pool dynamics, and market agent behavior. Perfect for analyzing tokenomics, stress-testing vesting schedules, and simulating market interactions.

## 📋 Table of Contents

- [Features](#features)
- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Usage Examples](#usage-examples)
- [Configuration](#configuration)
- [Strategies](#strategies)
- [API Reference](#api-reference)
- [Project Structure](#project-structure)
- [Contributing](#contributing)
- [License](#license)

## ✨ Features

- **Vesting Schedules**: Model complex vesting with cliffs, linear vesting, and TGE percentages
- **AMM Pool Simulation**: Simulate automated market maker behavior with slippage and fees
- **Market Agents**: 500+ configurable agents with 6 built-in trading strategies
- **Token Distribution**: Model multi-allocation tokenomics (team, community, investors, etc.)
- **Random Number Generation**: Seeded RNG for reproducible simulations
- **ES6 Modules**: Modern JavaScript with clean imports

## 📦 Prerequisites

- Node.js v14+ (recommended v16+)
- npm or yarn

## 🚀 Installation

1. Clone the repository

   ```bash
   git clone <repo-url>
   cd token-lifecycle-simulator
   ```

2. Install dependencies

   ```bash
   npm install
   ```

## ⚡ Quick Start

### Programmatic Usage

```javascript
import {
  TokenSimulator,
  AMMPool,
  VestingSchedule,
} from "token-lifecycle-simulator";
import { defaultConfig } from "token-lifecycle-simulator";

// Create simulator instance
const simulator = new TokenSimulator(defaultConfig);

// Run simulation for 52 weeks
for (let tick = 0; tick < 52; tick++) {
  simulator.onTick();
}

// Get final state
const finalState = simulator.getState();
console.log(finalState);
```

## 📚 Usage Examples

### Example 1: Custom Tokenomics Configuration

```javascript
import { TokenSimulator } from "token-lifecycle-simulator";

const customConfig = {
  tokenName: "MyToken",
  tokenSymbol: "MTK",
  totalSupply: 100_000_000,
  initialBaseLiquidity: 1_000_000,
  ammFeeBps: 25, // 0.25% fee
  totalTicks: 104, // 2 years (weekly)
  ticksPerMonth: 4.33,
  agentCount: 1000,
  seed: 12345,
  allocations: [
    {
      name: "seed_round",
      percentOfSupply: 0.1,
      tgePercent: 0.05,
      cliffMonths: 6,
      vestingMonths: 24,
    },
    {
      name: "public_sale",
      percentOfSupply: 0.2,
      tgePercent: 1.0,
      cliffMonths: 0,
      vestingMonths: 0,
    },
    {
      name: "team",
      percentOfSupply: 0.25,
      tgePercent: 0.0,
      cliffMonths: 12,
      vestingMonths: 36,
    },
    {
      name: "community",
      percentOfSupply: 0.45,
      tgePercent: 0.1,
      cliffMonths: 0,
      vestingMonths: 12,
    },
  ],
};

const simulator = new TokenSimulator(customConfig);

// Run simulation
for (let i = 0; i < 104; i++) {
  simulator.onTick();
}

console.log("Simulation complete!", simulator.getState());
```

### Example 2: Analyzing Vesting Schedules

```javascript
import { VestingSchedule, AllocationPlan } from "token-lifecycle-simulator";

// Create a vesting schedule
const allocation = new AllocationPlan({
  name: "team_allocation",
  percentOfSupply: 0.2,
  tgePercent: 0.0,
  cliffMonths: 12,
  vestingMonths: 24,
});

const schedule = new VestingSchedule(1_000_000, allocation);

// Check vesting progress at different months
for (let month = 0; month <= 36; month++) {
  const vested = schedule.getVestedAmount(month);
  const unlocked = schedule.getUnlockedAmount(month);
  console.log(`Month ${month}: Vested ${vested}, Unlocked ${unlocked}`);
}
```

### Example 3: Working with AMM Pools

```javascript
import { AMMPool } from "token-lifecycle-simulator";

// Create an AMM pool
const pool = new AMMPool({
  initialTokenReserve: 100_000,
  initialUsdcReserve: 10_000,
  feeBps: 30, // 0.30% fee
});

// Swap tokens
const usdcSpent = 100;
const tokensReceived = pool.swapUsdcForToken(usdcSpent);
console.log(`Spent ${usdcSpent} USDC, received ${tokensReceived} tokens`);

// Check pool state
const state = pool.getPoolState();
console.log("Pool reserves:", state);
```

### Example 4: Creating Market Agents with Strategies

```javascript
import { Agent } from "token-lifecycle-simulator";
import { MovingAverageCrossoverStrategy } from "token-lifecycle-simulator/strategies";

// Create an agent with a moving average crossover strategy
const agent = new Agent({
  id: 1,
  balance: 10_000, // USDC balance
  tokenBalance: 100, // Token balance
  strategy: MovingAverageCrossoverStrategy,
  strategyConfig: {
    shortWindow: 5,
    longWindow: 20,
    tradeSize: 0.1, // 10% of balance
  },
});

// Simulate agent trading over time
const priceHistory = [100, 102, 105, 103, 98, 95, 97, 100];
priceHistory.forEach((price, tick) => {
  agent.onTick(price);
});
```

### Example 5: Running a Full Simulation with State Tracking

```javascript
import { TokenSimulator } from "token-lifecycle-simulator";
import { defaultConfig } from "token-lifecycle-simulator";

const simulator = new TokenSimulator(defaultConfig);
const stateHistory = [];

// Run simulation and track state changes
for (let tick = 0; tick < 52; tick++) {
  simulator.onTick();

  const state = simulator.getState();
  stateHistory.push({
    tick,
    price: state.price,
    circulatingSupply: state.circulatingSupply,
    poolReserves: state.poolReserves,
    agentActivity: state.agentMetrics,
  });
}

// Analyze results
const finalState = stateHistory[stateHistory.length - 1];
console.log("Final price:", finalState.price);
console.log("Final circulating supply:", finalState.circulatingSupply);
```

### Example 6: Custom Simulation with Different Agent Populations

```javascript
import {
  TokenSimulator,
  generateAgentPopulation,
} from "token-lifecycle-simulator";
import { defaultConfig } from "token-lifecycle-simulator";

// Create a custom agent population mix
const agentMix = {
  dca: 0.4, // 40% DCA (Dollar Cost Averaging)
  movingAverageCrossover: 0.2, // 20% Technical traders
  whaleTrader: 0.1, // 10% Whale traders
  gridBot: 0.2, // 20% Grid bots
  marketMaker: 0.1, // 10% Market makers
};

const config = { ...defaultConfig, agentCount: 500 };
const simulator = new TokenSimulator(config);

// Generate custom population based on mix
const population = generateAgentPopulation(
  500,
  agentMix,
  config.totalSupply,
  config.seed,
);

// Run simulation with custom population
simulator.setAgentPopulation(population);

for (let tick = 0; tick < 52; tick++) {
  simulator.onTick();
}

console.log("Simulation complete with custom agent mix!");
```

## ⚙️ Configuration

All simulations are configured via a configuration object. See [defaultConfig.js](defaultConfig.js) for defaults.

### Configuration Parameters

```javascript
{
  // Token details
  tokenName: "String",                // Name of the token
  tokenSymbol: "String",              // Symbol (e.g., BLUST)
  totalSupply: Number,                // Total token supply

  // AMM Pool
  initialBaseLiquidity: Number,       // Initial liquidity in USDC
  ammFeeBps: Number,                  // Fee in basis points (30 = 0.30%)

  // Simulation parameters
  totalTicks: Number,                 // Total simulation duration
  ticksPerMonth: Number,              // Ticks per month (for vesting)
  agentCount: Number,                 // Number of agents
  seed: Number,                       // Random seed for reproducibility

  // Token allocations
  allocations: [
    {
      name: "String",                 // Allocation name
      percentOfSupply: Number,        // Percentage of total supply
      tgePercent: Number,             // Percentage unlocked at TGE (0-1)
      cliffMonths: Number,            // Cliff period in months
      vestingMonths: Number,          // Vesting period in months
    }
  ]
}
```

## 🎯 Strategies

The simulator includes 6 built-in trading strategies for agents:

1. **MovingAverageCrossover** - Technical analysis based on moving average crossovers
2. **RSI** - Relative Strength Index based strategy
3. **DCA** - Dollar Cost Averaging (consistent purchases)
4. **GridBot** - Grid trading strategy with defined price bands
5. **WhaleTrader** - Large volume trades with impact consideration
6. **MarketMaker** - Provides liquidity and profits from spreads

## 🔌 API Reference

### TokenSimulator

```javascript
const simulator = new TokenSimulator(config);

// Core methods
simulator.onTick(); // Advance one simulation step
simulator.getState(); // Get current simulator state
simulator.setAgentPopulation(); // Set custom agent population
```

### VestingSchedule

```javascript
const schedule = new VestingSchedule(totalAmount, allocation);

// Vesting methods
schedule.getVestedAmount(months); // Get total vested amount
schedule.getUnlockedAmount(months); // Get unlocked amount
schedule.getRemainingLocked(months); // Get remaining locked amount
```

### AMMPool

```javascript
const pool = new AMMPool(config);

// Pool methods
pool.swapUsdcForToken(usdcAmount); // Swap USDC for tokens
pool.swapTokenForUsdc(tokenAmount); // Swap tokens for USDC
pool.getPoolState(); // Get current pool reserves
pool.getPrice(); // Get current token price
```

### Agent

```javascript
const agent = new Agent(config);

// Agent methods
agent.onTick(currentPrice); // Process agent action for tick
agent.getPosition(); // Get current holdings
agent.getBalance(); // Get USDC balance
```

## 📁 Project Structure

```
token-lifecycle-simulator/
├── Agent.js                      # Individual agent class
├── AMMPool.js                    # AMM pool implementation
├── TokenSimulator.js             # Main simulator class
├── VestingSchedule.js            # Vesting logic
├── MarketAgents.js               # Agent orchestration
├── defaultConfig.js              # Default configuration
├── index.js                      # Main exports
├── package.json                  # Package metadata and scripts
├── README.md                     # This file
├── rng.js                        # Random number utilities
└── strategies/
    ├── index.js                  # Strategy registry
    ├── DCA.js                    # DCA strategy
    ├── GridBot.js                # Grid bot strategy
    ├── MarketMaker.js            # Market maker strategy
    ├── MovingAverageCrossover.js # MA crossover strategy
    ├── RSI.js                    # RSI strategy
    └── WhaleTrader.js            # Whale trader strategy
```

## 🤝 Contributing

Contributions are welcome! Please feel free to:

- Open issues for bugs or feature requests
- Submit pull requests with improvements
- Add new trading strategies
- Improve documentation and examples
- Add tests

## 📄 License

MIT
