Using dimensional analysis, you can categorically rule out a whole category of logic and arithmetic bugs that plague DeFi formulas. No code changes required, just better reasoning! One of the first lessons in physics is learning to think in terms of dimensions. Physicists can often spot a flawed formula in seconds just by checking whether the dimensions make sense. I once had a teacher who even kept a stamp that said “non-homogeneous formula” for that purpose (and it was used a lot on students’ work). Developers can use the same approach to spot incorrect arithmetic in smart contracts. In this post, we’ll start with the basics of dimensional analysis in physics and then apply the same reasoning to real DeFi formulas. We’ll also show you how this can be implemented in practice, using Reserve Protocol as an example. Along the way, we’ll see why developers need to think explicitly about dimensional safety when writing smart contracts, and why the DeFi ecosystem would benefit from tooling that can automatically catch these classes of bugs. Speaking of which, while putting together this post, we actually built a Claude plugin for this purpose (which we discuss in our follow-up post). Quantities and dimensions We will start with two formulas: $$\textit{Speed} = \textit{distance} + \textit{time}$$$$\textit{Speed} = \frac{\textit{distance}}{\textit{time}}$$Which of the two formulas is the correct way to calculate the speed of an object? Clearly, it’s the second one, but not just because you’ve memorized the correct formula. The deeper reason lies in dimensions. Physics recognizes seven fundamental quantities: length (meters), mass (grams), time (seconds), electric current (amps), thermodynamic temperature (kelvin), amount of substance (moles), and luminous intensity (candela). Every other physical concept, like speed, force, or energy, is a derived quantity, defined in terms of the fundamental ones. For example, this is how speed is defined: $$\textit{Speed} = \textit{dista

Read Full Article at Trail of Bits Blog →