Skip to content

Conversation

@mentatbot
Copy link
Contributor

@mentatbot mentatbot bot commented Jun 1, 2025

This commit implements the requested TWAP-based hourly price data table to address MEV manipulation concerns with the existing VWAP approach.

Changes Made

New Table: hourly_twap_data

  • token0, token1, hour: Primary key for token pair and time period
  • time_weighted_tick: Average tick weighted by time duration
  • average_price: Price derived from time-weighted tick using 1.0001^tick
  • total_time_seconds: Total time coverage within the hour
  • swap_count: Number of swaps used in calculation

TWAP Calculation Logic

The new calculation:

  1. For each token pair per hour, gets all swaps ordered chronologically
  2. Calculates time duration between consecutive swaps
  3. Weights each tick value by the time it was active
  4. Converts the time-weighted average tick to price using the standard formula

Benefits over VWAP

  • MEV Resistance: TWAP is not manipulated by sandwich attacks since it weights by time, not volume
  • Accurate Pricing: Reflects true time-weighted market prices rather than volume-distorted prices
  • Comprehensive Coverage: Accounts for all time periods within each hour

Closes #12


🤖 See my steps and cost here

  • Wake on any new activity.

This commit implements the requested TWAP-based hourly price data table to address MEV manipulation concerns with the existing VWAP approach.

## Changes Made

### New Table: `hourly_twap_data`
- `token0`, `token1`, `hour`: Primary key for token pair and time period
- `time_weighted_tick`: Average tick weighted by time duration
- `average_price`: Price derived from time-weighted tick using `1.0001^tick`
- `total_time_seconds`: Total time coverage within the hour
- `swap_count`: Number of swaps used in calculation

### TWAP Calculation Logic
The new calculation:
1. For each token pair per hour, gets all swaps ordered chronologically
2. Calculates time duration between consecutive swaps
3. Weights each tick value by the time it was active
4. Converts the time-weighted average tick to price using the standard formula

### Benefits over VWAP
- **MEV Resistance**: TWAP is not manipulated by sandwich attacks since it weights by time, not volume
- **Accurate Pricing**: Reflects true time-weighted market prices rather than volume-distorted prices
- **Comprehensive Coverage**: Accounts for all time periods within each hour

Closes # 12

Co-authored-by: moodysalem <7897876+moodysalem@users.noreply.github.com>
@mentatbot
Copy link
Contributor Author

mentatbot bot commented Jun 1, 2025

TWAP Implementation Complete

I've successfully implemented the hourly_twap_data table as requested in #12. Here's what was added:

Key Features

🎯 MEV-Resistant Pricing: Uses time-weighted average pricing instead of volume-weighted, making it resistant to sandwich attack manipulation

📊 Comprehensive Data: The new table includes:

  • time_weighted_tick: Average tick weighted by time duration
  • average_price: Price calculated as 1.0001^time_weighted_tick
  • total_time_seconds: Time coverage within each hour
  • swap_count: Number of swaps used in calculation

How It Works

The TWAP calculation:

  1. Gets all swaps for each token pair per hour, ordered chronologically
  2. Calculates the time duration each tick value was active
  3. Weights tick values by their time duration (not volume)
  4. Converts the time-weighted average tick to price using the standard Uniswap formula

Benefits Over Existing VWAP

  • Manipulation Resistant: Sandwich attacks can't distort TWAP since it's weighted by time, not volume
  • True Market Pricing: Reflects actual market prices over time periods
  • Complement to Existing Data: The original hourly_price_data table remains unchanged

The implementation integrates seamlessly with the existing refreshAnalyticalTables workflow and will populate automatically as new swap data comes in.

Ready for review! 🚀

- Remove price calculation, only compute average tick
- Weight pools by liquidity when aggregating across pools
- Calculate time-weighted tick per pool first, then aggregate
- Track liquidity-seconds for proper weighting
- Add pool_count to track number of pools in aggregation

This makes TWAP more resistant to manipulation through low-liquidity pools.
@mentatbot
Copy link
Contributor Author

mentatbot bot commented Jun 1, 2025

🔄 Updated TWAP Implementation with Liquidity Weighting

I've revised the implementation based on your feedback to address the manipulation concerns:

Key Changes

1. Removed Price Calculation

  • Now only computing average tick (liquidity_weighted_tick)
  • No conversion to price values

2. Liquidity-Weighted Aggregation

  • Each pool's tick contribution is weighted by liquidity * time
  • Formula: sum(tick * duration * liquidity) / sum(duration * liquidity)
  • Pools with zero liquidity are excluded

3. Pool-Level TWAP First

  • Calculate time-weighted tick per pool separately
  • Then aggregate across pools weighted by their liquidity-seconds
  • Track pool_count to show how many pools contributed

4. New Table Schema

CREATE TABLE hourly_twap_data (
    token0                      NUMERIC,
    token1                      NUMERIC,
    hour                        timestamptz,
    liquidity_weighted_tick     NUMERIC,  -- Average tick weighted by liquidity
    total_liquidity_seconds     NUMERIC,  -- Sum of liquidity * seconds
    total_time_seconds          NUMERIC,  -- Total time coverage
    swap_count                  NUMERIC,  -- Number of swaps
    pool_count                  NUMERIC,  -- Number of pools aggregated
    PRIMARY KEY (token0, token1, hour)
);

Why This Prevents Manipulation

  • Low liquidity pools have minimal impact: A pool with 1% of total liquidity only contributes 1% to the final tick value
  • Zero liquidity excluded: Periods or pools with no liquidity don't affect the calculation
  • Time AND liquidity weighted: Attackers would need to maintain both high liquidity AND sustain manipulation over time

The implementation now provides a robust, manipulation-resistant time-weighted average tick across all pools for each token pair.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

make the hourly_price_data table more accurate

0 participants