/-
  Curve.lean : the launch curve every coin uses, with its invariants.

  Plain Lean 4 core, no imports, no Mathlib, no `sorry`, no custom axioms.
  Pricing formulas follow `Examples/BondingCurve.lean` in
  github.com/aeyakovenko/lean-svm (Apache-2.0). `curve_buy_preserves_k`
  and `curve_sell_bounded_by_reserve` are adapted from that file.

  Scope: these theorems are about this model of the curve. They are not
  a proof about any deployed on-chain program.
-/
namespace Curve

/-- Basis-point denominator. -/
def bps : Nat := 10000

/-- Fee taken on an amount at `feeBps`. -/
def fee (amount feeBps : Nat) : Nat := amount * feeBps / bps

/-- Tokens out for `lamportsIn` on a virtual constant-product curve. -/
def calcBuyTokens (vSol vTok lamportsIn feeBps : Nat) : Nat :=
  let netSol := lamportsIn - fee lamportsIn feeBps
  netSol * vTok / (vSol + netSol)

/-- SOL out (after fee) for selling `tokensIn`. -/
def calcSellSol (vSol vTok tokensIn feeBps : Nat) : Nat :=
  let gross := tokensIn * vSol / (vTok + tokensIn)
  gross - fee gross feeBps

/-! ### Fees -/

/-- The fee can never exceed the amount it is charged on. -/
theorem fee_le_amount (amount feeBps : Nat) (h : feeBps ≤ bps) :
    fee amount feeBps ≤ amount := by
  unfold fee
  apply Nat.div_le_of_le_mul
  have : amount * feeBps ≤ amount * bps := Nat.mul_le_mul_left amount h
  rw [Nat.mul_comm bps amount]
  exact this

/-! ### Curve math -/

/-- Buying never decreases `k = vSol * vTok`. -/
theorem curve_buy_preserves_k (vSol vTok lamportsIn feeBps : Nat) :
    let netSol := lamportsIn - fee lamportsIn feeBps
    (vSol + netSol) * (vTok - calcBuyTokens vSol vTok lamportsIn feeBps)
      ≥ vSol * vTok := by
  intro netSol
  show (vSol + netSol) * (vTok - netSol * vTok / (vSol + netSol)) ≥ vSol * vTok
  by_cases hz : vSol + netSol = 0
  · have hv : vSol = 0 := by omega
    simp [hv]
  · have hmul : netSol * vTok / (vSol + netSol) * (vSol + netSol) ≤ netSol * vTok :=
      Nat.div_mul_le_self _ _
    rw [Nat.mul_sub_left_distrib]
    have hsub : (vSol + netSol) * (netSol * vTok / (vSol + netSol)) ≤ netSol * vTok := by
      rw [Nat.mul_comm]; exact hmul
    have hexp : (vSol + netSol) * vTok = vSol * vTok + netSol * vTok := Nat.add_mul _ _ _
    omega

/-- A buy can never empty the token side of the curve. -/
theorem buy_never_drains_tokens (vSol vTok lamportsIn feeBps : Nat)
    (hsol : 0 < vSol) (htok : 0 < vTok) :
    calcBuyTokens vSol vTok lamportsIn feeBps < vTok := by
  show (lamportsIn - fee lamportsIn feeBps) * vTok
      / (vSol + (lamportsIn - fee lamportsIn feeBps)) < vTok
  generalize lamportsIn - fee lamportsIn feeBps = n
  have hpos : 0 < vSol + n := by omega
  apply (Nat.div_lt_iff_lt_mul hpos).mpr
  rw [Nat.mul_add, Nat.mul_comm n vTok]
  have : 0 < vTok * vSol := Nat.mul_pos htok hsol
  omega

/-- A sell never pays out more than the SOL side of the curve. -/
theorem curve_sell_bounded_by_reserve (vSol vTok tokensIn feeBps : Nat)
    (hsol : 0 < vSol) (htok : 0 < vTok) :
    calcSellSol vSol vTok tokensIn feeBps < vSol := by
  show tokensIn * vSol / (vTok + tokensIn)
      - fee (tokensIn * vSol / (vTok + tokensIn)) feeBps < vSol
  have hpos : 0 < vTok + tokensIn := by omega
  have hgross : tokensIn * vSol / (vTok + tokensIn) < vSol := by
    apply (Nat.div_lt_iff_lt_mul hpos).mpr
    rw [Nat.mul_add, Nat.mul_comm vSol tokensIn]
    have : 0 < vSol * vTok := Nat.mul_pos hsol htok
    omega
  omega

/-! ### The launch state machine -/

/-- Everything the program tracks for one coin. -/
structure State where
  vSol      : Nat   -- virtual SOL reserve
  vTok      : Nat   -- virtual token reserve
  realSol   : Nat   -- lamports actually held by the curve vault
  supply    : Nat   -- tokens in circulation (minted minus burned)
  maxSupply : Nat   -- hard cap fixed at launch
  feeBps    : Nat   -- fee fixed at launch
  deriving Repr

/-- The only instructions. There is no `mint`, no `withdraw`, no `setFee`. -/
inductive Ix where
  | buy  (lamportsIn minOut : Nat)
  | sell (tokensIn minOut : Nat)

/-- Execute one instruction. `none` means the transaction is rejected. -/
def step (s : State) : Ix → Option State
  | .buy lamportsIn minOut =>
    let out := calcBuyTokens s.vSol s.vTok lamportsIn s.feeBps
    let net := lamportsIn - fee lamportsIn s.feeBps
    if out < minOut ∨ s.supply + out > s.maxSupply ∨ out ≥ s.vTok then none
    else some { s with vSol := s.vSol + net, vTok := s.vTok - out,
                       realSol := s.realSol + net, supply := s.supply + out }
  | .sell tokensIn minOut =>
    let out := calcSellSol s.vSol s.vTok tokensIn s.feeBps
    let gross := tokensIn * s.vSol / (s.vTok + tokensIn)
    if out < minOut ∨ tokensIn > s.supply ∨ gross > s.realSol then none
    else some { s with vSol := s.vSol - gross, vTok := s.vTok + tokensIn,
                       realSol := s.realSol - out, supply := s.supply - tokensIn }

/-- What must hold forever. -/
def Safe (s : State) : Prop :=
  s.supply ≤ s.maxSupply ∧ s.feeBps ≤ bps ∧ 0 < s.vTok

/-- States the program can ever be in, starting from a valid launch. -/
inductive Reachable : State → Prop where
  | launch (s : State) : s.supply = 0 → s.feeBps ≤ bps → 0 < s.vTok → Reachable s
  | next {s s' : State} (ix : Ix) : Reachable s → step s ix = some s' → Reachable s'

/-- One step preserves `Safe`. -/
theorem step_safe {s s' : State} (ix : Ix) (h : Safe s) (hs : step s ix = some s') :
    Safe s' := by
  obtain ⟨hsup, hfee, htok⟩ := h
  cases ix with
  | buy lamportsIn minOut =>
    simp only [step] at hs
    split at hs
    · contradiction
    · rename_i hc
      cases hs
      refine ⟨?_, hfee, ?_⟩ <;> simp <;> omega
  | sell tokensIn minOut =>
    simp only [step] at hs
    split at hs
    · contradiction
    · rename_i hc
      cases hs
      refine ⟨?_, hfee, ?_⟩ <;> simp <;> omega

/-- Every reachable state is safe. -/
theorem reachable_safe {s : State} (h : Reachable s) : Safe s := by
  induction h with
  | launch s h0 hf ht => exact ⟨by omega, hf, ht⟩
  | next ix _ hs ih => exact step_safe ix ih hs

/-- Supply can never exceed the cap set at launch. -/
theorem supply_capped {s : State} (h : Reachable s) : s.supply ≤ s.maxSupply :=
  (reachable_safe h).1

/-- The fee can never be raised: it is the same in every state after launch. -/
theorem fee_immutable {s s' : State} (ix : Ix) (hs : step s ix = some s') :
    s'.feeBps = s.feeBps ∧ s'.maxSupply = s.maxSupply := by
  cases ix <;> simp only [step] at hs <;> split at hs <;> first | contradiction | (cases hs; exact ⟨rfl, rfl⟩)

/-! ### The bounty

The bounty pays out if anyone reaches a state that breaks the invariant.
This theorem says no such state exists. -/

/-- The claim condition of the bounty. -/
def BountyClaimable : Prop :=
  ∃ s, Reachable s ∧ ¬ Safe s

theorem bounty_unclaimable : ¬ BountyClaimable := by
  intro ⟨s, hr, hbad⟩
  exact hbad (reachable_safe hr)

end Curve

#print axioms Curve.bounty_unclaimable
#print axioms Curve.curve_buy_preserves_k
#print axioms Curve.buy_never_drains_tokens
#print axioms Curve.curve_sell_bounded_by_reserve
#print axioms Curve.fee_le_amount
#print axioms Curve.fee_immutable
#print axioms Curve.supply_capped
