// SPDX-License-Identifier: UNLICENSEDpragmasolidity ^0.8.13;import"yield-utils-v2/contracts/token/IERC20.sol";/**@title An on-chain name registry@author Calnix@dev Vault for a specific ERC20 token; token address to be passed to constructor.@notice Vault for a pre-defined ERC20 token that was set on deployment. */contract BasicVault {///@notice ERC20 interface specifying token contract functions///@dev For constant variables, the value has to be fixed at compile-time, while for immutable, it can still be assigned at construction time. IERC20 publicimmutable wmdToken; ///@notice mapping addresses to their respective token balancesmapping(address=>uint) public balances;/// @notice Emit event when tokens are deposited into VaulteventDeposited(addressindexed from, uint amount);/// @notice Emit event when tokens are withdrawn from VaulteventWithdrawal(addressindexed from, uint amount);///@param wmdToken_ ERC20 contract addressconstructor(IERC20 wmdToken_){ wmdToken = wmdToken_; }/// @notice User can deposit tokens into Vault/// @dev Expect Deposit to revert if transferFrom fails/// @param amount The amount of tokens to depositfunctiondeposit(uint amount) external { balances[msg.sender] += amount;bool success = wmdToken.transferFrom(msg.sender,address(this), amount);require(success,"Deposit failed!"); emitDeposited(msg.sender, amount); }/// @notice User can withdraw tokens from Vault/// @dev Expect Withdraw to revert if transfer fails/// @param amount The amount of tokens to withdrawfunctionwithdraw(uint amount) external { balances[msg.sender] -= amount;bool success = wmdToken.transfer(msg.sender, amount);require(success,"Withdrawal failed!");emitWithdrawal(msg.sender, amount); }}
// SPDX-License-Identifier: UNLICENSEDpragmasolidity ^0.8.13;import"yield-utils-v2/contracts/mocks/ERC20Mock.sol";contractWMDTokenisERC20Mock {///@dev Inherited constructor from ERC20Mock.sol. ///@dev No parameters need to be passed for top-level constructor.constructor() ERC20Mock("WoMiGawd", "WMD") { }}
Checks-effect-interaction pattern
Why does it matter?
When calling an external address, for example when transferring tokens to another account, the calling contract is also transferring the control flow to the external entity.
Assuming this external entity is a smart contract as well, the external entity is now in charge of the control flow and can execute any inherent code within it.
This can leave your contract open to re-entrancy attacks.
The high-level idea is as follows:
check & update the internal states (balances)
keep external interactions (function calls) to the last step
Essentially we will update our mappings balances to reflect any outflow, before initiating the transfer.
No need to test ERC20Mock. Assume it has been battle-tested.
WMDTokenWithFailedTransfers.sol is used to simulate token transfer failure, so that we can ensure our Vault functions behave accordingly in such situations.
Testing States
StateZero (user has no tokens)
cannot deposit (testUserCannotWithdraw)
cannot withdraw (testUserCannotDeposit)
fuzz testing (testUserMintApproveDeposit)
StateTokensMinted (user has minted 100 wmd tokens - only action available is deposit)
if transfer fails, deposit should revert (testDepositRevertsIfTransferFails)
deposit tokens into vault (testDeposit)
StateTokensDeposited (user has deposited tokens into Vault)
cannot withdraw if transfer fails (testWithdrawRevertsIfTransferFails)
cannot withdraw more than deposit (testUserCannotWithdrawExcessOfDeposit)
partial withdrawal (testUserWithdrawPartial)
full withdrawal (testUserWithdrawAll)
It’s better to test for a specific error type, than use vm.expectRevert as a catch-all leading to false positives.
As such, with regards to failing token transfers, observe the use of stdError.arithmeticError in both
I realized that for future testing perhaps splitting each state into a different file would be more sensible and accessible for the reader.
Github CI
foundry-ci.yml
name:Foundry-CIon:push:branches: - RevisedCodepull_request:jobs:run-tests:# job_id valuename:Basic Vault# Use jobs.<job_id>.name to a name for the job, which is displayed on GitHub.runs-on:ubuntu-latest# Container OS envsteps: - uses:actions/checkout@v2with:submodules:recursive - name:Install Foundryuses:onbjerg/foundry-toolchain@v1with:version:nightly - name:Run Forge testsrun:forge testid:test
Its interesting to note that I could not apply this with windows-latest container. The action Install Foundry will return an Error: Unexpected HTTP response: 404)
# include .env file and export its env vars (-include to ignore error if it does not exist)-include.envdeploy-wmd:forgecreatesrc/WMDToken.sol:WMDToken--private-key ${PRIVATE_KEY_EDGE} --rpc-url ${RINKEBY_RPC_URL}verify-wmd:forgeverify-contract--chain-id ${RINKEBY_CHAINID} --compiler-versionv0.8.13+commit.abaa5c0e ${WMD_CONTRACT_ADDRESS} src/WMDToken.sol:WMDToken ${ETHERSCAN_API_KEY} --num-of-optimizations200--flattenverify-check-wmd:forgeverify-check--chain-id ${RINKEBY_CHAINID} ${WMD_GUID} ${ETHERSCAN_API_KEY}deploy-vault:forgecreatesrc/BasicVault.sol:BasicVault--private-key ${PRIVATE_KEY_EDGE} --rpc-url ${ETH_RPC_URL} --constructor-args"0xB725d02bf6B89E659762A4760109a8478C4d22D0"verify-vault:forgeverify-contract--chain-id ${RINKEBY_CHAINID} --compiler-versionv0.8.13+commit.abaa5c0e ${VAULT_CONTRACT_ADDRESS} src/BasicVault.sol:BasicVault ${ETHERSCAN_API_KEY} --num-of-optimizations200--flatten--constructor-args0x000000000000000000000000b725d02bf6b89e659762a4760109a8478c4d22d0verify-check-vault:forgeverify-check--chain-id ${RINKEBY_CHAINID} ${VAULT_GUID} ${ETHERSCAN_API_KEY}