Debt Splitter

View on GitHub


Debt Splitter is a trustless expense-splitting protocol built entirely in Solidity. No backend, no server — expenses and debts live on-chain. A factory contract deploys per-group instances that track member balances, compute minimal-transfer debt settlements with a greedy two-pointer algorithm, and settle everything in ETH atomically.

Highlights

  • Trustless — no backend, no server; expenses and debts live on-chain
  • RegistryGroups — factory that deploys and indexes Group contracts
  • Group — tracks member balances, computes debts via a greedy algorithm, and handles ETH settlement

Contract Architecture

flowchart TB
  subgraph REG["🏭  RegistryGroups — factory + global registry"]
    R1["deploys Group instances"]
    R2["holds a shared Utils instance"]
  end

  subgraph GRP["👥  Group — per-group logic"]
    G1["addExpense(payer, amount)"]
    G2["split()"]
    G3["payAll() { payable }"]
    G4["V2 stubs:<br/>addMember · pay · leaveGroup · dissolveGroup"]
  end

  subgraph UTL["🔧  Utils — stateless helpers (deployed once)"]
    U1["abs(int256) → uint256"]
    U2["isSorted / isSortedDesc"]
  end

  REG -->|deploys| GRP
  GRP -->|uses| UTL
  REG -->|shares| UTL

  classDef hl fill:#1f2230,stroke:#ff3b5c,stroke-width:1.5px,color:#e8ecf4;
  class R1,R2,G1,G2,G3,G4,U1,U2 hl;

Balance Model

Each member holds an int256 balance:

SignMeaning
PositiveCreditor — is owed money
NegativeDebtor — owes money
ZeroSettled

When addExpense(payer, amount) is called, the cost is split evenly among all members (amount / totalMembers). Integer-division remainder stays with the payer — no wei is ever trapped in the contract.

Debt Algorithm (split → getDebts)

split() partitions members into debtors (balance < 0) and creditors (balance ≥ 0), then calls getDebts(), which applies a greedy two-pointer algorithm to minimise the number of transfers required. Sorting by absolute balance descending is done off-chain (caller’s responsibility) to keep gas costs low.

Settlement with payAll

payAll() is payable and requires msg.value to exactly equal the caller’s total outstanding debt. It iterates over the debt array, transfers ETH directly to each creditor via .call{value}(), and updates all balances in the same block. Partial payments are not supported in V1.

Flow

sequenceDiagram
  autonumber
  actor User
  participant G as Group
  User->>G: addExpense(payer, amount)
  G-->>G: balances[] updated
  G-->>User: emit ExpenseAdded(...)

  User->>G: split()
  G-->>G: getDebts() — greedy two-pointer
  G-->>G: debts[] stored
  G-->>User: emit DebtsSplit(...)

  User->>G: payAll() { value }
  loop for each creditor
    G->>G: .call{value}(creditor)
  end
  G-->>G: balances reset
  G-->>User: emit AllPaid(...)

Test Coverage

ContractLinesStatementsBranchesFunctions
Group.sol92.59%98.95%82.61%58.33%
RegistryGroups.sol100.00%100.00%100.00%100.00%
Utils.sol27.27%17.65%25.00%33.33%
Total86.14%87.70%74.07%58.82%