├── .github └── CODEOWNERS ├── .gitignore ├── README.md ├── contracts ├── HyperlaneMessageReceiver.sol ├── HyperlaneMessageSender.sol ├── IInterchainAccountRouter.sol ├── IInterchainQueryRouter.sol ├── MockInterchainAccountRouter.sol ├── OwnableMulticall.sol ├── Ownee.sol ├── Owner.sol └── OwnerReader.sol ├── foundry.toml ├── hardhat.config.ts ├── lib └── forge-std │ ├── .github │ └── workflows │ │ └── tests.yml │ ├── .gitignore │ ├── .gitmodules │ ├── LICENSE-APACHE │ ├── LICENSE-MIT │ ├── README.md │ ├── lib │ └── ds-test │ │ ├── .gitignore │ │ ├── LICENSE │ │ ├── Makefile │ │ ├── default.nix │ │ ├── demo │ │ └── demo.sol │ │ └── src │ │ └── test.sol │ └── src │ ├── Test.sol │ ├── Vm.sol │ ├── console.sol │ ├── console2.sol │ └── test │ ├── StdAssertions.t.sol │ ├── StdCheats.t.sol │ ├── StdError.t.sol │ ├── StdMath.t.sol │ └── StdStorage.t.sol ├── package.json ├── remappings.txt ├── scripts └── deploy.ts ├── test ├── foundry │ ├── InterchainAccount.t.sol │ └── Messaging.t.sol ├── interchainaccounts.test.ts └── messaging.test.ts ├── tsconfig.json └── yarn.lock /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @nambrot @yorhodes 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .env 3 | coverage 4 | coverage.json 5 | typechain 6 | types 7 | 8 | #Hardhat files 9 | cache 10 | artifacts 11 | 12 | 13 | out 14 | forge-cache -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ⚠️ Archive Notice ⚠️ 2 | 3 | **This repo has been archived!** 4 | 5 | This repository was built for Hyperlane v2 and has not been updated to work with the latest Hyperlane version, v3. 6 | 7 | See the [Hyperlane Docs](https://docs.hyperlane.xyz) for information on building applications using Hyperlane v3. 8 | 9 | # Hyperlane Quickstart 10 | 11 | This repo contains example code that can be easily understood and modified. It should help you familiarize yourself with how to use the Hyperlane APIs to build your cross-chain application. Hyperlane offers several APIs: The Messaging API lets you send arbitrary bytes from a sender contract on the origin chain to a receiver contract on the destination chain. The accounts API lets senders specify abi-encoded Calls that can be executed from a sender's Interchain Account (ICA) on the destination chain. The Queries API allows you to make remote view calls with built-in callbacks without the need to deploy remote contracts. We built this quickstart with both Hardhat and Foundry in mind, so feel free to jump to the relevant sections. 12 | 13 | ## Setup 14 | 15 | ```shell 16 | $ yarn install 17 | ``` 18 | 19 | ## Hardhat 20 | 21 | We have both unit tests as well as hardhat tasks that show you how to develop on top of the Hyperlane APIs. To interact with the hardhat tasks on remote networks, you will need to add a private key configuration. Those keys need to have funds as well, we can recommend the Paradigm faucet at [https://faucet.paradigm.xyz](https://faucet.paradigm.xyz). 22 | 23 | When accounts are ready, start up building with hardhat, or see the `package.json` scripts for a set of common commands: 24 | 25 | ```shell 26 | $ yarn hardhat compile 27 | ``` 28 | 29 | ### Direct Messaging API 30 | 31 | If you just want to get started with sending a message, you can use the `send-message` task to send a message to a pre-deployed `TestRecipient`: 32 | 33 | ```shell 34 | $ yarn hardhat send-message --network goerli --remote mumbai --message "Your Message" 35 | ``` 36 | 37 | (Any Hyperlane-supported chain name can be used) 38 | 39 | ### Deploy Sender and Receiver contracts 40 | 41 | Now that you know how easy and quick sending Hyperlane messages are, you can deploy a sending and receiving contract. You can use the predefined `HyperlaneMessageSender/Receiver` contracts and tasks to get started: 42 | 43 | ```shell 44 | # Deploys the sender 45 | $ yarn hardhat deploy-message-sender --network mumbai 46 | 47 | # Deploys the receiver 48 | $ yarn hardhat deploy-message-receiver --network goerli --origin mumbai 49 | 50 | # Send a message via the sender contract to the receiver contract 51 | $ yarn hardhat send-message-via-HyperlaneMessageSender --sender "SENDER_ADDRESS" --receiver "RECEIVER_ADDRESS" --remote goerli --network mumbai --message "Your message" 52 | ``` 53 | 54 | ### Accounts API 55 | 56 | If you do not want to build a custom serialization format for your messages, you can also just use the Accounts API to make abi-encoded function calls from Interchain Accounts which are universal across chains for a given sender address on an origin chain. ICAs are identity proxy contracts which only accept calls from their designated owner on the origin chain. Thanks to the awesomness of CREATE2, calls can be referenced before they are deployed! This allows contracts on the destination chain with no custom Hyperlane or cross-chain logic to be interacted with from a remote chain! 57 | 58 | To demonstrate this, look at this simple `Ownee` contract: 59 | 60 | ```solidity 61 | contract Ownee is OwnableUpgradeable { 62 | uint256 public fee = 0; 63 | 64 | event NewFeeSet(uint256 newFee); 65 | 66 | constructor(address owner) { 67 | _transferOwnership(owner); 68 | } 69 | 70 | function setFee(uint256 newFee) onlyOwner external { 71 | fee = newFee; 72 | } 73 | } 74 | ``` 75 | 76 | We can have it be owned by a simple `Owner` contract that lives on a remote chain. First, let's deploy it: 77 | 78 | ```shell 79 | $ yarn hardhat deploy-owner --network goerli 80 | ``` 81 | 82 | Let's get the ICA account address for this contract: 83 | 84 | 85 | ```shell 86 | $ yarn hardhat get-ica-address --network goerli --address "OWNER_ADDRESS" 87 | ``` 88 | 89 | We can now deploy a (cross-chain-oblivious) `Ownee` contract on a remote chain: 90 | 91 | ```shell 92 | $ yarn hardhat deploy-ownee --owner "OWNER_ICA_ADDRESS" --network mumbai 93 | ``` 94 | 95 | We can now invoke the `setRemoteFee` function on the `Owner`: 96 | 97 | ```shell 98 | $ yarn hardhat set-remote-fee --owner "OWNER_ADDRESS" --ownee "OWNEE_ADDRESS" --network goerli --remote mumbai --newFee 42 99 | ``` 100 | 101 | After a short bit, you should be able to see that the value was set, without needing to do anything on the remote chain! 102 | 103 | ```shell 104 | $ yarn hardhat get-fee --ownee "OWNEE_ADDRESS" --network mumbai 105 | ``` 106 | 107 | ### Queries API 108 | 109 | What if you want to read instead of write across-chains. The Queries API is what you are looking for. The Queries API allows you to make a view call on another chain and get the result in a separate callback. 110 | 111 | To demonstrate this, lets look at this simple OwnerReader.contract: 112 | 113 | ```solidity 114 | contract OwnerReader { 115 | IInterchainQueryRouter router; 116 | 117 | address lastTarget; 118 | address lastOwner; 119 | 120 | constructor(address _router) { 121 | router = IInterchainQueryRouter(_router); 122 | } 123 | 124 | function readRemoteOwner(uint32 _destinationDomain, address target) 125 | external 126 | { 127 | router.query( 128 | _destinationDomain, 129 | Call({to: target, data: abi.encodePacked(Ownable.owner.selector)}), 130 | abi.encode(this.receiveQueryResult.selector, target) 131 | ); 132 | } 133 | 134 | function receiveQueryResult(address _target, address _owner) public { 135 | lastOwner = _owner; 136 | lastTarget = _target; 137 | } 138 | } 139 | ``` 140 | 141 | We can deploy it with: 142 | 143 | ```shell 144 | $ yarn hardhat deploy-reader --network goerli 145 | ``` 146 | 147 | Once deployed, you can have the contract make a query to read a remote owner. In this case, you can read the owner of a deployed `Owner` contract above: 148 | 149 | ```shell 150 | $ yarn hardhat read-remote-owner --reader "READER_ADDRESS" --remote fuji --target "OWNEE_ADDRESS" --network goerli 151 | ``` 152 | 153 | You can then read the query result via: 154 | 155 | ```shell 156 | $ yarn hardhat get-query-result --reader "READER_ADDRESS" --network goerli 157 | ``` 158 | 159 | 160 | ## Foundry 161 | 162 | _More details coming soon_ 163 | -------------------------------------------------------------------------------- /contracts/HyperlaneMessageReceiver.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: UNLICENSED 2 | pragma solidity ^0.8.9; 3 | 4 | // Uncomment this line to use console.log 5 | // import "hardhat/console.sol"; 6 | 7 | import "@hyperlane-xyz/core/interfaces/IMailbox.sol"; 8 | 9 | contract HyperlaneMessageReceiver { 10 | IMailbox inbox; 11 | bytes32 public lastSender; 12 | string public lastMessage; 13 | 14 | event ReceivedMessage(uint32 origin, bytes32 sender, bytes message); 15 | 16 | constructor(address _inbox) { 17 | inbox = IMailbox(_inbox); 18 | } 19 | 20 | function handle( 21 | uint32 _origin, 22 | bytes32 _sender, 23 | bytes calldata _message 24 | ) external { 25 | lastSender = _sender; 26 | lastMessage = string(_message); 27 | emit ReceivedMessage(_origin, _sender, _message); 28 | } 29 | } -------------------------------------------------------------------------------- /contracts/HyperlaneMessageSender.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: UNLICENSED 2 | pragma solidity ^0.8.9; 3 | 4 | // Uncomment this line to use console.log 5 | // import "hardhat/console.sol"; 6 | 7 | import "@hyperlane-xyz/core/interfaces/IMailbox.sol"; 8 | 9 | contract HyperlaneMessageSender { 10 | IMailbox outbox; 11 | event SentMessage(uint32 destinationDomain, bytes32 recipient, string message); 12 | 13 | constructor(address _outbox) { 14 | outbox = IMailbox(_outbox); 15 | } 16 | 17 | function sendString( 18 | uint32 _destinationDomain, 19 | bytes32 _recipient, 20 | string calldata _message 21 | ) external { 22 | outbox.dispatch(_destinationDomain, _recipient, bytes(_message)); 23 | emit SentMessage(_destinationDomain, _recipient, _message); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /contracts/IInterchainAccountRouter.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity ^0.8.13; 3 | 4 | import {Call} from "./OwnableMulticall.sol"; 5 | 6 | interface IInterchainAccountRouter { 7 | function dispatch(uint32 _destinationDomain, Call[] calldata calls) 8 | external; 9 | 10 | function getInterchainAccount(uint32 _origin, address _sender) external view; 11 | } 12 | -------------------------------------------------------------------------------- /contracts/IInterchainQueryRouter.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT OR Apache-2.0 2 | pragma solidity >=0.6.11; 3 | 4 | import {Call} from "./OwnableMulticall.sol"; 5 | 6 | interface IInterchainQueryRouter { 7 | function query( 8 | uint32 _destinationDomain, 9 | address target, 10 | bytes calldata queryData, 11 | bytes calldata callback 12 | ) external returns (uint256); 13 | 14 | function query( 15 | uint32 _destinationDomain, 16 | Call calldata call, 17 | bytes calldata callback 18 | ) external returns (uint256); 19 | 20 | function query( 21 | uint32 _destinationDomain, 22 | Call[] calldata calls, 23 | bytes[] calldata callbacks 24 | ) external returns (uint256); 25 | } 26 | -------------------------------------------------------------------------------- /contracts/MockInterchainAccountRouter.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity ^0.8.13; 3 | 4 | import {OwnableMulticall, Call} from "./OwnableMulticall.sol"; 5 | 6 | // ============ External Imports ============ 7 | import {Create2} from "@openzeppelin/contracts/utils/Create2.sol"; 8 | import {Address} from "@openzeppelin/contracts/utils/Address.sol"; 9 | 10 | /* 11 | * @title The Hello World App 12 | * @dev You can use this simple app as a starting point for your own application. 13 | */ 14 | contract MockInterchainAccountRouter { 15 | struct PendingCall { 16 | uint32 originDomain; 17 | address sender; 18 | bytes serializedCalls; 19 | } 20 | 21 | uint32 public originDomain; 22 | bytes constant bytecode = type(OwnableMulticall).creationCode; 23 | bytes32 constant bytecodeHash = bytes32(keccak256(bytecode)); 24 | 25 | mapping(uint256 => PendingCall) pendingCalls; 26 | uint256 totalCalls = 0; 27 | uint256 callsProcessed = 0; 28 | 29 | event InterchainAccountCreated( 30 | uint32 indexed origin, 31 | address sender, 32 | address account 33 | ); 34 | 35 | constructor(uint32 _originDomain) { 36 | originDomain = _originDomain; 37 | } 38 | 39 | function dispatch(uint32, Call[] calldata calls) external { 40 | pendingCalls[totalCalls] = PendingCall( 41 | originDomain, 42 | msg.sender, 43 | abi.encode(calls) 44 | ); 45 | totalCalls += 1; 46 | } 47 | 48 | function getInterchainAccount(uint32 _origin, address _sender) 49 | public 50 | view 51 | returns (address) 52 | { 53 | return _getInterchainAccount(_salt(_origin, _sender)); 54 | } 55 | 56 | function getDeployedInterchainAccount(uint32 _origin, address _sender) 57 | public 58 | returns (OwnableMulticall) 59 | { 60 | bytes32 salt = _salt(_origin, _sender); 61 | address interchainAccount = _getInterchainAccount(salt); 62 | if (!Address.isContract(interchainAccount)) { 63 | interchainAccount = Create2.deploy(0, salt, bytecode); 64 | emit InterchainAccountCreated(_origin, _sender, interchainAccount); 65 | } 66 | return OwnableMulticall(interchainAccount); 67 | } 68 | 69 | function _salt(uint32 _origin, address _sender) 70 | internal 71 | pure 72 | returns (bytes32) 73 | { 74 | return bytes32(abi.encodePacked(_origin, _sender)); 75 | } 76 | 77 | function _getInterchainAccount(bytes32 salt) 78 | internal 79 | view 80 | returns (address) 81 | { 82 | return Create2.computeAddress(salt, bytecodeHash); 83 | } 84 | 85 | function processNextPendingCall() public { 86 | PendingCall memory pendingCall = pendingCalls[callsProcessed]; 87 | Call[] memory calls = abi.decode(pendingCall.serializedCalls, (Call[])); 88 | 89 | getDeployedInterchainAccount(originDomain, pendingCall.sender) 90 | .proxyCalls(calls); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /contracts/OwnableMulticall.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity ^0.8.13; 3 | 4 | // ============ External Imports ============ 5 | 6 | import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; 7 | 8 | struct Call { 9 | address to; 10 | bytes data; 11 | } 12 | 13 | /* 14 | * @title OwnableMulticall 15 | * @dev Allows only only address to execute calls to other contracts 16 | 17 | */ 18 | contract OwnableMulticall is OwnableUpgradeable { 19 | constructor() { 20 | _transferOwnership(msg.sender); 21 | } 22 | 23 | function proxyCalls(Call[] calldata calls) external onlyOwner { 24 | for (uint256 i = 0; i < calls.length; i += 1) { 25 | (bool success, bytes memory returnData) = calls[i].to.call( 26 | calls[i].data 27 | ); 28 | if (!success) { 29 | assembly { 30 | revert(add(returnData, 32), returnData) 31 | } 32 | } 33 | } 34 | } 35 | 36 | function _call(Call[] memory calls, bytes[] memory callbacks) 37 | internal 38 | returns (bytes[] memory resolveCalls) 39 | { 40 | resolveCalls = new bytes[](callbacks.length); 41 | for (uint256 i = 0; i < calls.length; i++) { 42 | (bool success, bytes memory returnData) = calls[i].to.call( 43 | calls[i].data 44 | ); 45 | require(success, "Multicall: call failed"); 46 | resolveCalls[i] = bytes.concat(callbacks[i], returnData); 47 | } 48 | } 49 | 50 | // TODO: deduplicate 51 | function proxyCallBatch(address to, bytes[] memory calls) internal { 52 | for (uint256 i = 0; i < calls.length; i += 1) { 53 | (bool success, bytes memory returnData) = to.call(calls[i]); 54 | if (!success) { 55 | assembly { 56 | revert(add(returnData, 32), returnData) 57 | } 58 | } 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /contracts/Ownee.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity ^0.8.13; 3 | 4 | import "./IInterchainAccountRouter.sol"; 5 | import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; 6 | 7 | contract Ownee is OwnableUpgradeable { 8 | uint256 public fee = 0; 9 | 10 | event NewFeeSet(uint256 newFee); 11 | 12 | constructor(address owner) { 13 | _transferOwnership(owner); 14 | } 15 | 16 | function setFee(uint256 newFee) onlyOwner external { 17 | fee = newFee; 18 | } 19 | } -------------------------------------------------------------------------------- /contracts/Owner.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity ^0.8.13; 3 | 4 | import "./IInterchainAccountRouter.sol"; 5 | import {Call} from "./OwnableMulticall.sol"; 6 | 7 | contract Owner { 8 | IInterchainAccountRouter router; 9 | 10 | constructor(address _router) { 11 | router = IInterchainAccountRouter(_router); 12 | } 13 | 14 | function setRemoteFee( 15 | uint32 _destinationDomain, 16 | address target, 17 | uint256 newFee 18 | ) external { 19 | Call[] memory calls = new Call[](1); 20 | calls[0] = Call({ 21 | to: target, 22 | data: abi.encodeWithSelector(0x69fe0e2d, newFee) 23 | }); 24 | router.dispatch(_destinationDomain, calls); 25 | } 26 | 27 | function transferRemoteOwnership( 28 | uint32 _destinationDomain, 29 | address target, 30 | address newOwner 31 | ) external { 32 | Call[] memory calls = new Call[](1); 33 | calls[0] = Call({ 34 | to: target, 35 | data: abi.encodeWithSelector(0xf2fde38b, newOwner) 36 | }); 37 | router.dispatch(_destinationDomain, calls); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /contracts/OwnerReader.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity ^0.8.13; 3 | 4 | import {IInterchainQueryRouter} from "./IInterchainQueryRouter.sol"; 5 | import {Call} from "./OwnableMulticall.sol"; 6 | 7 | interface Ownable { 8 | function owner() external view returns (address); 9 | } 10 | 11 | contract OwnerReader { 12 | IInterchainQueryRouter router; 13 | 14 | address public lastTarget; 15 | uint32 public lastDomain; 16 | address public lastOwner; 17 | 18 | constructor(address _router) { 19 | router = IInterchainQueryRouter(_router); 20 | } 21 | 22 | function readRemoteOwner(uint32 _destinationDomain, address target) 23 | external 24 | { 25 | router.query( 26 | _destinationDomain, 27 | Call({to: target, data: abi.encodePacked(Ownable.owner.selector)}), 28 | abi.encodeWithSelector(this.receiveQueryResult.selector, target, _destinationDomain) 29 | ); 30 | } 31 | 32 | function receiveQueryResult(address _target, uint32 _domain, address _owner) public { 33 | lastOwner = _owner; 34 | lastDomain = _domain; 35 | lastTarget = _target; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /foundry.toml: -------------------------------------------------------------------------------- 1 | [profile.default] 2 | src = 'contracts' 3 | out = 'out' 4 | libs = ['node_modules', 'lib'] 5 | test = 'test/foundry' 6 | cache_path = 'forge-cache' -------------------------------------------------------------------------------- /hardhat.config.ts: -------------------------------------------------------------------------------- 1 | import { 2 | chainMetadata, 3 | ChainName, 4 | hyperlaneCoreAddresses as HyperlaneCoreAddresses, 5 | MultiProvider, 6 | objMap, 7 | } from "@hyperlane-xyz/sdk"; 8 | import { utils } from "@hyperlane-xyz/utils"; 9 | import { InterchainAccountRouter__factory } from "@hyperlane-xyz/core"; 10 | import "@nomicfoundation/hardhat-toolbox"; 11 | import "@nomiclabs/hardhat-etherscan"; 12 | import { HardhatUserConfig, task, types } from "hardhat/config"; 13 | import { ethers, Event } from "ethers"; 14 | import { Log } from "@ethersproject/abstract-provider"; 15 | 16 | // TODO loosen hyperlaneCoreAddresses type in SDK to work with ChainName keys 17 | const hyperlaneCoreAddresses = HyperlaneCoreAddresses; 18 | 19 | // Use mnemonic ... 20 | // const accounts = { 21 | // mnemonic: "test test test test test test test test test test test junk", 22 | // path: "m/44'/60'/0'/0", 23 | // initialIndex: 0, 24 | // count: 20, 25 | // passphrase: "", 26 | // } 27 | // ... or a direct private key 28 | const accounts = ["YOUR PRIVATE KEY"]; 29 | 30 | const config: HardhatUserConfig = { 31 | solidity: "0.8.17", 32 | networks: objMap(chainMetadata, (_chain, cc) => ({ 33 | // @ts-ignore 34 | url: cc.publicRpcUrls[0].http, 35 | accounts, 36 | })), 37 | etherscan: { 38 | apiKey: { 39 | // Your etherscan API keys here 40 | // polygonMumbai: "", 41 | // goerli: "", 42 | }, 43 | }, 44 | typechain: { 45 | outDir: "./types", 46 | target: "ethers-v5", 47 | alwaysGenerateOverloads: false, 48 | }, 49 | }; 50 | 51 | const multiProvider = new MultiProvider(); 52 | 53 | const MAILBOX_ABI = [ 54 | "function dispatch(uint32 destinationDomain, bytes32 recipient, bytes calldata message) returns (bytes32)", 55 | "event DispatchId(bytes32 indexed messageId)", 56 | ]; 57 | const INTERCHAIN_GAS_PAYMASTER_ABI = [ 58 | "function payForGas(bytes32 _messageId, uint32 _destinationDomain, uint256 _gasAmount, address _refundAddress) payable", 59 | "function quoteGasPayment(uint32 _destinationDomain, uint256 _gasAmount) public view returns (uint256)", 60 | ]; 61 | const INTERCHAIN_ACCOUNT_ROUTER_ABI = [ 62 | "function dispatch(uint32 _destinationDomain, (address, bytes)[] calldata calls)", 63 | ]; 64 | const TESTRECIPIENT_ABI = [ 65 | "function fooBar(uint256 amount, string calldata message)", 66 | ]; 67 | 68 | const INTERCHAIN_ACCOUNT_ROUTER = "0xc61Bbf8eAb0b748Ecb532A7ffC49Ab7ca6D3a39D"; 69 | const INTERCHAIN_QUERY_ROUTER = "0x6141e7E7fA2c1beB8be030B0a7DB4b8A10c7c3cd"; 70 | 71 | // A global constant for simplicity 72 | // This is the amount of gas you will be paying for for processing of a message on the destination 73 | const DESTINATIONGASAMOUNT = 1000000; 74 | 75 | task("send-message", "sends a message") 76 | .addParam( 77 | "remote", 78 | "The name of the destination chain of this message", 79 | undefined, 80 | types.string, 81 | false 82 | ) 83 | .addParam("message", "the message you want to send", "Hello World") 84 | .setAction(async (taskArgs, hre) => { 85 | const signer = (await hre.ethers.getSigners())[0]; 86 | const recipient = "0x36FdA966CfffF8a9Cdc814f546db0e6378bFef35"; 87 | const origin = hre.network.name as ChainName; 88 | const remote = taskArgs.remote as ChainName; 89 | const remoteDomain = multiProvider.getDomainId(remote); 90 | const outboxC = hyperlaneCoreAddresses[origin].mailbox; 91 | const igpAddress = hyperlaneCoreAddresses[origin].interchainGasPaymaster; 92 | 93 | const outbox = new hre.ethers.Contract(outboxC, MAILBOX_ABI, signer); 94 | console.log( 95 | `Sending message "${taskArgs.message}" from ${hre.network.name} to ${taskArgs.remote}` 96 | ); 97 | 98 | const tx = await outbox.dispatch( 99 | remoteDomain, 100 | utils.addressToBytes32(recipient), 101 | hre.ethers.utils.arrayify(hre.ethers.utils.toUtf8Bytes(taskArgs.message)) 102 | ); 103 | 104 | const receipt = await tx.wait(); 105 | console.log( 106 | `Send message at txHash ${tx.hash}. Check the explorer at https://explorer.hyperlane.xyz/?search=${tx.hash}` 107 | ); 108 | 109 | console.log( 110 | "Pay for processing of the message via the InterchainGasPaymaster" 111 | ); 112 | const messageId = getMessageIdFromDispatchLogs(receipt.logs); 113 | const igp = new hre.ethers.Contract( 114 | igpAddress, 115 | INTERCHAIN_GAS_PAYMASTER_ABI, 116 | signer 117 | ); 118 | const gasPayment = await igp.quoteGasPayment( 119 | remoteDomain, 120 | DESTINATIONGASAMOUNT 121 | ); 122 | const igpTx = await igp.payForGas( 123 | messageId, 124 | remoteDomain, 125 | DESTINATIONGASAMOUNT, 126 | await signer.getAddress(), 127 | { value: gasPayment } 128 | ); 129 | await igpTx.wait(); 130 | 131 | const recipientUrl = await multiProvider.tryGetExplorerAddressUrl( 132 | remote, 133 | recipient 134 | ); 135 | console.log( 136 | `Check out the explorer page for recipient ${recipientUrl}#events` 137 | ); 138 | }); 139 | 140 | task("make-ica-call", "Makes an Interchain Account call") 141 | .addParam( 142 | "remote", 143 | "The name of the remote chain as the destination of this message", 144 | undefined, 145 | types.string, 146 | false 147 | ) 148 | .addParam("message", "the message you want to send", "Hello World") 149 | .setAction(async (taskArgs, hre) => { 150 | const signer = (await hre.ethers.getSigners())[0]; 151 | const recipient = "0xBC3cFeca7Df5A45d61BC60E7898E63670e1654aE"; 152 | const interchainAccountAddress = 153 | "0x28DB114018576cF6c9A523C17903455A161d18C4"; 154 | const remote = taskArgs.remote as ChainName; 155 | const remoteDomain = multiProvider.getDomainId(remote); 156 | // Arbitrary values 157 | const amount = 42; 158 | 159 | const interchainAccountRouter = new hre.ethers.Contract( 160 | interchainAccountAddress, 161 | INTERCHAIN_ACCOUNT_ROUTER_ABI, 162 | signer 163 | ); 164 | 165 | const recipientInterface = new hre.ethers.utils.Interface( 166 | TESTRECIPIENT_ABI 167 | ); 168 | const calldata = recipientInterface.encodeFunctionData("fooBar", [ 169 | amount, 170 | taskArgs.message, 171 | ]); 172 | 173 | console.log( 174 | `Sending message "${taskArgs.message}" from ${hre.network.name} to ${taskArgs.remote}` 175 | ); 176 | 177 | const tx = await interchainAccountRouter.dispatch(remoteDomain, [ 178 | [recipient, calldata], 179 | ]); 180 | 181 | const receipt = await tx.wait(); 182 | console.log( 183 | `Sent message at txHash ${tx.hash}. Check the explorer at https://explorer.hyperlane.xyz/?search=${tx.hash}` 184 | ); 185 | 186 | console.log( 187 | "Pay for processing of the message via the InterchainGasPaymaster" 188 | ); 189 | const messageId = getMessageIdFromDispatchLogs(receipt.logs); 190 | const igpAddress = hyperlaneCoreAddresses[origin].interchainGasPaymaster; 191 | const igp = new hre.ethers.Contract( 192 | igpAddress, 193 | INTERCHAIN_GAS_PAYMASTER_ABI, 194 | signer 195 | ); 196 | const gasPayment = await igp.quoteGasPayment( 197 | remoteDomain, 198 | DESTINATIONGASAMOUNT 199 | ); 200 | const igpTx = await igp.payForGas( 201 | messageId, 202 | remoteDomain, 203 | DESTINATIONGASAMOUNT, 204 | await signer.getAddress(), 205 | { value: gasPayment } 206 | ); 207 | await igpTx.wait(); 208 | 209 | const recipientUrl = await multiProvider.tryGetExplorerAddressUrl( 210 | remote, 211 | recipient 212 | ); 213 | console.log( 214 | `Check out the explorer page for recipient ${recipientUrl}#events` 215 | ); 216 | }); 217 | 218 | task( 219 | "deploy-message-sender", 220 | "deploys the HyperlaneMessageSender contract" 221 | ).setAction(async (taskArgs, hre) => { 222 | console.log(`Deploying HyperlaneMessageSender on ${hre.network.name}`); 223 | const origin = hre.network.name as ChainName; 224 | const outbox = hyperlaneCoreAddresses[origin].mailbox; 225 | 226 | const factory = await hre.ethers.getContractFactory("HyperlaneMessageSender"); 227 | 228 | const contract = await factory.deploy(outbox); 229 | await contract.deployTransaction.wait(); 230 | 231 | console.log( 232 | `Deployed HyperlaneMessageSender to ${contract.address} on ${hre.network.name} with transaction ${contract.deployTransaction.hash}` 233 | ); 234 | 235 | console.log(`You can verify the contracts with:`); 236 | console.log( 237 | `$ yarn hardhat verify --network ${hre.network.name} ${contract.address} ${outbox}` 238 | ); 239 | }); 240 | 241 | task("deploy-message-receiver", "deploys the HyperlaneMessageReceiver contract") 242 | .setAction(async (taskArgs, hre) => { 243 | console.log( 244 | `Deploying HyperlaneMessageReceiver on ${hre.network.name} for messages` 245 | ); 246 | const remote = hre.network.name as ChainName; 247 | const mailbox = hyperlaneCoreAddresses[remote].mailbox; 248 | 249 | const factory = await hre.ethers.getContractFactory( 250 | "HyperlaneMessageReceiver" 251 | ); 252 | 253 | const contract = await factory.deploy(mailbox); 254 | await contract.deployTransaction.wait(); 255 | 256 | console.log( 257 | `Deployed HyperlaneMessageReceiver to ${contract.address} on ${hre.network.name} with transaction ${contract.deployTransaction.hash}` 258 | ); 259 | console.log(`You can verify the contracts with:`); 260 | console.log( 261 | `$ yarn hardhat verify --network ${hre.network.name} ${contract.address} ${mailbox}` 262 | ); 263 | }); 264 | 265 | task( 266 | "send-message-via-HyperlaneMessageSender", 267 | "sends a message via a deployed HyperlaneMessageSender" 268 | ) 269 | .addParam( 270 | "sender", 271 | "Address of the HyperlaneMessageSender", 272 | undefined, 273 | types.string, 274 | false 275 | ) 276 | .addParam( 277 | "receiver", 278 | "address of the HyperlaneMessageReceiver", 279 | undefined, 280 | types.string, 281 | false 282 | ) 283 | .addParam( 284 | "remote", 285 | "Name of the remote chain on which HyperlaneMessageReceiver is on", 286 | undefined, 287 | types.string, 288 | false 289 | ) 290 | .addParam("message", "the message you want to send", "HelloWorld") 291 | .setAction(async (taskArgs, hre) => { 292 | const signer = (await hre.ethers.getSigners())[0]; 293 | const remote = taskArgs.remote as ChainName; 294 | const remoteDomain = multiProvider.getDomainId(remote); 295 | const senderFactory = await hre.ethers.getContractFactory( 296 | "HyperlaneMessageSender" 297 | ); 298 | const sender = senderFactory.attach(taskArgs.sender); 299 | 300 | console.log( 301 | `Sending message "${taskArgs.message}" from ${hre.network.name} to ${taskArgs.remote}` 302 | ); 303 | 304 | const tx = await sender.sendString( 305 | remoteDomain, 306 | utils.addressToBytes32(taskArgs.receiver), 307 | taskArgs.message 308 | ); 309 | 310 | const receipt = await tx.wait(); 311 | console.log( 312 | `Send message at txHash ${tx.hash}. Check the explorer at https://explorer.hyperlane.xyz/?search=${tx.hash}` 313 | ); 314 | 315 | console.log( 316 | "Pay for processing of the message via the InterchainGasPaymaster" 317 | ); 318 | const messageId = getMessageIdFromDispatchLogs(receipt.logs); 319 | const igpAddress = hyperlaneCoreAddresses[hre.network.name].interchainGasPaymaster; 320 | const igp = new hre.ethers.Contract( 321 | igpAddress, 322 | INTERCHAIN_GAS_PAYMASTER_ABI, 323 | signer 324 | ); 325 | const gasPayment = await igp.quoteGasPayment( 326 | remoteDomain, 327 | DESTINATIONGASAMOUNT 328 | ); 329 | const igpTx = await igp.payForGas( 330 | messageId, 331 | remoteDomain, 332 | DESTINATIONGASAMOUNT, 333 | await signer.getAddress(), 334 | { value: gasPayment } 335 | ); 336 | await igpTx.wait(); 337 | 338 | const recipientUrl = await multiProvider.tryGetExplorerAddressUrl( 339 | remote, 340 | taskArgs.receiver 341 | ); 342 | console.log( 343 | `Check out the explorer page for receiver ${recipientUrl}#events` 344 | ); 345 | }); 346 | 347 | task( 348 | "deploy-owner", 349 | "deploys the Owner contract that can own things cross-chain" 350 | ).setAction(async (_, hre) => { 351 | console.log(`Deploying Owner on ${hre.network.name}`); 352 | const factory = await hre.ethers.getContractFactory("Owner"); 353 | const contract = await factory.deploy(INTERCHAIN_ACCOUNT_ROUTER); 354 | await contract.deployTransaction.wait(); 355 | 356 | console.log( 357 | `Deployed Owner to ${contract.address} on ${hre.network.name} with transaction ${contract.deployTransaction.hash}` 358 | ); 359 | console.log(`You can verify the contracts with:`); 360 | console.log( 361 | `$ yarn hardhat verify --network ${hre.network.name} ${contract.address} ${INTERCHAIN_ACCOUNT_ROUTER}` 362 | ); 363 | }); 364 | 365 | task( 366 | "get-ica-address", 367 | "Gets the ICA account address for an address on a given chain" 368 | ) 369 | .addParam( 370 | "address", 371 | "The address on the origin chain", 372 | undefined, 373 | types.string, 374 | false 375 | ) 376 | .setAction(async (taskArgs, hre) => { 377 | const router = await InterchainAccountRouter__factory.connect( 378 | INTERCHAIN_ACCOUNT_ROUTER, 379 | hre.ethers.getDefaultProvider() 380 | ); 381 | const originDomain = multiProvider.getDomainId(hre.network.name); 382 | const ica = await router["getInterchainAccount(uint32,address)"]( 383 | originDomain, 384 | taskArgs.address 385 | ); 386 | console.info( 387 | `The ICA of ${taskArgs.address} on ${hre.network.name} (${originDomain}) is ${ica}` 388 | ); 389 | }); 390 | 391 | task( 392 | "deploy-ownee", 393 | "deploys the Ownee contract (that has no cross-chain-specific code)" 394 | ) 395 | .addParam("owner", "address of the owner", undefined, types.string, false) 396 | .setAction(async (taskArgs, hre) => { 397 | console.log(`Deploying Ownee on ${hre.network.name}`); 398 | const factory = await hre.ethers.getContractFactory("Ownee"); 399 | const contract = await factory.deploy(taskArgs.owner); 400 | await contract.deployTransaction.wait(); 401 | 402 | console.log( 403 | `Deployed Ownee to ${contract.address} on ${hre.network.name} with transaction ${contract.deployTransaction.hash}` 404 | ); 405 | console.log(`You can verify the contracts with:`); 406 | console.log( 407 | `$ yarn hardhat verify --network ${hre.network.name} ${contract.address} ${taskArgs.ownee}` 408 | ); 409 | }); 410 | 411 | task( 412 | "set-remote-fee", 413 | "Allows an Owner contract to set the fee on a remote Ownee contract" 414 | ) 415 | .addParam( 416 | "owner", 417 | "Owner address on the origin chain", 418 | undefined, 419 | types.string, 420 | false 421 | ) 422 | .addParam( 423 | "ownee", 424 | "Ownee address on the remote chain", 425 | undefined, 426 | types.string, 427 | false 428 | ) 429 | .addParam( 430 | "remote", 431 | "The name of the remote chain on which the Ownee lives", 432 | undefined, 433 | types.string, 434 | false 435 | ) 436 | .addParam("newFee", "the new fee that should be set", 42, types.float) 437 | .setAction(async function (taskArgs, hre) { 438 | const factory = await hre.ethers.getContractFactory("Owner"); 439 | const owner = await factory.attach(taskArgs.owner); 440 | const destinationDomain = multiProvider.getDomainId(taskArgs.remote); 441 | const tx = await owner.setRemoteFee( 442 | destinationDomain, 443 | taskArgs.ownee, 444 | taskArgs.newFee 445 | ); 446 | await tx.wait(); 447 | 448 | console.log( 449 | `Set the fee on Ownee at ${taskArgs.ownee} on ${taskArgs.remote} at transaction ${tx.hash}.` 450 | ); 451 | }); 452 | 453 | task("get-fee", "Reads the fee of an Ownee") 454 | .addParam("ownee", "The address of the Ownee", undefined, types.string, false) 455 | .setAction(async (taskArgs, hre) => { 456 | const factory = await hre.ethers.getContractFactory("Ownee"); 457 | const ownee = factory.attach(taskArgs.ownee); 458 | 459 | const fee = await ownee.fee(); 460 | console.info( 461 | `The current set fee of ${taskArgs.ownee} on ${hre.network.name} is ${fee}` 462 | ); 463 | }); 464 | 465 | task( 466 | "deploy-reader", 467 | "deploys the OwnerReader contract that can owners of remote contracts" 468 | ).setAction(async (_, hre) => { 469 | console.log(`Deploying OwnerReader on ${hre.network.name}`); 470 | const factory = await hre.ethers.getContractFactory("OwnerReader"); 471 | const contract = await factory.deploy(INTERCHAIN_QUERY_ROUTER); 472 | await contract.deployTransaction.wait(); 473 | 474 | console.log( 475 | `Deployed OwnerReader to ${contract.address} on ${hre.network.name} with transaction ${contract.deployTransaction.hash}` 476 | ); 477 | console.log(`You can verify the contracts with:`); 478 | console.log( 479 | `$ yarn hardhat verify --network ${hre.network.name} ${contract.address} ${INTERCHAIN_QUERY_ROUTER}` 480 | ); 481 | }); 482 | 483 | task("read-remote-owner", "Allows readRemoteOwner on a OwnerReader contract") 484 | .addParam( 485 | "reader", 486 | "OwnerReader address on the origin chain", 487 | undefined, 488 | types.string, 489 | false 490 | ) 491 | .addParam( 492 | "target", 493 | "contract to read owner() on the remote chain", 494 | undefined, 495 | types.string, 496 | false 497 | ) 498 | .addParam( 499 | "remote", 500 | "The name of the remote chain on which the target lives", 501 | undefined, 502 | types.string, 503 | false 504 | ) 505 | .setAction(async function (taskArgs, hre) { 506 | const factory = await hre.ethers.getContractFactory("OwnerReader"); 507 | const reader = await factory.attach(taskArgs.reader); 508 | const destinationDomain = multiProvider.getDomainId(taskArgs.remote); 509 | 510 | const tx = await reader.readRemoteOwner(destinationDomain, taskArgs.target); 511 | await tx.wait(); 512 | 513 | console.log( 514 | `Initiated the owner() query on the contract at ${taskArgs.target} on ${taskArgs.remote} at transaction ${tx.hash}.` 515 | ); 516 | }); 517 | 518 | task("get-query-result", "Reads the queryResult on an OwnerReader") 519 | .addParam( 520 | "reader", 521 | "OwnerReader address on the origin chain", 522 | undefined, 523 | types.string, 524 | false 525 | ) 526 | .setAction(async (taskArgs, hre) => { 527 | const factory = await hre.ethers.getContractFactory("OwnerReader"); 528 | const reader = factory.attach(taskArgs.reader); 529 | 530 | const lastOwner = await reader.lastOwner(); 531 | const lastTarget = await reader.lastTarget(); 532 | const lastQueryDomainNumber = await reader.lastDomain(); 533 | const lastQueryDomain = multiProvider.getDomainId(lastQueryDomainNumber); 534 | 535 | console.info( 536 | `The currently recorded query result on ${taskArgs.reader} is that the owner of ${lastTarget} is ${lastOwner} on ${lastQueryDomain}` 537 | ); 538 | }); 539 | export default config; 540 | 541 | function getMessageIdFromDispatchLogs(logs: Log[]) { 542 | const mailboxInterface = new ethers.utils.Interface(MAILBOX_ABI); 543 | for (const log of logs) { 544 | try { 545 | const parsedLog = mailboxInterface.parseLog(log); 546 | if (parsedLog.name === "DispatchId") { 547 | return parsedLog.args.messageId; 548 | } 549 | } catch (e) {} 550 | } 551 | return undefined; 552 | } 553 | -------------------------------------------------------------------------------- /lib/forge-std/.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | on: [push, pull_request] 3 | 4 | jobs: 5 | check: 6 | name: Foundry project 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v2 10 | with: 11 | submodules: recursive 12 | 13 | - name: Install Foundry 14 | uses: onbjerg/foundry-toolchain@v1 15 | with: 16 | version: nightly 17 | 18 | - name: Install dependencies 19 | run: forge install 20 | - name: Run tests 21 | run: forge test -vvv 22 | - name: Build Test with older solc versions 23 | run: | 24 | forge build --contracts src/Test.sol --use solc:0.8.0 25 | forge build --contracts src/Test.sol --use solc:0.7.0 26 | forge build --contracts src/Test.sol --use solc:0.6.0 27 | -------------------------------------------------------------------------------- /lib/forge-std/.gitignore: -------------------------------------------------------------------------------- 1 | cache/ 2 | out/ 3 | -------------------------------------------------------------------------------- /lib/forge-std/.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "lib/ds-test"] 2 | path = lib/ds-test 3 | url = https://github.com/dapphub/ds-test 4 | -------------------------------------------------------------------------------- /lib/forge-std/LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2021 Brock Elmore 2 | 3 | Apache License 4 | Version 2.0, January 2004 5 | http://www.apache.org/licenses/ 6 | 7 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 8 | 9 | 1. Definitions. 10 | 11 | "License" shall mean the terms and conditions for use, reproduction, 12 | and distribution as defined by Sections 1 through 9 of this document. 13 | 14 | "Licensor" shall mean the copyright owner or entity authorized by 15 | the copyright owner that is granting the License. 16 | 17 | "Legal Entity" shall mean the union of the acting entity and all 18 | other entities that control, are controlled by, or are under common 19 | control with that entity. For the purposes of this definition, 20 | "control" means (i) the power, direct or indirect, to cause the 21 | direction or management of such entity, whether by contract or 22 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 23 | outstanding shares, or (iii) beneficial ownership of such entity. 24 | 25 | "You" (or "Your") shall mean an individual or Legal Entity 26 | exercising permissions granted by this License. 27 | 28 | "Source" form shall mean the preferred form for making modifications, 29 | including but not limited to software source code, documentation 30 | source, and configuration files. 31 | 32 | "Object" form shall mean any form resulting from mechanical 33 | transformation or translation of a Source form, including but 34 | not limited to compiled object code, generated documentation, 35 | and conversions to other media types. 36 | 37 | "Work" shall mean the work of authorship, whether in Source or 38 | Object form, made available under the License, as indicated by a 39 | copyright notice that is included in or attached to the work 40 | (an example is provided in the Appendix below). 41 | 42 | "Derivative Works" shall mean any work, whether in Source or Object 43 | form, that is based on (or derived from) the Work and for which the 44 | editorial revisions, annotations, elaborations, or other modifications 45 | represent, as a whole, an original work of authorship. For the purposes 46 | of this License, Derivative Works shall not include works that remain 47 | separable from, or merely link (or bind by name) to the interfaces of, 48 | the Work and Derivative Works thereof. 49 | 50 | "Contribution" shall mean any work of authorship, including 51 | the original version of the Work and any modifications or additions 52 | to that Work or Derivative Works thereof, that is intentionally 53 | submitted to Licensor for inclusion in the Work by the copyright owner 54 | or by an individual or Legal Entity authorized to submit on behalf of 55 | the copyright owner. For the purposes of this definition, "submitted" 56 | means any form of electronic, verbal, or written communication sent 57 | to the Licensor or its representatives, including but not limited to 58 | communication on electronic mailing lists, source code control systems, 59 | and issue tracking systems that are managed by, or on behalf of, the 60 | Licensor for the purpose of discussing and improving the Work, but 61 | excluding communication that is conspicuously marked or otherwise 62 | designated in writing by the copyright owner as "Not a Contribution." 63 | 64 | "Contributor" shall mean Licensor and any individual or Legal Entity 65 | on behalf of whom a Contribution has been received by Licensor and 66 | subsequently incorporated within the Work. 67 | 68 | 2. Grant of Copyright License. Subject to the terms and conditions of 69 | this License, each Contributor hereby grants to You a perpetual, 70 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 71 | copyright license to reproduce, prepare Derivative Works of, 72 | publicly display, publicly perform, sublicense, and distribute the 73 | Work and such Derivative Works in Source or Object form. 74 | 75 | 3. Grant of Patent License. Subject to the terms and conditions of 76 | this License, each Contributor hereby grants to You a perpetual, 77 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 78 | (except as stated in this section) patent license to make, have made, 79 | use, offer to sell, sell, import, and otherwise transfer the Work, 80 | where such license applies only to those patent claims licensable 81 | by such Contributor that are necessarily infringed by their 82 | Contribution(s) alone or by combination of their Contribution(s) 83 | with the Work to which such Contribution(s) was submitted. If You 84 | institute patent litigation against any entity (including a 85 | cross-claim or counterclaim in a lawsuit) alleging that the Work 86 | or a Contribution incorporated within the Work constitutes direct 87 | or contributory patent infringement, then any patent licenses 88 | granted to You under this License for that Work shall terminate 89 | as of the date such litigation is filed. 90 | 91 | 4. Redistribution. You may reproduce and distribute copies of the 92 | Work or Derivative Works thereof in any medium, with or without 93 | modifications, and in Source or Object form, provided that You 94 | meet the following conditions: 95 | 96 | (a) You must give any other recipients of the Work or 97 | Derivative Works a copy of this License; and 98 | 99 | (b) You must cause any modified files to carry prominent notices 100 | stating that You changed the files; and 101 | 102 | (c) You must retain, in the Source form of any Derivative Works 103 | that You distribute, all copyright, patent, trademark, and 104 | attribution notices from the Source form of the Work, 105 | excluding those notices that do not pertain to any part of 106 | the Derivative Works; and 107 | 108 | (d) If the Work includes a "NOTICE" text file as part of its 109 | distribution, then any Derivative Works that You distribute must 110 | include a readable copy of the attribution notices contained 111 | within such NOTICE file, excluding those notices that do not 112 | pertain to any part of the Derivative Works, in at least one 113 | of the following places: within a NOTICE text file distributed 114 | as part of the Derivative Works; within the Source form or 115 | documentation, if provided along with the Derivative Works; or, 116 | within a display generated by the Derivative Works, if and 117 | wherever such third-party notices normally appear. The contents 118 | of the NOTICE file are for informational purposes only and 119 | do not modify the License. You may add Your own attribution 120 | notices within Derivative Works that You distribute, alongside 121 | or as an addendum to the NOTICE text from the Work, provided 122 | that such additional attribution notices cannot be construed 123 | as modifying the License. 124 | 125 | You may add Your own copyright statement to Your modifications and 126 | may provide additional or different license terms and conditions 127 | for use, reproduction, or distribution of Your modifications, or 128 | for any such Derivative Works as a whole, provided Your use, 129 | reproduction, and distribution of the Work otherwise complies with 130 | the conditions stated in this License. 131 | 132 | 5. Submission of Contributions. Unless You explicitly state otherwise, 133 | any Contribution intentionally submitted for inclusion in the Work 134 | by You to the Licensor shall be under the terms and conditions of 135 | this License, without any additional terms or conditions. 136 | Notwithstanding the above, nothing herein shall supersede or modify 137 | the terms of any separate license agreement you may have executed 138 | with Licensor regarding such Contributions. 139 | 140 | 6. Trademarks. This License does not grant permission to use the trade 141 | names, trademarks, service marks, or product names of the Licensor, 142 | except as required for reasonable and customary use in describing the 143 | origin of the Work and reproducing the content of the NOTICE file. 144 | 145 | 7. Disclaimer of Warranty. Unless required by applicable law or 146 | agreed to in writing, Licensor provides the Work (and each 147 | Contributor provides its Contributions) on an "AS IS" BASIS, 148 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 149 | implied, including, without limitation, any warranties or conditions 150 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 151 | PARTICULAR PURPOSE. You are solely responsible for determining the 152 | appropriateness of using or redistributing the Work and assume any 153 | risks associated with Your exercise of permissions under this License. 154 | 155 | 8. Limitation of Liability. In no event and under no legal theory, 156 | whether in tort (including negligence), contract, or otherwise, 157 | unless required by applicable law (such as deliberate and grossly 158 | negligent acts) or agreed to in writing, shall any Contributor be 159 | liable to You for damages, including any direct, indirect, special, 160 | incidental, or consequential damages of any character arising as a 161 | result of this License or out of the use or inability to use the 162 | Work (including but not limited to damages for loss of goodwill, 163 | work stoppage, computer failure or malfunction, or any and all 164 | other commercial damages or losses), even if such Contributor 165 | has been advised of the possibility of such damages. 166 | 167 | 9. Accepting Warranty or Additional Liability. While redistributing 168 | the Work or Derivative Works thereof, You may choose to offer, 169 | and charge a fee for, acceptance of support, warranty, indemnity, 170 | or other liability obligations and/or rights consistent with this 171 | License. However, in accepting such obligations, You may act only 172 | on Your own behalf and on Your sole responsibility, not on behalf 173 | of any other Contributor, and only if You agree to indemnify, 174 | defend, and hold each Contributor harmless for any liability 175 | incurred by, or claims asserted against, such Contributor by reason 176 | of your accepting any such warranty or additional liability. 177 | 178 | END OF TERMS AND CONDITIONS 179 | 180 | APPENDIX: How to apply the Apache License to your work. 181 | 182 | To apply the Apache License to your work, attach the following 183 | boilerplate notice, with the fields enclosed by brackets "[]" 184 | replaced with your own identifying information. (Don't include 185 | the brackets!) The text should be enclosed in the appropriate 186 | comment syntax for the file format. We also recommend that a 187 | file or class name and description of purpose be included on the 188 | same "printed page" as the copyright notice for easier 189 | identification within third-party archives. 190 | 191 | Copyright [yyyy] [name of copyright owner] 192 | 193 | Licensed under the Apache License, Version 2.0 (the "License"); 194 | you may not use this file except in compliance with the License. 195 | You may obtain a copy of the License at 196 | 197 | http://www.apache.org/licenses/LICENSE-2.0 198 | 199 | Unless required by applicable law or agreed to in writing, software 200 | distributed under the License is distributed on an "AS IS" BASIS, 201 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 202 | See the License for the specific language governing permissions and 203 | limitations under the License. 204 | -------------------------------------------------------------------------------- /lib/forge-std/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2021 Brock Elmore 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE O THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE.R 26 | -------------------------------------------------------------------------------- /lib/forge-std/README.md: -------------------------------------------------------------------------------- 1 | # Forge Standard Library • [![tests](https://github.com/brockelmore/forge-std/actions/workflows/tests.yml/badge.svg)](https://github.com/brockelmore/forge-std/actions/workflows/tests.yml) 2 | 3 | Forge Standard Library is a collection of helpful contracts for use with [`forge` and `foundry`](https://github.com/foundry-rs/foundry). It leverages `forge`'s cheatcodes to make writing tests easier and faster, while improving the UX of cheatcodes. 4 | 5 | **Learn how to use Forge Std with the [📖 Foundry Book (Forge Std Guide)](https://book.getfoundry.sh/forge/forge-std.html).** 6 | 7 | ## Install 8 | 9 | ```bash 10 | forge install foundry-rs/forge-std 11 | ``` 12 | 13 | ## Contracts 14 | 15 | ### stdError 16 | 17 | This is a helper contract for errors and reverts. In `forge`, this contract is particularly helpful for the `expectRevert` cheatcode, as it provides all compiler builtin errors. 18 | 19 | See the contract itself for all error codes. 20 | 21 | #### Example usage 22 | 23 | ```solidity 24 | import 'forge-std/Test.sol'; 25 | 26 | contract TestContract is Test { 27 | ErrorsTest test; 28 | 29 | function setUp() public { 30 | test = new ErrorsTest(); 31 | } 32 | 33 | function testExpectArithmetic() public { 34 | vm.expectRevert(stdError.arithmeticError); 35 | test.arithmeticError(10); 36 | } 37 | } 38 | 39 | contract ErrorsTest { 40 | function arithmeticError(uint256 a) public { 41 | uint256 a = a - 100; 42 | } 43 | } 44 | 45 | ``` 46 | 47 | ### stdStorage 48 | 49 | This is a rather large contract due to all of the overloading to make the UX decent. Primarily, it is a wrapper around the `record` and `accesses` cheatcodes. It can _always_ find and write the storage slot(s) associated with a particular variable without knowing the storage layout. The one _major_ caveat to this is while a slot can be found for packed storage variables, we can't write to that variable safely. If a user tries to write to a packed slot, the execution throws an error, unless it is uninitialized (`bytes32(0)`). 50 | 51 | This works by recording all `SLOAD`s and `SSTORE`s during a function call. If there is a single slot read or written to, it immediately returns the slot. Otherwise, behind the scenes, we iterate through and check each one (assuming the user passed in a `depth` parameter). If the variable is a struct, you can pass in a `depth` parameter which is basically the field depth. 52 | 53 | I.e.: 54 | 55 | ```solidity 56 | struct T { 57 | // depth 0 58 | uint256 a; 59 | // depth 1 60 | uint256 b; 61 | } 62 | 63 | ``` 64 | 65 | #### Example usage 66 | 67 | ```solidity 68 | import 'forge-std/Test.sol'; 69 | 70 | contract TestContract is Test { 71 | using stdStorage for StdStorage; 72 | 73 | Storage test; 74 | 75 | function setUp() public { 76 | test = new Storage(); 77 | } 78 | 79 | function testFindExists() public { 80 | // Lets say we want to find the slot for the public 81 | // variable `exists`. We just pass in the function selector 82 | // to the `find` command 83 | uint256 slot = stdstore.target(address(test)).sig('exists()').find(); 84 | assertEq(slot, 0); 85 | } 86 | 87 | function testWriteExists() public { 88 | // Lets say we want to write to the slot for the public 89 | // variable `exists`. We just pass in the function selector 90 | // to the `checked_write` command 91 | stdstore.target(address(test)).sig('exists()').checked_write(100); 92 | assertEq(test.exists(), 100); 93 | } 94 | 95 | // It supports arbitrary storage layouts, like assembly based storage locations 96 | function testFindHidden() public { 97 | // `hidden` is a random hash of a bytes, iteration through slots would 98 | // not find it. Our mechanism does 99 | // Also, you can use the selector instead of a string 100 | uint256 slot = stdstore 101 | .target(address(test)) 102 | .sig(test.hidden.selector) 103 | .find(); 104 | assertEq(slot, uint256(keccak256('my.random.var'))); 105 | } 106 | 107 | // If targeting a mapping, you have to pass in the keys necessary to perform the find 108 | // i.e.: 109 | function testFindMapping() public { 110 | uint256 slot = stdstore 111 | .target(address(test)) 112 | .sig(test.map_addr.selector) 113 | .with_key(address(this)) 114 | .find(); 115 | // in the `Storage` constructor, we wrote that this address' value was 1 in the map 116 | // so when we load the slot, we expect it to be 1 117 | assertEq(uint256(vm.load(address(test), bytes32(slot))), 1); 118 | } 119 | 120 | // If the target is a struct, you can specify the field depth: 121 | function testFindStruct() public { 122 | // NOTE: see the depth parameter - 0 means 0th field, 1 means 1st field, etc. 123 | uint256 slot_for_a_field = stdstore 124 | .target(address(test)) 125 | .sig(test.basicStruct.selector) 126 | .depth(0) 127 | .find(); 128 | 129 | uint256 slot_for_b_field = stdstore 130 | .target(address(test)) 131 | .sig(test.basicStruct.selector) 132 | .depth(1) 133 | .find(); 134 | 135 | assertEq(uint256(vm.load(address(test), bytes32(slot_for_a_field))), 1); 136 | assertEq(uint256(vm.load(address(test), bytes32(slot_for_b_field))), 2); 137 | } 138 | } 139 | 140 | // A complex storage contract 141 | contract Storage { 142 | struct UnpackedStruct { 143 | uint256 a; 144 | uint256 b; 145 | } 146 | 147 | constructor() { 148 | map_addr[msg.sender] = 1; 149 | } 150 | 151 | uint256 public exists = 1; 152 | mapping(address => uint256) public map_addr; 153 | // mapping(address => Packed) public map_packed; 154 | mapping(address => UnpackedStruct) public map_struct; 155 | mapping(address => mapping(address => uint256)) public deep_map; 156 | mapping(address => mapping(address => UnpackedStruct)) public deep_map_struct; 157 | UnpackedStruct public basicStruct = UnpackedStruct({ a: 1, b: 2 }); 158 | 159 | function hidden() public view returns (bytes32 t) { 160 | // an extremely hidden storage slot 161 | bytes32 slot = keccak256('my.random.var'); 162 | assembly { 163 | t := sload(slot) 164 | } 165 | } 166 | } 167 | 168 | ``` 169 | 170 | ### stdCheats 171 | 172 | This is a wrapper over miscellaneous cheatcodes that need wrappers to be more dev friendly. Currently there are only functions related to `prank`. In general, users may expect ETH to be put into an address on `prank`, but this is not the case for safety reasons. Explicitly this `hoax` function should only be used for address that have expected balances as it will get overwritten. If an address already has ETH, you should just use `prank`. If you want to change that balance explicitly, just use `deal`. If you want to do both, `hoax` is also right for you. 173 | 174 | #### Example usage: 175 | 176 | ```solidity 177 | // SPDX-License-Identifier: Unlicense 178 | pragma solidity ^0.8.0; 179 | 180 | import 'forge-std/Test.sol'; 181 | 182 | // Inherit the stdCheats 183 | contract StdCheatsTest is Test { 184 | Bar test; 185 | 186 | function setUp() public { 187 | test = new Bar(); 188 | } 189 | 190 | function testHoax() public { 191 | // we call `hoax`, which gives the target address 192 | // eth and then calls `prank` 193 | hoax(address(1337)); 194 | test.bar{ value: 100 }(address(1337)); 195 | 196 | // overloaded to allow you to specify how much eth to 197 | // initialize the address with 198 | hoax(address(1337), 1); 199 | test.bar{ value: 1 }(address(1337)); 200 | } 201 | 202 | function testStartHoax() public { 203 | // we call `startHoax`, which gives the target address 204 | // eth and then calls `startPrank` 205 | // 206 | // it is also overloaded so that you can specify an eth amount 207 | startHoax(address(1337)); 208 | test.bar{ value: 100 }(address(1337)); 209 | test.bar{ value: 100 }(address(1337)); 210 | vm.stopPrank(); 211 | test.bar(address(this)); 212 | } 213 | } 214 | 215 | contract Bar { 216 | function bar(address expectedSender) public payable { 217 | require(msg.sender == expectedSender, '!prank'); 218 | } 219 | } 220 | 221 | ``` 222 | 223 | ### Std Assertions 224 | 225 | Expand upon the assertion functions from the `DSTest` library. 226 | 227 | ### `console.log` 228 | 229 | Usage follows the same format as [Hardhat](https://hardhat.org/hardhat-network/reference/#console-log). 230 | It's recommended to use `console2.sol` as shown below, as this will show the decoded logs in Forge traces. 231 | 232 | ```solidity 233 | // import it indirectly via Test.sol 234 | import "forge-std/Test.sol"; 235 | // or directly import it 236 | import "forge-std/console2.sol"; 237 | ... 238 | console2.log(someValue); 239 | ``` 240 | 241 | If you need compatibility with Hardhat, you must use the standard `console.sol` instead. 242 | Due to a bug in `console.sol`, logs that use `uint256` or `int256` types will not be properly decoded in Forge traces. 243 | 244 | ```solidity 245 | // import it indirectly via Test.sol 246 | import "forge-std/Test.sol"; 247 | // or directly import it 248 | import "forge-std/console.sol"; 249 | ... 250 | console.log(someValue); 251 | ``` 252 | -------------------------------------------------------------------------------- /lib/forge-std/lib/ds-test/.gitignore: -------------------------------------------------------------------------------- 1 | /.dapple 2 | /build 3 | /out 4 | -------------------------------------------------------------------------------- /lib/forge-std/lib/ds-test/LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /lib/forge-std/lib/ds-test/Makefile: -------------------------------------------------------------------------------- 1 | all:; dapp build 2 | 3 | test: 4 | -dapp --use solc:0.4.23 build 5 | -dapp --use solc:0.4.26 build 6 | -dapp --use solc:0.5.17 build 7 | -dapp --use solc:0.6.12 build 8 | -dapp --use solc:0.7.5 build 9 | 10 | demo: 11 | DAPP_SRC=demo dapp --use solc:0.7.5 build 12 | -hevm dapp-test --verbose 3 13 | 14 | .PHONY: test demo 15 | -------------------------------------------------------------------------------- /lib/forge-std/lib/ds-test/default.nix: -------------------------------------------------------------------------------- 1 | { solidityPackage, dappsys }: solidityPackage { 2 | name = "ds-test"; 3 | src = ./src; 4 | } 5 | -------------------------------------------------------------------------------- /lib/forge-std/lib/ds-test/demo/demo.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | pragma solidity >=0.4.23; 3 | 4 | import "../src/test.sol"; 5 | 6 | contract DemoTest is DSTest { 7 | function test_this() public pure { 8 | require(true); 9 | } 10 | 11 | function test_logs() public { 12 | emit log("-- log(string)"); 13 | emit log("a string"); 14 | 15 | emit log("-- log_named_uint(string, uint)"); 16 | log_named_uint("uint", 512); 17 | 18 | emit log("-- log_named_int(string, int)"); 19 | log_named_int("int", -512); 20 | 21 | emit log("-- log_named_address(string, address)"); 22 | log_named_address("address", address(this)); 23 | 24 | emit log("-- log_named_bytes32(string, bytes32)"); 25 | log_named_bytes32("bytes32", "a string"); 26 | 27 | emit log("-- log_named_bytes(string, bytes)"); 28 | log_named_bytes("bytes", hex"cafefe"); 29 | 30 | emit log("-- log_named_string(string, string)"); 31 | log_named_string("string", "a string"); 32 | 33 | emit log("-- log_named_decimal_uint(string, uint, uint)"); 34 | log_named_decimal_uint("decimal uint", 1.0e18, 18); 35 | 36 | emit log("-- log_named_decimal_int(string, int, uint)"); 37 | log_named_decimal_int("decimal int", -1.0e18, 18); 38 | } 39 | 40 | event log_old_named_uint(bytes32, uint256); 41 | 42 | function test_old_logs() public { 43 | log_old_named_uint("key", 500); 44 | log_named_bytes32("bkey", "val"); 45 | } 46 | 47 | function test_trace() public view { 48 | this.echo("string 1", "string 2"); 49 | } 50 | 51 | function test_multiline() public { 52 | emit log( 53 | "a multiline\\n" 54 | "string" 55 | ); 56 | emit log( 57 | "a multiline " 58 | "string" 59 | ); 60 | log_bytes("a string"); 61 | log_bytes( 62 | "a multiline\n" 63 | "string" 64 | ); 65 | log_bytes( 66 | "a multiline\\n" 67 | "string" 68 | ); 69 | emit log(unicode"Ώ"); 70 | logs(hex"0000"); 71 | log_named_bytes("0x0000", hex"0000"); 72 | logs(hex"ff"); 73 | } 74 | 75 | function echo(string memory s1, string memory s2) 76 | public 77 | pure 78 | returns (string memory, string memory) 79 | { 80 | return (s1, s2); 81 | } 82 | 83 | function prove_this(uint256 x) public { 84 | log_named_uint("sym x", x); 85 | assertGt(x + 1, 0); 86 | } 87 | 88 | function test_logn() public { 89 | assembly { 90 | log0(0x01, 0x02) 91 | log1(0x01, 0x02, 0x03) 92 | log2(0x01, 0x02, 0x03, 0x04) 93 | log3(0x01, 0x02, 0x03, 0x04, 0x05) 94 | } 95 | } 96 | 97 | event MyEvent(uint256, uint256 indexed, uint256, uint256 indexed); 98 | 99 | function test_events() public { 100 | emit MyEvent(1, 2, 3, 4); 101 | } 102 | 103 | function test_asserts() public { 104 | string memory err = "this test has failed!"; 105 | emit log("## assertTrue(bool)\n"); 106 | assertTrue(false); 107 | emit log("\n"); 108 | assertTrue(false, err); 109 | 110 | emit log("\n## assertEq(address,address)\n"); 111 | assertEq(address(this), msg.sender); 112 | emit log("\n"); 113 | assertEq(address(this), msg.sender, err); 114 | 115 | emit log("\n## assertEq32(bytes32,bytes32)\n"); 116 | assertEq32("bytes 1", "bytes 2"); 117 | emit log("\n"); 118 | assertEq32("bytes 1", "bytes 2", err); 119 | 120 | emit log("\n## assertEq(bytes32,bytes32)\n"); 121 | assertEq32("bytes 1", "bytes 2"); 122 | emit log("\n"); 123 | assertEq32("bytes 1", "bytes 2", err); 124 | 125 | emit log("\n## assertEq(uint,uint)\n"); 126 | assertEq(uint256(0), 1); 127 | emit log("\n"); 128 | assertEq(uint256(0), 1, err); 129 | 130 | emit log("\n## assertEq(int,int)\n"); 131 | assertEq(-1, -2); 132 | emit log("\n"); 133 | assertEq(-1, -2, err); 134 | 135 | emit log("\n## assertEqDecimal(int,int,uint)\n"); 136 | assertEqDecimal(-1.0e18, -1.1e18, 18); 137 | emit log("\n"); 138 | assertEqDecimal(-1.0e18, -1.1e18, 18, err); 139 | 140 | emit log("\n## assertEqDecimal(uint,uint,uint)\n"); 141 | assertEqDecimal(uint256(1.0e18), 1.1e18, 18); 142 | emit log("\n"); 143 | assertEqDecimal(uint256(1.0e18), 1.1e18, 18, err); 144 | 145 | emit log("\n## assertGt(uint,uint)\n"); 146 | assertGt(uint256(0), 0); 147 | emit log("\n"); 148 | assertGt(uint256(0), 0, err); 149 | 150 | emit log("\n## assertGt(int,int)\n"); 151 | assertGt(-1, -1); 152 | emit log("\n"); 153 | assertGt(-1, -1, err); 154 | 155 | emit log("\n## assertGtDecimal(int,int,uint)\n"); 156 | assertGtDecimal(-2.0e18, -1.1e18, 18); 157 | emit log("\n"); 158 | assertGtDecimal(-2.0e18, -1.1e18, 18, err); 159 | 160 | emit log("\n## assertGtDecimal(uint,uint,uint)\n"); 161 | assertGtDecimal(uint256(1.0e18), 1.1e18, 18); 162 | emit log("\n"); 163 | assertGtDecimal(uint256(1.0e18), 1.1e18, 18, err); 164 | 165 | emit log("\n## assertGe(uint,uint)\n"); 166 | assertGe(uint256(0), 1); 167 | emit log("\n"); 168 | assertGe(uint256(0), 1, err); 169 | 170 | emit log("\n## assertGe(int,int)\n"); 171 | assertGe(-1, 0); 172 | emit log("\n"); 173 | assertGe(-1, 0, err); 174 | 175 | emit log("\n## assertGeDecimal(int,int,uint)\n"); 176 | assertGeDecimal(-2.0e18, -1.1e18, 18); 177 | emit log("\n"); 178 | assertGeDecimal(-2.0e18, -1.1e18, 18, err); 179 | 180 | emit log("\n## assertGeDecimal(uint,uint,uint)\n"); 181 | assertGeDecimal(uint256(1.0e18), 1.1e18, 18); 182 | emit log("\n"); 183 | assertGeDecimal(uint256(1.0e18), 1.1e18, 18, err); 184 | 185 | emit log("\n## assertLt(uint,uint)\n"); 186 | assertLt(uint256(0), 0); 187 | emit log("\n"); 188 | assertLt(uint256(0), 0, err); 189 | 190 | emit log("\n## assertLt(int,int)\n"); 191 | assertLt(-1, -1); 192 | emit log("\n"); 193 | assertLt(-1, -1, err); 194 | 195 | emit log("\n## assertLtDecimal(int,int,uint)\n"); 196 | assertLtDecimal(-1.0e18, -1.1e18, 18); 197 | emit log("\n"); 198 | assertLtDecimal(-1.0e18, -1.1e18, 18, err); 199 | 200 | emit log("\n## assertLtDecimal(uint,uint,uint)\n"); 201 | assertLtDecimal(uint256(2.0e18), 1.1e18, 18); 202 | emit log("\n"); 203 | assertLtDecimal(uint256(2.0e18), 1.1e18, 18, err); 204 | 205 | emit log("\n## assertLe(uint,uint)\n"); 206 | assertLe(uint256(1), 0); 207 | emit log("\n"); 208 | assertLe(uint256(1), 0, err); 209 | 210 | emit log("\n## assertLe(int,int)\n"); 211 | assertLe(0, -1); 212 | emit log("\n"); 213 | assertLe(0, -1, err); 214 | 215 | emit log("\n## assertLeDecimal(int,int,uint)\n"); 216 | assertLeDecimal(-1.0e18, -1.1e18, 18); 217 | emit log("\n"); 218 | assertLeDecimal(-1.0e18, -1.1e18, 18, err); 219 | 220 | emit log("\n## assertLeDecimal(uint,uint,uint)\n"); 221 | assertLeDecimal(uint256(2.0e18), 1.1e18, 18); 222 | emit log("\n"); 223 | assertLeDecimal(uint256(2.0e18), 1.1e18, 18, err); 224 | 225 | emit log("\n## assertEq(string,string)\n"); 226 | string memory s1 = "string 1"; 227 | string memory s2 = "string 2"; 228 | assertEq(s1, s2); 229 | emit log("\n"); 230 | assertEq(s1, s2, err); 231 | 232 | emit log("\n## assertEq0(bytes,bytes)\n"); 233 | assertEq0(hex"abcdef01", hex"abcdef02"); 234 | log("\n"); 235 | assertEq0(hex"abcdef01", hex"abcdef02", err); 236 | } 237 | } 238 | 239 | contract DemoTestWithSetUp { 240 | function setUp() public {} 241 | 242 | function test_pass() public pure {} 243 | } 244 | -------------------------------------------------------------------------------- /lib/forge-std/lib/ds-test/src/test.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | 8 | // This program is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU General Public License for more details. 12 | 13 | // You should have received a copy of the GNU General Public License 14 | // along with this program. If not, see . 15 | 16 | pragma solidity >=0.5.0; 17 | 18 | contract DSTest { 19 | event log(string); 20 | event logs(bytes); 21 | 22 | event log_address(address); 23 | event log_bytes32(bytes32); 24 | event log_int(int256); 25 | event log_uint(uint256); 26 | event log_bytes(bytes); 27 | event log_string(string); 28 | 29 | event log_named_address(string key, address val); 30 | event log_named_bytes32(string key, bytes32 val); 31 | event log_named_decimal_int(string key, int256 val, uint256 decimals); 32 | event log_named_decimal_uint(string key, uint256 val, uint256 decimals); 33 | event log_named_int(string key, int256 val); 34 | event log_named_uint(string key, uint256 val); 35 | event log_named_bytes(string key, bytes val); 36 | event log_named_string(string key, string val); 37 | 38 | bool public IS_TEST = true; 39 | bool private _failed; 40 | 41 | address constant HEVM_ADDRESS = 42 | address(bytes20(uint160(uint256(keccak256("hevm cheat code"))))); 43 | 44 | modifier mayRevert() { 45 | _; 46 | } 47 | modifier testopts(string memory) { 48 | _; 49 | } 50 | 51 | function failed() public returns (bool) { 52 | if (_failed) { 53 | return _failed; 54 | } else { 55 | bool globalFailed = false; 56 | if (hasHEVMContext()) { 57 | (, bytes memory retdata) = HEVM_ADDRESS.call( 58 | abi.encodePacked( 59 | bytes4(keccak256("load(address,bytes32)")), 60 | abi.encode(HEVM_ADDRESS, bytes32("failed")) 61 | ) 62 | ); 63 | globalFailed = abi.decode(retdata, (bool)); 64 | } 65 | return globalFailed; 66 | } 67 | } 68 | 69 | function fail() internal { 70 | if (hasHEVMContext()) { 71 | (bool status, ) = HEVM_ADDRESS.call( 72 | abi.encodePacked( 73 | bytes4(keccak256("store(address,bytes32,bytes32)")), 74 | abi.encode( 75 | HEVM_ADDRESS, 76 | bytes32("failed"), 77 | bytes32(uint256(0x01)) 78 | ) 79 | ) 80 | ); 81 | status; // Silence compiler warnings 82 | } 83 | _failed = true; 84 | } 85 | 86 | function hasHEVMContext() internal view returns (bool) { 87 | uint256 hevmCodeSize = 0; 88 | assembly { 89 | hevmCodeSize := extcodesize( 90 | 0x7109709ECfa91a80626fF3989D68f67F5b1DD12D 91 | ) 92 | } 93 | return hevmCodeSize > 0; 94 | } 95 | 96 | modifier logs_gas() { 97 | uint256 startGas = gasleft(); 98 | _; 99 | uint256 endGas = gasleft(); 100 | emit log_named_uint("gas", startGas - endGas); 101 | } 102 | 103 | function assertTrue(bool condition) internal { 104 | if (!condition) { 105 | emit log("Error: Assertion Failed"); 106 | fail(); 107 | } 108 | } 109 | 110 | function assertTrue(bool condition, string memory err) internal { 111 | if (!condition) { 112 | emit log_named_string("Error", err); 113 | assertTrue(condition); 114 | } 115 | } 116 | 117 | function assertEq(address a, address b) internal { 118 | if (a != b) { 119 | emit log("Error: a == b not satisfied [address]"); 120 | emit log_named_address(" Expected", b); 121 | emit log_named_address(" Actual", a); 122 | fail(); 123 | } 124 | } 125 | 126 | function assertEq( 127 | address a, 128 | address b, 129 | string memory err 130 | ) internal { 131 | if (a != b) { 132 | emit log_named_string("Error", err); 133 | assertEq(a, b); 134 | } 135 | } 136 | 137 | function assertEq(bytes32 a, bytes32 b) internal { 138 | if (a != b) { 139 | emit log("Error: a == b not satisfied [bytes32]"); 140 | emit log_named_bytes32(" Expected", b); 141 | emit log_named_bytes32(" Actual", a); 142 | fail(); 143 | } 144 | } 145 | 146 | function assertEq( 147 | bytes32 a, 148 | bytes32 b, 149 | string memory err 150 | ) internal { 151 | if (a != b) { 152 | emit log_named_string("Error", err); 153 | assertEq(a, b); 154 | } 155 | } 156 | 157 | function assertEq32(bytes32 a, bytes32 b) internal { 158 | assertEq(a, b); 159 | } 160 | 161 | function assertEq32( 162 | bytes32 a, 163 | bytes32 b, 164 | string memory err 165 | ) internal { 166 | assertEq(a, b, err); 167 | } 168 | 169 | function assertEq(int256 a, int256 b) internal { 170 | if (a != b) { 171 | emit log("Error: a == b not satisfied [int]"); 172 | emit log_named_int(" Expected", b); 173 | emit log_named_int(" Actual", a); 174 | fail(); 175 | } 176 | } 177 | 178 | function assertEq( 179 | int256 a, 180 | int256 b, 181 | string memory err 182 | ) internal { 183 | if (a != b) { 184 | emit log_named_string("Error", err); 185 | assertEq(a, b); 186 | } 187 | } 188 | 189 | function assertEq(uint256 a, uint256 b) internal { 190 | if (a != b) { 191 | emit log("Error: a == b not satisfied [uint]"); 192 | emit log_named_uint(" Expected", b); 193 | emit log_named_uint(" Actual", a); 194 | fail(); 195 | } 196 | } 197 | 198 | function assertEq( 199 | uint256 a, 200 | uint256 b, 201 | string memory err 202 | ) internal { 203 | if (a != b) { 204 | emit log_named_string("Error", err); 205 | assertEq(a, b); 206 | } 207 | } 208 | 209 | function assertEqDecimal( 210 | int256 a, 211 | int256 b, 212 | uint256 decimals 213 | ) internal { 214 | if (a != b) { 215 | emit log("Error: a == b not satisfied [decimal int]"); 216 | emit log_named_decimal_int(" Expected", b, decimals); 217 | emit log_named_decimal_int(" Actual", a, decimals); 218 | fail(); 219 | } 220 | } 221 | 222 | function assertEqDecimal( 223 | int256 a, 224 | int256 b, 225 | uint256 decimals, 226 | string memory err 227 | ) internal { 228 | if (a != b) { 229 | emit log_named_string("Error", err); 230 | assertEqDecimal(a, b, decimals); 231 | } 232 | } 233 | 234 | function assertEqDecimal( 235 | uint256 a, 236 | uint256 b, 237 | uint256 decimals 238 | ) internal { 239 | if (a != b) { 240 | emit log("Error: a == b not satisfied [decimal uint]"); 241 | emit log_named_decimal_uint(" Expected", b, decimals); 242 | emit log_named_decimal_uint(" Actual", a, decimals); 243 | fail(); 244 | } 245 | } 246 | 247 | function assertEqDecimal( 248 | uint256 a, 249 | uint256 b, 250 | uint256 decimals, 251 | string memory err 252 | ) internal { 253 | if (a != b) { 254 | emit log_named_string("Error", err); 255 | assertEqDecimal(a, b, decimals); 256 | } 257 | } 258 | 259 | function assertGt(uint256 a, uint256 b) internal { 260 | if (a <= b) { 261 | emit log("Error: a > b not satisfied [uint]"); 262 | emit log_named_uint(" Value a", a); 263 | emit log_named_uint(" Value b", b); 264 | fail(); 265 | } 266 | } 267 | 268 | function assertGt( 269 | uint256 a, 270 | uint256 b, 271 | string memory err 272 | ) internal { 273 | if (a <= b) { 274 | emit log_named_string("Error", err); 275 | assertGt(a, b); 276 | } 277 | } 278 | 279 | function assertGt(int256 a, int256 b) internal { 280 | if (a <= b) { 281 | emit log("Error: a > b not satisfied [int]"); 282 | emit log_named_int(" Value a", a); 283 | emit log_named_int(" Value b", b); 284 | fail(); 285 | } 286 | } 287 | 288 | function assertGt( 289 | int256 a, 290 | int256 b, 291 | string memory err 292 | ) internal { 293 | if (a <= b) { 294 | emit log_named_string("Error", err); 295 | assertGt(a, b); 296 | } 297 | } 298 | 299 | function assertGtDecimal( 300 | int256 a, 301 | int256 b, 302 | uint256 decimals 303 | ) internal { 304 | if (a <= b) { 305 | emit log("Error: a > b not satisfied [decimal int]"); 306 | emit log_named_decimal_int(" Value a", a, decimals); 307 | emit log_named_decimal_int(" Value b", b, decimals); 308 | fail(); 309 | } 310 | } 311 | 312 | function assertGtDecimal( 313 | int256 a, 314 | int256 b, 315 | uint256 decimals, 316 | string memory err 317 | ) internal { 318 | if (a <= b) { 319 | emit log_named_string("Error", err); 320 | assertGtDecimal(a, b, decimals); 321 | } 322 | } 323 | 324 | function assertGtDecimal( 325 | uint256 a, 326 | uint256 b, 327 | uint256 decimals 328 | ) internal { 329 | if (a <= b) { 330 | emit log("Error: a > b not satisfied [decimal uint]"); 331 | emit log_named_decimal_uint(" Value a", a, decimals); 332 | emit log_named_decimal_uint(" Value b", b, decimals); 333 | fail(); 334 | } 335 | } 336 | 337 | function assertGtDecimal( 338 | uint256 a, 339 | uint256 b, 340 | uint256 decimals, 341 | string memory err 342 | ) internal { 343 | if (a <= b) { 344 | emit log_named_string("Error", err); 345 | assertGtDecimal(a, b, decimals); 346 | } 347 | } 348 | 349 | function assertGe(uint256 a, uint256 b) internal { 350 | if (a < b) { 351 | emit log("Error: a >= b not satisfied [uint]"); 352 | emit log_named_uint(" Value a", a); 353 | emit log_named_uint(" Value b", b); 354 | fail(); 355 | } 356 | } 357 | 358 | function assertGe( 359 | uint256 a, 360 | uint256 b, 361 | string memory err 362 | ) internal { 363 | if (a < b) { 364 | emit log_named_string("Error", err); 365 | assertGe(a, b); 366 | } 367 | } 368 | 369 | function assertGe(int256 a, int256 b) internal { 370 | if (a < b) { 371 | emit log("Error: a >= b not satisfied [int]"); 372 | emit log_named_int(" Value a", a); 373 | emit log_named_int(" Value b", b); 374 | fail(); 375 | } 376 | } 377 | 378 | function assertGe( 379 | int256 a, 380 | int256 b, 381 | string memory err 382 | ) internal { 383 | if (a < b) { 384 | emit log_named_string("Error", err); 385 | assertGe(a, b); 386 | } 387 | } 388 | 389 | function assertGeDecimal( 390 | int256 a, 391 | int256 b, 392 | uint256 decimals 393 | ) internal { 394 | if (a < b) { 395 | emit log("Error: a >= b not satisfied [decimal int]"); 396 | emit log_named_decimal_int(" Value a", a, decimals); 397 | emit log_named_decimal_int(" Value b", b, decimals); 398 | fail(); 399 | } 400 | } 401 | 402 | function assertGeDecimal( 403 | int256 a, 404 | int256 b, 405 | uint256 decimals, 406 | string memory err 407 | ) internal { 408 | if (a < b) { 409 | emit log_named_string("Error", err); 410 | assertGeDecimal(a, b, decimals); 411 | } 412 | } 413 | 414 | function assertGeDecimal( 415 | uint256 a, 416 | uint256 b, 417 | uint256 decimals 418 | ) internal { 419 | if (a < b) { 420 | emit log("Error: a >= b not satisfied [decimal uint]"); 421 | emit log_named_decimal_uint(" Value a", a, decimals); 422 | emit log_named_decimal_uint(" Value b", b, decimals); 423 | fail(); 424 | } 425 | } 426 | 427 | function assertGeDecimal( 428 | uint256 a, 429 | uint256 b, 430 | uint256 decimals, 431 | string memory err 432 | ) internal { 433 | if (a < b) { 434 | emit log_named_string("Error", err); 435 | assertGeDecimal(a, b, decimals); 436 | } 437 | } 438 | 439 | function assertLt(uint256 a, uint256 b) internal { 440 | if (a >= b) { 441 | emit log("Error: a < b not satisfied [uint]"); 442 | emit log_named_uint(" Value a", a); 443 | emit log_named_uint(" Value b", b); 444 | fail(); 445 | } 446 | } 447 | 448 | function assertLt( 449 | uint256 a, 450 | uint256 b, 451 | string memory err 452 | ) internal { 453 | if (a >= b) { 454 | emit log_named_string("Error", err); 455 | assertLt(a, b); 456 | } 457 | } 458 | 459 | function assertLt(int256 a, int256 b) internal { 460 | if (a >= b) { 461 | emit log("Error: a < b not satisfied [int]"); 462 | emit log_named_int(" Value a", a); 463 | emit log_named_int(" Value b", b); 464 | fail(); 465 | } 466 | } 467 | 468 | function assertLt( 469 | int256 a, 470 | int256 b, 471 | string memory err 472 | ) internal { 473 | if (a >= b) { 474 | emit log_named_string("Error", err); 475 | assertLt(a, b); 476 | } 477 | } 478 | 479 | function assertLtDecimal( 480 | int256 a, 481 | int256 b, 482 | uint256 decimals 483 | ) internal { 484 | if (a >= b) { 485 | emit log("Error: a < b not satisfied [decimal int]"); 486 | emit log_named_decimal_int(" Value a", a, decimals); 487 | emit log_named_decimal_int(" Value b", b, decimals); 488 | fail(); 489 | } 490 | } 491 | 492 | function assertLtDecimal( 493 | int256 a, 494 | int256 b, 495 | uint256 decimals, 496 | string memory err 497 | ) internal { 498 | if (a >= b) { 499 | emit log_named_string("Error", err); 500 | assertLtDecimal(a, b, decimals); 501 | } 502 | } 503 | 504 | function assertLtDecimal( 505 | uint256 a, 506 | uint256 b, 507 | uint256 decimals 508 | ) internal { 509 | if (a >= b) { 510 | emit log("Error: a < b not satisfied [decimal uint]"); 511 | emit log_named_decimal_uint(" Value a", a, decimals); 512 | emit log_named_decimal_uint(" Value b", b, decimals); 513 | fail(); 514 | } 515 | } 516 | 517 | function assertLtDecimal( 518 | uint256 a, 519 | uint256 b, 520 | uint256 decimals, 521 | string memory err 522 | ) internal { 523 | if (a >= b) { 524 | emit log_named_string("Error", err); 525 | assertLtDecimal(a, b, decimals); 526 | } 527 | } 528 | 529 | function assertLe(uint256 a, uint256 b) internal { 530 | if (a > b) { 531 | emit log("Error: a <= b not satisfied [uint]"); 532 | emit log_named_uint(" Value a", a); 533 | emit log_named_uint(" Value b", b); 534 | fail(); 535 | } 536 | } 537 | 538 | function assertLe( 539 | uint256 a, 540 | uint256 b, 541 | string memory err 542 | ) internal { 543 | if (a > b) { 544 | emit log_named_string("Error", err); 545 | assertLe(a, b); 546 | } 547 | } 548 | 549 | function assertLe(int256 a, int256 b) internal { 550 | if (a > b) { 551 | emit log("Error: a <= b not satisfied [int]"); 552 | emit log_named_int(" Value a", a); 553 | emit log_named_int(" Value b", b); 554 | fail(); 555 | } 556 | } 557 | 558 | function assertLe( 559 | int256 a, 560 | int256 b, 561 | string memory err 562 | ) internal { 563 | if (a > b) { 564 | emit log_named_string("Error", err); 565 | assertLe(a, b); 566 | } 567 | } 568 | 569 | function assertLeDecimal( 570 | int256 a, 571 | int256 b, 572 | uint256 decimals 573 | ) internal { 574 | if (a > b) { 575 | emit log("Error: a <= b not satisfied [decimal int]"); 576 | emit log_named_decimal_int(" Value a", a, decimals); 577 | emit log_named_decimal_int(" Value b", b, decimals); 578 | fail(); 579 | } 580 | } 581 | 582 | function assertLeDecimal( 583 | int256 a, 584 | int256 b, 585 | uint256 decimals, 586 | string memory err 587 | ) internal { 588 | if (a > b) { 589 | emit log_named_string("Error", err); 590 | assertLeDecimal(a, b, decimals); 591 | } 592 | } 593 | 594 | function assertLeDecimal( 595 | uint256 a, 596 | uint256 b, 597 | uint256 decimals 598 | ) internal { 599 | if (a > b) { 600 | emit log("Error: a <= b not satisfied [decimal uint]"); 601 | emit log_named_decimal_uint(" Value a", a, decimals); 602 | emit log_named_decimal_uint(" Value b", b, decimals); 603 | fail(); 604 | } 605 | } 606 | 607 | function assertLeDecimal( 608 | uint256 a, 609 | uint256 b, 610 | uint256 decimals, 611 | string memory err 612 | ) internal { 613 | if (a > b) { 614 | emit log_named_string("Error", err); 615 | assertGeDecimal(a, b, decimals); 616 | } 617 | } 618 | 619 | function assertEq(string memory a, string memory b) internal { 620 | if (keccak256(abi.encodePacked(a)) != keccak256(abi.encodePacked(b))) { 621 | emit log("Error: a == b not satisfied [string]"); 622 | emit log_named_string(" Expected", b); 623 | emit log_named_string(" Actual", a); 624 | fail(); 625 | } 626 | } 627 | 628 | function assertEq( 629 | string memory a, 630 | string memory b, 631 | string memory err 632 | ) internal { 633 | if (keccak256(abi.encodePacked(a)) != keccak256(abi.encodePacked(b))) { 634 | emit log_named_string("Error", err); 635 | assertEq(a, b); 636 | } 637 | } 638 | 639 | function checkEq0(bytes memory a, bytes memory b) 640 | internal 641 | pure 642 | returns (bool ok) 643 | { 644 | ok = true; 645 | if (a.length == b.length) { 646 | for (uint256 i = 0; i < a.length; i++) { 647 | if (a[i] != b[i]) { 648 | ok = false; 649 | } 650 | } 651 | } else { 652 | ok = false; 653 | } 654 | } 655 | 656 | function assertEq0(bytes memory a, bytes memory b) internal { 657 | if (!checkEq0(a, b)) { 658 | emit log("Error: a == b not satisfied [bytes]"); 659 | emit log_named_bytes(" Expected", b); 660 | emit log_named_bytes(" Actual", a); 661 | fail(); 662 | } 663 | } 664 | 665 | function assertEq0( 666 | bytes memory a, 667 | bytes memory b, 668 | string memory err 669 | ) internal { 670 | if (!checkEq0(a, b)) { 671 | emit log_named_string("Error", err); 672 | assertEq0(a, b); 673 | } 674 | } 675 | } 676 | -------------------------------------------------------------------------------- /lib/forge-std/src/Test.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Unlicense 2 | pragma solidity >=0.6.0 <0.9.0; 3 | 4 | import "./Vm.sol"; 5 | import "ds-test/test.sol"; 6 | import "./console.sol"; 7 | import "./console2.sol"; 8 | 9 | // Wrappers around Cheatcodes to avoid footguns 10 | abstract contract Test is DSTest { 11 | using stdStorage for StdStorage; 12 | 13 | uint256 private constant UINT256_MAX = 14 | 115792089237316195423570985008687907853269984665640564039457584007913129639935; 15 | 16 | event WARNING_Deprecated(string msg); 17 | 18 | Vm public constant vm = Vm(HEVM_ADDRESS); 19 | StdStorage internal stdstore; 20 | 21 | /*////////////////////////////////////////////////////////////////////////// 22 | STD-CHEATS 23 | //////////////////////////////////////////////////////////////////////////*/ 24 | 25 | // Skip forward or rewind time by the specified number of seconds 26 | function skip(uint256 time) public { 27 | vm.warp(block.timestamp + time); 28 | } 29 | 30 | function rewind(uint256 time) public { 31 | vm.warp(block.timestamp - time); 32 | } 33 | 34 | // Setup a prank from an address that has some ether 35 | function hoax(address who) public { 36 | vm.deal(who, 1 << 128); 37 | vm.prank(who); 38 | } 39 | 40 | function hoax(address who, uint256 give) public { 41 | vm.deal(who, give); 42 | vm.prank(who); 43 | } 44 | 45 | function hoax(address who, address origin) public { 46 | vm.deal(who, 1 << 128); 47 | vm.prank(who, origin); 48 | } 49 | 50 | function hoax( 51 | address who, 52 | address origin, 53 | uint256 give 54 | ) public { 55 | vm.deal(who, give); 56 | vm.prank(who, origin); 57 | } 58 | 59 | // Start perpetual prank from an address that has some ether 60 | function startHoax(address who) public { 61 | vm.deal(who, 1 << 128); 62 | vm.startPrank(who); 63 | } 64 | 65 | function startHoax(address who, uint256 give) public { 66 | vm.deal(who, give); 67 | vm.startPrank(who); 68 | } 69 | 70 | // Start perpetual prank from an address that has some ether 71 | // tx.origin is set to the origin parameter 72 | function startHoax(address who, address origin) public { 73 | vm.deal(who, 1 << 128); 74 | vm.startPrank(who, origin); 75 | } 76 | 77 | function startHoax( 78 | address who, 79 | address origin, 80 | uint256 give 81 | ) public { 82 | vm.deal(who, give); 83 | vm.startPrank(who, origin); 84 | } 85 | 86 | function changePrank(address who) internal { 87 | vm.stopPrank(); 88 | vm.startPrank(who); 89 | } 90 | 91 | // DEPRECATED: Use `deal` instead 92 | function tip( 93 | address token, 94 | address to, 95 | uint256 give 96 | ) public { 97 | emit WARNING_Deprecated( 98 | "The `tip` stdcheat has been deprecated. Use `deal` instead." 99 | ); 100 | stdstore.target(token).sig(0x70a08231).with_key(to).checked_write(give); 101 | } 102 | 103 | // The same as Hevm's `deal` 104 | // Use the alternative signature for ERC20 tokens 105 | function deal(address to, uint256 give) public { 106 | vm.deal(to, give); 107 | } 108 | 109 | // Set the balance of an account for any ERC20 token 110 | // Use the alternative signature to update `totalSupply` 111 | function deal( 112 | address token, 113 | address to, 114 | uint256 give 115 | ) public { 116 | deal(token, to, give, false); 117 | } 118 | 119 | function deal( 120 | address token, 121 | address to, 122 | uint256 give, 123 | bool adjust 124 | ) public { 125 | // get current balance 126 | (, bytes memory balData) = token.call( 127 | abi.encodeWithSelector(0x70a08231, to) 128 | ); 129 | uint256 prevBal = abi.decode(balData, (uint256)); 130 | 131 | // update balance 132 | stdstore.target(token).sig(0x70a08231).with_key(to).checked_write(give); 133 | 134 | // update total supply 135 | if (adjust) { 136 | (, bytes memory totSupData) = token.call( 137 | abi.encodeWithSelector(0x18160ddd) 138 | ); 139 | uint256 totSup = abi.decode(totSupData, (uint256)); 140 | if (give < prevBal) { 141 | totSup -= (prevBal - give); 142 | } else { 143 | totSup += (give - prevBal); 144 | } 145 | stdstore.target(token).sig(0x18160ddd).checked_write(totSup); 146 | } 147 | } 148 | 149 | function bound( 150 | uint256 x, 151 | uint256 min, 152 | uint256 max 153 | ) public returns (uint256 result) { 154 | require( 155 | min <= max, 156 | "Test bound(uint256,uint256,uint256): Max is less than min." 157 | ); 158 | 159 | uint256 size = max - min; 160 | 161 | if (size == 0) { 162 | result = min; 163 | } else if (size == UINT256_MAX) { 164 | result = x; 165 | } else { 166 | ++size; // make `max` inclusive 167 | uint256 mod = x % size; 168 | result = min + mod; 169 | } 170 | 171 | emit log_named_uint("Bound Result", result); 172 | } 173 | 174 | // Deploy a contract by fetching the contract bytecode from 175 | // the artifacts directory 176 | // e.g. `deployCode(code, abi.encode(arg1,arg2,arg3))` 177 | function deployCode(string memory what, bytes memory args) 178 | public 179 | returns (address addr) 180 | { 181 | bytes memory bytecode = abi.encodePacked(vm.getCode(what), args); 182 | /// @solidity memory-safe-assembly 183 | assembly { 184 | addr := create(0, add(bytecode, 0x20), mload(bytecode)) 185 | } 186 | 187 | require( 188 | addr != address(0), 189 | "Test deployCode(string,bytes): Deployment failed." 190 | ); 191 | } 192 | 193 | function deployCode(string memory what) public returns (address addr) { 194 | bytes memory bytecode = vm.getCode(what); 195 | /// @solidity memory-safe-assembly 196 | assembly { 197 | addr := create(0, add(bytecode, 0x20), mload(bytecode)) 198 | } 199 | 200 | require( 201 | addr != address(0), 202 | "Test deployCode(string): Deployment failed." 203 | ); 204 | } 205 | 206 | /*////////////////////////////////////////////////////////////////////////// 207 | STD-ASSERTIONS 208 | //////////////////////////////////////////////////////////////////////////*/ 209 | 210 | function fail(string memory err) internal virtual { 211 | emit log_named_string("Error", err); 212 | fail(); 213 | } 214 | 215 | function assertFalse(bool data) internal virtual { 216 | assertTrue(!data); 217 | } 218 | 219 | function assertFalse(bool data, string memory err) internal virtual { 220 | assertTrue(!data, err); 221 | } 222 | 223 | function assertEq(bool a, bool b) internal { 224 | if (a != b) { 225 | emit log("Error: a == b not satisfied [bool]"); 226 | emit log_named_string(" Expected", b ? "true" : "false"); 227 | emit log_named_string(" Actual", a ? "true" : "false"); 228 | fail(); 229 | } 230 | } 231 | 232 | function assertEq( 233 | bool a, 234 | bool b, 235 | string memory err 236 | ) internal { 237 | if (a != b) { 238 | emit log_named_string("Error", err); 239 | assertEq(a, b); 240 | } 241 | } 242 | 243 | function assertEq(bytes memory a, bytes memory b) internal { 244 | if (keccak256(a) != keccak256(b)) { 245 | emit log("Error: a == b not satisfied [bytes]"); 246 | emit log_named_bytes(" Expected", b); 247 | emit log_named_bytes(" Actual", a); 248 | fail(); 249 | } 250 | } 251 | 252 | function assertEq( 253 | bytes memory a, 254 | bytes memory b, 255 | string memory err 256 | ) internal { 257 | if (keccak256(a) != keccak256(b)) { 258 | emit log_named_string("Error", err); 259 | assertEq(a, b); 260 | } 261 | } 262 | 263 | function assertApproxEqAbs( 264 | uint256 a, 265 | uint256 b, 266 | uint256 maxDelta 267 | ) internal virtual { 268 | uint256 delta = stdMath.delta(a, b); 269 | 270 | if (delta > maxDelta) { 271 | emit log("Error: a ~= b not satisfied [uint]"); 272 | emit log_named_uint(" Expected", b); 273 | emit log_named_uint(" Actual", a); 274 | emit log_named_uint(" Max Delta", maxDelta); 275 | emit log_named_uint(" Delta", delta); 276 | fail(); 277 | } 278 | } 279 | 280 | function assertApproxEqAbs( 281 | uint256 a, 282 | uint256 b, 283 | uint256 maxDelta, 284 | string memory err 285 | ) internal virtual { 286 | uint256 delta = stdMath.delta(a, b); 287 | 288 | if (delta > maxDelta) { 289 | emit log_named_string("Error", err); 290 | assertApproxEqAbs(a, b, maxDelta); 291 | } 292 | } 293 | 294 | function assertApproxEqAbs( 295 | int256 a, 296 | int256 b, 297 | uint256 maxDelta 298 | ) internal virtual { 299 | uint256 delta = stdMath.delta(a, b); 300 | 301 | if (delta > maxDelta) { 302 | emit log("Error: a ~= b not satisfied [int]"); 303 | emit log_named_int(" Expected", b); 304 | emit log_named_int(" Actual", a); 305 | emit log_named_uint(" Max Delta", maxDelta); 306 | emit log_named_uint(" Delta", delta); 307 | fail(); 308 | } 309 | } 310 | 311 | function assertApproxEqAbs( 312 | int256 a, 313 | int256 b, 314 | uint256 maxDelta, 315 | string memory err 316 | ) internal virtual { 317 | uint256 delta = stdMath.delta(a, b); 318 | 319 | if (delta > maxDelta) { 320 | emit log_named_string("Error", err); 321 | assertApproxEqAbs(a, b, maxDelta); 322 | } 323 | } 324 | 325 | function assertApproxEqRel( 326 | uint256 a, 327 | uint256 b, 328 | uint256 maxPercentDelta // An 18 decimal fixed point number, where 1e18 == 100% 329 | ) internal virtual { 330 | if (b == 0) return assertEq(a, b); // If the expected is 0, actual must be too. 331 | 332 | uint256 percentDelta = stdMath.percentDelta(a, b); 333 | 334 | if (percentDelta > maxPercentDelta) { 335 | emit log("Error: a ~= b not satisfied [uint]"); 336 | emit log_named_uint(" Expected", b); 337 | emit log_named_uint(" Actual", a); 338 | emit log_named_decimal_uint(" Max % Delta", maxPercentDelta, 18); 339 | emit log_named_decimal_uint(" % Delta", percentDelta, 18); 340 | fail(); 341 | } 342 | } 343 | 344 | function assertApproxEqRel( 345 | uint256 a, 346 | uint256 b, 347 | uint256 maxPercentDelta, // An 18 decimal fixed point number, where 1e18 == 100% 348 | string memory err 349 | ) internal virtual { 350 | if (b == 0) return assertEq(a, b); // If the expected is 0, actual must be too. 351 | 352 | uint256 percentDelta = stdMath.percentDelta(a, b); 353 | 354 | if (percentDelta > maxPercentDelta) { 355 | emit log_named_string("Error", err); 356 | assertApproxEqRel(a, b, maxPercentDelta); 357 | } 358 | } 359 | 360 | function assertApproxEqRel( 361 | int256 a, 362 | int256 b, 363 | uint256 maxPercentDelta 364 | ) internal virtual { 365 | if (b == 0) return assertEq(a, b); // If the expected is 0, actual must be too. 366 | 367 | uint256 percentDelta = stdMath.percentDelta(a, b); 368 | 369 | if (percentDelta > maxPercentDelta) { 370 | emit log("Error: a ~= b not satisfied [int]"); 371 | emit log_named_int(" Expected", b); 372 | emit log_named_int(" Actual", a); 373 | emit log_named_decimal_uint(" Max % Delta", maxPercentDelta, 18); 374 | emit log_named_decimal_uint(" % Delta", percentDelta, 18); 375 | fail(); 376 | } 377 | } 378 | 379 | function assertApproxEqRel( 380 | int256 a, 381 | int256 b, 382 | uint256 maxPercentDelta, 383 | string memory err 384 | ) internal virtual { 385 | if (b == 0) return assertEq(a, b); // If the expected is 0, actual must be too. 386 | 387 | uint256 percentDelta = stdMath.percentDelta(a, b); 388 | 389 | if (percentDelta > maxPercentDelta) { 390 | emit log_named_string("Error", err); 391 | assertApproxEqRel(a, b, maxPercentDelta); 392 | } 393 | } 394 | } 395 | 396 | /*////////////////////////////////////////////////////////////////////////// 397 | STD-ERRORS 398 | //////////////////////////////////////////////////////////////////////////*/ 399 | 400 | library stdError { 401 | bytes public constant assertionError = 402 | abi.encodeWithSignature("Panic(uint256)", 0x01); 403 | bytes public constant arithmeticError = 404 | abi.encodeWithSignature("Panic(uint256)", 0x11); 405 | bytes public constant divisionError = 406 | abi.encodeWithSignature("Panic(uint256)", 0x12); 407 | bytes public constant enumConversionError = 408 | abi.encodeWithSignature("Panic(uint256)", 0x21); 409 | bytes public constant encodeStorageError = 410 | abi.encodeWithSignature("Panic(uint256)", 0x22); 411 | bytes public constant popError = 412 | abi.encodeWithSignature("Panic(uint256)", 0x31); 413 | bytes public constant indexOOBError = 414 | abi.encodeWithSignature("Panic(uint256)", 0x32); 415 | bytes public constant memOverflowError = 416 | abi.encodeWithSignature("Panic(uint256)", 0x41); 417 | bytes public constant zeroVarError = 418 | abi.encodeWithSignature("Panic(uint256)", 0x51); 419 | // DEPRECATED: Use Hevm's `expectRevert` without any arguments instead 420 | bytes public constant lowLevelError = bytes(""); // `0x` 421 | } 422 | 423 | /*////////////////////////////////////////////////////////////////////////// 424 | STD-STORAGE 425 | //////////////////////////////////////////////////////////////////////////*/ 426 | 427 | struct StdStorage { 428 | mapping(address => mapping(bytes4 => mapping(bytes32 => uint256))) slots; 429 | mapping(address => mapping(bytes4 => mapping(bytes32 => bool))) finds; 430 | bytes32[] _keys; 431 | bytes4 _sig; 432 | uint256 _depth; 433 | address _target; 434 | bytes32 _set; 435 | } 436 | 437 | library stdStorage { 438 | event SlotFound(address who, bytes4 fsig, bytes32 keysHash, uint256 slot); 439 | event WARNING_UninitedSlot(address who, uint256 slot); 440 | 441 | uint256 private constant UINT256_MAX = 442 | 115792089237316195423570985008687907853269984665640564039457584007913129639935; 443 | int256 private constant INT256_MAX = 444 | 57896044618658097711785492504343953926634992332820282019728792003956564819967; 445 | 446 | Vm private constant vm_std_store = 447 | Vm(address(uint160(uint256(keccak256("hevm cheat code"))))); 448 | 449 | function sigs(string memory sigStr) internal pure returns (bytes4) { 450 | return bytes4(keccak256(bytes(sigStr))); 451 | } 452 | 453 | /// @notice find an arbitrary storage slot given a function sig, input data, address of the contract and a value to check against 454 | // slot complexity: 455 | // if flat, will be bytes32(uint256(uint)); 456 | // if map, will be keccak256(abi.encode(key, uint(slot))); 457 | // if deep map, will be keccak256(abi.encode(key1, keccak256(abi.encode(key0, uint(slot))))); 458 | // if map struct, will be bytes32(uint256(keccak256(abi.encode(key1, keccak256(abi.encode(key0, uint(slot)))))) + structFieldDepth); 459 | function find(StdStorage storage self) internal returns (uint256) { 460 | address who = self._target; 461 | bytes4 fsig = self._sig; 462 | uint256 field_depth = self._depth; 463 | bytes32[] memory ins = self._keys; 464 | 465 | // calldata to test against 466 | if ( 467 | self.finds[who][fsig][keccak256(abi.encodePacked(ins, field_depth))] 468 | ) { 469 | return 470 | self.slots[who][fsig][ 471 | keccak256(abi.encodePacked(ins, field_depth)) 472 | ]; 473 | } 474 | bytes memory cald = abi.encodePacked(fsig, flatten(ins)); 475 | vm_std_store.record(); 476 | bytes32 fdat; 477 | { 478 | (, bytes memory rdat) = who.staticcall(cald); 479 | fdat = bytesToBytes32(rdat, 32 * field_depth); 480 | } 481 | 482 | (bytes32[] memory reads, ) = vm_std_store.accesses(address(who)); 483 | if (reads.length == 1) { 484 | bytes32 curr = vm_std_store.load(who, reads[0]); 485 | if (curr == bytes32(0)) { 486 | emit WARNING_UninitedSlot(who, uint256(reads[0])); 487 | } 488 | if (fdat != curr) { 489 | require( 490 | false, 491 | "stdStorage find(StdStorage): Packed slot. This would cause dangerous overwriting and currently isnt supported" 492 | ); 493 | } 494 | emit SlotFound( 495 | who, 496 | fsig, 497 | keccak256(abi.encodePacked(ins, field_depth)), 498 | uint256(reads[0]) 499 | ); 500 | self.slots[who][fsig][ 501 | keccak256(abi.encodePacked(ins, field_depth)) 502 | ] = uint256(reads[0]); 503 | self.finds[who][fsig][ 504 | keccak256(abi.encodePacked(ins, field_depth)) 505 | ] = true; 506 | } else if (reads.length > 1) { 507 | for (uint256 i = 0; i < reads.length; i++) { 508 | bytes32 prev = vm_std_store.load(who, reads[i]); 509 | if (prev == bytes32(0)) { 510 | emit WARNING_UninitedSlot(who, uint256(reads[i])); 511 | } 512 | // store 513 | vm_std_store.store(who, reads[i], bytes32(hex"1337")); 514 | bool success; 515 | bytes memory rdat; 516 | { 517 | (success, rdat) = who.staticcall(cald); 518 | fdat = bytesToBytes32(rdat, 32 * field_depth); 519 | } 520 | 521 | if (success && fdat == bytes32(hex"1337")) { 522 | // we found which of the slots is the actual one 523 | emit SlotFound( 524 | who, 525 | fsig, 526 | keccak256(abi.encodePacked(ins, field_depth)), 527 | uint256(reads[i]) 528 | ); 529 | self.slots[who][fsig][ 530 | keccak256(abi.encodePacked(ins, field_depth)) 531 | ] = uint256(reads[i]); 532 | self.finds[who][fsig][ 533 | keccak256(abi.encodePacked(ins, field_depth)) 534 | ] = true; 535 | vm_std_store.store(who, reads[i], prev); 536 | break; 537 | } 538 | vm_std_store.store(who, reads[i], prev); 539 | } 540 | } else { 541 | require( 542 | false, 543 | "stdStorage find(StdStorage): No storage use detected for target." 544 | ); 545 | } 546 | 547 | require( 548 | self.finds[who][fsig][ 549 | keccak256(abi.encodePacked(ins, field_depth)) 550 | ], 551 | "stdStorage find(StdStorage): Slot(s) not found." 552 | ); 553 | 554 | delete self._target; 555 | delete self._sig; 556 | delete self._keys; 557 | delete self._depth; 558 | 559 | return 560 | self.slots[who][fsig][ 561 | keccak256(abi.encodePacked(ins, field_depth)) 562 | ]; 563 | } 564 | 565 | function target(StdStorage storage self, address _target) 566 | internal 567 | returns (StdStorage storage) 568 | { 569 | self._target = _target; 570 | return self; 571 | } 572 | 573 | function sig(StdStorage storage self, bytes4 _sig) 574 | internal 575 | returns (StdStorage storage) 576 | { 577 | self._sig = _sig; 578 | return self; 579 | } 580 | 581 | function sig(StdStorage storage self, string memory _sig) 582 | internal 583 | returns (StdStorage storage) 584 | { 585 | self._sig = sigs(_sig); 586 | return self; 587 | } 588 | 589 | function with_key(StdStorage storage self, address who) 590 | internal 591 | returns (StdStorage storage) 592 | { 593 | self._keys.push(bytes32(uint256(uint160(who)))); 594 | return self; 595 | } 596 | 597 | function with_key(StdStorage storage self, uint256 amt) 598 | internal 599 | returns (StdStorage storage) 600 | { 601 | self._keys.push(bytes32(amt)); 602 | return self; 603 | } 604 | 605 | function with_key(StdStorage storage self, bytes32 key) 606 | internal 607 | returns (StdStorage storage) 608 | { 609 | self._keys.push(key); 610 | return self; 611 | } 612 | 613 | function depth(StdStorage storage self, uint256 _depth) 614 | internal 615 | returns (StdStorage storage) 616 | { 617 | self._depth = _depth; 618 | return self; 619 | } 620 | 621 | function checked_write(StdStorage storage self, address who) internal { 622 | checked_write(self, bytes32(uint256(uint160(who)))); 623 | } 624 | 625 | function checked_write(StdStorage storage self, uint256 amt) internal { 626 | checked_write(self, bytes32(amt)); 627 | } 628 | 629 | function checked_write(StdStorage storage self, bool write) internal { 630 | bytes32 t; 631 | /// @solidity memory-safe-assembly 632 | assembly { 633 | t := write 634 | } 635 | checked_write(self, t); 636 | } 637 | 638 | function checked_write(StdStorage storage self, bytes32 set) internal { 639 | address who = self._target; 640 | bytes4 fsig = self._sig; 641 | uint256 field_depth = self._depth; 642 | bytes32[] memory ins = self._keys; 643 | 644 | bytes memory cald = abi.encodePacked(fsig, flatten(ins)); 645 | if ( 646 | !self.finds[who][fsig][ 647 | keccak256(abi.encodePacked(ins, field_depth)) 648 | ] 649 | ) { 650 | find(self); 651 | } 652 | bytes32 slot = bytes32( 653 | self.slots[who][fsig][keccak256(abi.encodePacked(ins, field_depth))] 654 | ); 655 | 656 | bytes32 fdat; 657 | { 658 | (, bytes memory rdat) = who.staticcall(cald); 659 | fdat = bytesToBytes32(rdat, 32 * field_depth); 660 | } 661 | bytes32 curr = vm_std_store.load(who, slot); 662 | 663 | if (fdat != curr) { 664 | require( 665 | false, 666 | "stdStorage find(StdStorage): Packed slot. This would cause dangerous overwriting and currently isnt supported." 667 | ); 668 | } 669 | vm_std_store.store(who, slot, set); 670 | delete self._target; 671 | delete self._sig; 672 | delete self._keys; 673 | delete self._depth; 674 | } 675 | 676 | function read(StdStorage storage self) private returns (bytes memory) { 677 | address t = self._target; 678 | uint256 s = find(self); 679 | return abi.encode(vm_std_store.load(t, bytes32(s))); 680 | } 681 | 682 | function read_bytes32(StdStorage storage self) internal returns (bytes32) { 683 | return abi.decode(read(self), (bytes32)); 684 | } 685 | 686 | function read_bool(StdStorage storage self) internal returns (bool) { 687 | return abi.decode(read(self), (bool)); 688 | } 689 | 690 | function read_address(StdStorage storage self) internal returns (address) { 691 | return abi.decode(read(self), (address)); 692 | } 693 | 694 | function read_uint(StdStorage storage self) internal returns (uint256) { 695 | return abi.decode(read(self), (uint256)); 696 | } 697 | 698 | function read_int(StdStorage storage self) internal returns (int256) { 699 | return abi.decode(read(self), (int256)); 700 | } 701 | 702 | function bytesToBytes32(bytes memory b, uint256 offset) 703 | public 704 | pure 705 | returns (bytes32) 706 | { 707 | bytes32 out; 708 | 709 | uint256 max = b.length > 32 ? 32 : b.length; 710 | for (uint256 i = 0; i < max; i++) { 711 | out |= bytes32(b[offset + i] & 0xFF) >> (i * 8); 712 | } 713 | return out; 714 | } 715 | 716 | function flatten(bytes32[] memory b) private pure returns (bytes memory) { 717 | bytes memory result = new bytes(b.length * 32); 718 | for (uint256 i = 0; i < b.length; i++) { 719 | bytes32 k = b[i]; 720 | /// @solidity memory-safe-assembly 721 | assembly { 722 | mstore(add(result, add(32, mul(32, i))), k) 723 | } 724 | } 725 | 726 | return result; 727 | } 728 | } 729 | 730 | /*////////////////////////////////////////////////////////////////////////// 731 | STD-MATH 732 | //////////////////////////////////////////////////////////////////////////*/ 733 | 734 | library stdMath { 735 | int256 private constant INT256_MIN = 736 | -57896044618658097711785492504343953926634992332820282019728792003956564819968; 737 | 738 | function abs(int256 a) internal pure returns (uint256) { 739 | // Required or it will fail when `a = type(int256).min` 740 | if (a == INT256_MIN) 741 | return 742 | 57896044618658097711785492504343953926634992332820282019728792003956564819968; 743 | 744 | return uint256(a >= 0 ? a : -a); 745 | } 746 | 747 | function delta(uint256 a, uint256 b) internal pure returns (uint256) { 748 | return a > b ? a - b : b - a; 749 | } 750 | 751 | function delta(int256 a, int256 b) internal pure returns (uint256) { 752 | // a and b are of the same sign 753 | if ((a >= 0 && b >= 0) || (a < 0 && b < 0)) { 754 | return delta(abs(a), abs(b)); 755 | } 756 | 757 | // a and b are of opposite signs 758 | return abs(a) + abs(b); 759 | } 760 | 761 | function percentDelta(uint256 a, uint256 b) 762 | internal 763 | pure 764 | returns (uint256) 765 | { 766 | uint256 absDelta = delta(a, b); 767 | 768 | return (absDelta * 1e18) / b; 769 | } 770 | 771 | function percentDelta(int256 a, int256 b) internal pure returns (uint256) { 772 | uint256 absDelta = delta(a, b); 773 | uint256 absB = abs(b); 774 | 775 | return (absDelta * 1e18) / absB; 776 | } 777 | } 778 | -------------------------------------------------------------------------------- /lib/forge-std/src/Vm.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Unlicense 2 | pragma solidity >=0.6.0; 3 | pragma experimental ABIEncoderV2; 4 | 5 | interface Vm { 6 | // Set block.timestamp (newTimestamp) 7 | function warp(uint256) external; 8 | 9 | // Set block.height (newHeight) 10 | function roll(uint256) external; 11 | 12 | // Set block.basefee (newBasefee) 13 | function fee(uint256) external; 14 | 15 | // Set block.chainid 16 | function chainId(uint256) external; 17 | 18 | // Loads a storage slot from an address (who, slot) 19 | function load(address, bytes32) external returns (bytes32); 20 | 21 | // Stores a value to an address' storage slot, (who, slot, value) 22 | function store( 23 | address, 24 | bytes32, 25 | bytes32 26 | ) external; 27 | 28 | // Signs data, (privateKey, digest) => (v, r, s) 29 | function sign(uint256, bytes32) 30 | external 31 | returns ( 32 | uint8, 33 | bytes32, 34 | bytes32 35 | ); 36 | 37 | // Gets address for a given private key, (privateKey) => (address) 38 | function addr(uint256) external returns (address); 39 | 40 | // Gets the nonce of an account 41 | function getNonce(address) external returns (uint64); 42 | 43 | // Sets the nonce of an account; must be higher than the current nonce of the account 44 | function setNonce(address, uint64) external; 45 | 46 | // Performs a foreign function call via terminal, (stringInputs) => (result) 47 | function ffi(string[] calldata) external returns (bytes memory); 48 | 49 | // Sets the *next* call's msg.sender to be the input address 50 | function prank(address) external; 51 | 52 | // Sets all subsequent calls' msg.sender to be the input address until `stopPrank` is called 53 | function startPrank(address) external; 54 | 55 | // Sets the *next* call's msg.sender to be the input address, and the tx.origin to be the second input 56 | function prank(address, address) external; 57 | 58 | // Sets all subsequent calls' msg.sender to be the input address until `stopPrank` is called, and the tx.origin to be the second input 59 | function startPrank(address, address) external; 60 | 61 | // Resets subsequent calls' msg.sender to be `address(this)` 62 | function stopPrank() external; 63 | 64 | // Sets an address' balance, (who, newBalance) 65 | function deal(address, uint256) external; 66 | 67 | // Sets an address' code, (who, newCode) 68 | function etch(address, bytes calldata) external; 69 | 70 | // Expects an error on next call 71 | function expectRevert(bytes calldata) external; 72 | 73 | function expectRevert(bytes4) external; 74 | 75 | function expectRevert() external; 76 | 77 | // Record all storage reads and writes 78 | function record() external; 79 | 80 | // Gets all accessed reads and write slot from a recording session, for a given address 81 | function accesses(address) 82 | external 83 | returns (bytes32[] memory reads, bytes32[] memory writes); 84 | 85 | // Prepare an expected log with (bool checkTopic1, bool checkTopic2, bool checkTopic3, bool checkData). 86 | // Call this function, then emit an event, then call a function. Internally after the call, we check if 87 | // logs were emitted in the expected order with the expected topics and data (as specified by the booleans) 88 | function expectEmit( 89 | bool, 90 | bool, 91 | bool, 92 | bool 93 | ) external; 94 | 95 | function expectEmit( 96 | bool, 97 | bool, 98 | bool, 99 | bool, 100 | address 101 | ) external; 102 | 103 | // Mocks a call to an address, returning specified data. 104 | // Calldata can either be strict or a partial match, e.g. if you only 105 | // pass a Solidity selector to the expected calldata, then the entire Solidity 106 | // function will be mocked. 107 | function mockCall( 108 | address, 109 | bytes calldata, 110 | bytes calldata 111 | ) external; 112 | 113 | // Mocks a call to an address with a specific msg.value, returning specified data. 114 | // Calldata match takes precedence over msg.value in case of ambiguity. 115 | function mockCall( 116 | address, 117 | uint256, 118 | bytes calldata, 119 | bytes calldata 120 | ) external; 121 | 122 | // Clears all mocked calls 123 | function clearMockedCalls() external; 124 | 125 | // Expect a call to an address with the specified calldata. 126 | // Calldata can either be strict or a partial match 127 | function expectCall(address, bytes calldata) external; 128 | 129 | // Expect a call to an address with the specified msg.value and calldata 130 | function expectCall( 131 | address, 132 | uint256, 133 | bytes calldata 134 | ) external; 135 | 136 | // Gets the code from an artifact file. Takes in the relative path to the json file 137 | function getCode(string calldata) external returns (bytes memory); 138 | 139 | // Labels an address in call traces 140 | function label(address, string calldata) external; 141 | 142 | // If the condition is false, discard this run's fuzz inputs and generate new ones 143 | function assume(bool) external; 144 | 145 | // Set block.coinbase (who) 146 | function coinbase(address) external; 147 | } 148 | -------------------------------------------------------------------------------- /lib/forge-std/src/test/StdAssertions.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Unlicense 2 | pragma solidity >=0.7.0 <0.9.0; 3 | 4 | import "../Test.sol"; 5 | 6 | contract StdAssertionsTest is Test { 7 | string constant CUSTOM_ERROR = "guh!"; 8 | 9 | bool constant EXPECT_PASS = false; 10 | bool constant EXPECT_FAIL = true; 11 | 12 | TestTest t = new TestTest(); 13 | 14 | /*////////////////////////////////////////////////////////////////////////// 15 | FAIL(STRING) 16 | //////////////////////////////////////////////////////////////////////////*/ 17 | 18 | function testShouldFail() external { 19 | vm.expectEmit(false, false, false, true); 20 | emit log_named_string("Error", CUSTOM_ERROR); 21 | t._fail(CUSTOM_ERROR); 22 | } 23 | 24 | /*////////////////////////////////////////////////////////////////////////// 25 | ASSERT_FALSE 26 | //////////////////////////////////////////////////////////////////////////*/ 27 | 28 | function testAssertFalse_Pass() external { 29 | t._assertFalse(false, EXPECT_PASS); 30 | } 31 | 32 | function testAssertFalse_Fail() external { 33 | vm.expectEmit(false, false, false, true); 34 | emit log("Error: Assertion Failed"); 35 | t._assertFalse(true, EXPECT_FAIL); 36 | } 37 | 38 | function testAssertFalse_Err_Pass() external { 39 | t._assertFalse(false, CUSTOM_ERROR, EXPECT_PASS); 40 | } 41 | 42 | function testAssertFalse_Err_Fail() external { 43 | vm.expectEmit(true, false, false, true); 44 | emit log_named_string("Error", CUSTOM_ERROR); 45 | t._assertFalse(true, CUSTOM_ERROR, EXPECT_FAIL); 46 | } 47 | 48 | /*////////////////////////////////////////////////////////////////////////// 49 | ASSERT_EQ(BOOL) 50 | //////////////////////////////////////////////////////////////////////////*/ 51 | 52 | function testAssertEq_Bool_Pass(bool a, bool b) external { 53 | vm.assume(a == b); 54 | 55 | t._assertEq(a, b, EXPECT_PASS); 56 | } 57 | 58 | function testAssertEq_Bool_Fail(bool a, bool b) external { 59 | vm.assume(a != b); 60 | 61 | vm.expectEmit(false, false, false, true); 62 | emit log("Error: a == b not satisfied [bool]"); 63 | t._assertEq(a, b, EXPECT_FAIL); 64 | } 65 | 66 | function testAssertEq_BoolErr_Pass(bool a, bool b) external { 67 | vm.assume(a == b); 68 | 69 | t._assertEq(a, b, CUSTOM_ERROR, EXPECT_PASS); 70 | } 71 | 72 | function testAssertEq_BoolErr_Fail(bool a, bool b) external { 73 | vm.assume(a != b); 74 | 75 | vm.expectEmit(true, false, false, true); 76 | emit log_named_string("Error", CUSTOM_ERROR); 77 | t._assertEq(a, b, CUSTOM_ERROR, EXPECT_FAIL); 78 | } 79 | 80 | /*////////////////////////////////////////////////////////////////////////// 81 | ASSERT_EQ(BYTES) 82 | //////////////////////////////////////////////////////////////////////////*/ 83 | 84 | function testAssertEq_Bytes_Pass(bytes calldata a, bytes calldata b) 85 | external 86 | { 87 | vm.assume(keccak256(a) == keccak256(b)); 88 | 89 | t._assertEq(a, b, EXPECT_PASS); 90 | } 91 | 92 | function testAssertEq_Bytes_Fail(bytes calldata a, bytes calldata b) 93 | external 94 | { 95 | vm.assume(keccak256(a) != keccak256(b)); 96 | 97 | vm.expectEmit(false, false, false, true); 98 | emit log("Error: a == b not satisfied [bytes]"); 99 | t._assertEq(a, b, EXPECT_FAIL); 100 | } 101 | 102 | function testAssertEq_BytesErr_Pass(bytes calldata a, bytes calldata b) 103 | external 104 | { 105 | vm.assume(keccak256(a) == keccak256(b)); 106 | 107 | t._assertEq(a, b, CUSTOM_ERROR, EXPECT_PASS); 108 | } 109 | 110 | function testAssertEq_BytesErr_Fail(bytes calldata a, bytes calldata b) 111 | external 112 | { 113 | vm.assume(keccak256(a) != keccak256(b)); 114 | 115 | vm.expectEmit(true, false, false, true); 116 | emit log_named_string("Error", CUSTOM_ERROR); 117 | t._assertEq(a, b, CUSTOM_ERROR, EXPECT_FAIL); 118 | } 119 | 120 | /*////////////////////////////////////////////////////////////////////////// 121 | APPROX_EQ_ABS(UINT) 122 | //////////////////////////////////////////////////////////////////////////*/ 123 | 124 | function testAssertApproxEqAbs_Uint_Pass( 125 | uint256 a, 126 | uint256 b, 127 | uint256 maxDelta 128 | ) external { 129 | vm.assume(stdMath.delta(a, b) <= maxDelta); 130 | 131 | t._assertApproxEqAbs(a, b, maxDelta, EXPECT_PASS); 132 | } 133 | 134 | function testAssertApproxEqAbs_Uint_Fail( 135 | uint256 a, 136 | uint256 b, 137 | uint256 maxDelta 138 | ) external { 139 | vm.assume(stdMath.delta(a, b) > maxDelta); 140 | 141 | vm.expectEmit(false, false, false, true); 142 | emit log("Error: a ~= b not satisfied [uint]"); 143 | t._assertApproxEqAbs(a, b, maxDelta, EXPECT_FAIL); 144 | } 145 | 146 | function testAssertApproxEqAbs_UintErr_Pass( 147 | uint256 a, 148 | uint256 b, 149 | uint256 maxDelta 150 | ) external { 151 | vm.assume(stdMath.delta(a, b) <= maxDelta); 152 | 153 | t._assertApproxEqAbs(a, b, maxDelta, CUSTOM_ERROR, EXPECT_PASS); 154 | } 155 | 156 | function testAssertApproxEqAbs_UintErr_Fail( 157 | uint256 a, 158 | uint256 b, 159 | uint256 maxDelta 160 | ) external { 161 | vm.assume(stdMath.delta(a, b) > maxDelta); 162 | 163 | vm.expectEmit(true, false, false, true); 164 | emit log_named_string("Error", CUSTOM_ERROR); 165 | t._assertApproxEqAbs(a, b, maxDelta, CUSTOM_ERROR, EXPECT_FAIL); 166 | } 167 | 168 | /*////////////////////////////////////////////////////////////////////////// 169 | APPROX_EQ_ABS(INT) 170 | //////////////////////////////////////////////////////////////////////////*/ 171 | 172 | function testAssertApproxEqAbs_Int_Pass( 173 | int256 a, 174 | int256 b, 175 | uint256 maxDelta 176 | ) external { 177 | vm.assume(stdMath.delta(a, b) <= maxDelta); 178 | 179 | t._assertApproxEqAbs(a, b, maxDelta, EXPECT_PASS); 180 | } 181 | 182 | function testAssertApproxEqAbs_Int_Fail( 183 | int256 a, 184 | int256 b, 185 | uint256 maxDelta 186 | ) external { 187 | vm.assume(stdMath.delta(a, b) > maxDelta); 188 | 189 | vm.expectEmit(false, false, false, true); 190 | emit log("Error: a ~= b not satisfied [int]"); 191 | t._assertApproxEqAbs(a, b, maxDelta, EXPECT_FAIL); 192 | } 193 | 194 | function testAssertApproxEqAbs_IntErr_Pass( 195 | int256 a, 196 | int256 b, 197 | uint256 maxDelta 198 | ) external { 199 | vm.assume(stdMath.delta(a, b) <= maxDelta); 200 | 201 | t._assertApproxEqAbs(a, b, maxDelta, CUSTOM_ERROR, EXPECT_PASS); 202 | } 203 | 204 | function testAssertApproxEqAbs_IntErr_Fail( 205 | int256 a, 206 | int256 b, 207 | uint256 maxDelta 208 | ) external { 209 | vm.assume(stdMath.delta(a, b) > maxDelta); 210 | 211 | vm.expectEmit(true, false, false, true); 212 | emit log_named_string("Error", CUSTOM_ERROR); 213 | t._assertApproxEqAbs(a, b, maxDelta, CUSTOM_ERROR, EXPECT_FAIL); 214 | } 215 | 216 | /*////////////////////////////////////////////////////////////////////////// 217 | APPROX_EQ_REL(UINT) 218 | //////////////////////////////////////////////////////////////////////////*/ 219 | 220 | function testAssertApproxEqRel_Uint_Pass( 221 | uint256 a, 222 | uint256 b, 223 | uint256 maxPercentDelta 224 | ) external { 225 | vm.assume(a < type(uint128).max && b < type(uint128).max && b != 0); 226 | vm.assume(stdMath.percentDelta(a, b) <= maxPercentDelta); 227 | 228 | t._assertApproxEqRel(a, b, maxPercentDelta, EXPECT_PASS); 229 | } 230 | 231 | function testAssertApproxEqRel_Uint_Fail( 232 | uint256 a, 233 | uint256 b, 234 | uint256 maxPercentDelta 235 | ) external { 236 | vm.assume(a < type(uint128).max && b < type(uint128).max && b != 0); 237 | vm.assume(stdMath.percentDelta(a, b) > maxPercentDelta); 238 | 239 | vm.expectEmit(false, false, false, true); 240 | emit log("Error: a ~= b not satisfied [uint]"); 241 | t._assertApproxEqRel(a, b, maxPercentDelta, EXPECT_FAIL); 242 | } 243 | 244 | function testAssertApproxEqRel_UintErr_Pass( 245 | uint256 a, 246 | uint256 b, 247 | uint256 maxPercentDelta 248 | ) external { 249 | vm.assume(a < type(uint128).max && b < type(uint128).max && b != 0); 250 | vm.assume(stdMath.percentDelta(a, b) <= maxPercentDelta); 251 | 252 | t._assertApproxEqRel(a, b, maxPercentDelta, CUSTOM_ERROR, EXPECT_PASS); 253 | } 254 | 255 | function testAssertApproxEqRel_UintErr_Fail( 256 | uint256 a, 257 | uint256 b, 258 | uint256 maxPercentDelta 259 | ) external { 260 | vm.assume(a < type(uint128).max && b < type(uint128).max && b != 0); 261 | vm.assume(stdMath.percentDelta(a, b) > maxPercentDelta); 262 | 263 | vm.expectEmit(true, false, false, true); 264 | emit log_named_string("Error", CUSTOM_ERROR); 265 | t._assertApproxEqRel(a, b, maxPercentDelta, CUSTOM_ERROR, EXPECT_FAIL); 266 | } 267 | 268 | /*////////////////////////////////////////////////////////////////////////// 269 | APPROX_EQ_REL(INT) 270 | //////////////////////////////////////////////////////////////////////////*/ 271 | 272 | function testAssertApproxEqRel_Int_Pass( 273 | int128 a, 274 | int128 b, 275 | uint128 maxPercentDelta 276 | ) external { 277 | vm.assume(b != 0); 278 | vm.assume(stdMath.percentDelta(a, b) <= maxPercentDelta); 279 | 280 | t._assertApproxEqRel(a, b, maxPercentDelta, EXPECT_PASS); 281 | } 282 | 283 | function testAssertApproxEqRel_Int_Fail( 284 | int128 a, 285 | int128 b, 286 | uint128 maxPercentDelta 287 | ) external { 288 | vm.assume(b != 0); 289 | vm.assume(stdMath.percentDelta(a, b) > maxPercentDelta); 290 | 291 | vm.expectEmit(false, false, false, true); 292 | emit log("Error: a ~= b not satisfied [int]"); 293 | t._assertApproxEqRel(a, b, maxPercentDelta, EXPECT_FAIL); 294 | } 295 | 296 | function testAssertApproxEqRel_IntErr_Pass( 297 | int128 a, 298 | int128 b, 299 | uint128 maxPercentDelta 300 | ) external { 301 | vm.assume(b != 0); 302 | vm.assume(stdMath.percentDelta(a, b) <= maxPercentDelta); 303 | 304 | t._assertApproxEqRel(a, b, maxPercentDelta, CUSTOM_ERROR, EXPECT_PASS); 305 | } 306 | 307 | function testAssertApproxEqRel_IntErr_Fail( 308 | int128 a, 309 | int128 b, 310 | uint128 maxPercentDelta 311 | ) external { 312 | vm.assume(b != 0); 313 | vm.assume(stdMath.percentDelta(a, b) > maxPercentDelta); 314 | 315 | vm.expectEmit(true, false, false, true); 316 | emit log_named_string("Error", CUSTOM_ERROR); 317 | t._assertApproxEqRel(a, b, maxPercentDelta, CUSTOM_ERROR, EXPECT_FAIL); 318 | } 319 | } 320 | 321 | contract TestTest is Test { 322 | modifier expectFailure(bool expectFail) { 323 | bool preState = vm.load(HEVM_ADDRESS, bytes32("failed")) != 324 | bytes32(0x00); 325 | _; 326 | bool postState = vm.load(HEVM_ADDRESS, bytes32("failed")) != 327 | bytes32(0x00); 328 | 329 | if (preState == true) { 330 | return; 331 | } 332 | 333 | if (expectFail) { 334 | require(postState == true, "expected failure not triggered"); 335 | 336 | // unwind the expected failure 337 | vm.store(HEVM_ADDRESS, bytes32("failed"), bytes32(uint256(0x00))); 338 | } else { 339 | require(postState == false, "unexpected failure was triggered"); 340 | } 341 | } 342 | 343 | function _fail(string memory err) external expectFailure(true) { 344 | fail(err); 345 | } 346 | 347 | function _assertFalse(bool data, bool expectFail) 348 | external 349 | expectFailure(expectFail) 350 | { 351 | assertFalse(data); 352 | } 353 | 354 | function _assertFalse( 355 | bool data, 356 | string memory err, 357 | bool expectFail 358 | ) external expectFailure(expectFail) { 359 | assertFalse(data, err); 360 | } 361 | 362 | function _assertEq( 363 | bool a, 364 | bool b, 365 | bool expectFail 366 | ) external expectFailure(expectFail) { 367 | assertEq(a, b); 368 | } 369 | 370 | function _assertEq( 371 | bool a, 372 | bool b, 373 | string memory err, 374 | bool expectFail 375 | ) external expectFailure(expectFail) { 376 | assertEq(a, b, err); 377 | } 378 | 379 | function _assertEq( 380 | bytes memory a, 381 | bytes memory b, 382 | bool expectFail 383 | ) external expectFailure(expectFail) { 384 | assertEq(a, b); 385 | } 386 | 387 | function _assertEq( 388 | bytes memory a, 389 | bytes memory b, 390 | string memory err, 391 | bool expectFail 392 | ) external expectFailure(expectFail) { 393 | assertEq(a, b, err); 394 | } 395 | 396 | function _assertApproxEqAbs( 397 | uint256 a, 398 | uint256 b, 399 | uint256 maxDelta, 400 | bool expectFail 401 | ) external expectFailure(expectFail) { 402 | assertApproxEqAbs(a, b, maxDelta); 403 | } 404 | 405 | function _assertApproxEqAbs( 406 | uint256 a, 407 | uint256 b, 408 | uint256 maxDelta, 409 | string memory err, 410 | bool expectFail 411 | ) external expectFailure(expectFail) { 412 | assertApproxEqAbs(a, b, maxDelta, err); 413 | } 414 | 415 | function _assertApproxEqAbs( 416 | int256 a, 417 | int256 b, 418 | uint256 maxDelta, 419 | bool expectFail 420 | ) external expectFailure(expectFail) { 421 | assertApproxEqAbs(a, b, maxDelta); 422 | } 423 | 424 | function _assertApproxEqAbs( 425 | int256 a, 426 | int256 b, 427 | uint256 maxDelta, 428 | string memory err, 429 | bool expectFail 430 | ) external expectFailure(expectFail) { 431 | assertApproxEqAbs(a, b, maxDelta, err); 432 | } 433 | 434 | function _assertApproxEqRel( 435 | uint256 a, 436 | uint256 b, 437 | uint256 maxPercentDelta, 438 | bool expectFail 439 | ) external expectFailure(expectFail) { 440 | assertApproxEqRel(a, b, maxPercentDelta); 441 | } 442 | 443 | function _assertApproxEqRel( 444 | uint256 a, 445 | uint256 b, 446 | uint256 maxPercentDelta, 447 | string memory err, 448 | bool expectFail 449 | ) external expectFailure(expectFail) { 450 | assertApproxEqRel(a, b, maxPercentDelta, err); 451 | } 452 | 453 | function _assertApproxEqRel( 454 | int256 a, 455 | int256 b, 456 | uint256 maxPercentDelta, 457 | bool expectFail 458 | ) external expectFailure(expectFail) { 459 | assertApproxEqRel(a, b, maxPercentDelta); 460 | } 461 | 462 | function _assertApproxEqRel( 463 | int256 a, 464 | int256 b, 465 | uint256 maxPercentDelta, 466 | string memory err, 467 | bool expectFail 468 | ) external expectFailure(expectFail) { 469 | assertApproxEqRel(a, b, maxPercentDelta, err); 470 | } 471 | } 472 | -------------------------------------------------------------------------------- /lib/forge-std/src/test/StdCheats.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Unlicense 2 | pragma solidity >=0.7.0 <0.9.0; 3 | 4 | import "../Test.sol"; 5 | 6 | contract StdCheatsTest is Test { 7 | Bar test; 8 | 9 | function setUp() public { 10 | test = new Bar(); 11 | } 12 | 13 | function testSkip() public { 14 | vm.warp(100); 15 | skip(25); 16 | assertEq(block.timestamp, 125); 17 | } 18 | 19 | function testRewind() public { 20 | vm.warp(100); 21 | rewind(25); 22 | assertEq(block.timestamp, 75); 23 | } 24 | 25 | function testHoax() public { 26 | hoax(address(1337)); 27 | test.bar{value: 100}(address(1337)); 28 | } 29 | 30 | function testHoaxOrigin() public { 31 | hoax(address(1337), address(1337)); 32 | test.origin{value: 100}(address(1337)); 33 | } 34 | 35 | function testHoaxDifferentAddresses() public { 36 | hoax(address(1337), address(7331)); 37 | test.origin{value: 100}(address(1337), address(7331)); 38 | } 39 | 40 | function testStartHoax() public { 41 | startHoax(address(1337)); 42 | test.bar{value: 100}(address(1337)); 43 | test.bar{value: 100}(address(1337)); 44 | vm.stopPrank(); 45 | test.bar(address(this)); 46 | } 47 | 48 | function testStartHoaxOrigin() public { 49 | startHoax(address(1337), address(1337)); 50 | test.origin{value: 100}(address(1337)); 51 | test.origin{value: 100}(address(1337)); 52 | vm.stopPrank(); 53 | test.bar(address(this)); 54 | } 55 | 56 | function testChangePrank() public { 57 | vm.startPrank(address(1337)); 58 | test.bar(address(1337)); 59 | changePrank(address(0xdead)); 60 | test.bar(address(0xdead)); 61 | changePrank(address(1337)); 62 | test.bar(address(1337)); 63 | vm.stopPrank(); 64 | } 65 | 66 | function testDeal() public { 67 | deal(address(this), 1 ether); 68 | assertEq(address(this).balance, 1 ether); 69 | } 70 | 71 | function testDealToken() public { 72 | Bar barToken = new Bar(); 73 | address bar = address(barToken); 74 | deal(bar, address(this), 10000e18); 75 | assertEq(barToken.balanceOf(address(this)), 10000e18); 76 | } 77 | 78 | function testDealTokenAdjustTS() public { 79 | Bar barToken = new Bar(); 80 | address bar = address(barToken); 81 | deal(bar, address(this), 10000e18, true); 82 | assertEq(barToken.balanceOf(address(this)), 10000e18); 83 | assertEq(barToken.totalSupply(), 20000e18); 84 | deal(bar, address(this), 0, true); 85 | assertEq(barToken.balanceOf(address(this)), 0); 86 | assertEq(barToken.totalSupply(), 10000e18); 87 | } 88 | 89 | function testBound() public { 90 | assertEq(bound(5, 0, 4), 0); 91 | assertEq(bound(0, 69, 69), 69); 92 | assertEq(bound(0, 68, 69), 68); 93 | assertEq(bound(10, 150, 190), 160); 94 | assertEq(bound(300, 2800, 3200), 3100); 95 | assertEq(bound(9999, 1337, 6666), 6006); 96 | } 97 | 98 | function testCannotBoundMaxLessThanMin() public { 99 | vm.expectRevert( 100 | bytes("Test bound(uint256,uint256,uint256): Max is less than min.") 101 | ); 102 | bound(5, 100, 10); 103 | } 104 | 105 | function testBound( 106 | uint256 num, 107 | uint256 min, 108 | uint256 max 109 | ) public { 110 | if (min > max) (min, max) = (max, min); 111 | 112 | uint256 bounded = bound(num, min, max); 113 | 114 | assertGe(bounded, min); 115 | assertLe(bounded, max); 116 | } 117 | 118 | function testBoundUint256Max() public { 119 | assertEq( 120 | bound(0, type(uint256).max - 1, type(uint256).max), 121 | type(uint256).max - 1 122 | ); 123 | assertEq( 124 | bound(1, type(uint256).max - 1, type(uint256).max), 125 | type(uint256).max 126 | ); 127 | } 128 | 129 | function testCannotBoundMaxLessThanMin( 130 | uint256 num, 131 | uint256 min, 132 | uint256 max 133 | ) public { 134 | vm.assume(min > max); 135 | vm.expectRevert( 136 | bytes("Test bound(uint256,uint256,uint256): Max is less than min.") 137 | ); 138 | bound(num, min, max); 139 | } 140 | 141 | function testDeployCode() public { 142 | address deployed = deployCode( 143 | "StdCheats.t.sol:StdCheatsTest", 144 | bytes("") 145 | ); 146 | assertEq(string(getCode(deployed)), string(getCode(address(this)))); 147 | } 148 | 149 | function testDeployCodeNoArgs() public { 150 | address deployed = deployCode("StdCheats.t.sol:StdCheatsTest"); 151 | assertEq(string(getCode(deployed)), string(getCode(address(this)))); 152 | } 153 | 154 | function testDeployCodeFail() public { 155 | vm.expectRevert(bytes("Test deployCode(string): Deployment failed.")); 156 | this.deployCode("StdCheats.t.sol:RevertingContract"); 157 | } 158 | 159 | function getCode(address who) internal view returns (bytes memory o_code) { 160 | /// @solidity memory-safe-assembly 161 | assembly { 162 | // retrieve the size of the code, this needs assembly 163 | let size := extcodesize(who) 164 | // allocate output byte array - this could also be done without assembly 165 | // by using o_code = new bytes(size) 166 | o_code := mload(0x40) 167 | // new "memory end" including padding 168 | mstore( 169 | 0x40, 170 | add(o_code, and(add(add(size, 0x20), 0x1f), not(0x1f))) 171 | ) 172 | // store length in memory 173 | mstore(o_code, size) 174 | // actually retrieve the code, this needs assembly 175 | extcodecopy(who, add(o_code, 0x20), 0, size) 176 | } 177 | } 178 | } 179 | 180 | contract Bar { 181 | constructor() { 182 | /// `DEAL` STDCHEAT 183 | totalSupply = 10000e18; 184 | balanceOf[address(this)] = totalSupply; 185 | } 186 | 187 | /// `HOAX` STDCHEATS 188 | function bar(address expectedSender) public payable { 189 | require(msg.sender == expectedSender, "!prank"); 190 | } 191 | 192 | function origin(address expectedSender) public payable { 193 | require(msg.sender == expectedSender, "!prank"); 194 | require(tx.origin == expectedSender, "!prank"); 195 | } 196 | 197 | function origin(address expectedSender, address expectedOrigin) 198 | public 199 | payable 200 | { 201 | require(msg.sender == expectedSender, "!prank"); 202 | require(tx.origin == expectedOrigin, "!prank"); 203 | } 204 | 205 | /// `DEAL` STDCHEAT 206 | mapping(address => uint256) public balanceOf; 207 | uint256 public totalSupply; 208 | } 209 | 210 | contract RevertingContract { 211 | constructor() { 212 | revert(); 213 | } 214 | } 215 | -------------------------------------------------------------------------------- /lib/forge-std/src/test/StdError.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Unlicense 2 | pragma solidity >=0.8.10 <0.9.0; 3 | 4 | import "../Test.sol"; 5 | 6 | contract StdErrorsTest is Test { 7 | ErrorsTest test; 8 | 9 | function setUp() public { 10 | test = new ErrorsTest(); 11 | } 12 | 13 | function testExpectAssertion() public { 14 | vm.expectRevert(stdError.assertionError); 15 | test.assertionError(); 16 | } 17 | 18 | function testExpectArithmetic() public { 19 | vm.expectRevert(stdError.arithmeticError); 20 | test.arithmeticError(10); 21 | } 22 | 23 | function testExpectDiv() public { 24 | vm.expectRevert(stdError.divisionError); 25 | test.divError(0); 26 | } 27 | 28 | function testExpectMod() public { 29 | vm.expectRevert(stdError.divisionError); 30 | test.modError(0); 31 | } 32 | 33 | function testExpectEnum() public { 34 | vm.expectRevert(stdError.enumConversionError); 35 | test.enumConversion(1); 36 | } 37 | 38 | function testExpectEncodeStg() public { 39 | vm.expectRevert(stdError.encodeStorageError); 40 | test.encodeStgError(); 41 | } 42 | 43 | function testExpectPop() public { 44 | vm.expectRevert(stdError.popError); 45 | test.pop(); 46 | } 47 | 48 | function testExpectOOB() public { 49 | vm.expectRevert(stdError.indexOOBError); 50 | test.indexOOBError(1); 51 | } 52 | 53 | function testExpectMem() public { 54 | vm.expectRevert(stdError.memOverflowError); 55 | test.mem(); 56 | } 57 | 58 | function testExpectIntern() public { 59 | vm.expectRevert(stdError.zeroVarError); 60 | test.intern(); 61 | } 62 | 63 | function testExpectLowLvl() public { 64 | vm.expectRevert(stdError.lowLevelError); 65 | test.someArr(0); 66 | } 67 | } 68 | 69 | contract ErrorsTest { 70 | enum T { 71 | T1 72 | } 73 | 74 | uint256[] public someArr; 75 | bytes someBytes; 76 | 77 | function assertionError() public pure { 78 | assert(false); 79 | } 80 | 81 | function arithmeticError(uint256 a) public pure { 82 | a -= 100; 83 | } 84 | 85 | function divError(uint256 a) public pure { 86 | 100 / a; 87 | } 88 | 89 | function modError(uint256 a) public pure { 90 | 100 % a; 91 | } 92 | 93 | function enumConversion(uint256 a) public pure { 94 | T(a); 95 | } 96 | 97 | function encodeStgError() public { 98 | /// @solidity memory-safe-assembly 99 | assembly { 100 | sstore(someBytes.slot, 1) 101 | } 102 | keccak256(someBytes); 103 | } 104 | 105 | function pop() public { 106 | someArr.pop(); 107 | } 108 | 109 | function indexOOBError(uint256 a) public pure { 110 | uint256[] memory t = new uint256[](0); 111 | t[a]; 112 | } 113 | 114 | function mem() public pure { 115 | uint256 l = 2**256 / 32; 116 | new uint256[](l); 117 | } 118 | 119 | function intern() public returns (uint256) { 120 | function(uint256) internal returns (uint256) x; 121 | x(2); 122 | return 7; 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /lib/forge-std/src/test/StdMath.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Unlicense 2 | pragma solidity >=0.8.0 <0.9.0; 3 | 4 | import "../Test.sol"; 5 | 6 | contract StdMathTest is Test { 7 | function testGetAbs() external { 8 | assertEq(stdMath.abs(-50), 50); 9 | assertEq(stdMath.abs(50), 50); 10 | assertEq(stdMath.abs(-1337), 1337); 11 | assertEq(stdMath.abs(0), 0); 12 | 13 | assertEq(stdMath.abs(type(int256).min), (type(uint256).max >> 1) + 1); 14 | assertEq(stdMath.abs(type(int256).max), (type(uint256).max >> 1)); 15 | } 16 | 17 | function testGetAbs_Fuzz(int256 a) external { 18 | uint256 manualAbs = getAbs(a); 19 | 20 | uint256 abs = stdMath.abs(a); 21 | 22 | assertEq(abs, manualAbs); 23 | } 24 | 25 | function testGetDelta_Uint() external { 26 | assertEq(stdMath.delta(uint256(0), uint256(0)), 0); 27 | assertEq(stdMath.delta(uint256(0), uint256(1337)), 1337); 28 | assertEq(stdMath.delta(uint256(0), type(uint64).max), type(uint64).max); 29 | assertEq( 30 | stdMath.delta(uint256(0), type(uint128).max), 31 | type(uint128).max 32 | ); 33 | assertEq( 34 | stdMath.delta(uint256(0), type(uint256).max), 35 | type(uint256).max 36 | ); 37 | 38 | assertEq(stdMath.delta(0, uint256(0)), 0); 39 | assertEq(stdMath.delta(1337, uint256(0)), 1337); 40 | assertEq(stdMath.delta(type(uint64).max, uint256(0)), type(uint64).max); 41 | assertEq( 42 | stdMath.delta(type(uint128).max, uint256(0)), 43 | type(uint128).max 44 | ); 45 | assertEq( 46 | stdMath.delta(type(uint256).max, uint256(0)), 47 | type(uint256).max 48 | ); 49 | 50 | assertEq(stdMath.delta(1337, uint256(1337)), 0); 51 | assertEq(stdMath.delta(type(uint256).max, type(uint256).max), 0); 52 | assertEq(stdMath.delta(5000, uint256(1250)), 3750); 53 | } 54 | 55 | function testGetDelta_Uint_Fuzz(uint256 a, uint256 b) external { 56 | uint256 manualDelta; 57 | if (a > b) { 58 | manualDelta = a - b; 59 | } else { 60 | manualDelta = b - a; 61 | } 62 | 63 | uint256 delta = stdMath.delta(a, b); 64 | 65 | assertEq(delta, manualDelta); 66 | } 67 | 68 | function testGetDelta_Int() external { 69 | assertEq(stdMath.delta(int256(0), int256(0)), 0); 70 | assertEq(stdMath.delta(int256(0), int256(1337)), 1337); 71 | assertEq( 72 | stdMath.delta(int256(0), type(int64).max), 73 | type(uint64).max >> 1 74 | ); 75 | assertEq( 76 | stdMath.delta(int256(0), type(int128).max), 77 | type(uint128).max >> 1 78 | ); 79 | assertEq( 80 | stdMath.delta(int256(0), type(int256).max), 81 | type(uint256).max >> 1 82 | ); 83 | 84 | assertEq(stdMath.delta(0, int256(0)), 0); 85 | assertEq(stdMath.delta(1337, int256(0)), 1337); 86 | assertEq( 87 | stdMath.delta(type(int64).max, int256(0)), 88 | type(uint64).max >> 1 89 | ); 90 | assertEq( 91 | stdMath.delta(type(int128).max, int256(0)), 92 | type(uint128).max >> 1 93 | ); 94 | assertEq( 95 | stdMath.delta(type(int256).max, int256(0)), 96 | type(uint256).max >> 1 97 | ); 98 | 99 | assertEq(stdMath.delta(-0, int256(0)), 0); 100 | assertEq(stdMath.delta(-1337, int256(0)), 1337); 101 | assertEq( 102 | stdMath.delta(type(int64).min, int256(0)), 103 | (type(uint64).max >> 1) + 1 104 | ); 105 | assertEq( 106 | stdMath.delta(type(int128).min, int256(0)), 107 | (type(uint128).max >> 1) + 1 108 | ); 109 | assertEq( 110 | stdMath.delta(type(int256).min, int256(0)), 111 | (type(uint256).max >> 1) + 1 112 | ); 113 | 114 | assertEq(stdMath.delta(int256(0), -0), 0); 115 | assertEq(stdMath.delta(int256(0), -1337), 1337); 116 | assertEq( 117 | stdMath.delta(int256(0), type(int64).min), 118 | (type(uint64).max >> 1) + 1 119 | ); 120 | assertEq( 121 | stdMath.delta(int256(0), type(int128).min), 122 | (type(uint128).max >> 1) + 1 123 | ); 124 | assertEq( 125 | stdMath.delta(int256(0), type(int256).min), 126 | (type(uint256).max >> 1) + 1 127 | ); 128 | 129 | assertEq(stdMath.delta(1337, int256(1337)), 0); 130 | assertEq(stdMath.delta(type(int256).max, type(int256).max), 0); 131 | assertEq(stdMath.delta(type(int256).min, type(int256).min), 0); 132 | assertEq( 133 | stdMath.delta(type(int256).min, type(int256).max), 134 | type(uint256).max 135 | ); 136 | assertEq(stdMath.delta(5000, int256(1250)), 3750); 137 | } 138 | 139 | function testGetDelta_Int_Fuzz(int256 a, int256 b) external { 140 | uint256 absA = getAbs(a); 141 | uint256 absB = getAbs(b); 142 | uint256 absDelta = absA > absB ? absA - absB : absB - absA; 143 | 144 | uint256 manualDelta; 145 | if ((a >= 0 && b >= 0) || (a < 0 && b < 0)) { 146 | manualDelta = absDelta; 147 | } 148 | // (a < 0 && b >= 0) || (a >= 0 && b < 0) 149 | else { 150 | manualDelta = absA + absB; 151 | } 152 | 153 | uint256 delta = stdMath.delta(a, b); 154 | 155 | assertEq(delta, manualDelta); 156 | } 157 | 158 | function testGetPercentDelta_Uint() external { 159 | assertEq(stdMath.percentDelta(uint256(0), uint256(1337)), 1e18); 160 | assertEq(stdMath.percentDelta(uint256(0), type(uint64).max), 1e18); 161 | assertEq(stdMath.percentDelta(uint256(0), type(uint128).max), 1e18); 162 | assertEq(stdMath.percentDelta(uint256(0), type(uint192).max), 1e18); 163 | 164 | assertEq(stdMath.percentDelta(1337, uint256(1337)), 0); 165 | assertEq(stdMath.percentDelta(type(uint192).max, type(uint192).max), 0); 166 | assertEq(stdMath.percentDelta(0, uint256(2500)), 1e18); 167 | assertEq(stdMath.percentDelta(2500, uint256(2500)), 0); 168 | assertEq(stdMath.percentDelta(5000, uint256(2500)), 1e18); 169 | assertEq(stdMath.percentDelta(7500, uint256(2500)), 2e18); 170 | 171 | vm.expectRevert(stdError.divisionError); 172 | stdMath.percentDelta(uint256(1), 0); 173 | } 174 | 175 | function testGetPercentDelta_Uint_Fuzz(uint192 a, uint192 b) external { 176 | vm.assume(b != 0); 177 | uint256 manualDelta; 178 | if (a > b) { 179 | manualDelta = a - b; 180 | } else { 181 | manualDelta = b - a; 182 | } 183 | 184 | uint256 manualPercentDelta = (manualDelta * 1e18) / b; 185 | uint256 percentDelta = stdMath.percentDelta(a, b); 186 | 187 | assertEq(percentDelta, manualPercentDelta); 188 | } 189 | 190 | function testGetPercentDelta_Int() external { 191 | assertEq(stdMath.percentDelta(int256(0), int256(1337)), 1e18); 192 | assertEq(stdMath.percentDelta(int256(0), -1337), 1e18); 193 | assertEq(stdMath.percentDelta(int256(0), type(int64).min), 1e18); 194 | assertEq(stdMath.percentDelta(int256(0), type(int128).min), 1e18); 195 | assertEq(stdMath.percentDelta(int256(0), type(int192).min), 1e18); 196 | assertEq(stdMath.percentDelta(int256(0), type(int64).max), 1e18); 197 | assertEq(stdMath.percentDelta(int256(0), type(int128).max), 1e18); 198 | assertEq(stdMath.percentDelta(int256(0), type(int192).max), 1e18); 199 | 200 | assertEq(stdMath.percentDelta(1337, int256(1337)), 0); 201 | assertEq(stdMath.percentDelta(type(int192).max, type(int192).max), 0); 202 | assertEq(stdMath.percentDelta(type(int192).min, type(int192).min), 0); 203 | 204 | assertEq( 205 | stdMath.percentDelta(type(int192).min, type(int192).max), 206 | 2e18 207 | ); // rounds the 1 wei diff down 208 | assertEq( 209 | stdMath.percentDelta(type(int192).max, type(int192).min), 210 | 2e18 - 1 211 | ); // rounds the 1 wei diff down 212 | assertEq(stdMath.percentDelta(0, int256(2500)), 1e18); 213 | assertEq(stdMath.percentDelta(2500, int256(2500)), 0); 214 | assertEq(stdMath.percentDelta(5000, int256(2500)), 1e18); 215 | assertEq(stdMath.percentDelta(7500, int256(2500)), 2e18); 216 | 217 | vm.expectRevert(stdError.divisionError); 218 | stdMath.percentDelta(int256(1), 0); 219 | } 220 | 221 | function testGetPercentDelta_Int_Fuzz(int192 a, int192 b) external { 222 | vm.assume(b != 0); 223 | uint256 absA = getAbs(a); 224 | uint256 absB = getAbs(b); 225 | uint256 absDelta = absA > absB ? absA - absB : absB - absA; 226 | 227 | uint256 manualDelta; 228 | if ((a >= 0 && b >= 0) || (a < 0 && b < 0)) { 229 | manualDelta = absDelta; 230 | } 231 | // (a < 0 && b >= 0) || (a >= 0 && b < 0) 232 | else { 233 | manualDelta = absA + absB; 234 | } 235 | 236 | uint256 manualPercentDelta = (manualDelta * 1e18) / absB; 237 | uint256 percentDelta = stdMath.percentDelta(a, b); 238 | 239 | assertEq(percentDelta, manualPercentDelta); 240 | } 241 | 242 | /*////////////////////////////////////////////////////////////////////////// 243 | HELPERS 244 | //////////////////////////////////////////////////////////////////////////*/ 245 | 246 | function getAbs(int256 a) private pure returns (uint256) { 247 | if (a < 0) 248 | return 249 | a == type(int256).min 250 | ? uint256(type(int256).max) + 1 251 | : uint256(-a); 252 | 253 | return uint256(a); 254 | } 255 | } 256 | -------------------------------------------------------------------------------- /lib/forge-std/src/test/StdStorage.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Unlicense 2 | pragma solidity >=0.7.0 <0.9.0; 3 | 4 | import "../Test.sol"; 5 | 6 | contract StdStorageTest is Test { 7 | using stdStorage for StdStorage; 8 | 9 | StorageTest test; 10 | 11 | function setUp() public { 12 | test = new StorageTest(); 13 | } 14 | 15 | function testStorageHidden() public { 16 | assertEq( 17 | uint256(keccak256("my.random.var")), 18 | stdstore.target(address(test)).sig("hidden()").find() 19 | ); 20 | } 21 | 22 | function testStorageObvious() public { 23 | assertEq( 24 | uint256(0), 25 | stdstore.target(address(test)).sig("exists()").find() 26 | ); 27 | } 28 | 29 | function testStorageCheckedWriteHidden() public { 30 | stdstore.target(address(test)).sig(test.hidden.selector).checked_write( 31 | 100 32 | ); 33 | assertEq(uint256(test.hidden()), 100); 34 | } 35 | 36 | function testStorageCheckedWriteObvious() public { 37 | stdstore.target(address(test)).sig(test.exists.selector).checked_write( 38 | 100 39 | ); 40 | assertEq(test.exists(), 100); 41 | } 42 | 43 | function testStorageMapStructA() public { 44 | uint256 slot = stdstore 45 | .target(address(test)) 46 | .sig(test.map_struct.selector) 47 | .with_key(address(this)) 48 | .depth(0) 49 | .find(); 50 | assertEq(uint256(keccak256(abi.encode(address(this), 4))), slot); 51 | } 52 | 53 | function testStorageMapStructB() public { 54 | uint256 slot = stdstore 55 | .target(address(test)) 56 | .sig(test.map_struct.selector) 57 | .with_key(address(this)) 58 | .depth(1) 59 | .find(); 60 | assertEq(uint256(keccak256(abi.encode(address(this), 4))) + 1, slot); 61 | } 62 | 63 | function testStorageDeepMap() public { 64 | uint256 slot = stdstore 65 | .target(address(test)) 66 | .sig(test.deep_map.selector) 67 | .with_key(address(this)) 68 | .with_key(address(this)) 69 | .find(); 70 | assertEq( 71 | uint256( 72 | keccak256( 73 | abi.encode( 74 | address(this), 75 | keccak256(abi.encode(address(this), uint256(5))) 76 | ) 77 | ) 78 | ), 79 | slot 80 | ); 81 | } 82 | 83 | function testStorageCheckedWriteDeepMap() public { 84 | stdstore 85 | .target(address(test)) 86 | .sig(test.deep_map.selector) 87 | .with_key(address(this)) 88 | .with_key(address(this)) 89 | .checked_write(100); 90 | assertEq(100, test.deep_map(address(this), address(this))); 91 | } 92 | 93 | function testStorageDeepMapStructA() public { 94 | uint256 slot = stdstore 95 | .target(address(test)) 96 | .sig(test.deep_map_struct.selector) 97 | .with_key(address(this)) 98 | .with_key(address(this)) 99 | .depth(0) 100 | .find(); 101 | assertEq( 102 | bytes32( 103 | uint256( 104 | keccak256( 105 | abi.encode( 106 | address(this), 107 | keccak256(abi.encode(address(this), uint256(6))) 108 | ) 109 | ) 110 | ) + 0 111 | ), 112 | bytes32(slot) 113 | ); 114 | } 115 | 116 | function testStorageDeepMapStructB() public { 117 | uint256 slot = stdstore 118 | .target(address(test)) 119 | .sig(test.deep_map_struct.selector) 120 | .with_key(address(this)) 121 | .with_key(address(this)) 122 | .depth(1) 123 | .find(); 124 | assertEq( 125 | bytes32( 126 | uint256( 127 | keccak256( 128 | abi.encode( 129 | address(this), 130 | keccak256(abi.encode(address(this), uint256(6))) 131 | ) 132 | ) 133 | ) + 1 134 | ), 135 | bytes32(slot) 136 | ); 137 | } 138 | 139 | function testStorageCheckedWriteDeepMapStructA() public { 140 | stdstore 141 | .target(address(test)) 142 | .sig(test.deep_map_struct.selector) 143 | .with_key(address(this)) 144 | .with_key(address(this)) 145 | .depth(0) 146 | .checked_write(100); 147 | (uint256 a, uint256 b) = test.deep_map_struct( 148 | address(this), 149 | address(this) 150 | ); 151 | assertEq(100, a); 152 | assertEq(0, b); 153 | } 154 | 155 | function testStorageCheckedWriteDeepMapStructB() public { 156 | stdstore 157 | .target(address(test)) 158 | .sig(test.deep_map_struct.selector) 159 | .with_key(address(this)) 160 | .with_key(address(this)) 161 | .depth(1) 162 | .checked_write(100); 163 | (uint256 a, uint256 b) = test.deep_map_struct( 164 | address(this), 165 | address(this) 166 | ); 167 | assertEq(0, a); 168 | assertEq(100, b); 169 | } 170 | 171 | function testStorageCheckedWriteMapStructA() public { 172 | stdstore 173 | .target(address(test)) 174 | .sig(test.map_struct.selector) 175 | .with_key(address(this)) 176 | .depth(0) 177 | .checked_write(100); 178 | (uint256 a, uint256 b) = test.map_struct(address(this)); 179 | assertEq(a, 100); 180 | assertEq(b, 0); 181 | } 182 | 183 | function testStorageCheckedWriteMapStructB() public { 184 | stdstore 185 | .target(address(test)) 186 | .sig(test.map_struct.selector) 187 | .with_key(address(this)) 188 | .depth(1) 189 | .checked_write(100); 190 | (uint256 a, uint256 b) = test.map_struct(address(this)); 191 | assertEq(a, 0); 192 | assertEq(b, 100); 193 | } 194 | 195 | function testStorageStructA() public { 196 | uint256 slot = stdstore 197 | .target(address(test)) 198 | .sig(test.basic.selector) 199 | .depth(0) 200 | .find(); 201 | assertEq(uint256(7), slot); 202 | } 203 | 204 | function testStorageStructB() public { 205 | uint256 slot = stdstore 206 | .target(address(test)) 207 | .sig(test.basic.selector) 208 | .depth(1) 209 | .find(); 210 | assertEq(uint256(7) + 1, slot); 211 | } 212 | 213 | function testStorageCheckedWriteStructA() public { 214 | stdstore 215 | .target(address(test)) 216 | .sig(test.basic.selector) 217 | .depth(0) 218 | .checked_write(100); 219 | (uint256 a, uint256 b) = test.basic(); 220 | assertEq(a, 100); 221 | assertEq(b, 1337); 222 | } 223 | 224 | function testStorageCheckedWriteStructB() public { 225 | stdstore 226 | .target(address(test)) 227 | .sig(test.basic.selector) 228 | .depth(1) 229 | .checked_write(100); 230 | (uint256 a, uint256 b) = test.basic(); 231 | assertEq(a, 1337); 232 | assertEq(b, 100); 233 | } 234 | 235 | function testStorageMapAddrFound() public { 236 | uint256 slot = stdstore 237 | .target(address(test)) 238 | .sig(test.map_addr.selector) 239 | .with_key(address(this)) 240 | .find(); 241 | assertEq( 242 | uint256(keccak256(abi.encode(address(this), uint256(1)))), 243 | slot 244 | ); 245 | } 246 | 247 | function testStorageMapUintFound() public { 248 | uint256 slot = stdstore 249 | .target(address(test)) 250 | .sig(test.map_uint.selector) 251 | .with_key(100) 252 | .find(); 253 | assertEq(uint256(keccak256(abi.encode(100, uint256(2)))), slot); 254 | } 255 | 256 | function testStorageCheckedWriteMapUint() public { 257 | stdstore 258 | .target(address(test)) 259 | .sig(test.map_uint.selector) 260 | .with_key(100) 261 | .checked_write(100); 262 | assertEq(100, test.map_uint(100)); 263 | } 264 | 265 | function testStorageCheckedWriteMapAddr() public { 266 | stdstore 267 | .target(address(test)) 268 | .sig(test.map_addr.selector) 269 | .with_key(address(this)) 270 | .checked_write(100); 271 | assertEq(100, test.map_addr(address(this))); 272 | } 273 | 274 | function testStorageCheckedWriteMapBool() public { 275 | stdstore 276 | .target(address(test)) 277 | .sig(test.map_bool.selector) 278 | .with_key(address(this)) 279 | .checked_write(true); 280 | assertTrue(test.map_bool(address(this))); 281 | } 282 | 283 | function testFailStorageCheckedWriteMapPacked() public { 284 | // expect PackedSlot error but not external call so cant expectRevert 285 | stdstore 286 | .target(address(test)) 287 | .sig(test.read_struct_lower.selector) 288 | .with_key(address(uint160(1337))) 289 | .checked_write(100); 290 | } 291 | 292 | function testStorageCheckedWriteMapPackedSuccess() public { 293 | uint256 full = test.map_packed(address(1337)); 294 | // keep upper 128, set lower 128 to 1337 295 | full = (full & (uint256((1 << 128) - 1) << 128)) | 1337; 296 | stdstore 297 | .target(address(test)) 298 | .sig(test.map_packed.selector) 299 | .with_key(address(uint160(1337))) 300 | .checked_write(full); 301 | assertEq(1337, test.read_struct_lower(address(1337))); 302 | } 303 | 304 | function testFailStorageConst() public { 305 | // vm.expectRevert(abi.encodeWithSignature("NotStorage(bytes4)", bytes4(keccak256("const()")))); 306 | stdstore.target(address(test)).sig("const()").find(); 307 | } 308 | 309 | function testFailStorageNativePack() public { 310 | stdstore.target(address(test)).sig(test.tA.selector).find(); 311 | stdstore.target(address(test)).sig(test.tB.selector).find(); 312 | 313 | // these both would fail 314 | stdstore.target(address(test)).sig(test.tC.selector).find(); 315 | stdstore.target(address(test)).sig(test.tD.selector).find(); 316 | } 317 | 318 | function testStorageReadBytes32() public { 319 | bytes32 val = stdstore 320 | .target(address(test)) 321 | .sig(test.tE.selector) 322 | .read_bytes32(); 323 | assertEq(val, hex"1337"); 324 | } 325 | 326 | function testStorageReadBool() public { 327 | bool val = stdstore 328 | .target(address(test)) 329 | .sig(test.tB.selector) 330 | .read_bool(); 331 | assertEq(val, false); 332 | } 333 | 334 | function testStorageReadAddress() public { 335 | address val = stdstore 336 | .target(address(test)) 337 | .sig(test.tF.selector) 338 | .read_address(); 339 | assertEq(val, address(1337)); 340 | } 341 | 342 | function testStorageReadUint() public { 343 | uint256 val = stdstore 344 | .target(address(test)) 345 | .sig(test.exists.selector) 346 | .read_uint(); 347 | assertEq(val, 1); 348 | } 349 | 350 | function testStorageReadInt() public { 351 | int256 val = stdstore 352 | .target(address(test)) 353 | .sig(test.tG.selector) 354 | .read_int(); 355 | assertEq(val, type(int256).min); 356 | } 357 | } 358 | 359 | contract StorageTest { 360 | uint256 public exists = 1; 361 | mapping(address => uint256) public map_addr; 362 | mapping(uint256 => uint256) public map_uint; 363 | mapping(address => uint256) public map_packed; 364 | mapping(address => UnpackedStruct) public map_struct; 365 | mapping(address => mapping(address => uint256)) public deep_map; 366 | mapping(address => mapping(address => UnpackedStruct)) 367 | public deep_map_struct; 368 | UnpackedStruct public basic; 369 | 370 | uint248 public tA; 371 | bool public tB; 372 | 373 | bool public tC = false; 374 | uint248 public tD = 1; 375 | 376 | struct UnpackedStruct { 377 | uint256 a; 378 | uint256 b; 379 | } 380 | 381 | mapping(address => bool) public map_bool; 382 | 383 | bytes32 public tE = hex"1337"; 384 | address public tF = address(1337); 385 | int256 public tG = type(int256).min; 386 | 387 | constructor() { 388 | basic = UnpackedStruct({a: 1337, b: 1337}); 389 | 390 | uint256 two = (1 << 128) | 1; 391 | map_packed[msg.sender] = two; 392 | map_packed[address(bytes20(uint160(1337)))] = 1 << 128; 393 | } 394 | 395 | function read_struct_upper(address who) public view returns (uint256) { 396 | return map_packed[who] >> 128; 397 | } 398 | 399 | function read_struct_lower(address who) public view returns (uint256) { 400 | return map_packed[who] & ((1 << 128) - 1); 401 | } 402 | 403 | function hidden() public view returns (bytes32 t) { 404 | bytes32 slot = keccak256("my.random.var"); 405 | /// @solidity memory-safe-assembly 406 | assembly { 407 | t := sload(slot) 408 | } 409 | } 410 | 411 | function const() public pure returns (bytes32 t) { 412 | t = bytes32(hex"1337"); 413 | } 414 | } 415 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "hyperlane-quickstart", 3 | "description": "A set of files and configs for getting started using Hyperlane contracts", 4 | "version": "1.0.0", 5 | "dependencies": { 6 | "@hyperlane-xyz/sdk": "^1.2.2" 7 | }, 8 | "devDependencies": { 9 | "@nomicfoundation/hardhat-chai-matchers": "^1.0.0", 10 | "@nomicfoundation/hardhat-network-helpers": "^1.0.0", 11 | "@nomicfoundation/hardhat-toolbox": "^2.0.0", 12 | "@nomiclabs/hardhat-ethers": "^2.0.5", 13 | "@nomiclabs/hardhat-etherscan": "^3.0.0", 14 | "@typechain/ethers-v5": "^10.1.0", 15 | "@typechain/hardhat": "^6.1.2", 16 | "@types/chai": "^4.2.0", 17 | "@types/mocha": "^9.1.0", 18 | "@types/node": ">=12.0.0", 19 | "chai": "^4.3.0", 20 | "ethers": "^5.4.7", 21 | "hardhat": "^2.11.2", 22 | "hardhat-gas-reporter": "^1.0.8", 23 | "solidity-coverage": "^0.8.0", 24 | "ts-node": ">=8.0.0", 25 | "typechain": "^8.1.0", 26 | "typescript": ">=4.5.0" 27 | }, 28 | "license": "MIT", 29 | "main": "index.js", 30 | "scripts": { 31 | "hardhat:build": "hardhat compile", 32 | "hardhat:clean": "hardhat clean && rm -rf dist cache types", 33 | "hardhat:coverage": "hardhat coverage", 34 | "hardhat:test": "hardhat test ./test/*.test.ts" 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /remappings.txt: -------------------------------------------------------------------------------- 1 | ds-test/=lib/forge-std/lib/ds-test/src/ 2 | forge-std/=lib/forge-std/src/ -------------------------------------------------------------------------------- /scripts/deploy.ts: -------------------------------------------------------------------------------- 1 | import { ethers } from "hardhat"; 2 | 3 | async function main() { 4 | const currentTimestampInSeconds = Math.round(Date.now() / 1000); 5 | const ONE_YEAR_IN_SECS = 365 * 24 * 60 * 60; 6 | const unlockTime = currentTimestampInSeconds + ONE_YEAR_IN_SECS; 7 | 8 | const lockedAmount = ethers.utils.parseEther("1"); 9 | 10 | const Lock = await ethers.getContractFactory("Lock"); 11 | const lock = await Lock.deploy(unlockTime, { value: lockedAmount }); 12 | 13 | await lock.deployed(); 14 | 15 | console.log(`Lock with 1 ETH and unlock timestamp ${unlockTime} deployed to ${lock.address}`); 16 | } 17 | 18 | // We recommend this pattern to be able to use async/await everywhere 19 | // and properly handle errors. 20 | main().catch((error) => { 21 | console.error(error); 22 | process.exitCode = 1; 23 | }); 24 | -------------------------------------------------------------------------------- /test/foundry/InterchainAccount.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: UNLICENSED 2 | pragma solidity ^0.8.13; 3 | 4 | import "forge-std/Test.sol"; 5 | import {TypeCasts} from "@hyperlane-xyz/core/contracts/libs/TypeCasts.sol"; 6 | 7 | import "../../contracts/Owner.sol"; 8 | import "../../contracts/Ownee.sol"; 9 | import "../../contracts/MockInterchainAccountRouter.sol"; 10 | 11 | contract InterchainAccountTest is Test { 12 | Owner owner; 13 | Ownee ownee; 14 | MockInterchainAccountRouter router; 15 | uint32 originDomain = 1; 16 | uint32 remoteDomain = 2; 17 | 18 | function setUp() public { 19 | router = new MockInterchainAccountRouter(originDomain); 20 | owner = new Owner(address(router)); 21 | 22 | 23 | address ownerICA = router.getInterchainAccount( 24 | originDomain, 25 | address(owner) 26 | ); 27 | // Sets the ownee owner to the ICA of the owner; 28 | ownee = new Ownee(ownerICA); 29 | } 30 | 31 | function testSettingNewOwner(address newOwner) public { 32 | vm.assume(newOwner != address(0x0)); 33 | owner.transferRemoteOwnership(remoteDomain, address(ownee), newOwner); 34 | router.processNextPendingCall(); 35 | assertEq(ownee.owner(), newOwner); 36 | } 37 | 38 | function testSettingFee(uint256 newFee) public { 39 | vm.assume(newFee != 0); 40 | owner.setRemoteFee(remoteDomain, address(ownee), newFee); 41 | router.processNextPendingCall(); 42 | assertEq(ownee.fee(), newFee); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /test/foundry/Messaging.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: UNLICENSED 2 | pragma solidity ^0.8.13; 3 | 4 | import "forge-std/Test.sol"; 5 | import "@hyperlane-xyz/core/contracts/mock/MockMailbox.sol"; 6 | import {TypeCasts} from "@hyperlane-xyz/core/contracts/libs/TypeCasts.sol"; 7 | 8 | import "../../contracts/HyperlaneMessageSender.sol"; 9 | import "../../contracts/HyperlaneMessageReceiver.sol"; 10 | 11 | contract MessagingTest is Test { 12 | MockMailbox originMailbox; 13 | MockMailbox destinationMailbox; 14 | 15 | HyperlaneMessageSender sender; 16 | HyperlaneMessageReceiver receiver; 17 | 18 | uint32 originDomain = 1; 19 | uint32 destinationDomain = 2; 20 | 21 | function setUp() public { 22 | originMailbox = new MockMailbox(originDomain); 23 | destinationMailbox = new MockMailbox(destinationDomain); 24 | originMailbox.addRemoteMailbox(destinationDomain, destinationMailbox); 25 | sender = new HyperlaneMessageSender(address(originMailbox)); 26 | receiver = new HyperlaneMessageReceiver(address(destinationMailbox)); 27 | } 28 | 29 | function testSendMessage(string calldata _message) public { 30 | sender.sendString(destinationDomain, TypeCasts.addressToBytes32(address(receiver)), _message); 31 | destinationMailbox.processNextInboundMessage(); 32 | assertEq(receiver.lastMessage(), _message); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /test/interchainaccounts.test.ts: -------------------------------------------------------------------------------- 1 | import { expect } from "chai"; 2 | import { ethers } from "hardhat"; 3 | import { utils } from "@hyperlane-xyz/utils"; 4 | import { 5 | TestRecipient__factory, 6 | } from "@hyperlane-xyz/core"; 7 | import { MockInterchainAccountRouter, Ownee, Owner } from "../typechain-types"; 8 | 9 | describe("Hyperlane", function () { 10 | describe("Interchain Accounts", function () { 11 | const originDomain = 1; 12 | const destinationDomain = 2; 13 | 14 | let owner: Owner; 15 | let ownee: Ownee; 16 | let router: MockInterchainAccountRouter; 17 | 18 | beforeEach(async function () { 19 | const routerFactory = await ethers.getContractFactory( 20 | "MockInterchainAccountRouter" 21 | ); 22 | const ownerFactory = await ethers.getContractFactory("Owner"); 23 | const owneeFactory = await ethers.getContractFactory("Ownee"); 24 | 25 | router = await routerFactory.deploy(originDomain); 26 | owner = await ownerFactory.deploy(router.address); 27 | 28 | const ownerICA = await router.getInterchainAccount( 29 | originDomain, 30 | owner.address 31 | ); 32 | // Set ownee owner to the ICA of the owner 33 | ownee = await owneeFactory.deploy(ownerICA); 34 | }); 35 | 36 | it("can set a fee", async function () { 37 | const fee = 42; 38 | 39 | await owner.setRemoteFee(destinationDomain, ownee.address, fee); 40 | await router.processNextPendingCall(); 41 | expect((await ownee.fee()).toNumber()).to.eql(fee); 42 | }); 43 | 44 | it ("can transfer ownership", async function () { 45 | // Random new owner 46 | const newOwner = router.address; 47 | 48 | await owner.transferRemoteOwnership(destinationDomain, ownee.address, newOwner); 49 | await router.processNextPendingCall(); 50 | expect(await ownee.owner()).to.eql(newOwner); 51 | }) 52 | }); 53 | }); 54 | -------------------------------------------------------------------------------- /test/messaging.test.ts: -------------------------------------------------------------------------------- 1 | import { expect } from "chai"; 2 | import { ethers } from "hardhat"; 3 | import { utils } from "@hyperlane-xyz/utils"; 4 | import { 5 | MockMailbox__factory, 6 | TestRecipient__factory, 7 | } from "@hyperlane-xyz/core"; 8 | 9 | describe("Hyperlane", function () { 10 | describe("Hyperlane Message Sending and Receiving", function () { 11 | it("should be able to send a message directly", async function () { 12 | const originDomain = 1; 13 | const destinationDomain = 2 14 | const signer = (await ethers.getSigners())[0]; 15 | const destinationMailbox = await new MockMailbox__factory(signer).deploy(destinationDomain); 16 | await destinationMailbox.deployed(); 17 | const originMailbox = await new MockMailbox__factory(signer).deploy( 18 | originDomain 19 | ); 20 | await originMailbox.deployed(); 21 | await originMailbox.addRemoteMailbox(destinationDomain, destinationMailbox.address); 22 | 23 | const recipient = await new TestRecipient__factory(signer).deploy(); 24 | const data = ethers.utils.toUtf8Bytes("This is a test message"); 25 | 26 | await originMailbox.dispatch(destinationDomain, utils.addressToBytes32(recipient.address), data); 27 | await destinationMailbox.processNextInboundMessage(); 28 | 29 | const dataReceived = await recipient.lastData(); 30 | expect(dataReceived).to.eql(ethers.utils.hexlify(data)); 31 | }); 32 | 33 | it("can send a message via HyperlaneMessageSender/Receiver", async function () { 34 | const originDomain = 1; 35 | const destinationDomain = 2; 36 | const testString = "This is a test" 37 | const signer = (await ethers.getSigners())[0]; 38 | const destinationMailbox = await new MockMailbox__factory(signer).deploy(destinationDomain); 39 | await destinationMailbox.deployed(); 40 | const originMailbox = await new MockMailbox__factory(signer).deploy( 41 | originDomain 42 | ); 43 | await originMailbox.deployed(); 44 | await originMailbox.addRemoteMailbox(destinationDomain, destinationMailbox.address); 45 | 46 | const senderFactory = await ethers.getContractFactory( 47 | "HyperlaneMessageSender" 48 | ); 49 | const sender = await senderFactory.deploy(originMailbox.address); 50 | 51 | const receiverFactory = await ethers.getContractFactory( 52 | "HyperlaneMessageReceiver" 53 | ); 54 | const receiver = await receiverFactory.deploy(destinationMailbox.address); 55 | 56 | await sender.sendString( 57 | destinationDomain, 58 | utils.addressToBytes32(receiver.address), 59 | testString 60 | ); 61 | await destinationMailbox.processNextInboundMessage(); 62 | expect(await receiver.lastMessage()).to.eql(testString); 63 | }); 64 | }); 65 | }); 66 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es2020", 4 | "module": "commonjs", 5 | "esModuleInterop": true, 6 | "forceConsistentCasingInFileNames": true, 7 | "strict": true, 8 | "skipLibCheck": true 9 | } 10 | } 11 | --------------------------------------------------------------------------------