Beyond the incidents · ERC-4626

Four roundings. None written down.

EIP-4626 fixes four rounding directions, and every vault must get all four right by hand. Written with Dimension, each operation states which way its given amount moves, and the rest follows. The roundings it derives are exactly the ones OpenZeppelin's audited ERC4626 names.

How

The direction of what the vault gives back is the opposite of what it receives.

ingots/vault/src/vault.fefe
/// Shares for depositing `assets`: assets come in, shares go out.
pub fn preview_deposit<A>(_ v: Vault<A>, _ assets: Quantity<A, In, Given>) -> Quantity<
    Shares<A>,
    Out,
    Settled,
> {
    exchange(
        assets,
        numerator: v.total_shares.raw() + 1,
        denominator: v.total_assets.raw() + 1,
    )
}
ingots/dimension/src/value.fefe
/// Exchanges a given amount of `A` for an amount of `B` at the ratio
/// `numerator / denominator`, such as a vault's shares per asset. What the
/// protocol gives in return moves the other way, `G::Opposite`, and is rounded
/// by that direction's obligation: a payout rounds down, a charge rounds up.
/// So the rounding follows from which way the given amount moves.
pub fn exchange<A, B, G: Flow>(
    _ given: Quantity<A, G, Given>,
    numerator: u256,
    denominator: u256,
) -> Quantity<B, G::Opposite, Settled> {
    Quantity { v: <G::Opposite as Flow>::Obligation::mul_div(given.v, numerator, denominator) }
}
OperationGivenGiven backRounding that followsVectors equal to OpenZeppelinWhere the rounding decides
depositassets, Inshares, Outdown10,0008,402
mintshares, Outassets, Inup10,0008,440
withdrawassets, Outshares, Inup10,0008,402
redeemshares, Inassets, Outdown10,0008,440
Checked

Against OpenZeppelin, and against the exact rational result.

40,000
vectors equal to OpenZeppelin Contracts v5.1.0's ERC4626, in the same states
$ make vault
33,684
of them with a fractional exact result: the direction decided the answer
$ make vault
32,768
vault states, every preview exact against the rational result, on both backends
$ make unit
  • holds
    Do the vault's roundings, which no line of it names, give exactly what OpenZeppelin's ERC4626 gives?
    40,000 vectors over the four previews, each equal to OpenZeppelin v5.1.0 in the same state
  • holds
    Does the comparison test the rounding direction, not only the formula?
    in 33,684 of the vectors the exact result is fractional, so rounding the other way would differ

The vault, with its limits →