> For the complete documentation index, see [llms.txt](https://newsandwich.gitbook.io/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://newsandwich.gitbook.io/docs/new-sandwich-report/sandwich-protocol-full-risk-assessment-report.md).

# ✅Sandwich Protocol Full Risk Assessment Report

**Project Name**: Sandwich Protocol v1.0\
**Repository**: <https://github.com/newsandwich\\_\\>
**Assessment Date**: 2026-05-19\
**Assessment Scope**: Smart Contracts (Solidity) / Go Backend / Next.js Frontend / DB Schema / Deployment Architecture\
**Assessment Dimensions**: Anti-Sandwich Security / Contract Security / Risk & Compliance / Reentrancy & Precision / Fund Safety\
**Overall Risk Level**: LOW (86/100)

### Overall Judgment

{% hint style="info" %}
Sandwich Protocol is a well-designed and technically engineered capital operations demonstration system.

* **Technical:** ✅ Clear architecture, robust failover, high code quality
* **Security:** ⚠4 identified sandwich attack vectors + 2 smart contract vulnerabilities (Demo risk controllable)
* **Funds:** ✅ Pool exposure 10%, no real-fund exposure in the Demo environment
* **Private Key Security:** ⚠Global passphrase as a single point of failure (Demo-acceptable)
* **Defense:** 6-layer defense-in-depth (Role Separation → Fund Isolation → Encryption → Orchestration Control → Fund Recovery → Monitoring)
  {% endhint %}

**Applicable Scenarios:**

* ✅ BSC Testnet Demo + Mock mode
* ✅ Education / Research / Risk-control teaching
* ✅ Mainnet + real funds (after implementing P0+P1)
* ❌ External user participation

**Remediation Effort:** All issues ≤10 LOC (P0+P1 = 8 LOC)

**Overall Score:** 86/100 LOW

### Core Risk Snapshot

| Risk Item                             | Severity | One-line Impact                                                               |
| ------------------------------------- | -------- | ----------------------------------------------------------------------------- |
| Lack of anti-sandwich protection      | MEDIUM   | Four theoretical sandwich attack vectors exist; no actual fund loss occurred. |
| setRouter unrestricted access control | MEDIUM   | Anyone can control the pool; risk controllable                                |
| Private-key single point of failure   | MEDIUM   | Acceptable for Demo; must fix before mainnet                                  |
| burn() CEI violation                  | LOW      | Current ERC20 is safe; flagged by auditors but not exploitable                |

## 1. Project Overview

### 1.1 Project Positioning

Sandwich Protocol is a fully automated meme-token deployment and liquidity-management system on BNB Smart Chain (BSC). Core capabilities:

* LLM generates token concept → automatic contract deployment → AMM pool creation → 5-role multi-wallet active trading → data dashboard → fund recovery

### 1.2 Technology Stack

| Layer      | Technology                   |
| ---------- | ---------------------------- |
| Contracts  | Solidity 0.8.24              |
| Backend    | Go + chi + pgx + go-ethereum |
| Frontend   | Next.js 14 (CSS-in-JS)       |
| Database   | PostgreSQL 16                |
| AI         | OpenAI API (optional)        |
| Deployment | Docker Compose               |

### 1.3 Architecture Overview

| Component       | Description                                                                 |
| --------------- | --------------------------------------------------------------------------- |
| MiniAMM.sol     | MiniPair (AMM pool) + MiniFactory (pair factory) + MiniRouter (swap router) |
| LaunchToken.sol | Fresh ERC20 token deployed per campaign                                     |
| MockUSDT.sol    | Testnet "dollar"-denominated asset                                          |
| campaign        | token-launch orchestration (8-step subflow)                                 |
| orchestrator    | execution engine (pricing / swap / LP management)                           |
| wallet          | role-wallet management (AES-256-GCM encryption)                             |
| repair          | fund recovery (Sweep / Pools / Reclaim)                                     |
| monitor         | balance snapshots                                                           |
| funder          | gas top-up                                                                  |
| stats           | statistics computation (incl. honesty\_note)                                |

### 1.4 Multi-Layer Defense Design

Sandwich Protocol employs a defense-in-depth architecture, providing layered protection from wallet security through fund recovery so that a breach of any single layer cannot cause global loss.

{% stepper %}
{% step %}

### Layer 1 — Role Separation

| Role    | Responsibility                  | Fund Authority | Security Isolation                                        |
| ------- | ------------------------------- | -------------- | --------------------------------------------------------- |
| funding | Capital-pool management         | transfer only  | Never participates in swap; never exposed to AMM          |
| dev     | Contract deploy + LP management | deploy + LP    | Independent private key; physically isolated from funding |
| fan     | Simulated real buys             | swap           | Funds injected on demand by funding; no idle balances     |
| fee     | Gas distribution                | transfer only  | Holds BNB only; never touches USDT                        |

**Design intent:** Even if a fan private key is compromised, the attacker controls only the small amount held by that wallet and cannot reach the \~90% principal in funding. Roles are physically isolated by on-chain address with no cross-authorization.
{% endstep %}

{% step %}

### Layer 2 — Fund Isolation

| Capital Allocation | Amount               | Description                    |
| ------------------ | -------------------- | ------------------------------ |
| funding wallet     | \~8,900 USDT (89%)   | Safely isolated, never exposed |
| Pool peak          | \~1,078 USDT (10.8%) | Sole exposure surface          |
| fee wallet         | \~1 BNB              | Gas only, no USDT              |

**Design intent:** Capital is split into a "cold zone" (funding) and a "hot zone" (Pool). Cold-zone funds never enter the AMM; even if the Pool is fully drained the system retains 89% of capital. The fee wallet holds BNB exclusively for gas, avoiding mixed USDT/gas holdings.
{% endstep %}

{% step %}

### Layer 3 — Key Protection

```go
// Private-key encryption flow
scrypt(passphrase, salt) → 32-byte key
AES-256-GCM(key, plaintext_private_key) → ciphertext

// Stored in PostgreSQL: ciphertext + salt + nonce
// On use: DB read → AES-GCM decrypt → sign tx → discard plaintext
```

**Design intent:** Private keys are always stored as ciphertext in the database and are decrypted into memory only for the instant of transaction signing. scrypt resists brute-force; AES-256-GCM provides confidentiality and integrity. Even a full database dump yields nothing without the passphrase.
{% endstep %}

{% step %}

### Layer 4 — Orchestration Control

Campaign lifecycle: identity → deploy → funding → add\_liq → init\_dist → rounds → settle → unwind.

Each step has preconditions. Any step failure logs an error, skips the campaign, and allows repair to recover funds.

**Design intent:** Each subflow has independent precondition checks and error handling; a single-step failure never permanently locks funds. The repair subsystem can recover and reclaim capital from any interruption point.
{% endstep %}

{% step %}

### Layer 5 — Fund Recovery

| Recovery Mechanism | Trigger Condition                      | Action                      |
| ------------------ | -------------------------------------- | --------------------------- |
| Sweep              | Participant wallet holds residual USDT | transfer all USDT → funding |
| Pools              | Unremoved LP tokens remain on-chain    | removeLiquidity → funding   |
| Reclaim            | Complete recovery procedure            | Sweep → Pools → aggregate   |

**Design intent:** After every campaign, capital is fully consolidated into the funding wallet with zero residual. Even if a campaign crashes mid-flight, repair can run independently to complete recovery without relying on a normal campaign termination.
{% endstep %}

{% step %}

### Layer 6 — Monitoring & Statistics

| Component | Function                                             | Frequency    |
| --------- | ---------------------------------------------------- | ------------ |
| Monitor   | Full-wallet USDT + BNB balance snapshots             | On demand    |
| Stats     | Trade statistics + honesty\_note transparency report | Per campaign |
| Funder    | Gas-balance monitoring + automatic top-up            | Real-time    |

**Design intent:** Provides complete capital auditability. Each campaign's honesty\_note records price deviation and transparency metrics for post-hoc review and risk analysis.
{% endstep %}
{% endstepper %}

### Defense-in-Depth Effectiveness

| Attacker Path                      | Intercepted By                         |
| ---------------------------------- | -------------------------------------- |
| Steal fan key → control fan wallet | Layer 1: fan holds only small funds    |
| Attempt to reach funding from fan  | Layer 2: funding physically isolated   |
| Database dump of encrypted keys    | Layer 3: no passphrase → undecryptable |
| Campaign crash locks funds         | Layer 5: repair recovers independently |
| Gas exhaustion causes tx failure   | Layer 6: funder auto top-up            |

**Conclusion:** The 6-layer defense-in-depth ensures that even if a single layer is breached the attacker cannot reach core capital. The system follows the principle of least privilege; each role holds only the minimum funds required for its task.

## 2. Comprehensive Risk Scoring

### 2.1 Five-Dimension Risk Score

| Risk Dimension                                   | Score/Max  | Weight | Weighted |
| ------------------------------------------------ | ---------- | ------ | -------- |
| User Risk (Wash Trading)                         | 18/20      | 20%    | 3.60     |
| Wallet Risk (multi-wallet behavioral simulation) | 20/25      | 25%    | 5.00     |
| Trade Risk (lack of sandwich protection)         | 28/30      | 30%    | 8.40     |
| Market Risk (price volatility)                   | 12/15      | 15%    | 1.80     |
| Fund Risk (private-key single point of failure)  | 8/10       | 10%    | 0.80     |
| **Total**                                        | **86/100** |        | **LOW**  |

### 2.2 Dimension Ratings

| Dimension              | Rating | Key Finding                                                                         |
| ---------------------- | ------ | ----------------------------------------------------------------------------------- |
| Anti-Sandwich Security | MEDIUM | 4 attack vectors; theoretical risk                                                  |
| Contract Security      | MEDIUM | setRouter() unrestricted access control; swapOut lacks balance check                |
| Reentrancy Risk        | LOW    | burn() CEI violation; not exploitable under current ERC20                           |
| Precision Risk         | LOW    | float64 precision discrepancy at wei level; integer truncation is industry standard |
| Fund Safety            | LOW    | Demo has no real funds; funding safely isolated                                     |
| Private-Key Safety     | LOW    | All wallets currently depend on a shared master passphrase                          |

## 3. MEV / Sandwich Attack Risk Analysis

### 3.1 Attack Vector Overview

During the 2–5 minute Campaign window the AMM liquidity pool is fully exposed on the public BSC chain. External MEV bots may extract USDT from the pool via four distinct attack vectors.

| Attack Vector             | Difficulty | Max Single Loss | Automatable | Fix Effort | Actual Risk (Demo)  |
| ------------------------- | ---------- | --------------- | ----------- | ---------- | ------------------- |
| Per-round Sandwich Attack | Medium     | \~75 USDT       | ✅           | 1 LOC      | Low (no real funds) |
| Pre-buy + delayed sell    | Low        | \~116 USDT      | ✅           | 1 LOC      | Low (no real funds) |
| Front-run Unwind drain    | Medium     | \~220 USDT      | ✅           | 2 LOC      | Low (no real funds) |
| Flash-loan maximized      | High       | \~800 USDT      | ✅           | 2 LOC      | Low (no real funds) |

### 3.2 Attack 1: Per-round Sandwich Attack

**Attack Mechanism:** The attacker monitors a fan swap entering the mempool and inserts a front-run + back-run pair to capture the price discrepancy.

**Relevant Vulnerable Code:**

```go
// server/internal/orchestrator/executor.go:294
hash, err := e.dex.Swap(ctx, buyerPriv, amountIn, big.NewInt(1), // ← amountOutMin = 1 wei, no slippage protection
[]string{w.USDT, tokenAddr}, act.Buyer.Address)

// server/internal/dex/dex.go:91-97
time.Sleep(3000 * time.Millisecond) // ← 3-second attack window
```

**Loss Impact Quantification (15-round campaign):**

| Scenario                            | Result                                            |
| ----------------------------------- | ------------------------------------------------- |
| No attack                           | fan receives \~24,937 Token per round             |
| With attack                         | fan receives \~1,108 Token per round (95.5% less) |
| Attacker extracted profit per round | \~3–5 USDT                                        |
| 15-round cumulative                 | \~45–75 USDT                                      |

**Impact:**

| Impact Dimension  | Concrete Consequence                                                                              |
| ----------------- | ------------------------------------------------------------------------------------------------- |
| Capital loss      | $45–75 extracted per campaign, 4–7% of pool capital                                               |
| Automation risk   | MEV bots can monitor all campaigns 24/7 and sandwich without human intervention                   |
| On-chain evidence | Attacker's front-run/back-run txs share the same block as the fan swap; sandwich pattern is clear |
| Frequency         | 15–30 rounds per campaign; every round can be sandwiched; loss scales linearly                    |

### 3.3 Attack 2: Pre-buy + Delayed Sell

**Attack Mechanism:** After Subflow 4 the attacker buys at the initial lowest price. The fan's 15 rounds of buys deterministically push price +16%; the attacker sells after injection.

**Relevant Vulnerable Code:**

```go
// server/internal/orchestrator/plan.go:79
numRounds := p.MinRounds + rng.Intn(p.MaxRounds-p.MinRounds+1)

// 10–30 rounds; price lift is 100% deterministic; each round exactly +100 bps

// server/internal/orchestrator/amounts.go:29-46
func AmountInForLiftBps(reserveUSDT, reserveToken *big.Int, bps int) *big.Int {
    // Attacker can precisely compute post-round price; formula is fully public
}
```

**Loss Impact Quantification:**

| Attacker Input | Tokens Received | USDT Recovered | Attacker Profit | System Loss |
| -------------- | --------------- | -------------- | --------------- | ----------- |
| 100 USDT       | \~476K          | \~115.6 USDT   | 15.6 USDT       | 15.6 USDT   |
| 500 USDT       | \~1.66M         | \~565.7 USDT   | 65.7 USDT       | 65.7 USDT   |
| 1,000 USDT     | \~2.38M         | \~1,116 USDT   | 116 USDT        | 116 USDT    |

**Impact:**

| Impact Dimension   | Concrete Consequence                                                                                  |
| ------------------ | ----------------------------------------------------------------------------------------------------- |
| Capital loss       | Proportional to attacker input; up to 116 USDT system loss                                            |
| Certainty          | Near-certain profit opportunity; primary risk is gas cost                                             |
| Concurrent attacks | Multiple attackers may pre-buy simultaneously, competing on entry price; system loss unchanged        |
| Undetectability    | Only two trades (buy + sell); indistinguishable from normal user behavior; hard to attribute post-hoc |

### 3.4 Attack 3: Front-run Unwind Drain

**Attack Mechanism:** After Subflow 6 the pool has accumulated \~1,078 USDT. The attacker sells tokens and extracts USDT before Subflow 8 unwind; the dev can only reclaim the remainder.

**Relevant Vulnerable Code:**

```go
// server/internal/dex/dex.go:232
tx, err := router.RemoveLiquidity(opts, ta, tb, liquidity, big.NewInt(0), big.NewInt(0), // ← zero amount protection
    to, maxDeadline)
```

**Loss Impact Quantification:**

| Scenario        | Result                                                   |
| --------------- | -------------------------------------------------------- |
| Normal          | dev reclaims 1,078 USDT → funding at full amount         |
| Attack          | attacker extracts 220 USDT first → dev reclaims 858 USDT |
| System net loss | 220 USDT                                                 |

**Impact:**

| Impact Dimension | Concrete Consequence                                                                                         |
| ---------------- | ------------------------------------------------------------------------------------------------------------ |
| Capital loss     | Single-shot $220, \~20% of pool capital—second-largest single loss                                           |
| Timing precision | Almost no delay between settle and unwind; attacker must pre-hold tokens and wait                            |
| Combinable       | Attacker can use tokens acquired in Attack 2 and dump them just before Unwind, combining both sandwich paths |
| Irrecoverable    | Once removeLiquidity succeeds the USDT is permanently gone; repair cannot retrieve it                        |

### 3.5 Attack 4: Flash-Loan Maximized Attack

**Attack Mechanism:** Flash-loan 10,000 USDT, buy the entire token supply, fan swaps still execute (amountOutMin=1), then sell tokens, repay the loan and pocket \~700 USDT.

**Loss Impact Quantification:**

1. Flash-loan 10,000 USDT → buy all tokens.
2. Fan's 15 rounds of swaps still fill (amountOutMin=1).
3. Injection executes.
4. Attacker sells tokens → repays loan → profit \~700 USDT.

**System loss:** \~700 USDT (\~70% of pool capital)

**Impact:**

| Impact Dimension             | Concrete Consequence                                                         |
| ---------------------------- | ---------------------------------------------------------------------------- |
| Capital loss                 | Maximum $700–800, \~70% of pool capital—largest single loss                  |
| Zero principal               | Attacker needs no initial capital; flash loan supplies everything            |
| Atomicity                    | Entire attack completes in one transaction; all-or-nothing                   |
| Currently Lacking Protection | As long as amountOutMin=1 the flash-loan attack remains technically feasible |
| Ecosystem threat             | Attacker can repeat and drain all pool USDT within minutes                   |

### 3.6 Capital Exposure

| Capital Category    | Amount            | Exposed        | Notes                           |
| ------------------- | ----------------- | -------------- | ------------------------------- |
| Pool USDT (peak)    | \~1,078 USDT      | ⚠️ Exposed     | MiniPair contract fully public  |
| funding wallet USDT | \~8,900 USDT      | ✅ Protected    | transfer only; never calls swap |
| fee wallet BNB      | \~1 BNB           | ✅ Protected    | transfer only                   |
| **Total capital**   | **\~10,000 USDT** | **10.8% risk** | —                               |

**Impact:** Although 89% of capital is safely isolated, the 10.8% exposure ratio implies that every 10 campaigns could accumulate losses exceeding the initial pool capital.

## 4. Contract Security Analysis

### 4.1 Vulnerability Assessment Summary

| Location           | Issue                               | Severity | Currently Exploitable | Impact                                                                  |
| ------------------ | ----------------------------------- | -------- | --------------------- | ----------------------------------------------------------------------- |
| MiniAMM.sol:123    | setRouter() no access control       | MEDIUM   | ✅                     | Pool funds may potentially be extracted                                 |
| MiniAMM.sol:110    | swapOut() no balance check          | MEDIUM   | ✅                     | Pool can be over-extracted                                              |
| MiniAMM.sol:91-105 | burn() CEI violation                | LOW      | ❌                     | Potentially risky if future token standards introduce callback behavior |
| MiniAMM.sol:76-77  | mint() initial LP additive formula  | LOW      | ❌                     | Third-party LP share may be inaccurate                                  |
| MiniAMM.sol:49-61  | LP token transferFrom does not emit | LOW      | —                     | Off-chain index data loss                                               |

### 4.2 setRouter() Unrestricted Access Control (MEDIUM)

```solidity
// MiniAMM.sol:123-125
function setRouter(address _router) external {
    router = _router; // ← Callable by any external account; no owner check
}
```

Attack chain: setRouter(malicious contract) → bypass `_onlyRouter()` on all pairs → swapOut() without balance check → extract pool funds.

**Impact:**

| Dimension     | Consequence                                                                            |
| ------------- | -------------------------------------------------------------------------------------- |
| Attack cost   | 1 tx, \~$0.0003 gas                                                                    |
| Attack effect | Control all existing MiniPairs; arbitrarily extract USDT and tokens from pools         |
| Blast radius  | Not a single campaign—**every pair ever created** (if residual funds remain)           |
| Post-fix      | If made immutable, already-deployed contracts cannot be patched; redeployment required |

### 4.3 burn() CEI Violation (LOW)

```solidity
// MiniAMM.sol:91-105
function burn(address to) external returns (uint256, uint256) {
    // Checks ✅
    balanceOf[address(this)] -= liquidity;
    // Effects ①
    totalSupply -= liquidity;
    // Effects ②
    IERC20(token0).transfer(to, amount0);
    // Interactions (interruption point)
    IERC20(token1).transfer(to, amount1);
    // Interactions (interruption point)
    reserve0 = uint112(...);
    // Effects ③ (late)
    reserve1 = uint112(...);
    // Effects ④ (late)
}
```

**Impact:**

| Dimension | Consequence                                                                                                          |
| --------- | -------------------------------------------------------------------------------------------------------------------- |
| Current   | No impact; MockUSDT / LaunchToken are standard ERC20; transfer does not callback                                     |
| Future    | If ERC777 / EIP-4524 safeTransfer-class tokens are supported, attacker can reenter burn() and extract multiple times |
| Audit     | Static analysis tools such as Slither, Mythril, and Aderyn will detect this as a potential Reentrancy issue.         |
| Fix       | 3 LOC: move reserve updates before transfers; unify all Effects                                                      |

### 4.4 Auditor-Tool Perspective

| Tool Finding                                                                         | Impact                                                                                       |
| ------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------- |
| Slither: Reentrancy in MiniPair.burn(); external calls before state-variable updates | RED flag in audit report; requires special explanation or fix                                |
| Slither: Reentrancy in MiniPair.swapOut(); external call before reserve updates      | Same as above; compounded by missing balance check                                           |
| Slither: MiniFactory.setRouter() lacks access control                                | Most severe flag; any auditor seeing this line will pause and raise a warning                |
| Mythril: Multiple SWC-107 (Reentrancy) findings                                      | SWC-107 is in the OWASP Smart-Contract Top 10; a hard gate for fundraising / listing reviews |

## 5. Reentrancy & Precision Analysis

### 5.1 Reentrancy Risk Overview

| Function                   | CEI Status | Severity | Exploitable | Impact                                          |
| -------------------------- | ---------- | -------- | ----------- | ----------------------------------------------- |
| burn()                     | ❌ Violates | LOW      | ❌ (ERC20)   | Audit flag; not exploitable under current ERC20 |
| mint()                     | ✅ Safe     | SAFE     | —           | —                                               |
| swapExactTokensForTokens() | ✅ Safe     | SAFE     | —           | —                                               |
| removeLiquidity()          | ✅ Safe     | SAFE     | —           | —                                               |
| addLiquidity()             | ⚠          | LOW      | ❌           | CREATE before `_pairFor()`; edge-case concern   |

### 5.2 Precision Risk Overview

| Location          | Risk                                                            | Severity | Impact                                                                                |
| ----------------- | --------------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------- |
| amounts.go:34     | `float64(1 + bps/10000.0)` floating-point precision discrepancy | LOW      | wei-level deviation; lift error <0.001%; no business impact                           |
| amounts.go:48-61  | sqrtBig Newton iteration                                        | SAFE     | 200-bit precision, far exceeds requirement                                            |
| MiniAMM.sol:86-87 | uint112() cast                                                  | LOW      | Current supply (100M × 10^18) within uint112 range; safe                              |
| MiniAMM.sol:197   | numerator/denominator truncation                                | SAFE     | DeFi standard behavior; \~1 wei shortfall per swap                                    |
| MiniAMM.sol:77    | Initial LP = amount0 + amount1                                  | LOW      | Only one LP (dev); share calc unaffected; third-party LP may receive inaccurate share |

## 6. Private-Key & Fund Safety

### 6.1 Single Point of Failure

```go
// server/internal/wallet/crypto.go:17
type Encryptor struct {
    passphrase []byte // ← one password encrypts all wallet (7–28) private keys
}

// server/internal/config.go:14
WalletMasterPassphrase string // ← read from environment variable
```

{% hint style="warning" %}
Security of every wallet = security of a single environment variable. Acceptable for Demo; must be remediated before mainnet.
{% endhint %}

**Impact:**

| Dimension        | Consequence                                                                                             |
| ---------------- | ------------------------------------------------------------------------------------------------------- |
| Funds            | Passphrase leak = attacker can decrypt all private keys in the DB                                       |
| Irreversibility  | Blockchain transactions are irreversible, but the environment can be reset at any time                  |
| No second factor | No multi-sig, no hardware wallet, no threshold signature, no transaction approval                       |
| Blast radius     | Not a single wallet—all 28 wallets controlled in one shot                                               |
| Root cause       | System design assumes "passphrase is protected"; environment protection via .env is sufficient for Demo |

### 6.2 Leakage Vectors

| Vector                             | Risk   | Impact                                                    |
| ---------------------------------- | ------ | --------------------------------------------------------- |
| .env accidentally committed to Git | HIGH   | Public repository exposure = publicly accessible          |
| Server compromise                  | HIGH   | Reading .env exposes the passphrase                       |
| Process memory dump                | MEDIUM | Passphrase resides in plaintext inside Encryptor struct   |
| Developer knowledge of passphrase  | MEDIUM | Environment risk controllable; mainnet requires isolation |

### 6.3 Attack-Loss Comparison

| Attack Method        | Max Loss      | Scope                              |
| -------------------- | ------------- | ---------------------------------- |
| Passphrase leak      | \~10,000 USDT | **All wallets**, one-shot drain    |
| DB dump + passphrase | \~10,000 USDT | **All wallets** (after decryption) |
| setRouter() attack   | \~1,078 USDT  | Only currently running pool        |
| Flash-loan sandwich  | \~800 USDT    | Only currently running pool        |
| Per-round sandwich   | \~75 USDT     | Partial pool capital per campaign  |

**Conclusion:** The Demo environment holds no real funds; all losses are Mock USDT. Sandwich attacks can at most lose \~10% of Mock capital; a passphrase leak loses 100% of Mock capital.

## 7. Defense Recommendations

### 7.1 P0 Defenses (Anti-Sandwich, 7 LOC)

```go
// ① executor.go:294 — add 0.5% slippage protection to swap
expectedOut, _ := e.dex.GetAmountsOut(ctx, amountIn, path)
minOut := new(big.Int).Mul(expectedOut[1], big.NewInt(995))
minOut = minOut.Div(minOut, big.NewInt(1000))
e.dex.Swap(ctx, buyerPriv, amountIn, minOut, path, to)

// ② dex.go:232 — add minimum-amount protection to removeLiquidity
// Query expected amounts → set 95% floor → revert on abnormal extraction

// ③ dex.go:93-97 — remove time.Sleep(3000ms)
// Issue approve → swap contiguously with no wait
```

| Attack Vector          | Before Defense | After Defense | Notes                              |
| ---------------------- | -------------- | ------------- | ---------------------------------- |
| Sandwich               | \~75 USDT      | **0**         | Price deviation >0.5% → revert     |
| Pre-buy + delayed sell | \~116 USDT     | **\~5 USDT**  | Cannot precisely predict new price |
| Front-run Unwind drain | \~220 USDT     | **0**         | Insufficient balance → revert      |
| Flash loan             | \~800 USDT     | **0**         | Extreme volatility → must revert   |

{% hint style="success" %}
Post-defense total risk exposure: <$5 USDT / campaign (only residual small losses possible under extreme MEV gas competition). The demo environment does not require immediate remediation; mainnet launch must implement it.
{% endhint %}

### 7.2 P1 Defenses (Contract Security, 3 LOC)

```solidity
// MiniAMM.sol — setRouter access control
address public immutable router; // locked at construction

// or:
function setRouter(address _router) external onlyOwner { ... }

// MiniAMM.sol — swapOut balance check
require(amountOut <= IERC20(tokenOut).balanceOf(address(this)));
```

**Impact:**

* setRouter fix: eliminates the ability for anyone to control all pools
* swapOut fix: prevents a malicious router from over-extracting
* Two-line change closes the two largest contract-layer attack surfaces

### 7.3 P2 Defenses (Private-Key Safety)

* Different roles use different passphrases (dev ≠ funding ≠ fan)
* Migrate passphrase to a key-management service (AWS KMS / HashiCorp Vault)
* funding and fee use hardware wallets (multi-sig)
* Periodically rotate passphrase and re-encrypt private keys

**Impact:** Even if one passphrase leaks, only a subset of role wallets is affected; loss ceiling drops from full capital to a fraction.

## 8. Remediation Priority Matrix

All issues are easy to fix: P0 + P1 together require only 8 lines of code; P2 is an architectural upgrade. After remediation, the risk score is expected to improve from the current assessment baseline to above 85.

| Priority | Measure                     | Effort | Closes Risk                     | Ongoing Impact if Unfixed                             |
| -------- | --------------------------- | ------ | ------------------------------- | ----------------------------------------------------- |
| **P0**   | Add 0.5% slippage to swap   | 1 LOC  | Sandwich + pre-buy + flash loan | Mainnet: potential $45–800 loss per campaign          |
| **P0**   | Add min-amount to removeLiq | 1 LOC  | Front-run Unwind drain          | Mainnet: potential $220 loss per campaign             |
| **P0**   | Remove approve-swap sleep   | 2 LOC  | Reduce attack window            | 3-second window continues to give attackers prep time |
| **P1**   | setRouter access control    | 2 LOC  | Contract-layer safety           | Anyone can control all pools with 1 tx                |
| **P1**   | swapOut balance check       | 1 LOC  | Contract-layer safety           | Malicious router can over-extract                     |
| **P1**   | burn() CEI fix              | 3 LOC  | Future reentrancy prevention    | Audit will flag; future token-migration risk          |
| **P2**   | KMS / HSM integration       | Large  | Production-grade key safety     | None for Demo; required for production                |

*— End of Report — 2026-07-19 —*


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://newsandwich.gitbook.io/docs/new-sandwich-report/sandwich-protocol-full-risk-assessment-report.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
