# 🌐 EA Sports FC Open-Source Ecosystem: Comprehensive Repository & Technical Architecture Report

> **Target Scope:** EA Sports FC (FC 24, FC 25, FC 26, FC 27) and FIFA Ultimate Team (FUT)  
> **Status:** Canonical reference report for `@aphrody/fut` & Bxc Engine  
> **Classification:** Reverse Engineering, Architecture, Optimization Solvers & Data Ingestion  

---

## 1. Executive Summary

The open-source ecosystem surrounding EA Sports FC and FIFA Ultimate Team (FUT) spans over a decade of community engineering. Driven by the high complexity of the in-game economy—the Transfer Market, Squad Building Challenges (SBCs), chemistry systems, and real-time market price fluctuations—developers have produced automated tools across several languages: **Python**, **TypeScript/JavaScript**, **Rust**, **Go**, and **C#**.

This ecosystem divides into five primary functional categories:

```
┌─────────────────────────────────────────────────────────────────────────────────────────────┐
│                               EA Sports FC Open-Source Ecosystem                            │
├─────────────────────┬────────────────────┬────────────────────┬──────────────┬──────────────┤
│  1. SBC Solvers &   │ 2. EA UTAS & Web   │ 3. Extensions &    │ 4. Scrapers  │ 5. Datasets  │
│  Combinatorics      │    App API Clients │    Userscripts     │    & Market  │    & ML      │
│  (CP-SAT, ILP, GA)  │    (OAuth2, SID)   │    (Paletools, DOM)│    (Futbin)  │    (Kaggle)  │
└─────────────────────┴────────────────────┴────────────────────┴──────────────┴──────────────┘
```

1. **SBC Solvers & Mathematical Optimizers:** Formulating squad completion as an **Integer Linear Programming (ILP)** or **Constraint Satisfaction Problem (CSP)** using Google OR-Tools, Mixed-Integer Linear Programming (MILP), or Genetic Algorithms to minimize coin cost or maximize fodder utilization.
2. **EA UTAS API Clients & Reverse-Engineered SDKs:** Direct HTTP clients interacting with EA's private `utas` (Ultimate Team Application Server) endpoints using OAuth2, CAS sessions, and proprietary headers (`X-UT-SID`, `X-UT-PHISHING-TOKEN`).
3. **Web App Enhancers & Automation Suites:** Injected browser extensions and userscripts (most notably **Paletools**, **AutoPilot-SBC**, and legacy **FUT Trade Enhancer**) running in the browser context to bypass anti-bot challenges and streamline squad management.
4. **Market Scrapers & Aggregators:** Unofficial price trackers querying FUTBIN, FUT.gg, and SoFIFA via headless browsers, proxies, and Go/Python CLIs.
5. **Public Player Datasets:** Exhaustive player databases tracking attributes, PlayStyles, body types, and historical evolutions.

---

## 2. Directory of Key Repositories & Tools

### Summary Comparison Matrix

| Project | Primary Language | Category | Core Technology / Architecture | Status / Maintainability | Link |
| :--- | :--- | :--- | :--- | :--- | :--- |
| **`eafc-sbc-solver`** | Python | SBC Solver | Google OR-Tools (CP-SAT), Pandas | Highly active for FC 24/FC 25 | [GitHub](https://github.com/bartlomiej-niemiec/eafc-sbc-solver) |
| **`EA-FC-Automated-SBC-Solving`** | Python | SBC Solver | Google OR-Tools, Excel I/O, Discord Bot | Reference community solver | [GitHub](https://github.com/Regista6/EA-FC-Automated-SBC-Solving) |
| **`sbc-solver`** | Rust + TS / Wasm | SBC Solver | Genetic Algorithm, Rust compiled to Wasm | Experimental, GA engine | [GitHub](https://github.com/kosciukiewicz/sbc-solver) |
| **`AutoPilot-SBC`** | JavaScript / TS | Web App Extension | Browser extension, multi-solve, sequence solver | Active, Web App injected | [GitHub](https://github.com/icysymmetra/AutoPilot-SBC) |
| **`SbcCruncher`** | TypeScript / Next.js | Fodder Combinatorics | Web Workers, Combinatorial search | Web app, fodder calculator | [GitHub](https://github.com/mabenj/SbcCruncher) |
| **`fc24_sbc_bun`** | TypeScript / Bun | SBC Solver | Bun runtime, native TS algorithms | High performance Bun native | [GitHub](https://github.com/omerbn/fc24_sbc_bun) |
| **`fc24_sbc_rust`** | Rust | SBC Solver | Native Rust computational solver | Native Rust reference | [GitHub](https://github.com/omerbn/fc24_sbc_rust) |
| **`Auto-SBC`** | Python | SBC Solver | MIP Formulation, CSV Club export | Python solver baseline | [GitHub](https://github.com/ThomasSteere/Auto-SBC) |
| **`futapi/fut`** | Python | UTAS API Client | Requests, EA CAS/SSO OAuth2, UTAS headers | Gold-standard protocol reference | [GitHub](https://github.com/futapi/fut) |
| **`fut-trade-enhancer`** | JavaScript | Web App Script | Userscript (Tampermonkey), DOM hooking | Archived, base of modern scripts | [GitHub](https://github.com/ckalgos/fut-trade-enhancer) |
| **`Paletools` (pale.tools)** | JavaScript / Android | Injected Web Suite | Injected bookmarklet / Paledroid APK | Dominant tool (millions of users) | [Website](https://pale.tools/fifa/paletools.html) |
| **`futbin`** | Go | Scraper / CLI | Go HTTP client, HTML parsing, CLI | Fast Go terminal query tool | [GitHub](https://github.com/matheusfm/futbin) |
| **`rfutbin`** | R | Data Scraper | R package, FUTBIN scraping for analysis | Analytical research | [GitHub](https://github.com/danielredondo/rfutbin) |
| **`soccerdata`** | Python | Scraper Suite | Multi-site scraper including SoFIFA | Production-grade (2k+ stars) | [GitHub](https://github.com/probberechts/soccerdata) |
| **`sofifa-web-scraper`** | Python | Scraper | Playwright, async extraction | Modern headless scraper | [GitHub](https://github.com/prashantghimire/sofifa-web-scraper) |
| **`Fifa-Autobidder`** | Python | Market Bot | Selenium, Web App UI automation | 150+ stars, automated bidding | [GitHub](https://github.com/tmb5cg/Fifa-Autobidder) |
| **`FIFA-Toolkit`** | C# | UTAS API Client | Reverse-engineered UTAS HTTP client | Historical reference | [GitHub](https://github.com/trydis/FIFA-Ultimate-Team-Toolkit) |
| **`Kaggle FC24/25 Dataset`** | CSV / Data | Player Database | SoFIFA extraction, attributes, PlayStyles | Comprehensive stats archive | [Kaggle](https://www.kaggle.com/datasets/stefanoleone992/ea-sports-fc-24-complete-player-dataset) |

---

## 3. Deep-Dive Architecture & Protocol Analysis

### 3.1 EA Authentication Lifecycle (SSO, CAS, OAuth2 & UTAS)

The authentication protocol employed by EA for the FC Web and Companion apps is a multi-tier identity federation flow combining **EA CAS (Central Authentication Service)**, **EA Nucleus Identity**, and **UTAS Gateways**.

```mermaid
sequenceDiagram
    autonumber
    actor Client as BXC / Browser / Bot
    participant CAS as EA CAS / Accounts (accounts.ea.com)
    participant SSO as EA Sign-In (signin.ea.com)
    participant Gateway as EA Nucleus Gateway (gateway.ea.com)
    participant UTAS as UTAS Application Server (utas.mob.v2.prd.futc-ext.gcp.ea.com)

    Client->>CAS: GET /connect/auth (client_id=FUTWEB_BK_OL_SERVER, response_type=code)
    CAS-->>Client: Redirect to signin.ea.com/p/web2/login (execution token)
    Client->>SSO: POST credentials (email, password, _eventId=submit)
    alt 2FA Required
        SSO-->>Client: 2FA challenge (email / app / SMS)
        Client->>SSO: POST /twoFactorAuthenticate (code)
    end
    SSO-->>CAS: Session established (CASTGC cookie)
    CAS-->>Client: 302 Redirect with ?code=AUTH_CODE
    Client->>CAS: POST /connect/token (grant_type=authorization_code, code=AUTH_CODE)
    CAS-->>Client: Nucleus Access Token + refresh_token
    Client->>Gateway: GET /proxy/identity/pids/me (Bearer Token)
    Gateway-->>Client: Nucleus Persona ID + Account metadata
    Client->>UTAS: POST /ut/auth (nucleusPersonaId, sku=FFA25PCC, clientVersion=1)
    UTAS-->>Client: { sid: "JWT_TOKEN", phishingToken: "TOKEN", protocol: "https" }
    Note over Client,UTAS: All subsequent market/SBC calls use X-UT-SID & X-UT-PHISHING-TOKEN
```

#### Authentication Mechanics & Security Headers
1. **`client_id` Identifiers:**
   - Web App: `FUTWEB_BK_OL_SERVER`
   - Mobile Companion (Android): `FUT25_AND` / `FUT26_AND`
   - Mobile Companion (iOS): `FUT25_IOS` / `FUT26_IOS`
2. **Session Identification (`X-UT-SID`):**
   - A cryptographic session token returned upon successful invocation of `/ut/auth`.
   - Required on every authenticated request.
   - Expires periodically (typically after 30–60 minutes of inactivity) or immediately upon concurrent login from console or another web session.
3. **Phishing Protection Token (`X-UT-PHISHING-TOKEN`):**
   - A secondary session token established during initial persona validation.
   - Required for state-modifying actions (transfer market bidding, buy now, transfer listing, SBC squad submission).
   - Missing or mismatched tokens produce **HTTP 461 (Permission Denied)**.
4. **Origin & Referer Enforcements:**
   - Must strictly match `Origin: https://www.ea.com` and `Referer: https://www.ea.com/ea-sports-fc/ultimate-team/web-app/`.
   - Mismatched headers trigger Cloudflare/Akamai Edge block (HTTP 403).

---

### 3.2 UTAS Transfer Market Protocol

The Transfer Market runs on sharded clusters hosted on Google Cloud Platform (`utas.mob.v2.prd.futc-ext.gcp.ea.com`).

#### Query Parameter Structure
Search endpoint: `GET /ut/game/fc{year}/transfermarket`

| Parameter | Type | Meaning / Mapping | Example |
| :--- | :--- | :--- | :--- |
| `type` | String | Item category | `player`, `development`, `training` |
| `defId` | Integer | Exact player asset definition ID | `231747` (Mbappé) |
| `maskedDefId` | Integer | Base asset ID (for special card variants) | `231747` |
| `lev` | String | Card quality tier | `bronze`, `silver`, `gold`, `special` |
| `pos` | String | Pitch position | `GK`, `CB`, `LB`, `RB`, `CM`, `CAM`, `ST`, `RW`, `LW` |
| `nat` | Integer | Nation ID | `18` (France), `54` (Spain) |
| `leag` | Integer | League ID | `13` (Premier League), `53` (LaLiga) |
| `team` | Integer | Club ID | `241` (FC Barcelona), `1` (Arsenal) |
| `micr` | Integer | Minimum current bid price | `1000` |
| `macr` | Integer | Maximum current bid price | `25000` |
| `minb` | Integer | Minimum Buy Now price | `1000` |
| `maxb` | Integer | Maximum Buy Now price | `20000` |
| `num` | Integer | Page size (max 21) | `21` |
| `start` | Integer | Pagination offset | `0`, `21`, `42` |

#### Auction Actions & Endpoints
* **Place Bid / Buy Now:**  
  `PUT /ut/game/fc{year}/trade/{tradeId}/bid`  
  Payload: `{"bid": price}` (to buy now, set `bid` equal to `buyNowPrice`).
* **Tradepile Management:**  
  `GET /ut/game/fc{year}/tradepile`  
  `POST /ut/game/fc{year}/auctionhouse` (send item from unassigned/club to market listing).
* **Watchlist:**  
  `GET /ut/game/fc{year}/watchlist`  
  `PUT /ut/game/fc{year}/watchlist` (track item).
* **Quick Sell (Discard):**  
  `DELETE /ut/game/fc{year}/item/{itemId}`

#### Anti-Bot Countermeasures & Soft Bans
* **Soft Bans:** Exceeding ~20–30 transfer market queries per minute triggers temporary IP or account bans (HTTP 429 or UTAS error code 458/512), blocking market searches for 5 minutes up to 24 hours while keeping the rest of the game playable.
* **Arkose Labs (FunCaptcha):** Triggered when request patterns lack natural human variance or when rapid sniping occurs.
* **Mitigation Strategy in Top Projects:**
  - Inject pseudo-random jitter delays (e.g. `Gaussian(1200ms, 400ms)`).
  - Alternate search filters (`minb` stepped by +100 / -100) to force fresh cache-busting server responses without triggering suspicious query replay detection.
  - Run inside the real browser DOM (Paletools style) to leverage established TLS fingerprints and cookies.

---

### 3.3 Mathematical Formulation of SBC Solvers (ILP & CP-SAT)

Squad Building Challenges (SBCs) are NP-hard combinatorial optimization problems. The objective is to pick a valid 11-player squad meeting multiple structural constraints at minimal total cost.

#### 1. Optimization Formulation

Let:
* $\mathcal{P} = \{1, \dots, N\}$ be the pool of available players (from club inventory or market candidates).
* $\mathcal{S} = \{1, \dots, 11\}$ be the squad position slots defined by the formation.
* $c_i$ be the cost of acquiring/using player $i$ (for untradeable club players, $c_i = 0$ or an assigned opportunity value).
* $r_i$ be the overall rating of player $i$.
* $x_{i,s} \in \{0, 1\}$ be the binary decision variable indicating whether player $i$ is assigned to slot $s$.

**Objective Function:**
$$\min \sum_{i \in \mathcal{P}} \sum_{s \in \mathcal{S}} c_i \cdot x_{i,s}$$

#### 2. Structural Constraints
* **Slot Completeness:** Exactly one player per slot:
  $$\forall s \in \mathcal{S}, \quad \sum_{i \in \mathcal{P}} x_{i,s} = 1$$
* **Player Uniqueness:** Each player card can be used at most once in the squad:
  $$\forall i \in \mathcal{P}, \quad \sum_{s \in \mathcal{S}} x_{i,s} \le 1$$
* **Positional Validity:**
  $$x_{i,s} = 0 \quad \text{if position of slot } s \notin (\text{primaryPos}(i) \cup \text{altPositions}(i))$$

#### 3. Squad Rating Formula Linearization
The EA FC squad rating calculation is non-linear due to the excess adjustment factor:
$$\text{Average} = \frac{1}{11} \sum_{i \in \text{selected}} r_i$$
$$\text{Excess} = \sum_{i \in \text{selected}} \max(0, r_i - \text{Average})$$
$$\text{Calculated Rating} = \left\lfloor \frac{\sum r_i + \text{Excess}}{11} \right\rfloor$$

**Handling in ILP Solvers (`bartlomiej-niemiec/eafc-sbc-solver`, `Regista6`):**
Because $\max(0, r_i - \text{Avg})$ introduces a non-convex piece-wise non-linearity, open-source solvers handle this via two proven strategies:
1. **CP-SAT Solver Formulation:** Google OR-Tools CP-SAT supports integer expressions natively (`model.AddMaxEquality`), avoiding manual linearization.
2. **Pre-computed Rating Combination Trees:** SbcCruncher and MIP solvers pre-calculate valid integer partitions (e.g. to achieve an 85 squad rating: `[88, 85, 85, 84, 84, 84, 84, 84, 83, 83, 83]`), reducing the problem to satisfying fixed bucket counts:
   $$\sum_{i \in \mathcal{P}} \mathbb{I}(r_i = R_k) \cdot \sum_{s} x_{i,s} = n_k$$

#### 4. Chemistry Constraints Formulation (FC 24 / FC 25 / FC 26 / FC 27)
In the modern diamond chemistry system (0 to 3 points per player, max 33 team chemistry):
* Chemistry is awarded based on thresholds of shared **Club**, **League**, and **Nation**.

| Chemistry Tier | Club Threshold | League Threshold | Nation Threshold |
| :---: | :---: | :---: | :---: |
| **1 Point** | 2 players | 3 players | 2 players |
| **2 Points** | 4 players | 5 players | 5 players |
| **3 Points** | 7 players | 8 players | 8 players |

* **Special Rules:**
  - **Icons:** Automatically obtain 3 chemistry points in position; provide **+2** to their nation threshold and **+1** to **all active leagues** in the squad.
  - **Heroes:** Automatically obtain 3 chemistry points in position; provide **+1** to their nation threshold and **+2** to their specific league.
  - **Manager:** Adds **+1** to nationality and **+1** to league count.
  - **Out-of-position players:** Receive and contribute **0** chemistry.

**Linear Formulation for Chemistry Thresholds:**
For each club $k$, let count variable $C_k = \sum_{i \in \text{club}(k)} \sum_{s} x_{i,s}$.  
Define binary indicators $t_{k,1}, t_{k,2}, t_{k,3} \in \{0, 1\}$ corresponding to thresholds $T = [2, 4, 7]$:
$$C_k \ge 2 \cdot t_{k,1}, \quad C_k \ge 4 \cdot t_{k,2}, \quad C_k \ge 7 \cdot t_{k,3}$$
$$t_{k,1} \ge t_{k,2} \ge t_{k,3}$$
Player $i$ of club $k$ receives $t_{k,1} + t_{k,2} + t_{k,3}$ club chemistry points (capped such that player total chemistry $\le 3$).

---

## 4. Scrapers, Price Trackers & Public Datasets

### 4.1 Scrapers & External APIs
1. **FUTBIN:**
   - No public developer API.
   - Heavy Cloudflare Turnstile / Bot Management protection.
   - Scrapers like `matheusfm/futbin` (Go) query endpoints directly, while browser suites (`@aphrody/fut` stealth profile) utilize automated browser contexts with realistic fingerprinted navigators.
2. **FUT.gg:**
   - Clean Next.js SSR architecture.
   - Data can be scraped via lightweight HTTP requests and Cheerio / lol-html DOM parsing without executing full headless browsers.
3. **SoFIFA (`soccerdata`):**
   - The primary source for official EA attribute dumps, player potential ratings, work rates, traits, and physical dimensions.
   - `soccerdata` (Python) wraps SoFIFA with built-in rate-limiting, SQLite caching, and Pandas DataFrames.
4. **EA Content Public CDN (Unauthenticated):**
   - Direct JSON item dictionaries published on EA's CDN:
     `https://fifa21.content.easports.com/fifa/fltOnlineAssets/{buildGuid}/{year}/fut/items/web/players.json`
     `teams.json`, `leagues.json`, `nations.json`
   - High speed, zero auth requirement, perfectly synchronized asset IDs.

### 4.2 Machine Learning & Historical Datasets
* **`stefanoleone992/ea-sports-fc-24-complete-player-dataset` (Kaggle):**
  - Historical database from FIFA 15 through FC 24.
  - Standard dataset for training machine learning valuation models, player clustering, and career growth forecasting.
* **`nyagami/ea-sports-fc-25-database-ratings-and-stats` (Kaggle):**
  - Complete FC 25 player ratings, male & female leagues, PlayStyles, and PlayStyle+ designations.

---

## 5. Technology Evaluation: Python vs TypeScript/Bun vs Rust vs Go

| Dimension | Python (`eafc-sbc-solver`, `soccerdata`) | TypeScript / Bun (`@aphrody/fut`, `fc24_sbc_bun`) | Rust (`fc24_sbc_rust`, `sbc-solver`) | Go (`matheusfm/futbin`) |
| :--- | :--- | :--- | :--- | :--- |
| **Optimization Solvers** | ⭐⭐⭐⭐⭐ (Google OR-Tools, PuLP, SciPy) | ⭐⭐⭐ (JS-HiGHS, Wasm bindings) | ⭐⭐⭐⭐ (good_lp, HiGHS-sys, Wasm target) | ⭐⭐ (Limited MIP bindings) |
| **I/O & HTTP Speed** | ⭐⭐⭐ (Requests/Aiohttp) | ⭐⭐⭐⭐⭐ (Native Bun HTTP, ImpersonatedClient) | ⭐⭐⭐⭐⭐ (Reqwest, Hyper) | ⭐⭐⭐⭐⭐ (Fast standard net/http) |
| **DOM / Scraping** | ⭐⭐⭐⭐ (BeautifulSoup, Playwright) | ⭐⭐⭐⭐⭐ (lol-html FFI, Cheerio, CDP) | ⭐⭐⭐⭐ (scraper, lol-html) | ⭐⭐⭐ (goquery) |
| **Cross-Platform Deploy** | ⭐⭐⭐ (Requires venv, Python runtime) | ⭐⭐⭐⭐⭐ (Self-contained single binary `bun build --compile`) | ⭐⭐⭐⭐⭐ (Static binary, negligible memory) | ⭐⭐⭐⭐⭐ (Single static binary) |
| **Ecosystem Synergies** | Heavy data science & notebook ecosystem | Ideal for Web App injection, MCP & CLI | Ideal for ultra-fast Wasm embedded solvers | Ideal for background CLI utilities |

---

## 6. Strategic Integration Opportunities for `@aphrody/fut`

To position `@aphrody/fut` as the most advanced, unified Ultimate Team toolkit in the open-source world, the following enhancements are recommended:

```
                                  ┌──────────────────────────────────────────────┐
                                  │               @aphrody/fut                   │
                                  └──────────────────────┬───────────────────────┘
                                                         │
                ┌────────────────────────┬───────────────┴───────────────┬────────────────────────┐
                ▼                        ▼                               ▼                        ▼
      [ High-Performance ILP ]   [ Full UTAS Lifecycle ]         [ Unified Data Layer ]    [ Agentic MCP Tools ]
      - HiGHS Wasm / OR-Tools    - Complete market operations    - CDN + FUTBIN + SoFIFA   - Natural language
      - Exact chemistry model    - Auto session renewal          - SQLite FTS5 search      - Automated trading
      - Multi-SBC batch solve    - Anti-ban jitter & backoff     - Real-time price cache   - Squad recommendation
```

### Opportunity 1: Implement an Exact ILP SBC Engine (Replacing Greedy Search)
* **Current State:** `src/squad/solver.ts` uses a heuristic greedy algorithm with rating thresholds.
* **Target:** Incorporate a mathematical solver using **HiGHS (via Wasm)** or **Google OR-Tools (via Rust FFI / microservice)**.
* **Impact:** Solves any complex multi-league / multi-nation SBC with guaranteed mathematical cost optimality in under 100 milliseconds.

### Opportunity 2: Full UTAS Lifecycle Client in `src/ea/client.ts`
* **Current State:** `EaUtasClient` supports market search, user credits, and CDN dictionary fetching.
* **Target:** Implement full trading actions:
  - `bid(tradeId, amount)`
  - `buyNow(tradeId, price)`
  - `listAuction(itemData, startingBid, buyNowPrice, duration)`
  - `moveToTradepile(itemId)`
  - `submitSbc(challengeId, slotAssignments)`
  - Automated session refresh and Chromium cookie harvest integration.

### Opportunity 3: Multi-Source Data Harmonization
* Combine the static unauthenticated EA CDN dictionaries (`players.json`), SoFIFA physical & PlayStyle attributes, and live FUT.gg/FUTBIN prices into the local SQLite database (`fut_extracted_database.sqlite`).

### Opportunity 4: Direct Agentic Tools via MCP
* Connect the solved SBC squads and market sniper directly to AI agents via BXC MCP (`bxc_fut_sbc_solve`, `bxc_fut_snipe`, `bxc_fut_squad_build`), enabling conversational squad management and automated SBC farming.

---

## 7. Conclusion

The open-source EA Sports FC ecosystem is rich in specialized components: Python leads in linear programming solvers (OR-Tools), browser userscripts (Paletools) lead in real-world user adoption and anti-bot stealth, and Go/Rust provide lightweight scraper and simulation tools. 

By integrating an exact Wasm/Rust-backed ILP solver into `@aphrody/fut`, completing the UTAS client lifecycle, and harmonizing CDN/FUTBIN data in Bun, **`@aphrody/fut`** combines the strengths of these disconnected projects into a single, cohesive, production-ready ecosystem for autonomous AI agents and developers.
