Files
dex/test/e2e/trading_test.go
zeekayandHanzo Dev 10a084c0b2 refactor(dex): fold pkg/lx into pkg/dex — one matcher, one package
The matching engine (pkg/lx, 45.5K LOC incl. tests) and the deterministic
core layered on it (pkg/dex) are one matcher spread across two packages
(dex imported lx in 12 files; lx imported neither). Fold lx into dex and
drop the "lx" name entirely — pkg/dex is now the single matcher package.

Pure rename/fold, ZERO logic change. Behavior proven identical: the merged
pkg/dex runs 457 top-level tests (431 former-lx + 26 former-dex) and 489
test funcs (468 + 21), all green — matching, batch (BatchMatchEqualsSequential,
run-to-run determinism, tile boundary), GPU/CPU parity, truncation, and CL
swap math all pass unchanged.

What moved:
- git mv all 101 pkg/lx/*.go + 1 .c into pkg/dex/ (package lx -> package dex).
- lx's swap_test.go -> swap_math_test.go (only filename collision with dex's
  existing swap_test.go).
- Rewrote imports repo-wide: 54 pkg/lx import lines removed; 42 external
  importers (api, client, consensus, dchain, dpdk, lxgpu, marketdata, test/,
  tests/) repointed to pkg/dex with lx.X -> dex.X; the 12 in-package dex files
  had lx.X -> bare X. 717 selector lines rewritten. Stale pkg/lx comment refs
  updated (pkg/lxgpu left intact).

Collisions resolved (2, both package-level vars):
- ErrNoLiquidity: lx's pool-level error (dexError, used only in swap.go, never
  referenced via qualifier) renamed ErrPoolNoLiquidity to match the existing
  ErrPool* convention; dex's router-level ErrNoLiquidity (public, has errors.Is
  tests) kept.
- priceMultiplierBig: identical after fold (both big.NewInt(PriceMultiplier));
  deduped by deleting dex's copy.

Not folded — pkg/orderbook: it is NOT the GPU seam (that is orderbook_gpu.go,
which lives in the engine and folded in here). pkg/orderbook is a zero-importer,
placeholder-cgo island whose 13 core domain identifiers (Order, OrderBook, Trade,
OrderType, OrderStatus, PriceLevel, Buy, Sell, Market, Limit, Filled,
PartiallyFilled, NewOrderBook) collide incompatibly with the engine's. Folding
it verbatim breaks the build; folding via rename reintroduces the exact parallel
duplication this fold removes. Left for owner decision (recommend deletion as
dead code) — see refactor notes.

Follow-on (separate repos, not touched): 19 files under luxfi/dex import
pkg/lx externally — lux/precompile/dex, lux/precompile-dex/dex,
lux/consensus/examples/01-simple-bridge, lux/_consensus-v12537/examples,
lux/cex/pkg/engine — repoint to pkg/dex after this lands.

Verified: CGO_ENABLED=0 GOWORK=off go build ./... clean; go vet ./... clean;
go test ./... -count=1 all green (22 ok / 0 fail).

Co-authored-by: Hanzo Dev <[email protected]>
2026-07-02 00:57:08 -07:00

153 lines
4.0 KiB
Go

package e2e
import (
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/luxfi/dex/pkg/dex"
"github.com/stretchr/testify/assert"
)
// TestE2ETrading tests end-to-end trading flow
func TestE2ETrading(t *testing.T) {
// Create orderbook
ob := dex.NewOrderBook("BTC-USD")
// Simulate multiple traders
traders := 10
ordersPerTrader := 100
var wg sync.WaitGroup
successCount := int64(0)
for i := 0; i < traders; i++ {
wg.Add(1)
go func(traderID int) {
defer wg.Done()
for j := 0; j < ordersPerTrader; j++ {
side := dex.Buy
if (traderID+j)%2 == 0 {
side = dex.Sell
}
order := &dex.Order{
ID: uint64(traderID*ordersPerTrader + j + 1),
Symbol: "BTC-USD",
Type: dex.Limit,
Side: side,
Price: 50000 + float64(j%100),
Size: 0.1 + float64(j%10)/10,
UserID: fmt.Sprintf("trader_%d", traderID),
}
id := ob.AddOrder(order)
if id > 0 {
atomic.AddInt64(&successCount, 1)
} else if j == 0 && traderID == 0 {
// Debug first failure
t.Logf("First order failed: %+v", order)
}
}
}(i)
}
wg.Wait()
totalOrders := int64(traders * ordersPerTrader)
successRate := float64(successCount) / float64(totalOrders) * 100
t.Logf("E2E Trading: %d/%d orders successful (%.1f%%)",
successCount, totalOrders, successRate)
assert.Greater(t, successCount, int64(0))
assert.Greater(t, successRate, 80.0) // At least 80% success
}
// TestE2EPerformance tests performance requirements
func TestE2EPerformance(t *testing.T) {
ob := dex.NewOrderBook("PERF-USD")
numOrders := 10000
start := time.Now()
for i := 0; i < numOrders; i++ {
order := &dex.Order{
ID: uint64(i + 1),
Symbol: "PERF-USD",
Type: dex.Limit,
Side: dex.Side(i % 2),
Price: 100 + float64(i%100),
Size: 1,
UserID: "perf_test",
}
ob.AddOrder(order)
}
elapsed := time.Since(start)
ordersPerSecond := float64(numOrders) / elapsed.Seconds()
latencyPerOrder := elapsed.Nanoseconds() / int64(numOrders)
t.Logf("Performance: %.0f orders/sec, %d ns/order", ordersPerSecond, latencyPerOrder)
// Performance requirements
assert.Greater(t, ordersPerSecond, float64(50000), "Should process >50K orders/sec")
assert.Less(t, latencyPerOrder, int64(20000), "Should be <20μs per order")
}
// TestE2EMacStudioScale tests Mac Studio scale capabilities
func TestE2EMacStudioScale(t *testing.T) {
tests := []struct {
name string
markets int
orders int
target float64
}{
{"NYSE_Scale", 3000, 70000, 214},
{"NASDAQ_Scale", 5000, 115000, 130},
{"Crypto_Scale", 50000, 1000000, 150},
{"Forex_Scale", 100, 10000000, 15},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
// Calculate Mac Studio capacity
macStudioCapacity := float64(150000000) // orders/sec
multiple := macStudioCapacity / float64(test.orders)
t.Logf("%s: %d markets, %d orders/sec", test.name, test.markets, test.orders)
t.Logf("Mac Studio can handle %.1fx this load", multiple)
assert.Greater(t, multiple, 1.0, "Mac Studio should handle this load")
})
}
}
// TestE2EPlanetScale tests planet-scale capacity
func TestE2EPlanetScale(t *testing.T) {
// Planet scale metrics
totalMarkets := 5000000 // 6.4x Earth
ordersPerSec := 150000000 // Mac Studio capacity
powerWatts := 370 // Mac Studio power
// Calculate efficiency
ordersPerWatt := ordersPerSec / powerWatts
marketsPerGB := totalMarkets / 400 // 400GB for orderbooks
t.Logf("🌍 PLANET SCALE CAPACITY:")
t.Logf(" Markets: %d (6.4x Earth)", totalMarkets)
t.Logf(" Orders/sec: %d", ordersPerSec)
t.Logf(" Power: %dW (less than microwave)", powerWatts)
t.Logf(" Efficiency: %d orders/watt", ordersPerWatt)
t.Logf(" Density: %d markets/GB", marketsPerGB)
// Verify planet scale is achievable
assert.Greater(t, totalMarkets, 784000, "Should handle more than Earth's markets")
assert.Greater(t, ordersPerSec, 15000000, "Should handle global peak load")
assert.Less(t, powerWatts, 1000, "Should use less than 1kW")
}