Skip to content

Commit

Permalink
test: invariant tests for OptimismSuperchainERC20 (#11776)
Browse files Browse the repository at this point in the history
* chore: configure medusa with basic supERC20 self-bridging (#19)

- used --foundry-compile-all to ensure the test contract under
  `test/properties` is compiled (otherwise it is not compiled and medusa
  crashes when it can't find it's compiled representation)
- set src,test,script to test/properties/medusa to not waste time
  compiling contracts that are not required for the medusa campaign
- used an atomic bridge, which doesnt allow for testing of several of
  the proposed invariants

fix: delete dead code
test: give the fuzzer a head start
docs: fix properties order
test: document & implement assertions 22, 23  and 24
fix: fixes from self-review
test: guide the fuzzer a little bit less
  previously: initial mint, bound on transfer amount: 146625 calls in 200s
  now: no initial mint, no bound on transfer amount: 176835 calls in 200s
  it doesn't seem to slow the fuzzer down
fix: fixes after lovely feedback by disco
docs: merge both documents and categorized properties by their milestone
fix: fixes from parti's review
fix: feedback from disco
fix: feedback from doc
refactor: separate state transitions from pure properties
docs: update tested properties
refactor: move all assertions into properties contract
fix: move function without assertions back into handler
test: only use assertion mode
fix: improve justfile recipie for medusa

* feat: halmos symbolic tests (#21)

* feat: introduce OptimismSuperchainERC20

* fix: contract fixes

* feat: add snapshots and semver

* test: add supports interface tests

* test: add invariant test

* feat: add parameters to the RelayERC20 event

* fix: typo

* fix: from param description

* fix: event signature and interface pragma

* feat: add initializer

* feat: use unstructured storage and OZ v5

* feat: update superchain erc20 interfaces

* fix: adapt storage to ERC7201

* test: add initializable OZ v5 test

* fix: invariant docs

* fix: ERC165 implementation

* test: improve superc20 invariant (#11)

* fix: gas snapshot

* chore: configure medusa with basic supERC20 self-bridging

- used --foundry-compile-all to ensure the test contract under
  `test/properties` is compiled (otherwise it is not compiled and medusa
  crashes when it can't find it's compiled representation)
- set src,test,script to test/properties/medusa to not waste time
  compiling contracts that are not required for the medusa campaign
- used an atomic bridge, which doesnt allow for testing of several of
  the proposed invariants

* fix: delete dead code

* test: give the fuzzer a head start

* feat: create suite for sybolic tests with halmos

* test: setup and 3 properties with symbolic tests

* chore: remove todo comment

* docs: fix properties order

* test: document & implement assertions 22, 23  and 24

* fix: fixes from self-review

* test: guide the fuzzer a little bit less

previously: initial mint, bound on transfer amount: 146625 calls in 200s
now: no initial mint, no bound on transfer amount: 176835 calls in 200s

it doesn't seem to slow the fuzzer down

* feat: add property for burn

* refactor: remove symbolic address on mint property

* refactor: order the tests based on the property id

* feat: checkpoint

* chore: set xdomain sender on failing test

* chore: enhance mocks

* Revert "Merge branch 'chore/setup-medusa' into feat/halmos-symbolic-tests"

This reverts commit 945d6b6, reversing
changes made to 5dcb3a8.

* refactor: remove symbolic addresses to make all of the test work

* chore: remove console logs

* feat: add properties file

* chore: polish

* refactor: enhance test on property 7 using direct try catch (now works)

* fix: review comments

* refactor: add symbolic addresses on test functions

* feat: create halmos toml

* chore: polish test contract and mock

* chore: update property

* refactor: move symbolic folder into properties one

* feat: create advanced tests helper contract

* refactor: enhance tests using symbolic addresses instead of concrete ones

* chore: remove 0 property natspec

* feat: add halmos profile and just script

* chore: rename symbolic folder to halmos

* feat: add halmos commands to justfile

* chore: reorder assertions on one test

* refactor: complete test property seven

* chore: mark properties as completed

* chore: add halmos-cheatcodes dependency

* chore: rename advancedtest->halmosbase

* chore: minimize mocked messenger

* chore: delete empty halmos file

* chore: revert changes to medusa.json

* docs: update changes to PROPERTIES.md from base branch

* test: sendERC20 destination fix

* chore: natspec fixes

---------

Co-authored-by: agusduha <agusnduha@gmail.com>
Co-authored-by: 0xng <ng@defi.sucks>
Co-authored-by: teddy <teddy@defi.sucks>

* test: remaining protocol properties (#26)

* test: cross-user fuzzed bridges + actor setup

* test: fuzz properties 8 and 9

* test: properties 7 and 25

* fix: implement doc's feedback

* test: superc20 tob properties (#27)

* chore: add crytic/properties dependency

* test: extend protocol properties so it also covers ToB erc20 properties

* chore: small linter fixes

* docs: update property list

* test: handlers for remaining superc20 state transitions

* fix: disable ToB properties we are not using and guide the fuzzer a bit more

* fix: disable another ToB property not implemented by solady

* chore: remove zero-initializations

* fix: feedback from disco

* chore: separate fuzz campaign tests in guided vs unguided

* test: dont revert on successful unguided relay

* test: add fuzzed calls to burn and mint

* docs: document the separation of fuzz test functions

* chore: move the properties file to its own directory

* chore: consistently use fuzz_ and property_ + camelcase

* chore: fix typo

* chore: camelcase for handlers as well

* fix: revert change that broke halmos campaign compile :D

* test: fuzz non atomic bridging (#31)

* test: changed mocked messenger ABI for message sending but kept assertions the same

* docs: add new properties 26&27

* test: queue cross-chain messages and test related properties

* test: relay random messages from queue and check associated invariants

* chore: rename bridge->senderc20 method for consistency with relayerc20

* test: not-yet-deployed supertokens can get funds sent to them

* chore: medusa runs forever by default

doable since it also handles SIGINTs gracefully

* chore: document the reason behind relay zero and send zero inconsistencies

* fix: feedback from doc

* fix: walk around possible medusa issue

I'm getting an 'unknown opcode 0x4e' in ProtocolAtomic constructor when
calling the MockL2ToL2CrossDomainMessenger for the first time

* test: unguided handler for sendERC20

* fix: feedback from disco

* chore: remove halmos testsuite

* chore: foundry migration (#40)

* chore: track assertion failures

this is so foundry's invariant contract can check that an assertion
returned false in the handler, while still allowing `fail_on_revert =
false` so we can still take full advantage of medusa's fuzzer & coverage
reports

* fix: explicitly skip duplicate supertoken deployments

* chore: remove duplicated PROPERTIES.md file

* chore: expose data to foundry's external invariant checker

* test: run medusa fuzzing campaign from within foundry

* fix: eagerly check for duplicate deployments

* fix: feedback from doc

* chore: shoehorn medusa campaign into foundry dir structure

* chore: remove PROPERTIES.md file

* chore: delete medusa config

* docs: limited support for subdirectories in test/invariant

* chore: rename contracts to be more sneaky about medusa

* docs: rewrite invariant docs in a way compliant with autogen scripts

* chore: fixes from rebase

* fix: cleanup superc20 invariants (#46)

* chore: revert modifications from medusa campaign

* docs: extra docs on why ForTest contract is required

* doc: add list of all supertoken properties

* chore: run forge fmt

* ci: allow for testfiles to be deleted

* fix: run doc autogen script after rebase

---------

Co-authored-by: Disco <131301107+0xDiscotech@users.noreply.github.com>
Co-authored-by: agusduha <agusnduha@gmail.com>
Co-authored-by: 0xng <ng@defi.sucks>
  • Loading branch information
4 people authored Sep 18, 2024
1 parent 518b050 commit 9de48fc
Show file tree
Hide file tree
Showing 14 changed files with 928 additions and 231 deletions.
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
# `OptimismSuperchainERC20` Invariants

## Calls to sendERC20 should always succeed as long as the actor has enough balance. Actor's balance should also not increase out of nowhere but instead should decrease by the amount sent.
**Test:** [`OptimismSuperchainERC20.t.sol#L196`](../test/invariants/OptimismSuperchainERC20.t.sol#L196)
## sum of supertoken total supply across all chains is always <= to convert(legacy, super)- convert(super, legacy)
**Test:** [`OptimismSuperchainERC20#L36`](../test/invariants/OptimismSuperchainERC20#L36)



## Calls to relayERC20 should always succeeds when a message is received from another chain. Actor's balance should only increase by the amount relayed.
**Test:** [`OptimismSuperchainERC20.t.sol#L214`](../test/invariants/OptimismSuperchainERC20.t.sol#L214)
## sum of supertoken total supply across all chains is equal to convert(legacy, super)- convert(super, legacy) when all when all cross-chain messages are processed
**Test:** [`OptimismSuperchainERC20#L57`](../test/invariants/OptimismSuperchainERC20#L57)



## many other assertion mode invariants are also defined under `test/invariants/OptimismSuperchainERC20/fuzz/` .
**Test:** [`OptimismSuperchainERC20#L80`](../test/invariants/OptimismSuperchainERC20#L80)

since setting`fail_on_revert=false` also ignores StdAssertion failures, this invariant explicitly asks the handler for assertion test failures
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,12 @@ func docGen(invariantsDir, docsDir string) error {
// Read the contents of the invariant test file.
fileName := file.Name()
filePath := filepath.Join(invariantsDir, fileName)
// where invariants for a module have their own directory, interpret
// the test file with the same name as the directory as a 'main' of
// sorts, from where documentation is pulled
if file.IsDir() {
filePath = filepath.Join(filePath, strings.Join([]string{fileName, ".t.sol"}, ""))
}
fileContents, err := os.ReadFile(filePath)
if err != nil {
return fmt.Errorf("error reading file %q: %w", filePath, err)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ for FILE in $CHANGED_FILES; do
echo "skipping $FILE"
continue
fi
if [ ! -e "$FILE" ] ; then
echo "skipping $FILE since it was deleted"
continue
fi

# Get the diff for the file.
DIFF=$(git diff origin/develop...HEAD --unified=0 -- "$FILE")
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;

// Testing utilities
import { Test, StdUtils, Vm } from "forge-std/Test.sol";
import { StdInvariant } from "forge-std/StdInvariant.sol";
import { StdAssertions } from "forge-std/StdAssertions.sol";
import { EIP1967Helper } from "test/mocks/EIP1967Helper.sol";

// Libraries
import { Predeploys } from "src/libraries/Predeploys.sol";
import { OptimismSuperchainERC20 } from "src/L2/OptimismSuperchainERC20.sol";
import { IL2ToL2CrossDomainMessenger } from "src/L2/interfaces/IL2ToL2CrossDomainMessenger.sol";
import { ProtocolGuided } from "./fuzz/Protocol.guided.t.sol";
import { ProtocolUnguided } from "./fuzz/Protocol.unguided.t.sol";
import { HandlerGetters } from "./helpers/HandlerGetters.t.sol";
import { MockL2ToL2CrossDomainMessenger } from "./helpers/MockL2ToL2CrossDomainMessenger.t.sol";

contract OptimismSuperchainERC20Handler is HandlerGetters, ProtocolGuided, ProtocolUnguided { }

contract OptimismSuperchainERC20Properties is Test {
OptimismSuperchainERC20Handler internal handler;
MockL2ToL2CrossDomainMessenger internal constant MESSENGER =
MockL2ToL2CrossDomainMessenger(Predeploys.L2_TO_L2_CROSS_DOMAIN_MESSENGER);

function setUp() public {
handler = new OptimismSuperchainERC20Handler();
targetContract(address(handler));
}

// TODO: will need rework after
// - `convert`
/// @custom:invariant sum of supertoken total supply across all chains is always <= to convert(legacy, super)-
/// convert(super, legacy)
function invariant_totalSupplyAcrossChainsEqualsMintsMinusFundsInTransit() external view {
// iterate over unique deploy salts aka supertokens that are supposed to be compatible with each other
for (uint256 deploySaltIndex = 0; deploySaltIndex < handler.deploySaltsLength(); deploySaltIndex++) {
uint256 totalSupply = 0;
(bytes32 currentSalt, uint256 trackedSupply) = handler.totalSupplyAcrossChainsAtIndex(deploySaltIndex);
uint256 fundsInTransit = handler.tokensInTransitForDeploySalt(currentSalt);
// and then over all the (mocked) chain ids where that supertoken could be deployed
for (uint256 validChainId = 0; validChainId < handler.MAX_CHAINS(); validChainId++) {
address supertoken = MESSENGER.superTokenAddresses(validChainId, currentSalt);
if (supertoken != address(0)) {
totalSupply += OptimismSuperchainERC20(supertoken).totalSupply();
}
}
assertEq(trackedSupply, totalSupply + fundsInTransit);
}
}

// TODO: will need rework after
// - `convert`
/// @custom:invariant sum of supertoken total supply across all chains is equal to convert(legacy, super)-
/// convert(super, legacy) when all when all cross-chain messages are processed
function invariant_totalSupplyAcrossChainsEqualsMintsWhenQueueIsEmpty() external view {
if (MESSENGER.messageQueueLength() != 0) {
return;
}
// iterate over unique deploy salts aka supertokens that are supposed to be compatible with each other
for (uint256 deploySaltIndex = 0; deploySaltIndex < handler.deploySaltsLength(); deploySaltIndex++) {
uint256 totalSupply = 0;
(bytes32 currentSalt, uint256 trackedSupply) = handler.totalSupplyAcrossChainsAtIndex(deploySaltIndex);
// and then over all the (mocked) chain ids where that supertoken could be deployed
for (uint256 validChainId = 0; validChainId < handler.MAX_CHAINS(); validChainId++) {
address supertoken = MESSENGER.superTokenAddresses(validChainId, currentSalt);
if (supertoken != address(0)) {
totalSupply += OptimismSuperchainERC20(supertoken).totalSupply();
}
}
assertEq(trackedSupply, totalSupply);
}
}

/// @custom:invariant many other assertion mode invariants are also defined under
/// `test/invariants/OptimismSuperchainERC20/fuzz/` .
///
/// since setting`fail_on_revert=false` also ignores StdAssertion failures, this invariant explicitly asks the
/// handler for assertion test failures
function invariant_handlerAssertions() external view {
assertFalse(handler.failed());
}
}
Loading

0 comments on commit 9de48fc

Please sign in to comment.