ERC-20 Token Contract

Models a simplified ERC-20 token contract with four classes of vulnerability:

Run#

Shell
saple analyze examples/token_contract.spl

All four patterns match: reentrancy and unauthorizedMint (CRITICAL), integerOverflow and approvalRace (HIGH).

The reentrancy pattern repeats the binder from in its signature and states from == from, which always holds, so it is in effect purely structural: any debit, external call, debit sequence matches. The patterns page recommends distinct binder names with the equality in the constraint (from2 == from); the file is shown as shipped.

Complete model#

examples/token_contract.spl, as shipped:

SPL token_contract.spl
// ERC-20 Token Contract — Vulnerability Pattern Matching
//
// Models a simplified ERC-20 smart contract in SPL to detect
// reentrancy, integer overflow, and unauthorized access patterns.
// Demonstrates: vulnerability patterns with severity, guarded behaviors,
// two-level algebraic matching.
//
// A TokenContract agent serves transfers, approvals and owner-only
// mint/burn; an Attacker agent debits, calls out, and re-enters.
//
// What the analysis should find: all four patterns match — reentrancy and
// unauthorizedMint (CRITICAL), integerOverflow and approvalRace (HIGH).

// Outcome of a transaction.
type TxStatus = { PENDING, COMMITTED, REVERTED };

// ─── Actions ───
// Each action models a single atomic state change.

// Take `amount` from the sender's balance (needs enough funds).
transition debitSender(from : Int, amount : Int) {
    guard:  balances[from] >= amount && amount > 0 ;
    effect: balances[from] -= amount ;
}

// Add `amount` to the receiver's balance.
transition creditReceiver(to : Int, amount : Int) {
    guard:  amount > 0 ;
    effect: balances[to] += amount ;
}

// Set how much `owner` lets a spender take.
transition setAllowance(owner : Int, amount : Int) {
    guard:  amount >= 0 ;
    effect: allowances[owner] := amount ;
}

// Spend from an allowance (needs enough allowance).
transition deductAllowance(owner : Int, amount : Int) {
    guard:  allowances[owner] >= amount ;
    effect: allowances[owner] -= amount ;
}

// Call out to another contract; a callback may now come back in.
transition externalCall(target : Int) {
    guard:  true ;
    effect: callbackPending := true ;
}

// The pending callback returns.
transition resolveCallback() {
    guard:  callbackPending == true ;
    effect: callbackPending := false ;
}

// Owner-only: create new tokens for `to`.
transition mintTokens(to : Int, amount : Int) {
    guard:  caller == owner && amount > 0 ;
    effect: balances[to] += amount ;
}

// Owner-only: grow the total supply by the minted amount.
transition increaseTotalSupply(amount : Int) {
    guard:  caller == owner ;
    effect: totalSupply += amount ;
}

// Owner-only: destroy tokens held by `from`.
transition burnTokens(from : Int, amount : Int) {
    guard:  caller == owner && balances[from] >= amount ;
    effect: balances[from] -= amount ;
}

// Owner-only: shrink the total supply by the burned amount.
transition decreaseTotalSupply(amount : Int) {
    guard:  caller == owner ;
    effect: totalSupply -= amount ;
}

// ─── Agents ───

// The contract: serves user operations, and admin operations for the owner.
agent TokenContract() {
    attributes {
        txStatus : TxStatus = PENDING ;
    }
    process {
        // Normal operation cycle
        // Ready: the owner may run admin operations; anyone may run user operations.
        Ready    = [caller == owner] AdminOps + UserOps ;
        // UserOps: transfer, approve, or transfer on someone's behalf.
        UserOps  = Transfer + Approve + TransferFrom ;
        // Transfer: debit the caller, credit the recipient.
        Transfer = debitSender(caller, amount) . creditReceiver(recipient, amount) . Ready ;
        // Approve: set the caller's allowance.
        Approve  = setAllowance(caller, amount) . Ready ;
        // TransferFrom: spend an allowance, debit the source, credit the recipient.
        TransferFrom = deductAllowance(source, amount) .
                       debitSender(source, amount) .
                       creditReceiver(recipient, amount) . Ready ;
        // AdminOps: mint or burn, keeping the total supply in step.
        AdminOps = mintTokens(recipient, amount) . increaseTotalSupply(amount) . Ready
                 + burnTokens(source, amount) . decreaseTotalSupply(amount) . Ready ;
    }
}

// An adversary that re-enters the contract through the external call.
agent Attacker() {
    attributes {
        reentrancyCount : Int = 0 ;
    }
    process {
        // Reentrancy: trigger external call during transfer, then re-enter
        Attack = debitSender(victim, drainAmount) .
                 externalCall(contractAddr) .
                 ReentrantCallback ;
        // Each callback debits the victim again, or stops.
        ReentrantCallback = resolveCallback() .
                            debitSender(victim, drainAmount) .
                            ReentrantCallback
                          + resolveCallback() . done ;
    }
}

// ─── Environment ───

// Shared contract state.
schema TokenEnv {
    attributes {
        totalSupply : Int = 1000000 ;      // tokens in existence
        callbackPending : Bool = false ;   // an external call has not returned yet
        owner : Int = 0 ;                  // the contract owner
        caller : Int = 0 ;                 // who is calling now
    }
    invariants {
        // The supply never goes negative.
        totalSupply >= 0 ;
    }
}

// ─── Vulnerability Patterns ───

// Reentrancy: external call between balance debit operations
pattern reentrancy {
    signature {
        debitSender(from, amount) .
        externalCall(target) .
        debitSender(from, amount2) . done
    }
    constraints { from == from }
    severity: CRITICAL ;
}

// Integer overflow: mint without bounds check
pattern integerOverflow {
    signature {
        mintTokens(to, amount) . increaseTotalSupply(amount) . done
    }
    constraints { totalSupply + amount < totalSupply }
    severity: HIGH ;
}

// Unauthorized access: mint by non-owner
pattern unauthorizedMint {
    signature {
        mintTokens(to, amount) . done
    }
    constraints { caller != owner }
    severity: CRITICAL ;
}

// Double-spend via approval race
pattern approvalRace {
    signature {
        setAllowance(owner, amount1) .
        deductAllowance(owner, amount2) .
        setAllowance(owner, amount3) . done
    }
    constraints { amount2 > amount1 }
    severity: HIGH ;
}

// ─── System ───

// The contract and one attacker.
system TokenSystem {
    schema: TokenEnv ;
    agents {
        TokenContract() * 1 ;
        Attacker() * 1 ;
    }
    init {
        totalSupply == 1000000 ;
    }
    properties {
        // Conservation: total supply stays non-negative
        supplyConservation : totalSupply >= 0 ;

        // No reentrancy: callback never pending during debit
        noReentrancy : !(callbackPending == true) ;

        // Owner-only minting
        mintAuthorized : totalSupply <= 1000000 || caller == owner ;
    }
}
↑ ↓ to moveEnter to openEsc to close