Skip to content

Commit

Permalink
add totalSupply user balance invariant
Browse files Browse the repository at this point in the history
  • Loading branch information
iamchrissmith committed Feb 24, 2024
1 parent 5b552c0 commit 009c7f1
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 6 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,11 @@ You will need to decide whether you are going to `bound` your inputs so that cal
#### Requires/Reverts

You can add handler function level assertions to these functions if you want to assert certain things are true during a specific call. This makes the handler functions act like fuzz tests within your invariant test suite.

### 3 - Our First Invariant

branch: `3-add-balance-invariant`

Here we add our first "real" invariant. After setup and then after every handler function call this invariant will be tested to ensure it holds true. If it fails, we will get a sequence that can be used to analyze the calls that were made to cause the violation.

In this case, we are summing the balance of each destination (`dst`) actor and ensure that sum **always** equals the `dai.totalSupply()`.
16 changes: 11 additions & 5 deletions test/invariant/DaiInvariants.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,16 @@ contract DaiInvariants is Test {
targetContract(address(_daiHandler));
}

function invariant_dai_decimals() public {
require(
dai.decimals() == 18,
"Invariant Dai Decimals"
);
// Sum of all DST balances should equal total supply
function invariant_dai_balances_equal_totalSupply() public {
uint256 sumBalances;
uint256 dstCount = _daiHandler.dstsLength();

for (uint256 i = 0; i < dstCount; i++) {
(address addr, ) = _daiHandler.dsts(i);
sumBalances += dai.balanceOf(addr);
}

require(sumBalances == dai.totalSupply(), "DaiInvariants/sumBalances-not-equal-totalSupply");
}
}
6 changes: 5 additions & 1 deletion test/invariant/handlers/DaiHandler.sol
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ contract DaiHandler is Test {
console.log("TransferFrom succeeded");
} catch Error(string memory reason) {
if(dai.balanceOf(src.addr) < _wad) addExpectedError("Dai/insufficient-balance");
if(dai.allowance(actor.addr, src.addr) < _wad) addExpectedError("Dai/insufficient-allowance");
if(dai.allowance(src.addr, actor.addr) < _wad) addExpectedError("Dai/insufficient-allowance");
expectedError(reason);
} catch (bytes memory reason) {
console.log("TransferFrom failed: ");
Expand Down Expand Up @@ -203,6 +203,10 @@ contract DaiHandler is Test {
dst = dsts[index];
}

function dstsLength() external view returns (uint256) {
return dsts.length;
}

function addExpectedError(string memory _err) internal {
expectedErrors.push(keccak256(abi.encodePacked(_err)));
}
Expand Down

0 comments on commit 009c7f1

Please sign in to comment.