├── .gitattributes
├── .github
└── workflows
│ └── test.yaml
├── .gitignore
├── LICENSE
├── README.md
├── foundry.toml
├── lib
└── forge-std
│ ├── .github
│ └── workflows
│ │ └── tests.yml
│ ├── .gitignore
│ ├── .gitmodules
│ ├── LICENSE-APACHE
│ ├── LICENSE-MIT
│ ├── README.md
│ ├── foundry.toml
│ ├── lib
│ └── ds-test
│ │ ├── .gitignore
│ │ ├── LICENSE
│ │ ├── Makefile
│ │ ├── default.nix
│ │ ├── demo
│ │ └── demo.sol
│ │ └── src
│ │ └── test.sol
│ └── src
│ ├── Script.sol
│ ├── StdJson.sol
│ ├── Test.sol
│ ├── Vm.sol
│ ├── console.sol
│ ├── console2.sol
│ └── test
│ ├── Script.t.sol
│ ├── StdAssertions.t.sol
│ ├── StdCheats.t.sol
│ ├── StdError.t.sol
│ ├── StdMath.t.sol
│ ├── StdStorage.t.sol
│ └── fixtures
│ └── broadcast.log.json
├── src
├── BigNumbers.sol
└── utils
│ └── Crypto.sol
└── test
├── BigNumbers.t.sol
└── differential
├── BigNumbers.dt.sol
├── README.md
├── scripts
├── differential.ts
└── package.json
└── util
└── Strings.sol
/.gitattributes:
--------------------------------------------------------------------------------
1 | *.sol linguist-language=Solidity
2 |
--------------------------------------------------------------------------------
/.github/workflows/test.yaml:
--------------------------------------------------------------------------------
1 | name: test
2 |
3 | on:
4 | push:
5 | branches: [ "master" ]
6 | pull_request:
7 | branches: [ "master" ]
8 |
9 | workflow_dispatch:
10 |
11 | env:
12 | FOUNDRY_PROFILE: ci
13 |
14 | jobs:
15 | check:
16 | strategy:
17 | fail-fast: true
18 |
19 | name: Foundry project
20 | runs-on: ubuntu-latest
21 | steps:
22 | - uses: actions/checkout@v3
23 | with:
24 | submodules: recursive
25 |
26 | - name: Install Foundry
27 | uses: foundry-rs/foundry-toolchain@v1.2.0
28 |
29 | - name: Run Forge build
30 | run: |
31 | forge build --skip test --sizes
32 | forge build
33 | id: build
34 |
35 | - name: Run Forge unit tests
36 | run: |
37 | forge test --mc BigNumbersTest -vvv
38 | id: test
39 |
40 | # Node.js setup and differential testing steps
41 | - name: Set up Node.js
42 | uses: actions/setup-node@v3
43 | with:
44 | node-version: '14.17'
45 |
46 | - name: Install Node.js dependencies
47 | working-directory: ./test/differential/scripts
48 | run: npm install
49 |
50 | - name: Compile Node.js project
51 | working-directory: ./test/differential/scripts
52 | run: npm run compile
53 |
54 | - name: Run differential Forge test
55 | run: |
56 | forge test -vvv --ffi --mc BigNumbersDifferentialTest
57 | id: differential-test
58 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | cache/
2 | notes/
3 | out/
4 | test/differential/scripts/differential.js
5 | test/differential/scripts/node_modules
6 | test/differential/scripts/package-lock.json
7 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2022 riordant
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | # Big Number Library for Solidity
4 |
5 | # Disclaimer!
6 | **While extensive testing has occured, this code has _not_ been audited. The developers take no responsiblity should this code be used in a production environment without first auditing sections applicable to you by a reputable auditing firm.**
7 |
8 | ## Introduction
9 |
10 | With the release of Metropolis, and the precompiled contract allowing modular exponentiations for arbitrary-sized inputs, we can now process big integer functions on the EVM, ie. values greater than a single EVM word (256 bits). These functions can be used as the building blocks for various cryptographic operations, for example in RSA signature verification, and ring-signature schemes.
11 |
12 | ## Overview
13 | Values in memory on the EVM are in 256 bit (32 byte) words - `BigNumber`s in this library are considered to be consecutive words in big-endian order (top to bottom: word `0` - word `n`).
14 |
15 | The struct `BigNumber` defined in (`src/BigNumber.sol`) consists of the bytes value, the bit-length, and the sign of the value.
16 |
17 | The value is in the Solidity `bytes` data structure. by default, this data structure is 'tightly packed', ie. it has no leading zeroes, and it has a 'length' word indicating the number of bytes in the structure.
18 |
19 | We consider each BigNumber value to NOT be tightly packed in the bytes data structure, ie. it has a number of leading zeros such that the value aligns at exactly the size of a number of words.
20 | for explanation's sake, imagine that instead the EVM had a 32 bit word width, and the following value (in bytes):
21 |
22 | ae1b6b9f1be57476a6948f77effc
23 |
24 | this is 14 bytes. by default, solidity's `bytes` would prepend this structure with the value `0x0e` (14 in hex), and it's representation in memory would be like so:
25 |
26 | 0000000e - length
27 | ae1b6b9f - word 0
28 | 1be57476 - word 1
29 | a6948f77 - word 2
30 | effc0000 - word 3
31 |
32 | In our scheme, the values are literally shifted to the right by the amount of zero bytes in the final word, and the length is changed to include these bytes.
33 | our scheme:
34 |
35 | 00000010 - length (16 - num words * 4, 4 bytes per word)
36 | 0000ae1b - word 0
37 | 6b9f1be5 - word 1
38 | 7476a694 - word 2
39 | 8f77effc - word 3
40 |
41 | this is a kind of 'normalisation'. values will 'line up' with their number representation in memory and so it saves us the hassle of trying to manage the offset when performing operations like add and subtract.
42 |
43 | our scheme is the same as above with 32 byte words. This is actually how `uint[]` represents values (bar the length being the number of words as opposed to number of bytes); however, using raw bytes has a number of advantages.
44 |
45 | ## Rationale
46 | As we are using assembly to manipulate values directly in memory, `uint[]` is cumbersome and adds too much unnecessary overhead.
47 | Additionally, the modular exponentiation pre-compiled contract, used and derived from in the library for various operations, expects as parameters, AND returns, the bytes datatype, so it saves the conversion either side.
48 |
49 | The sign of the value is controlled artificially, as is the case with other big integer libraries.
50 |
51 | The most significant bit (`bitlen`) is tracked throughout the lifespan of the BigNumber instance. when the caller creates a BigNumber they can also indicate this value (which the contract verifies), or allow the contract to compute it itself.
52 |
53 |
54 | ## Verification
55 | In performing computations that consume an impossibly large amount of gas, it is necessary to compute them off-chain and have them verified on-chain. In this library, this is possible with two functions: `divVerify` and `modinvVerify`. in both cases, the user must pass the result of each computation along with the computation's inputs, and the contracts verifies that they were computed correctly, before returning the result.
56 |
57 | To make this as frictionless as possible:
58 |
59 | - Import your function into a Foundry test case
60 |
61 | - use the `ffi` cheatcode to call the real function in an external library
62 |
63 | - write the resulting calldata to be used for the function call.
64 |
65 | see `tests/differential` for examples of this.
66 |
67 | ## Usage
68 | If your functions directly take `BigNumber`s as arguments, it is required to first call `verify()` on these values to ensure that they are in the right format. See `src/utils/Crypto.sol` for an example of this.
69 |
70 | ## Crypto
71 | The library `src/utils/Crypto.sol` contains some common algorithms that can be used with this `BigNumber` library. Is also shows some example usage.
72 |
73 |
74 | ## Development
75 |
76 | This is a [Foundry](https://github.com/foundry-rs/foundry/) project. Ensure you have that installed.
77 |
78 | #### Build
79 | ```
80 | $ forge build
81 | ```
82 |
83 | #### Run Unit Tests
84 | ```
85 | $ forge test --mc BigNumbersTest
86 | ```
87 |
88 | ## Differential Testing
89 | Similar to [Murky](https://github.com/dmfxyz/murky/), this project makes use of Foundry's differential and fuzz testing capibilities. More info and setup is in `test/differential`.
90 |
91 | Any proposed extensions, improvements, issue discoveries etc. are welcomed!
92 |
--------------------------------------------------------------------------------
/foundry.toml:
--------------------------------------------------------------------------------
1 | [profile.default]
2 | src = 'src'
3 | out = 'out'
4 | libs = ['lib']
5 |
6 | [fuzz]
7 | runs = 100
8 |
9 | [profile.default.optimizer_details]
10 | yul = false
11 | # See more config options https://github.com/foundry-rs/foundry/tree/master/config
12 |
--------------------------------------------------------------------------------
/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.6
26 | forge build --contracts src/Test.sol --use solc:0.7.0
27 | forge build --contracts src/Test.sol --use solc:0.6.0
28 |
--------------------------------------------------------------------------------
/lib/forge-std/.gitignore:
--------------------------------------------------------------------------------
1 | cache/
2 | out/
3 | .vscode
4 | .idea
--------------------------------------------------------------------------------
/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) 2022 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) 2022 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 • [](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 | ### stdError
15 |
16 | 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.
17 |
18 | See the contract itself for all error codes.
19 |
20 | #### Example usage
21 |
22 | ```solidity
23 |
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 | ### stdStorage
47 |
48 | 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)`).
49 |
50 | 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.
51 |
52 | I.e.:
53 | ```solidity
54 | struct T {
55 | // depth 0
56 | uint256 a;
57 | // depth 1
58 | uint256 b;
59 | }
60 | ```
61 |
62 | #### Example usage
63 |
64 | ```solidity
65 | import "forge-std/Test.sol";
66 |
67 | contract TestContract is Test {
68 | using stdStorage for StdStorage;
69 |
70 | Storage test;
71 |
72 | function setUp() public {
73 | test = new Storage();
74 | }
75 |
76 | function testFindExists() public {
77 | // Lets say we want to find the slot for the public
78 | // variable `exists`. We just pass in the function selector
79 | // to the `find` command
80 | uint256 slot = stdstore.target(address(test)).sig("exists()").find();
81 | assertEq(slot, 0);
82 | }
83 |
84 | function testWriteExists() public {
85 | // Lets say we want to write to the slot for the public
86 | // variable `exists`. We just pass in the function selector
87 | // to the `checked_write` command
88 | stdstore.target(address(test)).sig("exists()").checked_write(100);
89 | assertEq(test.exists(), 100);
90 | }
91 |
92 | // It supports arbitrary storage layouts, like assembly based storage locations
93 | function testFindHidden() public {
94 | // `hidden` is a random hash of a bytes, iteration through slots would
95 | // not find it. Our mechanism does
96 | // Also, you can use the selector instead of a string
97 | uint256 slot = stdstore.target(address(test)).sig(test.hidden.selector).find();
98 | assertEq(slot, uint256(keccak256("my.random.var")));
99 | }
100 |
101 | // If targeting a mapping, you have to pass in the keys necessary to perform the find
102 | // i.e.:
103 | function testFindMapping() public {
104 | uint256 slot = stdstore
105 | .target(address(test))
106 | .sig(test.map_addr.selector)
107 | .with_key(address(this))
108 | .find();
109 | // in the `Storage` constructor, we wrote that this address' value was 1 in the map
110 | // so when we load the slot, we expect it to be 1
111 | assertEq(uint(vm.load(address(test), bytes32(slot))), 1);
112 | }
113 |
114 | // If the target is a struct, you can specify the field depth:
115 | function testFindStruct() public {
116 | // NOTE: see the depth parameter - 0 means 0th field, 1 means 1st field, etc.
117 | uint256 slot_for_a_field = stdstore
118 | .target(address(test))
119 | .sig(test.basicStruct.selector)
120 | .depth(0)
121 | .find();
122 |
123 | uint256 slot_for_b_field = stdstore
124 | .target(address(test))
125 | .sig(test.basicStruct.selector)
126 | .depth(1)
127 | .find();
128 |
129 | assertEq(uint(vm.load(address(test), bytes32(slot_for_a_field))), 1);
130 | assertEq(uint(vm.load(address(test), bytes32(slot_for_b_field))), 2);
131 | }
132 | }
133 |
134 | // A complex storage contract
135 | contract Storage {
136 | struct UnpackedStruct {
137 | uint256 a;
138 | uint256 b;
139 | }
140 |
141 | constructor() {
142 | map_addr[msg.sender] = 1;
143 | }
144 |
145 | uint256 public exists = 1;
146 | mapping(address => uint256) public map_addr;
147 | // mapping(address => Packed) public map_packed;
148 | mapping(address => UnpackedStruct) public map_struct;
149 | mapping(address => mapping(address => uint256)) public deep_map;
150 | mapping(address => mapping(address => UnpackedStruct)) public deep_map_struct;
151 | UnpackedStruct public basicStruct = UnpackedStruct({
152 | a: 1,
153 | b: 2
154 | });
155 |
156 | function hidden() public view returns (bytes32 t) {
157 | // an extremely hidden storage slot
158 | bytes32 slot = keccak256("my.random.var");
159 | assembly {
160 | t := sload(slot)
161 | }
162 | }
163 | }
164 | ```
165 |
166 | ### stdCheats
167 |
168 | 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.
169 |
170 |
171 | #### Example usage:
172 | ```solidity
173 |
174 | // SPDX-License-Identifier: MIT
175 | pragma solidity ^0.8.0;
176 |
177 | import "forge-std/Test.sol";
178 |
179 | // Inherit the stdCheats
180 | contract StdCheatsTest is Test {
181 | Bar test;
182 | function setUp() public {
183 | test = new Bar();
184 | }
185 |
186 | function testHoax() public {
187 | // we call `hoax`, which gives the target address
188 | // eth and then calls `prank`
189 | hoax(address(1337));
190 | test.bar{value: 100}(address(1337));
191 |
192 | // overloaded to allow you to specify how much eth to
193 | // initialize the address with
194 | hoax(address(1337), 1);
195 | test.bar{value: 1}(address(1337));
196 | }
197 |
198 | function testStartHoax() public {
199 | // we call `startHoax`, which gives the target address
200 | // eth and then calls `startPrank`
201 | //
202 | // it is also overloaded so that you can specify an eth amount
203 | startHoax(address(1337));
204 | test.bar{value: 100}(address(1337));
205 | test.bar{value: 100}(address(1337));
206 | vm.stopPrank();
207 | test.bar(address(this));
208 | }
209 | }
210 |
211 | contract Bar {
212 | function bar(address expectedSender) public payable {
213 | require(msg.sender == expectedSender, "!prank");
214 | }
215 | }
216 | ```
217 |
218 | ### Std Assertions
219 |
220 | Expand upon the assertion functions from the `DSTest` library.
221 |
222 | ### `console.log`
223 |
224 | Usage follows the same format as [Hardhat](https://hardhat.org/hardhat-network/reference/#console-log).
225 | It's recommended to use `console2.sol` as shown below, as this will show the decoded logs in Forge traces.
226 |
227 | ```solidity
228 | // import it indirectly via Test.sol
229 | import "forge-std/Test.sol";
230 | // or directly import it
231 | import "forge-std/console2.sol";
232 | ...
233 | console2.log(someValue);
234 | ```
235 |
236 | If you need compatibility with Hardhat, you must use the standard `console.sol` instead.
237 | Due to a bug in `console.sol`, logs that use `uint256` or `int256` types will not be properly decoded in Forge traces.
238 |
239 | ```solidity
240 | // import it indirectly via Test.sol
241 | import "forge-std/Test.sol";
242 | // or directly import it
243 | import "forge-std/console.sol";
244 | ...
245 | console.log(someValue);
246 | ```
247 |
--------------------------------------------------------------------------------
/lib/forge-std/foundry.toml:
--------------------------------------------------------------------------------
1 | [profile.default]
2 | fs_permissions = [{ access = "read-write", path = "./"}]
3 |
--------------------------------------------------------------------------------
/lib/forge-std/lib/ds-test/.gitignore:
--------------------------------------------------------------------------------
1 | /.dapple
2 | /build
3 | /out
4 |
--------------------------------------------------------------------------------
/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.5.0;
3 |
4 | import "../src/test.sol";
5 |
6 | contract DemoTest is DSTest {
7 | function test_this() public pure {
8 | require(true);
9 | }
10 | function test_logs() public {
11 | emit log("-- log(string)");
12 | emit log("a string");
13 |
14 | emit log("-- log_named_uint(string, uint)");
15 | emit log_named_uint("uint", 512);
16 |
17 | emit log("-- log_named_int(string, int)");
18 | emit log_named_int("int", -512);
19 |
20 | emit log("-- log_named_address(string, address)");
21 | emit log_named_address("address", address(this));
22 |
23 | emit log("-- log_named_bytes32(string, bytes32)");
24 | emit log_named_bytes32("bytes32", "a string");
25 |
26 | emit log("-- log_named_bytes(string, bytes)");
27 | emit log_named_bytes("bytes", hex"cafefe");
28 |
29 | emit log("-- log_named_string(string, string)");
30 | emit log_named_string("string", "a string");
31 |
32 | emit log("-- log_named_decimal_uint(string, uint, uint)");
33 | emit log_named_decimal_uint("decimal uint", 1.0e18, 18);
34 |
35 | emit log("-- log_named_decimal_int(string, int, uint)");
36 | emit log_named_decimal_int("decimal int", -1.0e18, 18);
37 | }
38 | event log_old_named_uint(bytes32,uint);
39 | function test_old_logs() public {
40 | emit log_old_named_uint("key", 500);
41 | emit log_named_bytes32("bkey", "val");
42 | }
43 | function test_trace() public view {
44 | this.echo("string 1", "string 2");
45 | }
46 | function test_multiline() public {
47 | emit log("a multiline\\nstring");
48 | emit log("a multiline string");
49 | emit log_bytes("a string");
50 | emit log_bytes("a multiline\nstring");
51 | emit log_bytes("a multiline\\nstring");
52 | emit logs(hex"0000");
53 | emit log_named_bytes("0x0000", hex"0000");
54 | emit logs(hex"ff");
55 | }
56 | function echo(string memory s1, string memory s2) public pure
57 | returns (string memory, string memory)
58 | {
59 | return (s1, s2);
60 | }
61 |
62 | function prove_this(uint x) public {
63 | emit log_named_uint("sym x", x);
64 | assertGt(x + 1, 0);
65 | }
66 |
67 | function test_logn() public {
68 | assembly {
69 | log0(0x01, 0x02)
70 | log1(0x01, 0x02, 0x03)
71 | log2(0x01, 0x02, 0x03, 0x04)
72 | log3(0x01, 0x02, 0x03, 0x04, 0x05)
73 | }
74 | }
75 |
76 | event MyEvent(uint, uint indexed, uint, uint indexed);
77 | function test_events() public {
78 | emit MyEvent(1, 2, 3, 4);
79 | }
80 |
81 | function test_asserts() public {
82 | string memory err = "this test has failed!";
83 | emit log("## assertTrue(bool)\n");
84 | assertTrue(false);
85 | emit log("\n");
86 | assertTrue(false, err);
87 |
88 | emit log("\n## assertEq(address,address)\n");
89 | assertEq(address(this), msg.sender);
90 | emit log("\n");
91 | assertEq(address(this), msg.sender, err);
92 |
93 | emit log("\n## assertEq32(bytes32,bytes32)\n");
94 | assertEq32("bytes 1", "bytes 2");
95 | emit log("\n");
96 | assertEq32("bytes 1", "bytes 2", err);
97 |
98 | emit log("\n## assertEq(bytes32,bytes32)\n");
99 | assertEq32("bytes 1", "bytes 2");
100 | emit log("\n");
101 | assertEq32("bytes 1", "bytes 2", err);
102 |
103 | emit log("\n## assertEq(uint,uint)\n");
104 | assertEq(uint(0), 1);
105 | emit log("\n");
106 | assertEq(uint(0), 1, err);
107 |
108 | emit log("\n## assertEq(int,int)\n");
109 | assertEq(-1, -2);
110 | emit log("\n");
111 | assertEq(-1, -2, err);
112 |
113 | emit log("\n## assertEqDecimal(int,int,uint)\n");
114 | assertEqDecimal(-1.0e18, -1.1e18, 18);
115 | emit log("\n");
116 | assertEqDecimal(-1.0e18, -1.1e18, 18, err);
117 |
118 | emit log("\n## assertEqDecimal(uint,uint,uint)\n");
119 | assertEqDecimal(uint(1.0e18), 1.1e18, 18);
120 | emit log("\n");
121 | assertEqDecimal(uint(1.0e18), 1.1e18, 18, err);
122 |
123 | emit log("\n## assertGt(uint,uint)\n");
124 | assertGt(uint(0), 0);
125 | emit log("\n");
126 | assertGt(uint(0), 0, err);
127 |
128 | emit log("\n## assertGt(int,int)\n");
129 | assertGt(-1, -1);
130 | emit log("\n");
131 | assertGt(-1, -1, err);
132 |
133 | emit log("\n## assertGtDecimal(int,int,uint)\n");
134 | assertGtDecimal(-2.0e18, -1.1e18, 18);
135 | emit log("\n");
136 | assertGtDecimal(-2.0e18, -1.1e18, 18, err);
137 |
138 | emit log("\n## assertGtDecimal(uint,uint,uint)\n");
139 | assertGtDecimal(uint(1.0e18), 1.1e18, 18);
140 | emit log("\n");
141 | assertGtDecimal(uint(1.0e18), 1.1e18, 18, err);
142 |
143 | emit log("\n## assertGe(uint,uint)\n");
144 | assertGe(uint(0), 1);
145 | emit log("\n");
146 | assertGe(uint(0), 1, err);
147 |
148 | emit log("\n## assertGe(int,int)\n");
149 | assertGe(-1, 0);
150 | emit log("\n");
151 | assertGe(-1, 0, err);
152 |
153 | emit log("\n## assertGeDecimal(int,int,uint)\n");
154 | assertGeDecimal(-2.0e18, -1.1e18, 18);
155 | emit log("\n");
156 | assertGeDecimal(-2.0e18, -1.1e18, 18, err);
157 |
158 | emit log("\n## assertGeDecimal(uint,uint,uint)\n");
159 | assertGeDecimal(uint(1.0e18), 1.1e18, 18);
160 | emit log("\n");
161 | assertGeDecimal(uint(1.0e18), 1.1e18, 18, err);
162 |
163 | emit log("\n## assertLt(uint,uint)\n");
164 | assertLt(uint(0), 0);
165 | emit log("\n");
166 | assertLt(uint(0), 0, err);
167 |
168 | emit log("\n## assertLt(int,int)\n");
169 | assertLt(-1, -1);
170 | emit log("\n");
171 | assertLt(-1, -1, err);
172 |
173 | emit log("\n## assertLtDecimal(int,int,uint)\n");
174 | assertLtDecimal(-1.0e18, -1.1e18, 18);
175 | emit log("\n");
176 | assertLtDecimal(-1.0e18, -1.1e18, 18, err);
177 |
178 | emit log("\n## assertLtDecimal(uint,uint,uint)\n");
179 | assertLtDecimal(uint(2.0e18), 1.1e18, 18);
180 | emit log("\n");
181 | assertLtDecimal(uint(2.0e18), 1.1e18, 18, err);
182 |
183 | emit log("\n## assertLe(uint,uint)\n");
184 | assertLe(uint(1), 0);
185 | emit log("\n");
186 | assertLe(uint(1), 0, err);
187 |
188 | emit log("\n## assertLe(int,int)\n");
189 | assertLe(0, -1);
190 | emit log("\n");
191 | assertLe(0, -1, err);
192 |
193 | emit log("\n## assertLeDecimal(int,int,uint)\n");
194 | assertLeDecimal(-1.0e18, -1.1e18, 18);
195 | emit log("\n");
196 | assertLeDecimal(-1.0e18, -1.1e18, 18, err);
197 |
198 | emit log("\n## assertLeDecimal(uint,uint,uint)\n");
199 | assertLeDecimal(uint(2.0e18), 1.1e18, 18);
200 | emit log("\n");
201 | assertLeDecimal(uint(2.0e18), 1.1e18, 18, err);
202 |
203 | emit log("\n## assertEq(string,string)\n");
204 | string memory s1 = "string 1";
205 | string memory s2 = "string 2";
206 | assertEq(s1, s2);
207 | emit log("\n");
208 | assertEq(s1, s2, err);
209 |
210 | emit log("\n## assertEq0(bytes,bytes)\n");
211 | assertEq0(hex"abcdef01", hex"abcdef02");
212 | emit log("\n");
213 | assertEq0(hex"abcdef01", hex"abcdef02", err);
214 | }
215 | }
216 |
217 | contract DemoTestWithSetUp {
218 | function setUp() public {
219 | }
220 | function test_pass() public pure {
221 | }
222 | }
223 |
--------------------------------------------------------------------------------
/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 (int);
25 | event log_uint (uint);
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, int val, uint decimals);
32 | event log_named_decimal_uint (string key, uint val, uint decimals);
33 | event log_named_int (string key, int val);
34 | event log_named_uint (string key, uint 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 | modifier testopts(string memory) { _; }
46 |
47 | function failed() public returns (bool) {
48 | if (_failed) {
49 | return _failed;
50 | } else {
51 | bool globalFailed = false;
52 | if (hasHEVMContext()) {
53 | (, bytes memory retdata) = HEVM_ADDRESS.call(
54 | abi.encodePacked(
55 | bytes4(keccak256("load(address,bytes32)")),
56 | abi.encode(HEVM_ADDRESS, bytes32("failed"))
57 | )
58 | );
59 | globalFailed = abi.decode(retdata, (bool));
60 | }
61 | return globalFailed;
62 | }
63 | }
64 |
65 | function fail() internal {
66 | if (hasHEVMContext()) {
67 | (bool status, ) = HEVM_ADDRESS.call(
68 | abi.encodePacked(
69 | bytes4(keccak256("store(address,bytes32,bytes32)")),
70 | abi.encode(HEVM_ADDRESS, bytes32("failed"), bytes32(uint256(0x01)))
71 | )
72 | );
73 | status; // Silence compiler warnings
74 | }
75 | _failed = true;
76 | }
77 |
78 | function hasHEVMContext() internal view returns (bool) {
79 | uint256 hevmCodeSize = 0;
80 | assembly {
81 | hevmCodeSize := extcodesize(0x7109709ECfa91a80626fF3989D68f67F5b1DD12D)
82 | }
83 | return hevmCodeSize > 0;
84 | }
85 |
86 | modifier logs_gas() {
87 | uint startGas = gasleft();
88 | _;
89 | uint endGas = gasleft();
90 | emit log_named_uint("gas", startGas - endGas);
91 | }
92 |
93 | function assertTrue(bool condition) internal {
94 | if (!condition) {
95 | emit log("Error: Assertion Failed");
96 | fail();
97 | }
98 | }
99 |
100 | function assertTrue(bool condition, string memory err) internal {
101 | if (!condition) {
102 | emit log_named_string("Error", err);
103 | assertTrue(condition);
104 | }
105 | }
106 |
107 | function assertEq(address a, address b) internal {
108 | if (a != b) {
109 | emit log("Error: a == b not satisfied [address]");
110 | emit log_named_address(" Expected", b);
111 | emit log_named_address(" Actual", a);
112 | fail();
113 | }
114 | }
115 | function assertEq(address a, address b, string memory err) internal {
116 | if (a != b) {
117 | emit log_named_string ("Error", err);
118 | assertEq(a, b);
119 | }
120 | }
121 |
122 | function assertEq(bytes32 a, bytes32 b) internal {
123 | if (a != b) {
124 | emit log("Error: a == b not satisfied [bytes32]");
125 | emit log_named_bytes32(" Expected", b);
126 | emit log_named_bytes32(" Actual", a);
127 | fail();
128 | }
129 | }
130 | function assertEq(bytes32 a, bytes32 b, string memory err) internal {
131 | if (a != b) {
132 | emit log_named_string ("Error", err);
133 | assertEq(a, b);
134 | }
135 | }
136 | function assertEq32(bytes32 a, bytes32 b) internal {
137 | assertEq(a, b);
138 | }
139 | function assertEq32(bytes32 a, bytes32 b, string memory err) internal {
140 | assertEq(a, b, err);
141 | }
142 |
143 | function assertEq(int a, int b) internal {
144 | if (a != b) {
145 | emit log("Error: a == b not satisfied [int]");
146 | emit log_named_int(" Expected", b);
147 | emit log_named_int(" Actual", a);
148 | fail();
149 | }
150 | }
151 | function assertEq(int a, int b, string memory err) internal {
152 | if (a != b) {
153 | emit log_named_string("Error", err);
154 | assertEq(a, b);
155 | }
156 | }
157 | function assertEq(uint a, uint b) internal {
158 | if (a != b) {
159 | emit log("Error: a == b not satisfied [uint]");
160 | emit log_named_uint(" Expected", b);
161 | emit log_named_uint(" Actual", a);
162 | fail();
163 | }
164 | }
165 | function assertEq(uint a, uint b, string memory err) internal {
166 | if (a != b) {
167 | emit log_named_string("Error", err);
168 | assertEq(a, b);
169 | }
170 | }
171 | function assertEqDecimal(int a, int b, uint decimals) internal {
172 | if (a != b) {
173 | emit log("Error: a == b not satisfied [decimal int]");
174 | emit log_named_decimal_int(" Expected", b, decimals);
175 | emit log_named_decimal_int(" Actual", a, decimals);
176 | fail();
177 | }
178 | }
179 | function assertEqDecimal(int a, int b, uint decimals, string memory err) internal {
180 | if (a != b) {
181 | emit log_named_string("Error", err);
182 | assertEqDecimal(a, b, decimals);
183 | }
184 | }
185 | function assertEqDecimal(uint a, uint b, uint decimals) internal {
186 | if (a != b) {
187 | emit log("Error: a == b not satisfied [decimal uint]");
188 | emit log_named_decimal_uint(" Expected", b, decimals);
189 | emit log_named_decimal_uint(" Actual", a, decimals);
190 | fail();
191 | }
192 | }
193 | function assertEqDecimal(uint a, uint b, uint decimals, string memory err) internal {
194 | if (a != b) {
195 | emit log_named_string("Error", err);
196 | assertEqDecimal(a, b, decimals);
197 | }
198 | }
199 |
200 | function assertGt(uint a, uint b) internal {
201 | if (a <= b) {
202 | emit log("Error: a > b not satisfied [uint]");
203 | emit log_named_uint(" Value a", a);
204 | emit log_named_uint(" Value b", b);
205 | fail();
206 | }
207 | }
208 | function assertGt(uint a, uint b, string memory err) internal {
209 | if (a <= b) {
210 | emit log_named_string("Error", err);
211 | assertGt(a, b);
212 | }
213 | }
214 | function assertGt(int a, int b) internal {
215 | if (a <= b) {
216 | emit log("Error: a > b not satisfied [int]");
217 | emit log_named_int(" Value a", a);
218 | emit log_named_int(" Value b", b);
219 | fail();
220 | }
221 | }
222 | function assertGt(int a, int b, string memory err) internal {
223 | if (a <= b) {
224 | emit log_named_string("Error", err);
225 | assertGt(a, b);
226 | }
227 | }
228 | function assertGtDecimal(int a, int b, uint decimals) internal {
229 | if (a <= b) {
230 | emit log("Error: a > b not satisfied [decimal int]");
231 | emit log_named_decimal_int(" Value a", a, decimals);
232 | emit log_named_decimal_int(" Value b", b, decimals);
233 | fail();
234 | }
235 | }
236 | function assertGtDecimal(int a, int b, uint decimals, string memory err) internal {
237 | if (a <= b) {
238 | emit log_named_string("Error", err);
239 | assertGtDecimal(a, b, decimals);
240 | }
241 | }
242 | function assertGtDecimal(uint a, uint b, uint decimals) internal {
243 | if (a <= b) {
244 | emit log("Error: a > b not satisfied [decimal uint]");
245 | emit log_named_decimal_uint(" Value a", a, decimals);
246 | emit log_named_decimal_uint(" Value b", b, decimals);
247 | fail();
248 | }
249 | }
250 | function assertGtDecimal(uint a, uint b, uint decimals, string memory err) internal {
251 | if (a <= b) {
252 | emit log_named_string("Error", err);
253 | assertGtDecimal(a, b, decimals);
254 | }
255 | }
256 |
257 | function assertGe(uint a, uint b) internal {
258 | if (a < b) {
259 | emit log("Error: a >= b not satisfied [uint]");
260 | emit log_named_uint(" Value a", a);
261 | emit log_named_uint(" Value b", b);
262 | fail();
263 | }
264 | }
265 | function assertGe(uint a, uint b, string memory err) internal {
266 | if (a < b) {
267 | emit log_named_string("Error", err);
268 | assertGe(a, b);
269 | }
270 | }
271 | function assertGe(int a, int b) internal {
272 | if (a < b) {
273 | emit log("Error: a >= b not satisfied [int]");
274 | emit log_named_int(" Value a", a);
275 | emit log_named_int(" Value b", b);
276 | fail();
277 | }
278 | }
279 | function assertGe(int a, int b, string memory err) internal {
280 | if (a < b) {
281 | emit log_named_string("Error", err);
282 | assertGe(a, b);
283 | }
284 | }
285 | function assertGeDecimal(int a, int b, uint decimals) internal {
286 | if (a < b) {
287 | emit log("Error: a >= b not satisfied [decimal int]");
288 | emit log_named_decimal_int(" Value a", a, decimals);
289 | emit log_named_decimal_int(" Value b", b, decimals);
290 | fail();
291 | }
292 | }
293 | function assertGeDecimal(int a, int b, uint decimals, string memory err) internal {
294 | if (a < b) {
295 | emit log_named_string("Error", err);
296 | assertGeDecimal(a, b, decimals);
297 | }
298 | }
299 | function assertGeDecimal(uint a, uint b, uint decimals) internal {
300 | if (a < b) {
301 | emit log("Error: a >= b not satisfied [decimal uint]");
302 | emit log_named_decimal_uint(" Value a", a, decimals);
303 | emit log_named_decimal_uint(" Value b", b, decimals);
304 | fail();
305 | }
306 | }
307 | function assertGeDecimal(uint a, uint b, uint decimals, string memory err) internal {
308 | if (a < b) {
309 | emit log_named_string("Error", err);
310 | assertGeDecimal(a, b, decimals);
311 | }
312 | }
313 |
314 | function assertLt(uint a, uint b) internal {
315 | if (a >= b) {
316 | emit log("Error: a < b not satisfied [uint]");
317 | emit log_named_uint(" Value a", a);
318 | emit log_named_uint(" Value b", b);
319 | fail();
320 | }
321 | }
322 | function assertLt(uint a, uint b, string memory err) internal {
323 | if (a >= b) {
324 | emit log_named_string("Error", err);
325 | assertLt(a, b);
326 | }
327 | }
328 | function assertLt(int a, int b) internal {
329 | if (a >= b) {
330 | emit log("Error: a < b not satisfied [int]");
331 | emit log_named_int(" Value a", a);
332 | emit log_named_int(" Value b", b);
333 | fail();
334 | }
335 | }
336 | function assertLt(int a, int b, string memory err) internal {
337 | if (a >= b) {
338 | emit log_named_string("Error", err);
339 | assertLt(a, b);
340 | }
341 | }
342 | function assertLtDecimal(int a, int b, uint decimals) internal {
343 | if (a >= b) {
344 | emit log("Error: a < b not satisfied [decimal int]");
345 | emit log_named_decimal_int(" Value a", a, decimals);
346 | emit log_named_decimal_int(" Value b", b, decimals);
347 | fail();
348 | }
349 | }
350 | function assertLtDecimal(int a, int b, uint decimals, string memory err) internal {
351 | if (a >= b) {
352 | emit log_named_string("Error", err);
353 | assertLtDecimal(a, b, decimals);
354 | }
355 | }
356 | function assertLtDecimal(uint a, uint b, uint decimals) internal {
357 | if (a >= b) {
358 | emit log("Error: a < b not satisfied [decimal uint]");
359 | emit log_named_decimal_uint(" Value a", a, decimals);
360 | emit log_named_decimal_uint(" Value b", b, decimals);
361 | fail();
362 | }
363 | }
364 | function assertLtDecimal(uint a, uint b, uint decimals, string memory err) internal {
365 | if (a >= b) {
366 | emit log_named_string("Error", err);
367 | assertLtDecimal(a, b, decimals);
368 | }
369 | }
370 |
371 | function assertLe(uint a, uint b) internal {
372 | if (a > b) {
373 | emit log("Error: a <= b not satisfied [uint]");
374 | emit log_named_uint(" Value a", a);
375 | emit log_named_uint(" Value b", b);
376 | fail();
377 | }
378 | }
379 | function assertLe(uint a, uint b, string memory err) internal {
380 | if (a > b) {
381 | emit log_named_string("Error", err);
382 | assertLe(a, b);
383 | }
384 | }
385 | function assertLe(int a, int b) internal {
386 | if (a > b) {
387 | emit log("Error: a <= b not satisfied [int]");
388 | emit log_named_int(" Value a", a);
389 | emit log_named_int(" Value b", b);
390 | fail();
391 | }
392 | }
393 | function assertLe(int a, int b, string memory err) internal {
394 | if (a > b) {
395 | emit log_named_string("Error", err);
396 | assertLe(a, b);
397 | }
398 | }
399 | function assertLeDecimal(int a, int b, uint decimals) internal {
400 | if (a > b) {
401 | emit log("Error: a <= b not satisfied [decimal int]");
402 | emit log_named_decimal_int(" Value a", a, decimals);
403 | emit log_named_decimal_int(" Value b", b, decimals);
404 | fail();
405 | }
406 | }
407 | function assertLeDecimal(int a, int b, uint decimals, string memory err) internal {
408 | if (a > b) {
409 | emit log_named_string("Error", err);
410 | assertLeDecimal(a, b, decimals);
411 | }
412 | }
413 | function assertLeDecimal(uint a, uint b, uint decimals) internal {
414 | if (a > b) {
415 | emit log("Error: a <= b not satisfied [decimal uint]");
416 | emit log_named_decimal_uint(" Value a", a, decimals);
417 | emit log_named_decimal_uint(" Value b", b, decimals);
418 | fail();
419 | }
420 | }
421 | function assertLeDecimal(uint a, uint b, uint decimals, string memory err) internal {
422 | if (a > b) {
423 | emit log_named_string("Error", err);
424 | assertGeDecimal(a, b, decimals);
425 | }
426 | }
427 |
428 | function assertEq(string memory a, string memory b) internal {
429 | if (keccak256(abi.encodePacked(a)) != keccak256(abi.encodePacked(b))) {
430 | emit log("Error: a == b not satisfied [string]");
431 | emit log_named_string(" Expected", b);
432 | emit log_named_string(" Actual", a);
433 | fail();
434 | }
435 | }
436 | function assertEq(string memory a, string memory b, string memory err) internal {
437 | if (keccak256(abi.encodePacked(a)) != keccak256(abi.encodePacked(b))) {
438 | emit log_named_string("Error", err);
439 | assertEq(a, b);
440 | }
441 | }
442 |
443 | function checkEq0(bytes memory a, bytes memory b) internal pure returns (bool ok) {
444 | ok = true;
445 | if (a.length == b.length) {
446 | for (uint i = 0; i < a.length; i++) {
447 | if (a[i] != b[i]) {
448 | ok = false;
449 | }
450 | }
451 | } else {
452 | ok = false;
453 | }
454 | }
455 | function assertEq0(bytes memory a, bytes memory b) internal {
456 | if (!checkEq0(a, b)) {
457 | emit log("Error: a == b not satisfied [bytes]");
458 | emit log_named_bytes(" Expected", b);
459 | emit log_named_bytes(" Actual", a);
460 | fail();
461 | }
462 | }
463 | function assertEq0(bytes memory a, bytes memory b, string memory err) internal {
464 | if (!checkEq0(a, b)) {
465 | emit log_named_string("Error", err);
466 | assertEq0(a, b);
467 | }
468 | }
469 | }
470 |
--------------------------------------------------------------------------------
/lib/forge-std/src/Script.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity >=0.6.0 <0.9.0;
3 |
4 | import "./console.sol";
5 | import "./console2.sol";
6 | import "./StdJson.sol";
7 |
8 | abstract contract Script {
9 | bool public IS_SCRIPT = true;
10 | address constant private VM_ADDRESS =
11 | address(bytes20(uint160(uint256(keccak256('hevm cheat code')))));
12 |
13 | Vm public constant vm = Vm(VM_ADDRESS);
14 |
15 | /// @dev Compute the address a contract will be deployed at for a given deployer address and nonce
16 | /// @notice adapated from Solmate implementation (https://github.com/transmissions11/solmate/blob/main/src/utils/LibRLP.sol)
17 | function computeCreateAddress(address deployer, uint256 nonce) internal pure returns (address) {
18 | // The integer zero is treated as an empty byte string, and as a result it only has a length prefix, 0x80, computed via 0x80 + 0.
19 | // A one byte integer uses its own value as its length prefix, there is no additional "0x80 + length" prefix that comes before it.
20 | if (nonce == 0x00) return addressFromLast20Bytes(keccak256(abi.encodePacked(bytes1(0xd6), bytes1(0x94), deployer, bytes1(0x80))));
21 | if (nonce <= 0x7f) return addressFromLast20Bytes(keccak256(abi.encodePacked(bytes1(0xd6), bytes1(0x94), deployer, uint8(nonce))));
22 |
23 | // Nonces greater than 1 byte all follow a consistent encoding scheme, where each value is preceded by a prefix of 0x80 + length.
24 | if (nonce <= 2**8 - 1) return addressFromLast20Bytes(keccak256(abi.encodePacked(bytes1(0xd7), bytes1(0x94), deployer, bytes1(0x81), uint8(nonce))));
25 | if (nonce <= 2**16 - 1) return addressFromLast20Bytes(keccak256(abi.encodePacked(bytes1(0xd8), bytes1(0x94), deployer, bytes1(0x82), uint16(nonce))));
26 | if (nonce <= 2**24 - 1) return addressFromLast20Bytes(keccak256(abi.encodePacked(bytes1(0xd9), bytes1(0x94), deployer, bytes1(0x83), uint24(nonce))));
27 |
28 | // More details about RLP encoding can be found here: https://eth.wiki/fundamentals/rlp
29 | // 0xda = 0xc0 (short RLP prefix) + 0x16 (length of: 0x94 ++ proxy ++ 0x84 ++ nonce)
30 | // 0x94 = 0x80 + 0x14 (0x14 = the length of an address, 20 bytes, in hex)
31 | // 0x84 = 0x80 + 0x04 (0x04 = the bytes length of the nonce, 4 bytes, in hex)
32 | // We assume nobody can have a nonce large enough to require more than 32 bytes.
33 | return addressFromLast20Bytes(keccak256(abi.encodePacked(bytes1(0xda), bytes1(0x94), deployer, bytes1(0x84), uint32(nonce))));
34 | }
35 |
36 | function addressFromLast20Bytes(bytes32 bytesValue) internal pure returns (address) {
37 | return address(uint160(uint256(bytesValue)));
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/lib/forge-std/src/StdJson.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity >=0.6.0 <0.9.0;
3 | pragma experimental ABIEncoderV2;
4 |
5 | import "./Vm.sol";
6 |
7 | // Helpers for parsing keys into types.
8 | library stdJson {
9 |
10 | Vm private constant vm = Vm(address(uint160(uint256(keccak256("hevm cheat code")))));
11 |
12 | function parseRaw(string memory json, string memory key)
13 | internal
14 | returns (bytes memory)
15 | {
16 | return vm.parseJson(json, key);
17 | }
18 |
19 | function readUint(string memory json, string memory key)
20 | internal
21 | returns (uint256)
22 | {
23 | return abi.decode(vm.parseJson(json, key), (uint256));
24 | }
25 |
26 | function readUintArray(string memory json, string memory key)
27 | internal
28 | returns (uint256[] memory)
29 | {
30 | return abi.decode(vm.parseJson(json, key), (uint256[]));
31 | }
32 |
33 | function readInt(string memory json, string memory key)
34 | internal
35 | returns (int256)
36 | {
37 | return abi.decode(vm.parseJson(json, key), (int256));
38 | }
39 |
40 | function readIntArray(string memory json, string memory key)
41 | internal
42 | returns (int256[] memory)
43 | {
44 | return abi.decode(vm.parseJson(json, key), (int256[]));
45 | }
46 |
47 | function readBytes32(string memory json, string memory key)
48 | internal
49 | returns (bytes32)
50 | {
51 | return abi.decode(vm.parseJson(json, key), (bytes32));
52 | }
53 |
54 | function readBytes32Array(string memory json, string memory key)
55 | internal
56 | returns (bytes32[] memory)
57 | {
58 | return abi.decode(vm.parseJson(json, key), (bytes32[]));
59 | }
60 |
61 | function readString(string memory json, string memory key)
62 | internal
63 | returns (string memory)
64 | {
65 | return abi.decode(vm.parseJson(json, key), (string));
66 | }
67 |
68 | function readStringArray(string memory json, string memory key)
69 | internal
70 | returns (string[] memory)
71 | {
72 | return abi.decode(vm.parseJson(json, key), (string[]));
73 | }
74 |
75 | function readAddress(string memory json, string memory key)
76 | internal
77 | returns (address)
78 | {
79 | return abi.decode(vm.parseJson(json, key), (address));
80 | }
81 |
82 | function readAddressArray(string memory json, string memory key)
83 | internal
84 | returns (address[] memory)
85 | {
86 | return abi.decode(vm.parseJson(json, key), (address[]));
87 | }
88 |
89 | function readBool(string memory json, string memory key)
90 | internal
91 | returns (bool)
92 | {
93 | return abi.decode(vm.parseJson(json, key), (bool));
94 | }
95 |
96 | function readBoolArray(string memory json, string memory key)
97 | internal
98 | returns (bool[] memory)
99 | {
100 | return abi.decode(vm.parseJson(json, key), (bool[]));
101 | }
102 |
103 | function readBytes(string memory json, string memory key)
104 | internal
105 | returns (bytes memory)
106 | {
107 | return abi.decode(vm.parseJson(json, key), (bytes));
108 | }
109 |
110 | function readBytesArray(string memory json, string memory key)
111 | internal
112 | returns (bytes[] memory)
113 | {
114 | return abi.decode(vm.parseJson(json, key), (bytes[]));
115 | }
116 |
117 |
118 | }
119 |
--------------------------------------------------------------------------------
/lib/forge-std/src/Vm.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity >=0.6.0 <0.9.0;
3 | pragma experimental ABIEncoderV2;
4 |
5 | interface Vm {
6 | struct Log {
7 | bytes32[] topics;
8 | bytes data;
9 | }
10 |
11 | // Sets block.timestamp (newTimestamp)
12 | function warp(uint256) external;
13 | // Sets block.height (newHeight)
14 | function roll(uint256) external;
15 | // Sets block.basefee (newBasefee)
16 | function fee(uint256) external;
17 | // Sets block.difficulty (newDifficulty)
18 | function difficulty(uint256) external;
19 | // Sets block.chainid
20 | function chainId(uint256) external;
21 | // Loads a storage slot from an address (who, slot)
22 | function load(address,bytes32) external returns (bytes32);
23 | // Stores a value to an address' storage slot, (who, slot, value)
24 | function store(address,bytes32,bytes32) external;
25 | // Signs data, (privateKey, digest) => (v, r, s)
26 | function sign(uint256,bytes32) external returns (uint8,bytes32,bytes32);
27 | // Gets the address for a given private key, (privateKey) => (address)
28 | function addr(uint256) external returns (address);
29 | // Gets the nonce of an account
30 | function getNonce(address) external returns (uint64);
31 | // Sets the nonce of an account; must be higher than the current nonce of the account
32 | function setNonce(address, uint64) external;
33 | // Performs a foreign function call via the terminal, (stringInputs) => (result)
34 | function ffi(string[] calldata) external returns (bytes memory);
35 | // Sets environment variables, (name, value)
36 | function setEnv(string calldata, string calldata) external;
37 | // Reads environment variables, (name) => (value)
38 | function envBool(string calldata) external returns (bool);
39 | function envUint(string calldata) external returns (uint256);
40 | function envInt(string calldata) external returns (int256);
41 | function envAddress(string calldata) external returns (address);
42 | function envBytes32(string calldata) external returns (bytes32);
43 | function envString(string calldata) external returns (string memory);
44 | function envBytes(string calldata) external returns (bytes memory);
45 | // Reads environment variables as arrays, (name, delim) => (value[])
46 | function envBool(string calldata, string calldata) external returns (bool[] memory);
47 | function envUint(string calldata, string calldata) external returns (uint256[] memory);
48 | function envInt(string calldata, string calldata) external returns (int256[] memory);
49 | function envAddress(string calldata, string calldata) external returns (address[] memory);
50 | function envBytes32(string calldata, string calldata) external returns (bytes32[] memory);
51 | function envString(string calldata, string calldata) external returns (string[] memory);
52 | function envBytes(string calldata, string calldata) external returns (bytes[] memory);
53 | // Sets the *next* call's msg.sender to be the input address
54 | function prank(address) external;
55 | // Sets all subsequent calls' msg.sender to be the input address until `stopPrank` is called
56 | function startPrank(address) external;
57 | // Sets the *next* call's msg.sender to be the input address, and the tx.origin to be the second input
58 | function prank(address,address) external;
59 | // Sets all subsequent calls' msg.sender to be the input address until `stopPrank` is called, and the tx.origin to be the second input
60 | function startPrank(address,address) external;
61 | // Resets subsequent calls' msg.sender to be `address(this)`
62 | function stopPrank() external;
63 | // Sets an address' balance, (who, newBalance)
64 | function deal(address, uint256) external;
65 | // Sets an address' code, (who, newCode)
66 | function etch(address, bytes calldata) external;
67 | // Expects an error on next call
68 | function expectRevert(bytes calldata) external;
69 | function expectRevert(bytes4) external;
70 | function expectRevert() external;
71 | // Records all storage reads and writes
72 | function record() external;
73 | // Gets all accessed reads and write slot from a recording session, for a given address
74 | function accesses(address) external returns (bytes32[] memory reads, bytes32[] memory writes);
75 | // Prepare an expected log with (bool checkTopic1, bool checkTopic2, bool checkTopic3, bool checkData).
76 | // Call this function, then emit an event, then call a function. Internally after the call, we check if
77 | // logs were emitted in the expected order with the expected topics and data (as specified by the booleans)
78 | function expectEmit(bool,bool,bool,bool) external;
79 | function expectEmit(bool,bool,bool,bool,address) external;
80 | // Mocks a call to an address, returning specified data.
81 | // Calldata can either be strict or a partial match, e.g. if you only
82 | // pass a Solidity selector to the expected calldata, then the entire Solidity
83 | // function will be mocked.
84 | function mockCall(address,bytes calldata,bytes calldata) external;
85 | // Mocks a call to an address with a specific msg.value, returning specified data.
86 | // Calldata match takes precedence over msg.value in case of ambiguity.
87 | function mockCall(address,uint256,bytes calldata,bytes calldata) external;
88 | // Clears all mocked calls
89 | function clearMockedCalls() external;
90 | // Expects a call to an address with the specified calldata.
91 | // Calldata can either be a strict or a partial match
92 | function expectCall(address,bytes calldata) external;
93 | // Expects a call to an address with the specified msg.value and calldata
94 | function expectCall(address,uint256,bytes calldata) external;
95 | // Gets the code from an artifact file. Takes in the relative path to the json file
96 | function getCode(string calldata) external returns (bytes memory);
97 | // Labels an address in call traces
98 | function label(address, string calldata) external;
99 | // If the condition is false, discard this run's fuzz inputs and generate new ones
100 | function assume(bool) external;
101 | // Sets block.coinbase (who)
102 | function coinbase(address) external;
103 | // Using the address that calls the test contract, has the next call (at this call depth only) create a transaction that can later be signed and sent onchain
104 | function broadcast() external;
105 | // Has the next call (at this call depth only) create a transaction with the address provided as the sender that can later be signed and sent onchain
106 | function broadcast(address) external;
107 | // Using the address that calls the test contract, has all subsequent calls (at this call depth only) create transactions that can later be signed and sent onchain
108 | function startBroadcast() external;
109 | // Has all subsequent calls (at this call depth only) create transactions that can later be signed and sent onchain
110 | function startBroadcast(address) external;
111 | // Stops collecting onchain transactions
112 | function stopBroadcast() external;
113 |
114 | // Reads the entire content of file to string, (path) => (data)
115 | function readFile(string calldata) external returns (string memory);
116 | // Get the path of the current project root
117 | function projectRoot() external returns (string memory);
118 | // Reads next line of file to string, (path) => (line)
119 | function readLine(string calldata) external returns (string memory);
120 | // Writes data to file, creating a file if it does not exist, and entirely replacing its contents if it does.
121 | // (path, data) => ()
122 | function writeFile(string calldata, string calldata) external;
123 | // Writes line to file, creating a file if it does not exist.
124 | // (path, data) => ()
125 | function writeLine(string calldata, string calldata) external;
126 | // Closes file for reading, resetting the offset and allowing to read it from beginning with readLine.
127 | // (path) => ()
128 | function closeFile(string calldata) external;
129 | // Removes file. This cheatcode will revert in the following situations, but is not limited to just these cases:
130 | // - Path points to a directory.
131 | // - The file doesn't exist.
132 | // - The user lacks permissions to remove the file.
133 | // (path) => ()
134 | function removeFile(string calldata) external;
135 |
136 | // Convert values to a string, (value) => (stringified value)
137 | function toString(address) external returns(string memory);
138 | function toString(bytes calldata) external returns(string memory);
139 | function toString(bytes32) external returns(string memory);
140 | function toString(bool) external returns(string memory);
141 | function toString(uint256) external returns(string memory);
142 | function toString(int256) external returns(string memory);
143 |
144 | // Convert values from a string, (string) => (parsed value)
145 | function parseBytes(string calldata) external returns (bytes memory);
146 | function parseAddress(string calldata) external returns (address);
147 | function parseUint(string calldata) external returns (uint256);
148 | function parseInt(string calldata) external returns (int256);
149 | function parseBytes32(string calldata) external returns (bytes32);
150 | function parseBool(string calldata) external returns (bool);
151 |
152 | // Record all the transaction logs
153 | function recordLogs() external;
154 | // Gets all the recorded logs, () => (logs)
155 | function getRecordedLogs() external returns (Log[] memory);
156 | // Snapshot the current state of the evm.
157 | // Returns the id of the snapshot that was created.
158 | // To revert a snapshot use `revertTo`
159 | function snapshot() external returns(uint256);
160 | // Revert the state of the evm to a previous snapshot
161 | // Takes the snapshot id to revert to.
162 | // This deletes the snapshot and all snapshots taken after the given snapshot id.
163 | function revertTo(uint256) external returns(bool);
164 |
165 | // Creates a new fork with the given endpoint and block and returns the identifier of the fork
166 | function createFork(string calldata,uint256) external returns(uint256);
167 | // Creates a new fork with the given endpoint and the _latest_ block and returns the identifier of the fork
168 | function createFork(string calldata) external returns(uint256);
169 | // Creates _and_ also selects a new fork with the given endpoint and block and returns the identifier of the fork
170 | function createSelectFork(string calldata,uint256) external returns(uint256);
171 | // Creates _and_ also selects a new fork with the given endpoint and the latest block and returns the identifier of the fork
172 | function createSelectFork(string calldata) external returns(uint256);
173 | // Takes a fork identifier created by `createFork` and sets the corresponding forked state as active.
174 | function selectFork(uint256) external;
175 | /// Returns the currently active fork
176 | /// Reverts if no fork is currently active
177 | function activeFork() external returns(uint256);
178 | // Updates the currently active fork to given block number
179 | // This is similar to `roll` but for the currently active fork
180 | function rollFork(uint256) external;
181 | // Updates the given fork to given block number
182 | function rollFork(uint256 forkId, uint256 blockNumber) external;
183 |
184 | // Marks that the account(s) should use persistent storage across fork swaps in a multifork setup
185 | // Meaning, changes made to the state of this account will be kept when switching forks
186 | function makePersistent(address) external;
187 | function makePersistent(address, address) external;
188 | function makePersistent(address, address, address) external;
189 | function makePersistent(address[] calldata) external;
190 | // Revokes persistent status from the address, previously added via `makePersistent`
191 | function revokePersistent(address) external;
192 | function revokePersistent(address[] calldata) external;
193 | // Returns true if the account is marked as persistent
194 | function isPersistent(address) external returns (bool);
195 |
196 | // Returns the RPC url for the given alias
197 | function rpcUrl(string calldata) external returns(string memory);
198 | // Returns all rpc urls and their aliases `[alias, url][]`
199 | function rpcUrls() external returns(string[2][] memory);
200 |
201 | // Derive a private key from a provided mnenomic string (or mnenomic file path) at the derivation path m/44'/60'/0'/0/{index}
202 | function deriveKey(string calldata, uint32) external returns (uint256);
203 | // Derive a private key from a provided mnenomic string (or mnenomic file path) at the derivation path {path}{index}
204 | function deriveKey(string calldata, string calldata, uint32) external returns (uint256);
205 | // parseJson
206 |
207 | // Given a string of JSON, return the ABI-encoded value of provided key
208 | // (stringified json, key) => (ABI-encoded data)
209 | // Read the note below!
210 | function parseJson(string calldata, string calldata) external returns(bytes memory);
211 |
212 | // Given a string of JSON, return it as ABI-encoded, (stringified json, key) => (ABI-encoded data)
213 | // Read the note below!
214 | function parseJson(string calldata) external returns(bytes memory);
215 |
216 | // Note:
217 | // ----
218 | // In case the returned value is a JSON object, it's encoded as a ABI-encoded tuple. As JSON objects
219 | // don't have the notion of ordered, but tuples do, they JSON object is encoded with it's fields ordered in
220 | // ALPHABETICAL ordser. That means that in order to succesfully decode the tuple, we need to define a tuple that
221 | // encodes the fields in the same order, which is alphabetical. In the case of Solidity structs, they are encoded
222 | // as tuples, with the attributes in the order in which they are defined.
223 | // For example: json = { 'a': 1, 'b': 0xa4tb......3xs}
224 | // a: uint256
225 | // b: address
226 | // To decode that json, we need to define a struct or a tuple as follows:
227 | // struct json = { uint256 a; address b; }
228 | // If we defined a json struct with the opposite order, meaning placing the address b first, it would try to
229 | // decode the tuple in that order, and thus fail.
230 |
231 | }
232 |
--------------------------------------------------------------------------------
/lib/forge-std/src/test/Script.t.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity >=0.7.0 <0.9.0;
3 |
4 | import "../Test.sol";
5 |
6 | contract ScriptTest is Test
7 | {
8 | function testGenerateCorrectAddress() external {
9 | address creation = computeCreateAddress(0x6C9FC64A53c1b71FB3f9Af64d1ae3A4931A5f4E9, 14);
10 | assertEq(creation, 0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45);
11 | }
12 | }
--------------------------------------------------------------------------------
/lib/forge-std/src/test/StdAssertions.t.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity >=0.7.0 <0.9.0;
3 |
4 | import "../Test.sol";
5 |
6 | contract StdAssertionsTest is Test
7 | {
8 | string constant CUSTOM_ERROR = "guh!";
9 |
10 | bool constant EXPECT_PASS = false;
11 | bool constant EXPECT_FAIL = true;
12 |
13 | TestTest t = new TestTest();
14 |
15 | /*//////////////////////////////////////////////////////////////////////////
16 | ASSERT_EQ(UINT)
17 | //////////////////////////////////////////////////////////////////////////*/
18 |
19 | function testAssertions() public {
20 | assertEqUint(uint32(1), uint32(1));
21 | assertEqUint(uint64(1), uint64(1));
22 | assertEqUint(uint96(1), uint96(1));
23 | assertEqUint(uint128(1), uint128(1));
24 | }
25 |
26 | /*//////////////////////////////////////////////////////////////////////////
27 | FAIL(STRING)
28 | //////////////////////////////////////////////////////////////////////////*/
29 |
30 | function testShouldFail() external {
31 | vm.expectEmit(false, false, false, true);
32 | emit log_named_string("Error", CUSTOM_ERROR);
33 | t._fail(CUSTOM_ERROR);
34 | }
35 |
36 | /*//////////////////////////////////////////////////////////////////////////
37 | ASSERT_FALSE
38 | //////////////////////////////////////////////////////////////////////////*/
39 |
40 | function testAssertFalse_Pass() external {
41 | t._assertFalse(false, EXPECT_PASS);
42 | }
43 |
44 | function testAssertFalse_Fail() external {
45 | vm.expectEmit(false, false, false, true);
46 | emit log("Error: Assertion Failed");
47 | t._assertFalse(true, EXPECT_FAIL);
48 | }
49 |
50 | function testAssertFalse_Err_Pass() external {
51 | t._assertFalse(false, CUSTOM_ERROR, EXPECT_PASS);
52 | }
53 |
54 | function testAssertFalse_Err_Fail() external {
55 | vm.expectEmit(false, false, false, true);
56 | emit log_named_string("Error", CUSTOM_ERROR);
57 | t._assertFalse(true, CUSTOM_ERROR, EXPECT_FAIL);
58 | }
59 |
60 | /*//////////////////////////////////////////////////////////////////////////
61 | ASSERT_EQ(BOOL)
62 | //////////////////////////////////////////////////////////////////////////*/
63 |
64 | function testAssertEq_Bool_Pass(bool a) external {
65 | t._assertEq(a, a, EXPECT_PASS);
66 | }
67 |
68 | function testAssertEq_Bool_Fail(bool a, bool b) external {
69 | vm.assume(a != b);
70 |
71 | vm.expectEmit(false, false, false, true);
72 | emit log("Error: a == b not satisfied [bool]");
73 | t._assertEq(a, b, EXPECT_FAIL);
74 | }
75 |
76 | function testAssertEq_BoolErr_Pass(bool a) external {
77 | t._assertEq(a, a, CUSTOM_ERROR, EXPECT_PASS);
78 | }
79 |
80 | function testAssertEq_BoolErr_Fail(bool a, bool b) external {
81 | vm.assume(a != b);
82 |
83 | vm.expectEmit(false, false, false, true);
84 | emit log_named_string("Error", CUSTOM_ERROR);
85 | t._assertEq(a, b, CUSTOM_ERROR, EXPECT_FAIL);
86 | }
87 |
88 | /*//////////////////////////////////////////////////////////////////////////
89 | ASSERT_EQ(BYTES)
90 | //////////////////////////////////////////////////////////////////////////*/
91 |
92 | function testAssertEq_Bytes_Pass(bytes calldata a) external {
93 | t._assertEq(a, a, EXPECT_PASS);
94 | }
95 |
96 | function testAssertEq_Bytes_Fail(bytes calldata a, bytes calldata b) external {
97 | vm.assume(keccak256(a) != keccak256(b));
98 |
99 | vm.expectEmit(false, false, false, true);
100 | emit log("Error: a == b not satisfied [bytes]");
101 | t._assertEq(a, b, EXPECT_FAIL);
102 | }
103 |
104 | function testAssertEq_BytesErr_Pass(bytes calldata a) external {
105 | t._assertEq(a, a, CUSTOM_ERROR, EXPECT_PASS);
106 | }
107 |
108 | function testAssertEq_BytesErr_Fail(bytes calldata a, bytes calldata b) external {
109 | vm.assume(keccak256(a) != keccak256(b));
110 |
111 | vm.expectEmit(false, false, false, true);
112 | emit log_named_string("Error", CUSTOM_ERROR);
113 | t._assertEq(a, b, CUSTOM_ERROR, EXPECT_FAIL);
114 | }
115 |
116 | /*//////////////////////////////////////////////////////////////////////////
117 | ASSERT_EQ(ARRAY)
118 | //////////////////////////////////////////////////////////////////////////*/
119 |
120 | function testAssertEq_UintArr_Pass(uint256 e0, uint256 e1, uint256 e2) public {
121 | uint256[] memory a = new uint256[](3);
122 | a[0] = e0;
123 | a[1] = e1;
124 | a[2] = e2;
125 | uint256[] memory b = new uint256[](3);
126 | b[0] = e0;
127 | b[1] = e1;
128 | b[2] = e2;
129 |
130 | t._assertEq(a, b, EXPECT_PASS);
131 | }
132 |
133 | function testAssertEq_IntArr_Pass(int256 e0, int256 e1, int256 e2) public {
134 | int256[] memory a = new int256[](3);
135 | a[0] = e0;
136 | a[1] = e1;
137 | a[2] = e2;
138 | int256[] memory b = new int256[](3);
139 | b[0] = e0;
140 | b[1] = e1;
141 | b[2] = e2;
142 |
143 | t._assertEq(a, b, EXPECT_PASS);
144 | }
145 |
146 | function testAssertEq_AddressArr_Pass(address e0, address e1, address e2) public {
147 | address[] memory a = new address[](3);
148 | a[0] = e0;
149 | a[1] = e1;
150 | a[2] = e2;
151 | address[] memory b = new address[](3);
152 | b[0] = e0;
153 | b[1] = e1;
154 | b[2] = e2;
155 |
156 | t._assertEq(a, b, EXPECT_PASS);
157 | }
158 |
159 | function testAssertEq_UintArr_FailEl(uint256 e1) public {
160 | vm.assume(e1 != 0);
161 | uint256[] memory a = new uint256[](3);
162 | uint256[] memory b = new uint256[](3);
163 | b[1] = e1;
164 |
165 | vm.expectEmit(false, false, false, true);
166 | emit log("Error: a == b not satisfied [uint[]]");
167 | t._assertEq(a, b, EXPECT_FAIL);
168 | }
169 |
170 | function testAssertEq_IntArr_FailEl(int256 e1) public {
171 | vm.assume(e1 != 0);
172 | int256[] memory a = new int256[](3);
173 | int256[] memory b = new int256[](3);
174 | b[1] = e1;
175 |
176 | vm.expectEmit(false, false, false, true);
177 | emit log("Error: a == b not satisfied [int[]]");
178 | t._assertEq(a, b, EXPECT_FAIL);
179 | }
180 |
181 |
182 | function testAssertEq_AddressArr_FailEl(address e1) public {
183 | vm.assume(e1 != address(0));
184 | address[] memory a = new address[](3);
185 | address[] memory b = new address[](3);
186 | b[1] = e1;
187 |
188 | vm.expectEmit(false, false, false, true);
189 | emit log("Error: a == b not satisfied [address[]]");
190 | t._assertEq(a, b, EXPECT_FAIL);
191 | }
192 |
193 | function testAssertEq_UintArrErr_FailEl(uint256 e1) public {
194 | vm.assume(e1 != 0);
195 | uint256[] memory a = new uint256[](3);
196 | uint256[] memory b = new uint256[](3);
197 | b[1] = e1;
198 |
199 | vm.expectEmit(false, false, false, true);
200 | emit log_named_string("Error", CUSTOM_ERROR);
201 | vm.expectEmit(false, false, false, true);
202 | emit log("Error: a == b not satisfied [uint[]]");
203 | t._assertEq(a, b, CUSTOM_ERROR, EXPECT_FAIL);
204 | }
205 |
206 | function testAssertEq_IntArrErr_FailEl(int256 e1) public {
207 | vm.assume(e1 != 0);
208 | int256[] memory a = new int256[](3);
209 | int256[] memory b = new int256[](3);
210 | b[1] = e1;
211 |
212 | vm.expectEmit(false, false, false, true);
213 | emit log_named_string("Error", CUSTOM_ERROR);
214 | vm.expectEmit(false, false, false, true);
215 | emit log("Error: a == b not satisfied [int[]]");
216 | t._assertEq(a, b, CUSTOM_ERROR, EXPECT_FAIL);
217 | }
218 |
219 |
220 | function testAssertEq_AddressArrErr_FailEl(address e1) public {
221 | vm.assume(e1 != address(0));
222 | address[] memory a = new address[](3);
223 | address[] memory b = new address[](3);
224 | b[1] = e1;
225 |
226 | vm.expectEmit(false, false, false, true);
227 | emit log_named_string("Error", CUSTOM_ERROR);
228 | vm.expectEmit(false, false, false, true);
229 | emit log("Error: a == b not satisfied [address[]]");
230 | t._assertEq(a, b, CUSTOM_ERROR, EXPECT_FAIL);
231 | }
232 |
233 | function testAssertEq_UintArr_FailLen(uint256 lenA, uint256 lenB) public {
234 | vm.assume(lenA != lenB);
235 | vm.assume(lenA <= 10000);
236 | vm.assume(lenB <= 10000);
237 | uint256[] memory a = new uint256[](lenA);
238 | uint256[] memory b = new uint256[](lenB);
239 |
240 | vm.expectEmit(false, false, false, true);
241 | emit log("Error: a == b not satisfied [uint[]]");
242 | t._assertEq(a, b, EXPECT_FAIL);
243 | }
244 |
245 | function testAssertEq_IntArr_FailLen(uint256 lenA, uint256 lenB) public {
246 | vm.assume(lenA != lenB);
247 | vm.assume(lenA <= 10000);
248 | vm.assume(lenB <= 10000);
249 | int256[] memory a = new int256[](lenA);
250 | int256[] memory b = new int256[](lenB);
251 |
252 | vm.expectEmit(false, false, false, true);
253 | emit log("Error: a == b not satisfied [int[]]");
254 | t._assertEq(a, b, EXPECT_FAIL);
255 | }
256 |
257 | function testAssertEq_AddressArr_FailLen(uint256 lenA, uint256 lenB) public {
258 | vm.assume(lenA != lenB);
259 | vm.assume(lenA <= 10000);
260 | vm.assume(lenB <= 10000);
261 | address[] memory a = new address[](lenA);
262 | address[] memory b = new address[](lenB);
263 |
264 | vm.expectEmit(false, false, false, true);
265 | emit log("Error: a == b not satisfied [address[]]");
266 | t._assertEq(a, b, EXPECT_FAIL);
267 | }
268 |
269 | function testAssertEq_UintArrErr_FailLen(uint256 lenA, uint256 lenB) public {
270 | vm.assume(lenA != lenB);
271 | vm.assume(lenA <= 10000);
272 | vm.assume(lenB <= 10000);
273 | uint256[] memory a = new uint256[](lenA);
274 | uint256[] memory b = new uint256[](lenB);
275 |
276 | vm.expectEmit(false, false, false, true);
277 | emit log_named_string("Error", CUSTOM_ERROR);
278 | vm.expectEmit(false, false, false, true);
279 | emit log("Error: a == b not satisfied [uint[]]");
280 | t._assertEq(a, b, CUSTOM_ERROR, EXPECT_FAIL);
281 | }
282 |
283 | function testAssertEq_IntArrErr_FailLen(uint256 lenA, uint256 lenB) public {
284 | vm.assume(lenA != lenB);
285 | vm.assume(lenA <= 10000);
286 | vm.assume(lenB <= 10000);
287 | int256[] memory a = new int256[](lenA);
288 | int256[] memory b = new int256[](lenB);
289 |
290 | vm.expectEmit(false, false, false, true);
291 | emit log_named_string("Error", CUSTOM_ERROR);
292 | vm.expectEmit(false, false, false, true);
293 | emit log("Error: a == b not satisfied [int[]]");
294 | t._assertEq(a, b, CUSTOM_ERROR, EXPECT_FAIL);
295 | }
296 |
297 | function testAssertEq_AddressArrErr_FailLen(uint256 lenA, uint256 lenB) public {
298 | vm.assume(lenA != lenB);
299 | vm.assume(lenA <= 10000);
300 | vm.assume(lenB <= 10000);
301 | address[] memory a = new address[](lenA);
302 | address[] memory b = new address[](lenB);
303 |
304 | vm.expectEmit(false, false, false, true);
305 | emit log_named_string("Error", CUSTOM_ERROR);
306 | vm.expectEmit(false, false, false, true);
307 | emit log("Error: a == b not satisfied [address[]]");
308 | t._assertEq(a, b, CUSTOM_ERROR, EXPECT_FAIL);
309 | }
310 |
311 | /*//////////////////////////////////////////////////////////////////////////
312 | APPROX_EQ_ABS(UINT)
313 | //////////////////////////////////////////////////////////////////////////*/
314 |
315 | function testAssertApproxEqAbs_Uint_Pass(uint256 a, uint256 b, uint256 maxDelta) external {
316 | vm.assume(stdMath.delta(a, b) <= maxDelta);
317 |
318 | t._assertApproxEqAbs(a, b, maxDelta, EXPECT_PASS);
319 | }
320 |
321 | function testAssertApproxEqAbs_Uint_Fail(uint256 a, uint256 b, uint256 maxDelta) external {
322 | vm.assume(stdMath.delta(a, b) > maxDelta);
323 |
324 | vm.expectEmit(false, false, false, true);
325 | emit log("Error: a ~= b not satisfied [uint]");
326 | t._assertApproxEqAbs(a, b, maxDelta, EXPECT_FAIL);
327 | }
328 |
329 | function testAssertApproxEqAbs_UintErr_Pass(uint256 a, uint256 b, uint256 maxDelta) external {
330 | vm.assume(stdMath.delta(a, b) <= maxDelta);
331 |
332 | t._assertApproxEqAbs(a, b, maxDelta, CUSTOM_ERROR, EXPECT_PASS);
333 | }
334 |
335 | function testAssertApproxEqAbs_UintErr_Fail(uint256 a, uint256 b, uint256 maxDelta) external {
336 | vm.assume(stdMath.delta(a, b) > maxDelta);
337 |
338 | vm.expectEmit(false, false, false, true);
339 | emit log_named_string("Error", CUSTOM_ERROR);
340 | t._assertApproxEqAbs(a, b, maxDelta, CUSTOM_ERROR, EXPECT_FAIL);
341 | }
342 |
343 | /*//////////////////////////////////////////////////////////////////////////
344 | APPROX_EQ_ABS(INT)
345 | //////////////////////////////////////////////////////////////////////////*/
346 |
347 | function testAssertApproxEqAbs_Int_Pass(int256 a, int256 b, uint256 maxDelta) external {
348 | vm.assume(stdMath.delta(a, b) <= maxDelta);
349 |
350 | t._assertApproxEqAbs(a, b, maxDelta, EXPECT_PASS);
351 | }
352 |
353 | function testAssertApproxEqAbs_Int_Fail(int256 a, int256 b, uint256 maxDelta) external {
354 | vm.assume(stdMath.delta(a, b) > maxDelta);
355 |
356 | vm.expectEmit(false, false, false, true);
357 | emit log("Error: a ~= b not satisfied [int]");
358 | t._assertApproxEqAbs(a, b, maxDelta, EXPECT_FAIL);
359 | }
360 |
361 | function testAssertApproxEqAbs_IntErr_Pass(int256 a, int256 b, uint256 maxDelta) external {
362 | vm.assume(stdMath.delta(a, b) <= maxDelta);
363 |
364 | t._assertApproxEqAbs(a, b, maxDelta, CUSTOM_ERROR, EXPECT_PASS);
365 | }
366 |
367 | function testAssertApproxEqAbs_IntErr_Fail(int256 a, int256 b, uint256 maxDelta) external {
368 | vm.assume(stdMath.delta(a, b) > maxDelta);
369 |
370 | vm.expectEmit(false, false, false, true);
371 | emit log_named_string("Error", CUSTOM_ERROR);
372 | t._assertApproxEqAbs(a, b, maxDelta, CUSTOM_ERROR, EXPECT_FAIL);
373 | }
374 |
375 | /*//////////////////////////////////////////////////////////////////////////
376 | APPROX_EQ_REL(UINT)
377 | //////////////////////////////////////////////////////////////////////////*/
378 |
379 | function testAssertApproxEqRel_Uint_Pass(uint256 a, uint256 b, uint256 maxPercentDelta) external {
380 | vm.assume(a < type(uint128).max && b < type(uint128).max && b != 0);
381 | vm.assume(stdMath.percentDelta(a, b) <= maxPercentDelta);
382 |
383 | t._assertApproxEqRel(a, b, maxPercentDelta, EXPECT_PASS);
384 | }
385 |
386 | function testAssertApproxEqRel_Uint_Fail(uint256 a, uint256 b, uint256 maxPercentDelta) external {
387 | vm.assume(a < type(uint128).max && b < type(uint128).max && b != 0);
388 | vm.assume(stdMath.percentDelta(a, b) > maxPercentDelta);
389 |
390 | vm.expectEmit(false, false, false, true);
391 | emit log("Error: a ~= b not satisfied [uint]");
392 | t._assertApproxEqRel(a, b, maxPercentDelta, EXPECT_FAIL);
393 | }
394 |
395 | function testAssertApproxEqRel_UintErr_Pass(uint256 a, uint256 b, uint256 maxPercentDelta) external {
396 | vm.assume(a < type(uint128).max && b < type(uint128).max && b != 0);
397 | vm.assume(stdMath.percentDelta(a, b) <= maxPercentDelta);
398 |
399 | t._assertApproxEqRel(a, b, maxPercentDelta, CUSTOM_ERROR, EXPECT_PASS);
400 | }
401 |
402 | function testAssertApproxEqRel_UintErr_Fail(uint256 a, uint256 b, uint256 maxPercentDelta) external {
403 | vm.assume(a < type(uint128).max && b < type(uint128).max && b != 0);
404 | vm.assume(stdMath.percentDelta(a, b) > maxPercentDelta);
405 |
406 | vm.expectEmit(false, false, false, true);
407 | emit log_named_string("Error", CUSTOM_ERROR);
408 | t._assertApproxEqRel(a, b, maxPercentDelta, CUSTOM_ERROR, EXPECT_FAIL);
409 | }
410 |
411 | /*//////////////////////////////////////////////////////////////////////////
412 | APPROX_EQ_REL(INT)
413 | //////////////////////////////////////////////////////////////////////////*/
414 |
415 | function testAssertApproxEqRel_Int_Pass(int128 a, int128 b, uint128 maxPercentDelta) external {
416 | vm.assume(b != 0);
417 | vm.assume(stdMath.percentDelta(a, b) <= maxPercentDelta);
418 |
419 | t._assertApproxEqRel(a, b, maxPercentDelta, EXPECT_PASS);
420 | }
421 |
422 | function testAssertApproxEqRel_Int_Fail(int128 a, int128 b, uint128 maxPercentDelta) external {
423 | vm.assume(b != 0);
424 | vm.assume(stdMath.percentDelta(a, b) > maxPercentDelta);
425 |
426 | vm.expectEmit(false, false, false, true);
427 | emit log("Error: a ~= b not satisfied [int]");
428 | t._assertApproxEqRel(a, b, maxPercentDelta, EXPECT_FAIL);
429 | }
430 |
431 | function testAssertApproxEqRel_IntErr_Pass(int128 a, int128 b, uint128 maxPercentDelta) external {
432 | vm.assume(b != 0);
433 | vm.assume(stdMath.percentDelta(a, b) <= maxPercentDelta);
434 |
435 | t._assertApproxEqRel(a, b, maxPercentDelta, CUSTOM_ERROR, EXPECT_PASS);
436 | }
437 |
438 | function testAssertApproxEqRel_IntErr_Fail(int128 a, int128 b, uint128 maxPercentDelta) external {
439 | vm.assume(b != 0);
440 | vm.assume(stdMath.percentDelta(a, b) > maxPercentDelta);
441 |
442 | vm.expectEmit(false, false, false, true);
443 | emit log_named_string("Error", CUSTOM_ERROR);
444 | t._assertApproxEqRel(a, b, maxPercentDelta, CUSTOM_ERROR, EXPECT_FAIL);
445 | }
446 | }
447 |
448 |
449 | contract TestTest is Test
450 | {
451 | modifier expectFailure(bool expectFail) {
452 | bool preState = vm.load(HEVM_ADDRESS, bytes32("failed")) != bytes32(0x00);
453 | _;
454 | bool postState = vm.load(HEVM_ADDRESS, bytes32("failed")) != bytes32(0x00);
455 |
456 | if (preState == true) {
457 | return;
458 | }
459 |
460 | if (expectFail) {
461 | require(postState == true, "expected failure not triggered");
462 |
463 | // unwind the expected failure
464 | vm.store(HEVM_ADDRESS, bytes32("failed"), bytes32(uint256(0x00)));
465 | } else {
466 | require(postState == false, "unexpected failure was triggered");
467 | }
468 | }
469 |
470 | function _fail(string memory err) external expectFailure(true) {
471 | fail(err);
472 | }
473 |
474 | function _assertFalse(bool data, bool expectFail) external expectFailure(expectFail) {
475 | assertFalse(data);
476 | }
477 |
478 | function _assertFalse(bool data, string memory err, bool expectFail) external expectFailure(expectFail) {
479 | assertFalse(data, err);
480 | }
481 |
482 | function _assertEq(bool a, bool b, bool expectFail) external expectFailure(expectFail) {
483 | assertEq(a, b);
484 | }
485 |
486 | function _assertEq(bool a, bool b, string memory err, bool expectFail) external expectFailure(expectFail) {
487 | assertEq(a, b, err);
488 | }
489 |
490 | function _assertEq(bytes memory a, bytes memory b, bool expectFail) external expectFailure(expectFail) {
491 | assertEq(a, b);
492 | }
493 |
494 | function _assertEq(bytes memory a,
495 | bytes memory b,
496 | string memory err,
497 | bool expectFail
498 | ) external expectFailure(expectFail) {
499 | assertEq(a, b, err);
500 | }
501 |
502 | function _assertEq(uint256[] memory a, uint256[] memory b, bool expectFail) external expectFailure(expectFail) {
503 | assertEq(a, b);
504 | }
505 |
506 | function _assertEq(int256[] memory a, int256[] memory b, bool expectFail) external expectFailure(expectFail) {
507 | assertEq(a, b);
508 | }
509 |
510 | function _assertEq(address[] memory a, address[] memory b, bool expectFail) external expectFailure(expectFail) {
511 | assertEq(a, b);
512 | }
513 |
514 | function _assertEq(uint256[] memory a, uint256[] memory b, string memory err, bool expectFail) external expectFailure(expectFail) {
515 | assertEq(a, b, err);
516 | }
517 |
518 | function _assertEq(int256[] memory a, int256[] memory b, string memory err, bool expectFail) external expectFailure(expectFail) {
519 | assertEq(a, b, err);
520 | }
521 |
522 | function _assertEq(address[] memory a, address[] memory b, string memory err, bool expectFail) external expectFailure(expectFail) {
523 | assertEq(a, b, err);
524 | }
525 |
526 |
527 | function _assertApproxEqAbs(
528 | uint256 a,
529 | uint256 b,
530 | uint256 maxDelta,
531 | bool expectFail
532 | ) external expectFailure(expectFail) {
533 | assertApproxEqAbs(a, b, maxDelta);
534 | }
535 |
536 | function _assertApproxEqAbs(
537 | uint256 a,
538 | uint256 b,
539 | uint256 maxDelta,
540 | string memory err,
541 | bool expectFail
542 | ) external expectFailure(expectFail) {
543 | assertApproxEqAbs(a, b, maxDelta, err);
544 | }
545 |
546 | function _assertApproxEqAbs(
547 | int256 a,
548 | int256 b,
549 | uint256 maxDelta,
550 | bool expectFail
551 | ) external expectFailure(expectFail) {
552 | assertApproxEqAbs(a, b, maxDelta);
553 | }
554 |
555 | function _assertApproxEqAbs(
556 | int256 a,
557 | int256 b,
558 | uint256 maxDelta,
559 | string memory err,
560 | bool expectFail
561 | ) external expectFailure(expectFail) {
562 | assertApproxEqAbs(a, b, maxDelta, err);
563 | }
564 |
565 | function _assertApproxEqRel(
566 | uint256 a,
567 | uint256 b,
568 | uint256 maxPercentDelta,
569 | bool expectFail
570 | ) external expectFailure(expectFail) {
571 | assertApproxEqRel(a, b, maxPercentDelta);
572 | }
573 |
574 | function _assertApproxEqRel(
575 | uint256 a,
576 | uint256 b,
577 | uint256 maxPercentDelta,
578 | string memory err,
579 | bool expectFail
580 | ) external expectFailure(expectFail) {
581 | assertApproxEqRel(a, b, maxPercentDelta, err);
582 | }
583 |
584 | function _assertApproxEqRel(
585 | int256 a,
586 | int256 b,
587 | uint256 maxPercentDelta,
588 | bool expectFail
589 | ) external expectFailure(expectFail) {
590 | assertApproxEqRel(a, b, maxPercentDelta);
591 | }
592 |
593 | function _assertApproxEqRel(
594 | int256 a,
595 | int256 b,
596 | uint256 maxPercentDelta,
597 | string memory err,
598 | bool expectFail
599 | ) external expectFailure(expectFail) {
600 | assertApproxEqRel(a, b, maxPercentDelta, err);
601 | }
602 | }
603 |
--------------------------------------------------------------------------------
/lib/forge-std/src/test/StdCheats.t.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity >=0.7.0 <0.9.0;
3 |
4 | import "../Test.sol";
5 | import "../StdJson.sol";
6 |
7 | contract StdCheatsTest is Test {
8 | Bar test;
9 |
10 | using stdJson for string;
11 |
12 | function setUp() public {
13 | test = new Bar();
14 | }
15 |
16 | function testSkip() public {
17 | vm.warp(100);
18 | skip(25);
19 | assertEq(block.timestamp, 125);
20 | }
21 |
22 | function testRewind() public {
23 | vm.warp(100);
24 | rewind(25);
25 | assertEq(block.timestamp, 75);
26 | }
27 |
28 | function testHoax() public {
29 | hoax(address(1337));
30 | test.bar{value: 100}(address(1337));
31 | }
32 |
33 | function testHoaxOrigin() public {
34 | hoax(address(1337), address(1337));
35 | test.origin{value: 100}(address(1337));
36 | }
37 |
38 | function testHoaxDifferentAddresses() public {
39 | hoax(address(1337), address(7331));
40 | test.origin{value: 100}(address(1337), address(7331));
41 | }
42 |
43 | function testStartHoax() public {
44 | startHoax(address(1337));
45 | test.bar{value: 100}(address(1337));
46 | test.bar{value: 100}(address(1337));
47 | vm.stopPrank();
48 | test.bar(address(this));
49 | }
50 |
51 | function testStartHoaxOrigin() public {
52 | startHoax(address(1337), address(1337));
53 | test.origin{value: 100}(address(1337));
54 | test.origin{value: 100}(address(1337));
55 | vm.stopPrank();
56 | test.bar(address(this));
57 | }
58 |
59 | function testChangePrank() public {
60 | vm.startPrank(address(1337));
61 | test.bar(address(1337));
62 | changePrank(address(0xdead));
63 | test.bar(address(0xdead));
64 | changePrank(address(1337));
65 | test.bar(address(1337));
66 | vm.stopPrank();
67 | }
68 |
69 | function testMakeAddrEquivalence() public {
70 | (address addr, ) = makeAddrAndKey("1337");
71 | assertEq(makeAddr("1337"), addr);
72 | }
73 |
74 | function testMakeAddrSigning() public {
75 | (address addr, uint256 key) = makeAddrAndKey("1337");
76 | bytes32 hash = keccak256("some_message");
77 |
78 | (uint8 v, bytes32 r, bytes32 s) = vm.sign(key, hash);
79 | assertEq(ecrecover(hash, v, r, s), addr);
80 | }
81 |
82 | function testDeal() public {
83 | deal(address(this), 1 ether);
84 | assertEq(address(this).balance, 1 ether);
85 | }
86 |
87 | function testDealToken() public {
88 | Bar barToken = new Bar();
89 | address bar = address(barToken);
90 | deal(bar, address(this), 10000e18);
91 | assertEq(barToken.balanceOf(address(this)), 10000e18);
92 | }
93 |
94 | function testDealTokenAdjustTS() public {
95 | Bar barToken = new Bar();
96 | address bar = address(barToken);
97 | deal(bar, address(this), 10000e18, true);
98 | assertEq(barToken.balanceOf(address(this)), 10000e18);
99 | assertEq(barToken.totalSupply(), 20000e18);
100 | deal(bar, address(this), 0, true);
101 | assertEq(barToken.balanceOf(address(this)), 0);
102 | assertEq(barToken.totalSupply(), 10000e18);
103 | }
104 |
105 | function testBound() public {
106 | assertEq(bound(5, 0, 4), 0);
107 | assertEq(bound(0, 69, 69), 69);
108 | assertEq(bound(0, 68, 69), 68);
109 | assertEq(bound(10, 150, 190), 160);
110 | assertEq(bound(300, 2800, 3200), 3100);
111 | assertEq(bound(9999, 1337, 6666), 6006);
112 | }
113 |
114 | function testCannotBoundMaxLessThanMin() public {
115 | vm.expectRevert(bytes("Test bound(uint256,uint256,uint256): Max is less than min."));
116 | bound(5, 100, 10);
117 | }
118 |
119 | function testBound(
120 | uint256 num,
121 | uint256 min,
122 | uint256 max
123 | ) public {
124 | if (min > max) (min, max) = (max, min);
125 |
126 | uint256 bounded = bound(num, min, max);
127 |
128 | assertGe(bounded, min);
129 | assertLe(bounded, max);
130 | }
131 |
132 | function testBoundUint256Max() public {
133 | assertEq(bound(0, type(uint256).max - 1, type(uint256).max), type(uint256).max - 1);
134 | assertEq(bound(1, type(uint256).max - 1, type(uint256).max), type(uint256).max);
135 | }
136 |
137 | function testCannotBoundMaxLessThanMin(
138 | uint256 num,
139 | uint256 min,
140 | uint256 max
141 | ) public {
142 | vm.assume(min > max);
143 | vm.expectRevert(bytes("Test bound(uint256,uint256,uint256): Max is less than min."));
144 | bound(num, min, max);
145 | }
146 |
147 | function testDeployCode() public {
148 | address deployed = deployCode("StdCheats.t.sol:StdCheatsTest", bytes(""));
149 | assertEq(string(getCode(deployed)), string(getCode(address(this))));
150 | }
151 |
152 | function testDeployCodeNoArgs() public {
153 | address deployed = deployCode("StdCheats.t.sol:StdCheatsTest");
154 | assertEq(string(getCode(deployed)), string(getCode(address(this))));
155 | }
156 |
157 | // We need that payable constructor in order to send ETH on construction
158 | constructor() payable {}
159 |
160 | function testDeployCodeVal() public {
161 | address deployed = deployCode("StdCheats.t.sol:StdCheatsTest", bytes(""), 1 ether);
162 | assertEq(string(getCode(deployed)), string(getCode(address(this))));
163 | assertEq(deployed.balance, 1 ether);
164 | }
165 |
166 | function testDeployCodeValNoArgs() public {
167 | address deployed = deployCode("StdCheats.t.sol:StdCheatsTest", 1 ether);
168 | assertEq(string(getCode(deployed)), string(getCode(address(this))));
169 | assertEq(deployed.balance, 1 ether);
170 | }
171 |
172 | // We need this so we can call "this.deployCode" rather than "deployCode" directly
173 | function deployCodeHelper(string memory what) external {
174 | deployCode(what);
175 | }
176 |
177 | function testDeployCodeFail() public {
178 | vm.expectRevert(bytes("Test deployCode(string): Deployment failed."));
179 | this.deployCodeHelper("StdCheats.t.sol:RevertingContract");
180 | }
181 |
182 | function getCode(address who) internal view returns (bytes memory o_code) {
183 | /// @solidity memory-safe-assembly
184 | assembly {
185 | // retrieve the size of the code, this needs assembly
186 | let size := extcodesize(who)
187 | // allocate output byte array - this could also be done without assembly
188 | // by using o_code = new bytes(size)
189 | o_code := mload(0x40)
190 | // new "memory end" including padding
191 | mstore(0x40, add(o_code, and(add(add(size, 0x20), 0x1f), not(0x1f))))
192 | // store length in memory
193 | mstore(o_code, size)
194 | // actually retrieve the code, this needs assembly
195 | extcodecopy(who, add(o_code, 0x20), 0, size)
196 | }
197 | }
198 |
199 | function testBytesToUint() public {
200 | assertEq(3, bytesToUint(hex'03'));
201 | assertEq(2, bytesToUint(hex'02'));
202 | assertEq(255, bytesToUint(hex'ff'));
203 | assertEq(29625, bytesToUint(hex'73b9'));
204 | }
205 |
206 | function testParseJsonTxDetail() public {
207 | string memory root = vm.projectRoot();
208 | string memory path = string.concat(root, "/src/test/fixtures/broadcast.log.json");
209 | string memory json = vm.readFile(path);
210 | bytes memory transactionDetails = json.parseRaw(".transactions[0].tx");
211 | RawTx1559Detail memory rawTxDetail = abi.decode(transactionDetails, (RawTx1559Detail));
212 | Tx1559Detail memory txDetail = rawToConvertedEIP1559Detail(rawTxDetail);
213 | assertEq(txDetail.from, 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266);
214 | assertEq(txDetail.to, 0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512);
215 | assertEq(txDetail.data, hex'23e99187000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000013370000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000000000000000000000000000000000004');
216 | assertEq(txDetail.nonce, 3);
217 | assertEq(txDetail.txType, 2);
218 | assertEq(txDetail.gas, 29625);
219 | assertEq(txDetail.value, 0);
220 | }
221 |
222 | function testReadEIP1559Transaction() public {
223 | string memory root = vm.projectRoot();
224 | string memory path = string.concat(root, "/src/test/fixtures/broadcast.log.json");
225 | uint256 index = 0;
226 | Tx1559 memory transaction = readTx1559(path, index);
227 | }
228 |
229 | function testReadEIP1559Transactions() public {
230 | string memory root = vm.projectRoot();
231 | string memory path = string.concat(root, "/src/test/fixtures/broadcast.log.json");
232 | Tx1559[] memory transactions = readTx1559s(path);
233 | }
234 |
235 | function testReadReceipt() public {
236 | string memory root = vm.projectRoot();
237 | string memory path = string.concat(root, "/src/test/fixtures/broadcast.log.json");
238 | uint index = 5;
239 | Receipt memory receipt = readReceipt(path, index);
240 | assertEq(receipt.logsBloom,
241 | hex"00000000000800000000000000000010000000000000000000000000000180000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100");
242 | }
243 |
244 | function testReadReceipts() public {
245 | string memory root = vm.projectRoot();
246 | string memory path = string.concat(root, "/src/test/fixtures/broadcast.log.json");
247 | Receipt[] memory receipts = readReceipts(path);
248 | }
249 |
250 | }
251 |
252 | contract Bar {
253 | constructor() {
254 | /// `DEAL` STDCHEAT
255 | totalSupply = 10000e18;
256 | balanceOf[address(this)] = totalSupply;
257 | }
258 |
259 | /// `HOAX` STDCHEATS
260 | function bar(address expectedSender) public payable {
261 | require(msg.sender == expectedSender, "!prank");
262 | }
263 | function origin(address expectedSender) public payable {
264 | require(msg.sender == expectedSender, "!prank");
265 | require(tx.origin == expectedSender, "!prank");
266 | }
267 | function origin(address expectedSender, address expectedOrigin) public payable {
268 | require(msg.sender == expectedSender, "!prank");
269 | require(tx.origin == expectedOrigin, "!prank");
270 | }
271 |
272 | /// `DEAL` STDCHEAT
273 | mapping (address => uint256) public balanceOf;
274 | uint256 public totalSupply;
275 | }
276 |
277 | contract RevertingContract {
278 | constructor() {
279 | revert();
280 | }
281 | }
282 |
283 |
--------------------------------------------------------------------------------
/lib/forge-std/src/test/StdError.t.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
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: MIT
2 | pragma solidity >=0.8.0 <0.9.0;
3 |
4 | import "../Test.sol";
5 |
6 | contract StdMathTest is Test
7 | {
8 | function testGetAbs() external {
9 | assertEq(stdMath.abs(-50), 50);
10 | assertEq(stdMath.abs(50), 50);
11 | assertEq(stdMath.abs(-1337), 1337);
12 | assertEq(stdMath.abs(0), 0);
13 |
14 | assertEq(stdMath.abs(type(int256).min), (type(uint256).max >> 1) + 1);
15 | assertEq(stdMath.abs(type(int256).max), (type(uint256).max >> 1));
16 | }
17 |
18 | function testGetAbs_Fuzz(int256 a) external {
19 | uint256 manualAbs = getAbs(a);
20 |
21 | uint256 abs = stdMath.abs(a);
22 |
23 | assertEq(abs, manualAbs);
24 | }
25 |
26 | function testGetDelta_Uint() external {
27 | assertEq(stdMath.delta(uint256(0), uint256(0)), 0);
28 | assertEq(stdMath.delta(uint256(0), uint256(1337)), 1337);
29 | assertEq(stdMath.delta(uint256(0), type(uint64).max), type(uint64).max);
30 | assertEq(stdMath.delta(uint256(0), type(uint128).max), type(uint128).max);
31 | assertEq(stdMath.delta(uint256(0), type(uint256).max), type(uint256).max);
32 |
33 | assertEq(stdMath.delta(0, uint256(0)), 0);
34 | assertEq(stdMath.delta(1337, uint256(0)), 1337);
35 | assertEq(stdMath.delta(type(uint64).max, uint256(0)), type(uint64).max);
36 | assertEq(stdMath.delta(type(uint128).max, uint256(0)), type(uint128).max);
37 | assertEq(stdMath.delta(type(uint256).max, uint256(0)), type(uint256).max);
38 |
39 | assertEq(stdMath.delta(1337, uint256(1337)), 0);
40 | assertEq(stdMath.delta(type(uint256).max, type(uint256).max), 0);
41 | assertEq(stdMath.delta(5000, uint256(1250)), 3750);
42 | }
43 |
44 | function testGetDelta_Uint_Fuzz(uint256 a, uint256 b) external {
45 | uint256 manualDelta;
46 | if (a > b) {
47 | manualDelta = a - b;
48 | } else {
49 | manualDelta = b - a;
50 | }
51 |
52 | uint256 delta = stdMath.delta(a, b);
53 |
54 | assertEq(delta, manualDelta);
55 | }
56 |
57 | function testGetDelta_Int() external {
58 | assertEq(stdMath.delta(int256(0), int256(0)), 0);
59 | assertEq(stdMath.delta(int256(0), int256(1337)), 1337);
60 | assertEq(stdMath.delta(int256(0), type(int64).max), type(uint64).max >> 1);
61 | assertEq(stdMath.delta(int256(0), type(int128).max), type(uint128).max >> 1);
62 | assertEq(stdMath.delta(int256(0), type(int256).max), type(uint256).max >> 1);
63 |
64 | assertEq(stdMath.delta(0, int256(0)), 0);
65 | assertEq(stdMath.delta(1337, int256(0)), 1337);
66 | assertEq(stdMath.delta(type(int64).max, int256(0)), type(uint64).max >> 1);
67 | assertEq(stdMath.delta(type(int128).max, int256(0)), type(uint128).max >> 1);
68 | assertEq(stdMath.delta(type(int256).max, int256(0)), type(uint256).max >> 1);
69 |
70 | assertEq(stdMath.delta(-0, int256(0)), 0);
71 | assertEq(stdMath.delta(-1337, int256(0)), 1337);
72 | assertEq(stdMath.delta(type(int64).min, int256(0)), (type(uint64).max >> 1) + 1);
73 | assertEq(stdMath.delta(type(int128).min, int256(0)), (type(uint128).max >> 1) + 1);
74 | assertEq(stdMath.delta(type(int256).min, int256(0)), (type(uint256).max >> 1) + 1);
75 |
76 | assertEq(stdMath.delta(int256(0), -0), 0);
77 | assertEq(stdMath.delta(int256(0), -1337), 1337);
78 | assertEq(stdMath.delta(int256(0), type(int64).min), (type(uint64).max >> 1) + 1);
79 | assertEq(stdMath.delta(int256(0), type(int128).min), (type(uint128).max >> 1) + 1);
80 | assertEq(stdMath.delta(int256(0), type(int256).min), (type(uint256).max >> 1) + 1);
81 |
82 | assertEq(stdMath.delta(1337, int256(1337)), 0);
83 | assertEq(stdMath.delta(type(int256).max, type(int256).max), 0);
84 | assertEq(stdMath.delta(type(int256).min, type(int256).min), 0);
85 | assertEq(stdMath.delta(type(int256).min, type(int256).max), type(uint256).max);
86 | assertEq(stdMath.delta(5000, int256(1250)), 3750);
87 | }
88 |
89 | function testGetDelta_Int_Fuzz(int256 a, int256 b) external {
90 | uint256 absA = getAbs(a);
91 | uint256 absB = getAbs(b);
92 | uint256 absDelta = absA > absB
93 | ? absA - absB
94 | : absB - absA;
95 |
96 | uint256 manualDelta;
97 | if ((a >= 0 && b >= 0) || (a < 0 && b < 0)) {
98 | manualDelta = absDelta;
99 | }
100 | // (a < 0 && b >= 0) || (a >= 0 && b < 0)
101 | else {
102 | manualDelta = absA + absB;
103 | }
104 |
105 | uint256 delta = stdMath.delta(a, b);
106 |
107 | assertEq(delta, manualDelta);
108 | }
109 |
110 | function testGetPercentDelta_Uint() external {
111 | assertEq(stdMath.percentDelta(uint256(0), uint256(1337)), 1e18);
112 | assertEq(stdMath.percentDelta(uint256(0), type(uint64).max), 1e18);
113 | assertEq(stdMath.percentDelta(uint256(0), type(uint128).max), 1e18);
114 | assertEq(stdMath.percentDelta(uint256(0), type(uint192).max), 1e18);
115 |
116 | assertEq(stdMath.percentDelta(1337, uint256(1337)), 0);
117 | assertEq(stdMath.percentDelta(type(uint192).max, type(uint192).max), 0);
118 | assertEq(stdMath.percentDelta(0, uint256(2500)), 1e18);
119 | assertEq(stdMath.percentDelta(2500, uint256(2500)), 0);
120 | assertEq(stdMath.percentDelta(5000, uint256(2500)), 1e18);
121 | assertEq(stdMath.percentDelta(7500, uint256(2500)), 2e18);
122 |
123 | vm.expectRevert(stdError.divisionError);
124 | stdMath.percentDelta(uint256(1), 0);
125 | }
126 |
127 | function testGetPercentDelta_Uint_Fuzz(uint192 a, uint192 b) external {
128 | vm.assume(b != 0);
129 | uint256 manualDelta;
130 | if (a > b) {
131 | manualDelta = a - b;
132 | } else {
133 | manualDelta = b - a;
134 | }
135 |
136 | uint256 manualPercentDelta = manualDelta * 1e18 / b;
137 | uint256 percentDelta = stdMath.percentDelta(a, b);
138 |
139 | assertEq(percentDelta, manualPercentDelta);
140 | }
141 |
142 | function testGetPercentDelta_Int() external {
143 | assertEq(stdMath.percentDelta(int256(0), int256(1337)), 1e18);
144 | assertEq(stdMath.percentDelta(int256(0), -1337), 1e18);
145 | assertEq(stdMath.percentDelta(int256(0), type(int64).min), 1e18);
146 | assertEq(stdMath.percentDelta(int256(0), type(int128).min), 1e18);
147 | assertEq(stdMath.percentDelta(int256(0), type(int192).min), 1e18);
148 | assertEq(stdMath.percentDelta(int256(0), type(int64).max), 1e18);
149 | assertEq(stdMath.percentDelta(int256(0), type(int128).max), 1e18);
150 | assertEq(stdMath.percentDelta(int256(0), type(int192).max), 1e18);
151 |
152 | assertEq(stdMath.percentDelta(1337, int256(1337)), 0);
153 | assertEq(stdMath.percentDelta(type(int192).max, type(int192).max), 0);
154 | assertEq(stdMath.percentDelta(type(int192).min, type(int192).min), 0);
155 |
156 | assertEq(stdMath.percentDelta(type(int192).min, type(int192).max), 2e18); // rounds the 1 wei diff down
157 | assertEq(stdMath.percentDelta(type(int192).max, type(int192).min), 2e18 - 1); // rounds the 1 wei diff down
158 | assertEq(stdMath.percentDelta(0, int256(2500)), 1e18);
159 | assertEq(stdMath.percentDelta(2500, int256(2500)), 0);
160 | assertEq(stdMath.percentDelta(5000, int256(2500)), 1e18);
161 | assertEq(stdMath.percentDelta(7500, int256(2500)), 2e18);
162 |
163 | vm.expectRevert(stdError.divisionError);
164 | stdMath.percentDelta(int256(1), 0);
165 | }
166 |
167 | function testGetPercentDelta_Int_Fuzz(int192 a, int192 b) external {
168 | vm.assume(b != 0);
169 | uint256 absA = getAbs(a);
170 | uint256 absB = getAbs(b);
171 | uint256 absDelta = absA > absB
172 | ? absA - absB
173 | : absB - absA;
174 |
175 | uint256 manualDelta;
176 | if ((a >= 0 && b >= 0) || (a < 0 && b < 0)) {
177 | manualDelta = absDelta;
178 | }
179 | // (a < 0 && b >= 0) || (a >= 0 && b < 0)
180 | else {
181 | manualDelta = absA + absB;
182 | }
183 |
184 | uint256 manualPercentDelta = manualDelta * 1e18 / absB;
185 | uint256 percentDelta = stdMath.percentDelta(a, b);
186 |
187 | assertEq(percentDelta, manualPercentDelta);
188 | }
189 |
190 | /*//////////////////////////////////////////////////////////////////////////
191 | HELPERS
192 | //////////////////////////////////////////////////////////////////////////*/
193 |
194 | function getAbs(int256 a) private pure returns (uint256) {
195 | if (a < 0)
196 | return a == type(int256).min ? uint256(type(int256).max) + 1 : uint256(-a);
197 |
198 | return uint256(a);
199 | }
200 | }
201 |
--------------------------------------------------------------------------------
/lib/forge-std/src/test/StdStorage.t.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
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(uint256(keccak256("my.random.var")), stdstore.target(address(test)).sig("hidden()").find());
17 | }
18 |
19 | function testStorageObvious() public {
20 | assertEq(uint256(0), stdstore.target(address(test)).sig("exists()").find());
21 | }
22 |
23 | function testStorageCheckedWriteHidden() public {
24 | stdstore.target(address(test)).sig(test.hidden.selector).checked_write(100);
25 | assertEq(uint256(test.hidden()), 100);
26 | }
27 |
28 | function testStorageCheckedWriteObvious() public {
29 | stdstore.target(address(test)).sig(test.exists.selector).checked_write(100);
30 | assertEq(test.exists(), 100);
31 | }
32 |
33 | function testStorageMapStructA() public {
34 | uint256 slot = stdstore
35 | .target(address(test))
36 | .sig(test.map_struct.selector)
37 | .with_key(address(this))
38 | .depth(0)
39 | .find();
40 | assertEq(uint256(keccak256(abi.encode(address(this), 4))), slot);
41 | }
42 |
43 | function testStorageMapStructB() public {
44 | uint256 slot = stdstore
45 | .target(address(test))
46 | .sig(test.map_struct.selector)
47 | .with_key(address(this))
48 | .depth(1)
49 | .find();
50 | assertEq(uint256(keccak256(abi.encode(address(this), 4))) + 1, slot);
51 | }
52 |
53 | function testStorageDeepMap() public {
54 | uint256 slot = stdstore
55 | .target(address(test))
56 | .sig(test.deep_map.selector)
57 | .with_key(address(this))
58 | .with_key(address(this))
59 | .find();
60 | assertEq(uint256(keccak256(abi.encode(address(this), keccak256(abi.encode(address(this), uint(5)))))), slot);
61 | }
62 |
63 | function testStorageCheckedWriteDeepMap() public {
64 | stdstore
65 | .target(address(test))
66 | .sig(test.deep_map.selector)
67 | .with_key(address(this))
68 | .with_key(address(this))
69 | .checked_write(100);
70 | assertEq(100, test.deep_map(address(this), address(this)));
71 | }
72 |
73 | function testStorageDeepMapStructA() public {
74 | uint256 slot = stdstore
75 | .target(address(test))
76 | .sig(test.deep_map_struct.selector)
77 | .with_key(address(this))
78 | .with_key(address(this))
79 | .depth(0)
80 | .find();
81 | assertEq(bytes32(uint256(keccak256(abi.encode(address(this), keccak256(abi.encode(address(this), uint(6)))))) + 0), bytes32(slot));
82 | }
83 |
84 | function testStorageDeepMapStructB() public {
85 | uint256 slot = stdstore
86 | .target(address(test))
87 | .sig(test.deep_map_struct.selector)
88 | .with_key(address(this))
89 | .with_key(address(this))
90 | .depth(1)
91 | .find();
92 | assertEq(bytes32(uint256(keccak256(abi.encode(address(this), keccak256(abi.encode(address(this), uint(6)))))) + 1), bytes32(slot));
93 | }
94 |
95 | function testStorageCheckedWriteDeepMapStructA() public {
96 | stdstore
97 | .target(address(test))
98 | .sig(test.deep_map_struct.selector)
99 | .with_key(address(this))
100 | .with_key(address(this))
101 | .depth(0)
102 | .checked_write(100);
103 | (uint256 a, uint256 b) = test.deep_map_struct(address(this), address(this));
104 | assertEq(100, a);
105 | assertEq(0, b);
106 | }
107 |
108 | function testStorageCheckedWriteDeepMapStructB() public {
109 | stdstore
110 | .target(address(test))
111 | .sig(test.deep_map_struct.selector)
112 | .with_key(address(this))
113 | .with_key(address(this))
114 | .depth(1)
115 | .checked_write(100);
116 | (uint256 a, uint256 b) = test.deep_map_struct(address(this), address(this));
117 | assertEq(0, a);
118 | assertEq(100, b);
119 | }
120 |
121 | function testStorageCheckedWriteMapStructA() public {
122 | stdstore
123 | .target(address(test))
124 | .sig(test.map_struct.selector)
125 | .with_key(address(this))
126 | .depth(0)
127 | .checked_write(100);
128 | (uint256 a, uint256 b) = test.map_struct(address(this));
129 | assertEq(a, 100);
130 | assertEq(b, 0);
131 | }
132 |
133 | function testStorageCheckedWriteMapStructB() public {
134 | stdstore
135 | .target(address(test))
136 | .sig(test.map_struct.selector)
137 | .with_key(address(this))
138 | .depth(1)
139 | .checked_write(100);
140 | (uint256 a, uint256 b) = test.map_struct(address(this));
141 | assertEq(a, 0);
142 | assertEq(b, 100);
143 | }
144 |
145 | function testStorageStructA() public {
146 | uint256 slot = stdstore.target(address(test)).sig(test.basic.selector).depth(0).find();
147 | assertEq(uint256(7), slot);
148 | }
149 |
150 | function testStorageStructB() public {
151 | uint256 slot = stdstore.target(address(test)).sig(test.basic.selector).depth(1).find();
152 | assertEq(uint256(7) + 1, slot);
153 | }
154 |
155 | function testStorageCheckedWriteStructA() public {
156 | stdstore.target(address(test)).sig(test.basic.selector).depth(0).checked_write(100);
157 | (uint256 a, uint256 b) = test.basic();
158 | assertEq(a, 100);
159 | assertEq(b, 1337);
160 | }
161 |
162 | function testStorageCheckedWriteStructB() public {
163 | stdstore.target(address(test)).sig(test.basic.selector).depth(1).checked_write(100);
164 | (uint256 a, uint256 b) = test.basic();
165 | assertEq(a, 1337);
166 | assertEq(b, 100);
167 | }
168 |
169 | function testStorageMapAddrFound() public {
170 | uint256 slot = stdstore.target(address(test)).sig(test.map_addr.selector).with_key(address(this)).find();
171 | assertEq(uint256(keccak256(abi.encode(address(this), uint(1)))), slot);
172 | }
173 |
174 | function testStorageMapUintFound() public {
175 | uint256 slot = stdstore.target(address(test)).sig(test.map_uint.selector).with_key(100).find();
176 | assertEq(uint256(keccak256(abi.encode(100, uint(2)))), slot);
177 | }
178 |
179 | function testStorageCheckedWriteMapUint() public {
180 | stdstore.target(address(test)).sig(test.map_uint.selector).with_key(100).checked_write(100);
181 | assertEq(100, test.map_uint(100));
182 | }
183 |
184 | function testStorageCheckedWriteMapAddr() public {
185 | stdstore.target(address(test)).sig(test.map_addr.selector).with_key(address(this)).checked_write(100);
186 | assertEq(100, test.map_addr(address(this)));
187 | }
188 |
189 | function testStorageCheckedWriteMapBool() public {
190 | stdstore.target(address(test)).sig(test.map_bool.selector).with_key(address(this)).checked_write(true);
191 | assertTrue(test.map_bool(address(this)));
192 | }
193 |
194 | function testFailStorageCheckedWriteMapPacked() public {
195 | // expect PackedSlot error but not external call so cant expectRevert
196 | stdstore.target(address(test)).sig(test.read_struct_lower.selector).with_key(address(uint160(1337))).checked_write(100);
197 | }
198 |
199 | function testStorageCheckedWriteMapPackedSuccess() public {
200 | uint256 full = test.map_packed(address(1337));
201 | // keep upper 128, set lower 128 to 1337
202 | full = (full & (uint256((1 << 128) - 1) << 128)) | 1337;
203 | stdstore.target(address(test)).sig(test.map_packed.selector).with_key(address(uint160(1337))).checked_write(full);
204 | assertEq(1337, test.read_struct_lower(address(1337)));
205 | }
206 |
207 | function testFailStorageConst() public {
208 | // vm.expectRevert(abi.encodeWithSignature("NotStorage(bytes4)", bytes4(keccak256("const()"))));
209 | stdstore.target(address(test)).sig("const()").find();
210 | }
211 |
212 | function testFailStorageNativePack() public {
213 | stdstore.target(address(test)).sig(test.tA.selector).find();
214 | stdstore.target(address(test)).sig(test.tB.selector).find();
215 |
216 | // these both would fail
217 | stdstore.target(address(test)).sig(test.tC.selector).find();
218 | stdstore.target(address(test)).sig(test.tD.selector).find();
219 | }
220 |
221 | function testStorageReadBytes32() public {
222 | bytes32 val = stdstore.target(address(test)).sig(test.tE.selector).read_bytes32();
223 | assertEq(val, hex"1337");
224 | }
225 |
226 | function testStorageReadBool_False() public {
227 | bool val = stdstore.target(address(test)).sig(test.tB.selector).read_bool();
228 | assertEq(val, false);
229 | }
230 |
231 | function testStorageReadBool_True() public {
232 | bool val = stdstore.target(address(test)).sig(test.tH.selector).read_bool();
233 | assertEq(val, true);
234 | }
235 |
236 | function testStorageReadBool_Revert() public {
237 | vm.expectRevert("stdStorage read_bool(StdStorage): Cannot decode. Make sure you are reading a bool.");
238 | this.readNonBoolValue();
239 | }
240 |
241 | function readNonBoolValue() public {
242 | stdstore.target(address(test)).sig(test.tE.selector).read_bool();
243 | }
244 |
245 | function testStorageReadAddress() public {
246 | address val = stdstore.target(address(test)).sig(test.tF.selector).read_address();
247 | assertEq(val, address(1337));
248 | }
249 |
250 | function testStorageReadUint() public {
251 | uint256 val = stdstore.target(address(test)).sig(test.exists.selector).read_uint();
252 | assertEq(val, 1);
253 | }
254 |
255 | function testStorageReadInt() public {
256 | int256 val = stdstore.target(address(test)).sig(test.tG.selector).read_int();
257 | assertEq(val, type(int256).min);
258 | }
259 | }
260 |
261 | contract StorageTest {
262 | uint256 public exists = 1;
263 | mapping(address => uint256) public map_addr;
264 | mapping(uint256 => uint256) public map_uint;
265 | mapping(address => uint256) public map_packed;
266 | mapping(address => UnpackedStruct) public map_struct;
267 | mapping(address => mapping(address => uint256)) public deep_map;
268 | mapping(address => mapping(address => UnpackedStruct)) public deep_map_struct;
269 | UnpackedStruct public basic;
270 |
271 | uint248 public tA;
272 | bool public tB;
273 |
274 |
275 | bool public tC = false;
276 | uint248 public tD = 1;
277 |
278 |
279 | struct UnpackedStruct {
280 | uint256 a;
281 | uint256 b;
282 | }
283 |
284 | mapping(address => bool) public map_bool;
285 |
286 | bytes32 public tE = hex"1337";
287 | address public tF = address(1337);
288 | int256 public tG = type(int256).min;
289 | bool public tH = true;
290 |
291 | constructor() {
292 | basic = UnpackedStruct({
293 | a: 1337,
294 | b: 1337
295 | });
296 |
297 | uint256 two = (1<<128) | 1;
298 | map_packed[msg.sender] = two;
299 | map_packed[address(bytes20(uint160(1337)))] = 1<<128;
300 | }
301 |
302 | function read_struct_upper(address who) public view returns (uint256) {
303 | return map_packed[who] >> 128;
304 | }
305 |
306 | function read_struct_lower(address who) public view returns (uint256) {
307 | return map_packed[who] & ((1 << 128) - 1);
308 | }
309 |
310 | function hidden() public view returns (bytes32 t) {
311 | bytes32 slot = keccak256("my.random.var");
312 | /// @solidity memory-safe-assembly
313 | assembly {
314 | t := sload(slot)
315 | }
316 | }
317 |
318 | function const() public pure returns (bytes32 t) {
319 | t = bytes32(hex"1337");
320 | }
321 | }
322 |
--------------------------------------------------------------------------------
/lib/forge-std/src/test/fixtures/broadcast.log.json:
--------------------------------------------------------------------------------
1 | {
2 | "transactions": [
3 | {
4 | "hash": "0xc6006863c267735a11476b7f15b15bc718e117e2da114a2be815dd651e1a509f",
5 | "type": "CALL",
6 | "contractName": "Test",
7 | "contractAddress": "0xe7f1725e7734ce288f8367e1bb143e90bb3f0512",
8 | "function": "multiple_arguments(uint256,address,uint256[]):(uint256)",
9 | "arguments": ["1", "0000000000000000000000000000000000001337", "[3,4]"],
10 | "tx": {
11 | "type": "0x02",
12 | "from": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266",
13 | "to": "0xe7f1725e7734ce288f8367e1bb143e90bb3f0512",
14 | "gas": "0x73b9",
15 | "value": "0x0",
16 | "data": "0x23e99187000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000013370000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000000000000000000000000000000000004",
17 | "nonce": "0x3",
18 | "accessList": []
19 | }
20 | },
21 | {
22 | "hash": "0xedf2b38d8d896519a947a1acf720f859bb35c0c5ecb8dd7511995b67b9853298",
23 | "type": "CALL",
24 | "contractName": "Test",
25 | "contractAddress": "0xe7f1725e7734ce288f8367e1bb143e90bb3f0512",
26 | "function": "inc():(uint256)",
27 | "arguments": [],
28 | "tx": {
29 | "type": "0x02",
30 | "from": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266",
31 | "to": "0xe7f1725e7734ce288f8367e1bb143e90bb3f0512",
32 | "gas": "0xdcb2",
33 | "value": "0x0",
34 | "data": "0x371303c0",
35 | "nonce": "0x4",
36 | "accessList": []
37 | }
38 | },
39 | {
40 | "hash": "0xa57e8e3981a6c861442e46c9471bd19cb3e21f9a8a6c63a72e7b5c47c6675a7c",
41 | "type": "CALL",
42 | "contractName": "Test",
43 | "contractAddress": "0x7c6b4bbe207d642d98d5c537142d85209e585087",
44 | "function": "t(uint256):(uint256)",
45 | "arguments": ["1"],
46 | "tx": {
47 | "type": "0x02",
48 | "from": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266",
49 | "to": "0x7c6b4bbe207d642d98d5c537142d85209e585087",
50 | "gas": "0x8599",
51 | "value": "0x0",
52 | "data": "0xafe29f710000000000000000000000000000000000000000000000000000000000000001",
53 | "nonce": "0x5",
54 | "accessList": []
55 | }
56 | }
57 | ],
58 | "receipts": [
59 | {
60 | "transactionHash": "0x481dc86e40bba90403c76f8e144aa9ff04c1da2164299d0298573835f0991181",
61 | "transactionIndex": "0x0",
62 | "blockHash": "0xef0730448490304e5403be0fa8f8ce64f118e9adcca60c07a2ae1ab921d748af",
63 | "blockNumber": "0x1",
64 | "from": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266",
65 | "to": null,
66 | "cumulativeGasUsed": "0x13f3a",
67 | "gasUsed": "0x13f3a",
68 | "contractAddress": "0x5fbdb2315678afecb367f032d93f642f64180aa3",
69 | "logs": [],
70 | "status": "0x1",
71 | "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
72 | "effectiveGasPrice": "0xee6b2800"
73 | },
74 | {
75 | "transactionHash": "0x6a187183545b8a9e7f1790e847139379bf5622baff2cb43acf3f5c79470af782",
76 | "transactionIndex": "0x0",
77 | "blockHash": "0xf3acb96a90071640c2a8c067ae4e16aad87e634ea8d8bbbb5b352fba86ba0148",
78 | "blockNumber": "0x2",
79 | "from": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266",
80 | "to": null,
81 | "cumulativeGasUsed": "0x45d80",
82 | "gasUsed": "0x45d80",
83 | "contractAddress": "0xe7f1725e7734ce288f8367e1bb143e90bb3f0512",
84 | "logs": [],
85 | "status": "0x1",
86 | "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
87 | "effectiveGasPrice": "0xee6b2800"
88 | },
89 | {
90 | "transactionHash": "0x064ad173b4867bdef2fb60060bbdaf01735fbf10414541ea857772974e74ea9d",
91 | "transactionIndex": "0x0",
92 | "blockHash": "0x8373d02109d3ee06a0225f23da4c161c656ccc48fe0fcee931d325508ae73e58",
93 | "blockNumber": "0x3",
94 | "from": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266",
95 | "to": "0x4e59b44847b379578588920ca78fbf26c0b4956c",
96 | "cumulativeGasUsed": "0x45feb",
97 | "gasUsed": "0x45feb",
98 | "contractAddress": null,
99 | "logs": [],
100 | "status": "0x1",
101 | "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
102 | "effectiveGasPrice": "0xee6b2800"
103 | },
104 | {
105 | "transactionHash": "0xc6006863c267735a11476b7f15b15bc718e117e2da114a2be815dd651e1a509f",
106 | "transactionIndex": "0x0",
107 | "blockHash": "0x16712fae5c0e18f75045f84363fb6b4d9a9fe25e660c4ce286833a533c97f629",
108 | "blockNumber": "0x4",
109 | "from": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266",
110 | "to": "0xe7f1725e7734ce288f8367e1bb143e90bb3f0512",
111 | "cumulativeGasUsed": "0x5905",
112 | "gasUsed": "0x5905",
113 | "contractAddress": null,
114 | "logs": [],
115 | "status": "0x1",
116 | "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
117 | "effectiveGasPrice": "0xee6b2800"
118 | },
119 | {
120 | "transactionHash": "0xedf2b38d8d896519a947a1acf720f859bb35c0c5ecb8dd7511995b67b9853298",
121 | "transactionIndex": "0x0",
122 | "blockHash": "0x156b88c3eb9a1244ba00a1834f3f70de735b39e3e59006dd03af4fe7d5480c11",
123 | "blockNumber": "0x5",
124 | "from": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266",
125 | "to": "0xe7f1725e7734ce288f8367e1bb143e90bb3f0512",
126 | "cumulativeGasUsed": "0xa9c4",
127 | "gasUsed": "0xa9c4",
128 | "contractAddress": null,
129 | "logs": [],
130 | "status": "0x1",
131 | "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
132 | "effectiveGasPrice": "0xee6b2800"
133 | },
134 | {
135 | "transactionHash": "0xa57e8e3981a6c861442e46c9471bd19cb3e21f9a8a6c63a72e7b5c47c6675a7c",
136 | "transactionIndex": "0x0",
137 | "blockHash": "0xcf61faca67dbb2c28952b0b8a379e53b1505ae0821e84779679390cb8571cadb",
138 | "blockNumber": "0x6",
139 | "from": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266",
140 | "to": "0x7c6b4bbe207d642d98d5c537142d85209e585087",
141 | "cumulativeGasUsed": "0x66c5",
142 | "gasUsed": "0x66c5",
143 | "contractAddress": null,
144 | "logs": [
145 | {
146 | "address": "0x7c6b4bbe207d642d98d5c537142d85209e585087",
147 | "topics": [
148 | "0x0b2e13ff20ac7b474198655583edf70dedd2c1dc980e329c4fbb2fc0748b796b"
149 | ],
150 | "data": "0x000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000046865726500000000000000000000000000000000000000000000000000000000",
151 | "blockHash": "0xcf61faca67dbb2c28952b0b8a379e53b1505ae0821e84779679390cb8571cadb",
152 | "blockNumber": "0x6",
153 | "transactionHash": "0xa57e8e3981a6c861442e46c9471bd19cb3e21f9a8a6c63a72e7b5c47c6675a7c",
154 | "transactionIndex": "0x1",
155 | "logIndex": "0x0",
156 | "transactionLogIndex": "0x0",
157 | "removed": false
158 | }
159 | ],
160 | "status": "0x1",
161 | "logsBloom": "0x00000000000800000000000000000010000000000000000000000000000180000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100",
162 | "effectiveGasPrice": "0xee6b2800"
163 | },
164 | {
165 | "transactionHash": "0x11fbb10230c168ca1e36a7e5c69a6dbcd04fd9e64ede39d10a83e36ee8065c16",
166 | "transactionIndex": "0x0",
167 | "blockHash": "0xf1e0ed2eda4e923626ec74621006ed50b3fc27580dc7b4cf68a07ca77420e29c",
168 | "blockNumber": "0x7",
169 | "from": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266",
170 | "to": "0x0000000000000000000000000000000000001337",
171 | "cumulativeGasUsed": "0x5208",
172 | "gasUsed": "0x5208",
173 | "contractAddress": null,
174 | "logs": [],
175 | "status": "0x1",
176 | "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
177 | "effectiveGasPrice": "0xee6b2800"
178 | }
179 | ],
180 | "libraries": [
181 | "src/Broadcast.t.sol:F:0x5fbdb2315678afecb367f032d93f642f64180aa3"
182 | ],
183 | "pending": [],
184 | "path": "broadcast/Broadcast.t.sol/31337/run-latest.json",
185 | "returns": {},
186 | "timestamp": 1655140035
187 | }
188 |
--------------------------------------------------------------------------------
/src/utils/Crypto.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.17;
3 |
4 | import "../BigNumbers.sol";
5 |
6 | library Crypto {
7 | using BigNumbers for *;
8 |
9 | /** @notice Verifies a PKCSv1.5 SHA256 signature
10 | * @dev credit: https://github.com/adria0/SolRsaVerify
11 | * @param _sha256 is the sha256 of the data
12 | * @param _s is the signature
13 | * @param _e is the exponent
14 | * @param _m is the modulus
15 | * @return 0 if success, >0 otherwise
16 | */
17 | function pkcs1Sha256Verify(
18 | bytes32 _sha256,
19 | BigNumber memory _s,
20 | BigNumber memory _e,
21 | BigNumber memory _m
22 | ) internal view verifyParams(_s,_e,_m) returns (uint) {
23 | return _pkcs1Sha256Verify(_sha256,_s,_e,_m);
24 | }
25 |
26 | /** @notice Verifies a PKCSv1.5 SHA256 signature
27 | * @dev credit: https://github.com/adria0/SolRsaVerify
28 | * @param _data to verify
29 | * @param _s is the signature
30 | * @param _e is the exponent
31 | * @param _m is the modulus
32 | * @return 0 if success, >0 otherwise
33 | */
34 | function pkcs1Sha256VerifyRaw(
35 | bytes memory _data,
36 | BigNumber memory _s,
37 | BigNumber memory _e,
38 | BigNumber memory _m
39 | ) internal view verifyParams(_s,_e,_m) returns (uint) {
40 | return _pkcs1Sha256Verify(sha256(_data),_s,_e,_m);
41 | }
42 |
43 | /** @notice executes Miller-Rabin Primality Test to see whether input BigNumber is prime or not.
44 | * @dev isPrime: executes Miller-Rabin Primality Test to see whether input BigNumber is prime or not.
45 | * 'randomness' is expected to be provided.
46 | * TODO: 1. add Oraclize randomness generation code template to be added to calling contract.
47 | * TODO generalize for any size input - currently just works for 850-1300 bit primes
48 | *
49 | * @param a BigNumber value to check
50 | * @param randomness BigNumber array of randomness
51 | * @return bool indicating primality.
52 | */
53 | function isPrime(
54 | BigNumber memory a,
55 | BigNumber[3] memory randomness
56 | ) internal view returns (bool){
57 |
58 | BigNumber memory one = BigNumbers.one();
59 | BigNumber memory two = BigNumbers.two();
60 |
61 | int compare = a.cmp(two,true);
62 | if (compare < 0){
63 | // if value is < 2
64 | return false;
65 | }
66 | if(compare == 0){
67 | // if value is 2
68 | return true;
69 | }
70 | // if a is even and not 2 (checked): return false
71 | if (!a.isOdd()) {
72 | return false;
73 | }
74 |
75 | BigNumber memory a1 = a.sub(one);
76 |
77 | uint k = getK(a1);
78 | BigNumber memory a1_odd = a1.val.init(a1.neg);
79 | a1_odd._shr(k);
80 |
81 | int j;
82 | uint num_checks = primeChecksForSize(a.bitlen);
83 | BigNumber memory check;
84 | for (uint i = 0; i < num_checks; i++) {
85 |
86 | check = randomness[i].add(one);
87 | // now 1 <= check < a.
88 |
89 | j = witness(check, a, a1, a1_odd, k);
90 |
91 | if(j==-1 || j==1) return false;
92 | }
93 |
94 | //if we've got to here, a is likely a prime.
95 | return true;
96 | }
97 |
98 | /** @notice Verifies a PKCSv1.5 SHA256 signature
99 | * @dev credit: https://github.com/adria0/SolRsaVerify
100 | * @param _sha256 to verify
101 | * @param _s is the signature
102 | * @param _e is the exponent
103 | * @param _m is the modulus
104 | * @return 0 if success, >0 otherwise
105 | */
106 | function _pkcs1Sha256Verify(
107 | bytes32 _sha256,
108 | BigNumber memory _s,
109 | BigNumber memory _e,
110 | BigNumber memory _m
111 | ) private view returns (uint) {
112 |
113 | uint8[19] memory sha256Prefix = [
114 | 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20
115 | ];
116 |
117 | require(_m.val.length >= sha256Prefix.length+_sha256.length+11);
118 |
119 | /// decipher
120 | uint decipherlen = _m.val.length;
121 | bytes memory decipher = (_s.modexp(_e, _m)).val;
122 |
123 | /// 0x00 || 0x01 || PS || 0x00 || DigestInfo
124 | /// PS is padding filled with 0xff
125 | // DigestInfo ::= SEQUENCE {
126 | // digestAlgorithm AlgorithmIdentifier,
127 | // digest OCTET STRING
128 | // }
129 | uint i;
130 | uint paddingLen = decipherlen - 3 - sha256Prefix.length - 32;
131 | if (decipher[0] != 0 || uint8(decipher[1]) != 1) {
132 | return 1;
133 | }
134 | for (i = 2;i<2+paddingLen;i++) {
135 | if (decipher[i] != 0xff) {
136 | return 2;
137 | }
138 | }
139 | if (decipher[2+paddingLen] != 0) {
140 | return 3;
141 | }
142 | for (i = 0;i= 1300 ? 2 :
187 | bit_size >= 850 ? 3 :
188 | bit_size >= 650 ? 4 :
189 | bit_size >= 550 ? 5 :
190 | bit_size >= 450 ? 6 :
191 | bit_size >= 400 ? 7 :
192 | bit_size >= 350 ? 8 :
193 | bit_size >= 300 ? 9 :
194 | bit_size >= 250 ? 12 :
195 | bit_size >= 200 ? 15 :
196 | bit_size >= 150 ? 18 :
197 | /* b >= 100 */ 27;
198 | }
199 |
200 | function witness(
201 | BigNumber memory w,
202 | BigNumber memory a,
203 | BigNumber memory a1,
204 | BigNumber memory a1_odd,
205 | uint k
206 | ) private view returns (int){
207 | BigNumber memory one = BigNumbers.one();
208 | BigNumber memory two = BigNumbers.two();
209 | // returns - 0: likely prime, 1: composite number (definite non-prime).
210 |
211 | w = w.modexp(a1_odd, a); // w := w^a1_odd mod a
212 |
213 | if (w.cmp(one,true)==0) return 0; // probably prime.
214 |
215 | if (w.cmp(a1,true)==0) return 0; // w == -1 (mod a), 'a' is probably prime
216 |
217 | for (;k != 0; k=k-1) {
218 | w = w.modexp(two,a); // w := w^2 mod a
219 |
220 | if (w.cmp(one,true)==0) return 1; // // 'a' is composite, otherwise a previous 'w' would have been == -1 (mod 'a')
221 |
222 | if (w.cmp(a1,true)==0) return 0; // w == -1 (mod a), 'a' is probably prime
223 |
224 | }
225 | /*
226 | * If we get here, 'w' is the (a-1)/2-th power of the original 'w', and
227 | * it is neither -1 nor +1 -- so 'a' cannot be prime
228 | */
229 | return 1;
230 | }
231 |
232 | modifier verifyParams(
233 | BigNumber memory s,
234 | BigNumber memory e,
235 | BigNumber memory m
236 | ) {
237 | s.verify();
238 | e.verify();
239 | m.verify();
240 | _;
241 | }
242 | }
243 |
--------------------------------------------------------------------------------
/test/BigNumbers.t.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.17;
3 |
4 | import "forge-std/Test.sol";
5 | import "../src/BigNumbers.sol";
6 | import "../src/utils/Crypto.sol";
7 |
8 | contract BigNumbersTest is Test {
9 | using BigNumbers for *;
10 | using Crypto for *;
11 |
12 | function testRSA() public {
13 | bytes memory message = hex'68656c6c6f20776f726c64'; // "hello world" in hex
14 |
15 | BigNumber memory signature = hex"079bed733b48d69bdb03076cb17d9809072a5a765460bc72072d687dba492afe951d75b814f561f253ee5cc0f3d703b6eab5b5df635b03a5437c0a5c179309812f5b5c97650361c645bc99f806054de21eb187bc0a704ed38d3d4c2871a117c19b6da7e9a3d808481c46b22652d15b899ad3792da5419e50ee38759560002388".init(false);
16 |
17 | BigNumber memory exponent = hex"010001".init(false);
18 |
19 | BigNumber memory modulus = hex"df3edde009b96bc5b03b48bd73fe70a3ad20eaf624d0dc1ba121a45cc739893741b7cf82acf1c91573ec8266538997c6699760148de57e54983191eca0176f518e547b85fe0bb7d9e150df19eee734cf5338219c7f8f7b13b39f5384179f62c135e544cb70be7505751f34568e06981095aeec4f3a887639718a3e11d48c240d".init(false);
20 |
21 | assertEq(Crypto.pkcs1Sha256VerifyRaw(message, signature, exponent, modulus), 0);
22 | }
23 |
24 | function testInit() public {
25 | bytes memory val;
26 | BigNumber memory bn;
27 |
28 | val = hex"ffffffff";
29 | bn = BigNumbers.init(val, false, 36);
30 | assertEq(bn.val.length, 0x20);
31 | assertEq(bn.val, hex"00000000000000000000000000000000000000000000000000000000ffffffff");
32 | assertEq(bn.neg, false);
33 | assertEq(bn.bitlen, 36);
34 |
35 | val = hex"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
36 | bn = BigNumbers.init(val, true);
37 | assertEq(bn.val.length, 0x20);
38 | assertEq(bn.val, hex"00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
39 | assertEq(bn.neg, true);
40 | assertEq(bn.bitlen, 248);
41 |
42 | val = hex"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
43 | bn = BigNumbers.init(val, false);
44 | assertEq(bn.val.length, 0x20);
45 | assertEq(bn.val, hex"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
46 | assertEq(bn.neg, false);
47 | assertEq(bn.bitlen, 256);
48 | }
49 |
50 | function testVerify() public pure {
51 | BigNumber memory bn;
52 | bn = BigNumber({
53 | val: hex"00000000000000000000000000000000000000000000bccc69e47d98498430b725f7ff5af5be936fb1ccde3fdcda3b0882a9082eab761e75b34da18d8923d70b481d89e2e936eecec248b3d456b580900a18bcd39b3948bc956139367b89dde7",
54 | neg: false,
55 | bitlen: 592
56 | });
57 | bn.verify();
58 |
59 | bn = BigNumber({
60 | val: hex"8000000000000000000000000000000000000000000000000000000000000000",
61 | neg: false,
62 | bitlen: 256
63 | });
64 | bn.verify();
65 | }
66 |
67 | function testFailVerifyBitlen() public pure {
68 | BigNumber memory bn = BigNumber({
69 | val: hex"00000000000000000000000000000000000000000000bccc69e47d98498430b725f7ff5af5be936fb1ccde3fdcda3b0882a9082eab761e75b34da18d8923d70b481d89e2e936eecec248b3d456b580900a18bcd39b3948bc956139367b89dde7",
70 | neg: false,
71 | bitlen: 1
72 | });
73 | bn.verify();
74 | }
75 |
76 | function testFailVerifyLength() public pure {
77 | BigNumber memory bn = BigNumber({
78 | val: hex"000000000000000000000000000000000000000000bccc69e47d98498430b725f7ff5af5be936fb1ccde3fdcda3b0882a9082eab761e75b34da18d8923d70b481d89e2e936eecec248b3d456b580900a18bcd39b3948bc956139367b89dde7",
79 | neg: false,
80 | bitlen: 592
81 | });
82 | bn.verify();
83 | }
84 |
85 | function testLengths() public {
86 | BigNumber memory val = hex"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff".init(false);
87 | assertEq(BigNumbers.bitLength(val), 256);
88 | val = hex"0000000000000000000000000000000000000000000000000000000000000000".init(false);
89 | assertEq(BigNumbers.bitLength(val), 0);
90 | val = hex"0000000000000000000000000000000000000000000000000000000000000001".init(false);
91 | assertEq(BigNumbers.bitLength(val), 1);
92 | val = hex"f000000000000000000000000000000000000000000000000000000000000000".init(false);
93 | assertEq(BigNumbers.bitLength(val), 256);
94 |
95 | assertEq(BigNumbers.bitLength(0), 0);
96 | assertEq(BigNumbers.bitLength(1), 1);
97 | assertEq(BigNumbers.bitLength(1 << 200), 201);
98 | assertEq(BigNumbers.bitLength((1 << 200)+1), 201);
99 | assertEq(BigNumbers.bitLength(1 << 255), 256);
100 | }
101 |
102 | function testAdd() public {
103 | BigNumber memory lhs = hex"010000000000000000000000000000000000000000000000000000000000000001".init(false);
104 | BigNumber memory rhs = hex"01".init(false);
105 |
106 | BigNumber memory r = lhs.add(rhs);
107 |
108 | assertEq(r.val, hex"00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002");
109 | assertEq(r.bitlen, 257);
110 | assertEq(r.neg, false);
111 |
112 | lhs = hex"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff".init(false);
113 | rhs = hex"01".init(false);
114 |
115 | r = lhs.add(rhs);
116 |
117 | assertEq(r.val, hex"00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000");
118 | assertEq(r.bitlen, 257);
119 | assertEq(r.neg, false);
120 |
121 | lhs = hex"0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff".init(false);
122 | rhs = hex"01".init(false);
123 |
124 | r = lhs.add(rhs);
125 |
126 | assertEq(r.val, hex"00000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000");
127 | assertEq(r.bitlen, 261);
128 | assertEq(r.neg, false);
129 | }
130 |
131 | function testShiftRight() public {
132 | // shift by value greater than word length
133 | BigNumber memory r;
134 | BigNumber memory bn = BigNumber({
135 | val: hex"1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111",
136 | neg: false,
137 | bitlen: 1024
138 | });
139 | r = bn.shr(500);
140 |
141 | assertEq(r.val, hex"000000000000000000000000000000000000000000000000000000000000011111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111");
142 | assertEq(r.val.length, 0x60);
143 | assertEq(r.bitlen, 524);
144 | assertEq(r.neg, false);
145 |
146 | // shift by value greater than word length and multiple of 8
147 | bn = BigNumber({
148 | val: hex"11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111",
149 | neg: false,
150 | bitlen: 512
151 | });
152 | r = bn.shr(264); // shift right by 33 bytes
153 |
154 | assertEq(r.val, hex"0011111111111111111111111111111111111111111111111111111111111111");
155 | assertEq(r.val.length, 0x20);
156 | assertEq(r.bitlen, 248);
157 | assertEq(r.neg, false);
158 |
159 | // shift by value >= bit length
160 | bn = BigNumber({
161 | val: hex"11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111",
162 | neg: false,
163 | bitlen: 512
164 | });
165 | r = bn.shr(512);
166 |
167 | assertEq(r.val, hex"0000000000000000000000000000000000000000000000000000000000000000");
168 | assertEq(r.val.length, 0x20);
169 | assertEq(r.bitlen, 0);
170 | assertEq(r.neg, false);
171 |
172 | // shift by value with a remaining leading zero word
173 | bn = BigNumber({
174 | val: hex"00000000000000000000000000000000000000000000000000000000000011111111111111111111111111111111111111111111111111111111111111111111",
175 | neg: false,
176 | bitlen: 272
177 | });
178 | r = bn.shr(17);
179 |
180 | assertEq(r.val, hex"0888888888888888888888888888888888888888888888888888888888888888");
181 | assertEq(r.val.length, 0x20);
182 | assertEq(r.bitlen, 255);
183 | assertEq(r.neg, false);
184 |
185 | r = ((hex'ffff').init(false)).shr(192);
186 | assertEq(r.val.length, 0x20);
187 | assertEq(r.bitlen, 0);
188 | assertEq(r.neg, false);
189 | }
190 |
191 | function testShiftLeft() public {
192 |
193 | // fails: [0x8000000000000000000000000000000000000000000000000000000000000000, 0]
194 | BigNumber memory r;
195 | BigNumber memory bn;
196 | // shift by value within this word length
197 | bn = BigNumber({
198 | val: hex"00001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111",
199 | neg: false,
200 | bitlen: 496
201 | });
202 | r = bn.shl(12);
203 |
204 | assertEq(r.val, hex"01111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111000");
205 | assertEq(r.val.length, 0x40);
206 | assertEq(r.bitlen, 508);
207 | assertEq(r.neg, false);
208 |
209 | // shift by value within this word length and multiple of 8
210 | bn = BigNumber({
211 | val: hex"00001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111",
212 | neg: false,
213 | bitlen: 496
214 | });
215 | r = bn.shl(8);
216 |
217 | assertEq(r.val, hex"00111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111100");
218 | assertEq(r.val.length, 0x40);
219 | assertEq(r.bitlen, 504);
220 | assertEq(r.neg, false);
221 |
222 | // shift creating extra trailing word
223 | bn = BigNumber({
224 | val: hex"00001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111",
225 | neg: false,
226 | bitlen: 496
227 | });
228 | r = bn.shl(268);
229 |
230 | assertEq(r.val, hex"011111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000000000");
231 | assertEq(r.val.length, 0x60);
232 | assertEq(r.bitlen, 764);
233 | assertEq(r.neg, false);
234 |
235 |
236 | // shift creating extra trailing word and multiple of 8
237 | bn = BigNumber({
238 | val: hex"00001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111",
239 | neg: false,
240 | bitlen: 496
241 | });
242 | r = bn.shl(264);
243 |
244 | assertEq(r.val, hex"001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111000000000000000000000000000000000000000000000000000000000000000000");
245 | assertEq(r.val.length, 0x60);
246 | assertEq(r.bitlen, 760);
247 | assertEq(r.neg, false);
248 |
249 | // shift creating extra leading word
250 | bn = BigNumber({
251 | val: hex"00001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111",
252 | neg: false,
253 | bitlen: 496
254 | });
255 | r = bn.shl(20);
256 |
257 | assertEq(r.val, hex"000000000000000000000000000000000000000000000000000000000000000111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111100000");
258 | assertEq(r.val.length, 0x60);
259 | assertEq(r.bitlen, 516);
260 | assertEq(r.neg, false);
261 |
262 | // shift creating extra leading word and multiple of 8
263 | bn = BigNumber({
264 | val: hex"00001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111",
265 | neg: false,
266 | bitlen: 496
267 | });
268 | r = bn.shl(24);
269 |
270 | assertEq(r.val, hex"000000000000000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111000000");
271 | assertEq(r.val.length, 0x60);
272 | assertEq(r.bitlen, 520);
273 | assertEq(r.neg, false);
274 | }
275 |
276 | function testDiv() public view {
277 | bytes memory _a = hex"c44185bd565bf73657762992dd9825b34c44c95f3845fa188bf98d3f36db0b38cdad5a8be77f36baf8467826c4574b2e3cbdc1a4d4b0fc4ff667434a6ac644e7d8349833f80b82e901";
278 | bytes memory _b = hex"4807722751c4327f377e03";
279 | bytes memory _res = hex"02b98463de4a24865849566e8398b60d2596843283dbff493f37f0efb8f738cd9f06dedf61a7b6177f41732cfb722c585edab0e6bfcdaf7a0f7df79756732a";
280 | BigNumber memory a = _a.init(true);
281 | BigNumber memory b = _b.init(false);
282 | BigNumber memory res = _res.init(true);
283 |
284 | a.divVerify(b, res);
285 | }
286 |
287 | function testModMul() public {
288 | bytes memory _a = hex"1f78";
289 | bytes memory _b = hex"0309";
290 | bytes memory _m = hex"3178";
291 | BigNumber memory a = _a.init(false);
292 | BigNumber memory b = _b.init(false);
293 | BigNumber memory m = _m.init(false);
294 | BigNumber memory res = a.modmul(b, m);
295 |
296 | assertEq(res.val, hex"0000000000000000000000000000000000000000000000000000000000000da8");
297 | assertEq(res.bitlen, 12);
298 | assertEq(res.neg, false);
299 |
300 | bytes memory _g = hex"04";
301 | bytes memory _x = hex"03";
302 | bytes memory _p = hex"0800";
303 | BigNumber memory g = _g.init(false);
304 | BigNumber memory x = _x.init(false);
305 | BigNumber memory p = _p.init(false);
306 |
307 | BigNumber memory newRes = g.modmul(x, p);
308 |
309 | assertEq(newRes.val, hex"000000000000000000000000000000000000000000000000000000000000000c");
310 | assertEq(newRes.bitlen, 4);
311 | assertEq(newRes.neg, false);
312 | }
313 |
314 | function testMul() public {
315 | BigNumber memory a = hex"00000000000000000000000000000000000000000000000000000000000000003a1eb8ecccb55eb177961acd4c55f91ef6c4170e945167941c74977784dd6b9e2487c70e96fac3618a421b447ad1ab9374a860c6abba75a084894be7d4effb1921608b187b7cfc65e5daa562e66b3567668c5411cf8646c44e3794834d81e259fb0ab419e7f3b8604a0cfbe2e4e7a7e54b0cf98fb04741796f8be7a63f56f827fa8f321e0cb7a81ae02c3c9093ba34db4c65b8f41bfca39ccf0d421c281688ff18463d09bff3aec8ea60bd8e98773afe513d5aec79a11ab4b668315ec11cbf36a8cc2ef9c06b2e7aaa52c009b1f75e2bbf3e695bb5d026fbdca56622bb7d8427ce9158666fec53a5409de3f1c774c1c6a47a64c715b85038169e49970e224cbf98e1ef4d6c0577b887820a1ed7226739efdfc8f21520e1561e23f6596d4bbfc3b558c1d8bf06ada55b649a33a1f9e034cb9885c93dc1d0d8c58d98214087da1ada5a83ef4e59fe5bc718347af72d0f7438fffe17f45177876e51df89e7cb9bd93e928002920dc45366b4b68dab6ef6665b6bbae5aa81a49559434ebe16ddc1249ded47867fb779fe464c2234cb4c89275a2c6bc735e623e678de4ae5d3e87b3aff5b5c85bc7139addefff6f39af790f75be6a14d85cd34976429b81b9428272976bf55a590dc7c25b4576846fbd1b8121820a7284e580de9012f6d8aee2a0700d26664cb92c0cf00d0509bf5406d122d69a01746031ef3a34f36ecbf1d9e3acd24c01b0b9273cf8d5b8561b4d2b03b66de8d630a02422cbb4449d4bb14c6a03777a3c9333c9e190da63372dc586c12add8cf77924a8e76143e6d1be24165d05f05e0796f24dbfaa48bcbadf424db7d8b37b73aec5d9cbda41a7f202ed16508fad952219514419dca7067fda497d2c6d274fb60c5578eb3a493ae3ca0e4e5e3d8e4e6e6b7ad1c70e4897e2631f223f45bfc154a1c9c9c4e5d803473ee26b56fa45bd58358a6e86bc9e138d1a608a398939977899db7a4f17e9a176626e7f33e6a5420b1b4bf056d9f7422b020d75833a728b8496256b599a5634e4f29b52660795a778dace7cb3aeec09e6dbf972f2803a008314e3cf18230579200e390bb04e7".init(false, 6142);
316 |
317 | BigNumber memory b = hex"00000000000000000000000000000000000000000000000000000000000000004cff437bbe7c242e9254ce4fb0191d1b64586f79c7504f2447713f2408a797740f535e74854c4e64bdbf7040e5831c776892698e30ab990060e541e00462a58d6c42e4b066006939975f17251b7779460c00306c68af3530458d04df217a659055dfe61bcfee8d5da8b6d20832bbd87f7a35c4ed709f65609562eff75cfe1cd4944fd6a12c7224852123cce3775e13ea9baeb72d0fb2b742af5ea6de5cad0b40f5f62dd4d6a26eaf135e9c96a3f812856117d61379e0a6f468e76af8707cbc67a2e35a75c0cf750d823aac4a45bdd9831c9d62978727f009b96d0c14ba7b66c43a8d1419df0f9a7218495f0fca6ab02a2517c4f3e56aa840c20b56e90007a46b4f80ba2ebf11b01bf4a1b43c4a0d7b6418ff29f025802ef84642232fbb78a6ff53bb2f5b237a26a2d26ff4eb2c8511674b029101c0a3972c8e71fb67008a004b0005a045b4c2ff1641682cded289719b955c46ec39710c103a477565f70ea2663402320a04c0eebf84069bc7b166df8618635fdb9ece51760eb05c5888cdf34c46f7bfde13d9a32887e1a814d79c835e758ffd7b0d657f1d52f049ccb0b0827bb407b59d918028c50c8f882611f68107423e232dfb6534ad54861cc35e42d22ed4e204364642cc4984735e58e4ed31b10056a28be2a033bec4c6137cd8b99a865bfdb804efeabd3ca5ee8aa0dda14722c2dc5b8081b32b135a62980170c1ae5c5efc5126987632d7b6e089c7d9bf9f625324e8996ac4ec53316d263406d58f6c9830d6a47fb2ee8fb548a224d776e7dc4e3099fbfdc296e4924d48aa18813910d6e6d3d953aee65c9fe906ae2c544bb6354a57c3f4851daebedafad128942956c4073cb781b0e9d9d97e195b71ed310b8e71e4d56e4df8aa3eafda6cec80e4c29556aee87de93a55ee47b6994181072699c9498247d1b93c69b6d87b00b5de1b08167122f7f2c9b2057b8a4e3f8dd41d7961a25456d14117b9776dd1eaf65aaa2b2243014e413f5931fd470f0953b956e37a8f3561b10b207c09f7d77bfa7eb46e5b5ebe2527003b7828f72337ffbf84f02c45c35fd640b79ed6d8dacbe44531".init(false, 6143);
318 |
319 | BigNumber memory res = a.mul(b);
320 |
321 | BigNumber memory expectedRes = hex"117b12d2a30d90780c94b1e4cca184946ce13f68a1efe8c5fc57e5d253cf1ddde4e13c8a17830c20caa12395de287187f19da2cbf9579cbcbad81cbcd390f3e0711894551edd48a855b134e007e09c48f9e53f9a97b84c11079c41b3408554f9c5b870420bf82deb10f841e3d9c7966962b7c8889a99484438ea7f294736da2bd9cf952fbf737a160b1fcee9d6c13ee28eba7cc8358fca401ab095a4317d9f2f7c3ae17979cd96995efae9f0f9b2b2f9e766233d983faca337b2c7e0942ffb456c1506edf3fed40d8ee9d41f0b7c6560c3c0ef017466ade93e8ea5d11492b6064d0aeb704041d0c051b804dadababb8a890055171423c5a1a7e61d7bece23ba9e8f9cbbff2685c1db5fe12471bc73ab8d5268935fd6d05990244c652cc7f9777777884fa0a5943fac2225ee9666a4b892553f8fe25d94bf36a3f8d119cbc93a5e016c9a76822473e2cf0ca32644730bc72164532731b3e3cd2b8aa425430d9c91aa9b2017158f1fbef0b7e7a27dc6107bdbdb3c46b4e10f21a79c06fa15df20568eaeaaba4ecb61e93fd5bddbe46cc4ad41fe6348efd1ce4c896ac1fff3bd8f8277e5640737719ff1358ee6b3bb2e0617a986d9155f0ec7c059ef29f04eeb3d81396d95ce97f96d6545884ae3e09df97118602726ba3bf58291fc840555f98cb1c72175277201201f0f3f98a8d46a75995aef560ce9c707364fc89e58a2a65c37ff4cc317506281593c25874fd35b7336f2166d4e94e888bad7e94ae1c9e0f26b9fcfb4c4eebbfa3462e0acf71ef43382a0233560411b5add36accbfb1662fe0226eeca0650f291cfd39228f14c6ac33d32b2ffdb7267b83423c224f52ea998bcdec0e52b4356797be39042f867f862ce5447dbbec7db58d765be145c6cc8e1f29d3cca962e05bcf5e56be33c99e4cfcca3a1710f607ae908f0d5c173b7f3958c50f5ec914d19402296a60ad55603e1c981c6b00d70e0c89ad3c73c826b7d7ab2e45c4af7bc19a51e1cf0fcb2081f9f03fb3bc2e9cdd59ff99914073b75d416b5102e0b4228101febed8b61c756c8dd2eb20642cd0fb3cf107d5d5b6e04abb7b8531f25db68cffa90d406cda5aa9a9f70ed54cb835d59c1bbd99a23e1535cfeaa42dd89bec3f76b909548fce40d2f8bf903551d4f1d0248c122bb33e199c21c7e9364a86347e49a1d5305399be8e75218c1ce40477dfac74414218c7042dea15a48ebb8ef6d03368c0d66c32b2ffc121c3b6067a82b62c3c34ecf20ae5e919452eac400e3c4cafc7e322d6ae5e22dc618eae5b1efb69f9292eb32c61a213f826aefb1b2d50a3eaa95bf0074caa96df0dccbf0cfc15a09f6aa7cf086338a8099881d690a213442121a522ce1badd08445883af37f020efbbe24a532b3e4d096e9b431cd7290223f9bb45b3c5946ccf3b1bf017d27ae36b82e3426107f67b44bd0ae4aac8ae4dcdfa3617e899b21c4210e388c4b095255f3ba7fa1e44ea0ca647c1896858a94a552e09ea2bf1dacb5a336f32ab6d2e8fceda3cbe85255907c7a06ecfdda11a8db2d6d4733a19779ea87035aa3009d3b25c4ed31ec9ce57668f6ec15a4ec7c6718c0703410d9c7fad5a75bdfe9f8bd5890a04965a5d2393ea80b9508490dbb18b0c5c1fe90a252c6c6c4d75a010f02531e8dd40cc7f375fce800b3d83cff2baaf433eefd6baf8cc78e6eae8302d94dad8e9cc527e19cbc6b0445626a2641485280e9e2bc5f9b25ba4f22ac06518b99262baff360ac34bc705e9be26b7d79024c6e0f0ef5a3b73f249a0320aa617728d9143950dca21bd5b8e2f34e7e98cd77bb2ba0856e4442a6e455de6543ae079466e65bc8f79df2962e0f75fad039180062142c493354576a21405623126c41f41bbbc2c0824a4a5998035d79fe846a5627d29a25631de5a1730c9aa13736448e40699370606d349d84022eb2fb1cc09f7304a08434c771201f0bbcf847872868e97e8465a5a1d4e57b92f47f86351f7d11b00341b3208ec5ca02e5dd1c5e95041c1e60f2f5b989fad8febe8ff99b409347a45f64651694fc94640c494e366fb69f486f96511e7dd06771203b02b9b85904863ab8576eddd1dccfbc7d8c2e5c27ec5081b0d0025d6296b369a4cba650a10d86284c81e94a80ca114a8879d7305a087725fd121fc9baa6da3337".init(false);
322 |
323 | assertEq(res.eq(expectedRes), true);
324 | }
325 | }
326 |
--------------------------------------------------------------------------------
/test/differential/BigNumbers.dt.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.17;
3 |
4 | import "../../src/BigNumbers.sol";
5 | import "./util/Strings.sol";
6 | import "forge-std/Test.sol";
7 | import "forge-std/console.sol";
8 |
9 | contract BigNumbersDifferentialTest is Test {
10 | using BigNumbers for *;
11 | using Strings for *;
12 | bytes constant ZERO = hex"0000000000000000000000000000000000000000000000000000000000000000";
13 | bytes constant ONE = hex"0000000000000000000000000000000000000000000000000000000000000001";
14 | bytes constant TWO = hex"0000000000000000000000000000000000000000000000000000000000000002";
15 |
16 | function testAddMatchesJSImplementationFuzzed(bytes memory a_val, bytes memory b_val, bool a_neg, bool b_neg) public {
17 | vm.assume(a_val.length > 1 && b_val.length > 1);
18 |
19 | BigNumber memory a = a_val.init(a_neg);
20 | BigNumber memory b = b_val.init(b_neg);
21 | BigNumber memory res = a.add(b);
22 | if(res.isZero()) res.neg = false;
23 |
24 | string[] memory runJsInputs = new string[](11);
25 |
26 | // build ffi command string
27 | runJsInputs[0] = 'npm';
28 | runJsInputs[1] = '--prefix';
29 | runJsInputs[2] = 'test/differential/scripts/';
30 | runJsInputs[3] = '--silent';
31 | runJsInputs[4] = 'run';
32 | runJsInputs[5] = 'differential';
33 | runJsInputs[6] = 'add';
34 | runJsInputs[7] = a_val.toHexString();
35 | runJsInputs[8] = b_val.toHexString();
36 | runJsInputs[9] = a_neg.toString();
37 | runJsInputs[10] = b_neg.toString();
38 |
39 | // run and captures output
40 | bytes memory jsResult = vm.ffi(runJsInputs);
41 | (bool neg, bytes memory js_res_val ) = abi.decode(jsResult, (bool, bytes));
42 | BigNumber memory js_res = js_res_val.init(neg);
43 |
44 | assertEq(js_res.neg, res.neg);
45 | assertEq(js_res.val, res.val);
46 | }
47 |
48 | function testSubMatchesJSImplementationFuzzed(bytes memory a_val, bytes memory b_val, bool a_neg, bool b_neg) public {
49 | vm.assume(a_val.length > 1 && b_val.length > 1);
50 |
51 | BigNumber memory a = a_val.init(a_neg);
52 | BigNumber memory b = b_val.init(b_neg);
53 | BigNumber memory res = a.sub(b);
54 | if(res.isZero()) res.neg = false;
55 |
56 | string[] memory runJsInputs = new string[](11);
57 |
58 | // build ffi command string
59 | runJsInputs[0] = 'npm';
60 | runJsInputs[1] = '--prefix';
61 | runJsInputs[2] = 'test/differential/scripts/';
62 | runJsInputs[3] = '--silent';
63 | runJsInputs[4] = 'run';
64 | runJsInputs[5] = 'differential';
65 | runJsInputs[6] = 'sub';
66 | runJsInputs[7] = a_val.toHexString();
67 | runJsInputs[8] = b_val.toHexString();
68 | runJsInputs[9] = a_neg.toString();
69 | runJsInputs[10] = b_neg.toString();
70 |
71 | // run and captures output
72 | bytes memory jsResult = vm.ffi(runJsInputs);
73 | (bool neg, bytes memory js_res_val ) = abi.decode(jsResult, (bool, bytes));
74 | BigNumber memory js_res = js_res_val.init(neg);
75 |
76 | assertEq(js_res.neg, res.neg);
77 | assertEq(js_res.val, res.val);
78 | }
79 |
80 | function testMulMatchesJSImplementationFuzzed(bytes memory a_val, bytes memory b_val, bool a_neg, bool b_neg) public {
81 | vm.assume(a_val.length > 1 && b_val.length > 1);
82 |
83 | BigNumber memory a = a_val.init(true);
84 | BigNumber memory b = b_val.init(false);
85 | BigNumber memory res = a.mul(b);
86 | //if(res.isZero()) res.neg = false;
87 |
88 | string[] memory runJsInputs = new string[](11);
89 |
90 | // build ffi command string
91 | runJsInputs[0] = 'npm';
92 | runJsInputs[1] = '--prefix';
93 | runJsInputs[2] = 'test/differential/scripts/';
94 | runJsInputs[3] = '--silent';
95 | runJsInputs[4] = 'run';
96 | runJsInputs[5] = 'differential';
97 | runJsInputs[6] = 'mul';
98 | runJsInputs[7] = a_val.toHexString();
99 | runJsInputs[8] = b_val.toHexString();
100 | runJsInputs[9] = a_neg.toString();
101 | runJsInputs[10] = b_neg.toString();
102 |
103 | // run and captures output
104 | bytes memory jsResult = vm.ffi(runJsInputs);
105 | (bool neg, bytes memory js_res_val ) = abi.decode(jsResult, (bool, bytes));
106 | BigNumber memory js_res = js_res_val.init(neg);
107 |
108 | //assertEq(js_res.neg, res.neg);
109 | assertEq(js_res.val, res.val);
110 | }
111 |
112 | function testDivMatchesJSImplementationFuzzed(bytes memory a_val, bytes memory b_val, bool a_neg, bool b_neg) public {
113 | vm.assume(a_val.length > 1 && b_val.length > 1);
114 | BigNumber memory b = b_val.init(b_neg);
115 | BigNumber memory zero = BigNumber(ZERO,false,0);
116 | vm.assume(b.cmp(zero, false)!=0); // assert that b is not zero
117 |
118 | BigNumber memory a = a_val.init(a_neg);
119 |
120 | string[] memory runJsInputs = new string[](11);
121 |
122 | // build ffi command string
123 | runJsInputs[0] = 'npm';
124 | runJsInputs[1] = '--prefix';
125 | runJsInputs[2] = 'test/differential/scripts/';
126 | runJsInputs[3] = '--silent';
127 | runJsInputs[4] = 'run';
128 | runJsInputs[5] = 'differential';
129 | runJsInputs[6] = 'div';
130 | runJsInputs[7] = a_val.toHexString();
131 | runJsInputs[8] = b_val.toHexString();
132 | runJsInputs[9] = a_neg.toString();
133 | runJsInputs[10] = b_neg.toString();
134 |
135 | // run and captures output
136 | bytes memory jsResult = vm.ffi(runJsInputs);
137 | (bool neg, bytes memory js_res_val ) = abi.decode(jsResult, (bool, bytes));
138 | BigNumber memory js_res = js_res_val.init(neg);
139 | // function will fail if js_res is not the division result
140 | a.divVerify(b, js_res);
141 | }
142 |
143 | function testModMatchesJSImplementationFuzzed(bytes memory a_val, bytes memory n_val, bool a_neg) public {
144 | vm.assume(a_val.length > 1 && n_val.length > 1);
145 | BigNumber memory n = n_val.init(false);
146 | BigNumber memory zero = BigNumber(ZERO,false,0);
147 | vm.assume(n.cmp(zero, true)!=0); // assert that n is not zero
148 |
149 | BigNumber memory a = a_val.init(a_neg);
150 | BigNumber memory res = a.mod(n);
151 | if(res.isZero()) res.neg = false;
152 |
153 | string[] memory runJsInputs = new string[](11);
154 |
155 | // build ffi command string
156 | runJsInputs[0] = 'npm';
157 | runJsInputs[1] = '--prefix';
158 | runJsInputs[2] = 'test/differential/scripts/';
159 | runJsInputs[3] = '--silent';
160 | runJsInputs[4] = 'run';
161 | runJsInputs[5] = 'differential';
162 | runJsInputs[6] = 'mod';
163 | runJsInputs[7] = a_val.toHexString();
164 | runJsInputs[8] = n_val.toHexString();
165 | runJsInputs[9] = a_neg.toString();
166 |
167 | // run and captures output
168 | bytes memory jsResult = vm.ffi(runJsInputs);
169 | (bool neg, bytes memory js_res_val ) = abi.decode(jsResult, (bool, bytes));
170 | BigNumber memory js_res = js_res_val.init(neg);
171 |
172 | assertEq(js_res.neg, res.neg);
173 | assertEq(js_res.val, res.val);
174 | }
175 |
176 | function testShlMatchesJSImplementationFuzzed(bytes memory a_val, uint bits) public {
177 | vm.assume(a_val.length > 1 && bits <= 2048);
178 |
179 | BigNumber memory a = a_val.init(false);
180 | BigNumber memory res = a.shl(bits);
181 | if(res.isZero()) res.neg = false;
182 |
183 | console.log('res out:');
184 | console.logBytes(res.val);
185 |
186 | string[] memory runJsInputs = new string[](9);
187 |
188 | // build ffi command string
189 | runJsInputs[0] = 'npm';
190 | runJsInputs[1] = '--prefix';
191 | runJsInputs[2] = 'test/differential/scripts/';
192 | runJsInputs[3] = '--silent';
193 | runJsInputs[4] = 'run';
194 | runJsInputs[5] = 'differential';
195 | runJsInputs[6] = 'shl';
196 | runJsInputs[7] = a_val.toHexString();
197 | runJsInputs[8] = bits.toString();
198 |
199 | // run and captures output
200 | bytes memory jsResult = vm.ffi(runJsInputs);
201 | (bool neg, bytes memory js_res_val ) = abi.decode(jsResult, (bool, bytes));
202 | BigNumber memory js_res = js_res_val.init(neg);
203 |
204 | assertEq(js_res.cmp(res, true), 0);
205 | }
206 |
207 | function testShrMatchesJSImplementationFuzzed(bytes memory a_val, uint bits) public {
208 | vm.assume(a_val.length > 1 && bits <= 2048);
209 |
210 | BigNumber memory a = a_val.init(false);
211 | BigNumber memory res = a.shr(bits);
212 | if(res.isZero()) res.neg = false;
213 |
214 | string[] memory runJsInputs = new string[](9);
215 |
216 | // build ffi command string
217 | runJsInputs[0] = 'npm';
218 | runJsInputs[1] = '--prefix';
219 | runJsInputs[2] = 'test/differential/scripts/';
220 | runJsInputs[3] = '--silent';
221 | runJsInputs[4] = 'run';
222 | runJsInputs[5] = 'differential';
223 | runJsInputs[6] = 'shr';
224 | runJsInputs[7] = a_val.toHexString();
225 | runJsInputs[8] = bits.toString();
226 |
227 | // run and captures output
228 | bytes memory jsResult = vm.ffi(runJsInputs);
229 | (bool neg, bytes memory js_res_val ) = abi.decode(jsResult, (bool, bytes));
230 | BigNumber memory js_res = js_res_val.init(neg);
231 |
232 | assertEq(js_res.cmp(res, true), 0);
233 | }
234 |
235 | function testCmpMatchesJSImplementationFuzzed(bytes memory a_val, bytes memory b_val, bool a_neg, bool b_neg, bool signed) public {
236 | vm.assume(a_val.length > 1 && b_val.length > 1);
237 |
238 | BigNumber memory a = a_val.init(a_neg);
239 | BigNumber memory b = b_val.init(b_neg);
240 | int res = a.cmp(b, signed);
241 |
242 | string[] memory runJsInputs = new string[](12);
243 |
244 | // build ffi command string
245 | runJsInputs[0] = 'npm';
246 | runJsInputs[1] = '--prefix';
247 | runJsInputs[2] = 'test/differential/scripts/';
248 | runJsInputs[3] = '--silent';
249 | runJsInputs[4] = 'run';
250 | runJsInputs[5] = 'differential';
251 | runJsInputs[6] = 'cmp';
252 | runJsInputs[7] = a_val.toHexString();
253 | runJsInputs[8] = b_val.toHexString();
254 | runJsInputs[9] = a_neg.toString();
255 | runJsInputs[10] = b_neg.toString();
256 | runJsInputs[11] = signed.toString();
257 |
258 | // run and captures output
259 | bytes memory jsResult = vm.ffi(runJsInputs);
260 | int js_res = abi.decode(jsResult, (int));
261 |
262 | assertEq(js_res, res);
263 | }
264 |
265 | function testModMulMatchesJSImplementationFuzzed(bytes memory a_val, bytes memory b_val, bytes memory n_val, bool a_neg, bool b_neg) public {
266 | vm.assume(a_val.length > 1 && b_val.length > 1 && n_val.length > 1);
267 |
268 | BigNumber memory a = a_val.init(a_neg);
269 | BigNumber memory b = b_val.init(b_neg);
270 | BigNumber memory n = n_val.init(false);
271 | BigNumber memory zero = BigNumber(ZERO,false,0);
272 | vm.assume(n.cmp(zero, true)!=0); // assert that n is not zero
273 |
274 | BigNumber memory res = a.modmul(b, n);
275 | if(res.isZero()) res.neg = false;
276 |
277 | string[] memory runJsInputs = new string[](12);
278 |
279 | // build ffi command string
280 | runJsInputs[0] = 'npm';
281 | runJsInputs[1] = '--prefix';
282 | runJsInputs[2] = 'test/differential/scripts/';
283 | runJsInputs[3] = '--silent';
284 | runJsInputs[4] = 'run';
285 | runJsInputs[5] = 'differential';
286 | runJsInputs[6] = 'modmul';
287 | runJsInputs[7] = a_val.toHexString();
288 | runJsInputs[8] = b_val.toHexString();
289 | runJsInputs[9] = n_val.toHexString();
290 | runJsInputs[10] = a_neg.toString();
291 | runJsInputs[11] = b_neg.toString();
292 |
293 | // run and captures output
294 | bytes memory jsResult = vm.ffi(runJsInputs);
295 | (bool neg, bytes memory js_res_val ) = abi.decode(jsResult, (bool, bytes));
296 | BigNumber memory js_res = js_res_val.init(neg);
297 |
298 | assertEq(js_res.eq(res), true);
299 | }
300 |
301 | function testInvModMatchesJSImplementationFuzzed(bytes memory a_val, bytes memory m_val) public {
302 | vm.assume(a_val.length > 1 && m_val.length > 1);
303 | BigNumber memory m = m_val.init(false);
304 | BigNumber memory zero = BigNumber(ZERO,false,0);
305 | vm.assume(!m.eq(zero)); // assert that modulus is not zero
306 |
307 | BigNumber memory a = a_val.init(false);
308 |
309 | (bool valid, BigNumber memory js_res ) = invMod(a, m);
310 | vm.assume(valid); // we don't continue if there is no modular multiplicative inverse for a
311 |
312 | // function will fail if js_res is not the inverse mod result
313 | a.modinvVerify(m, js_res);
314 | }
315 |
316 | function testModExpMatchesJSImplementationFuzzed(bytes memory a_val, bytes memory e_val, bytes memory m_val) public {
317 | vm.assume(a_val.length > 1 && e_val.length > 1 && m_val.length > 1);
318 | BigNumber memory m = m_val.init(false);
319 | BigNumber memory zero = BigNumber(ZERO,false,0);
320 | vm.assume(!m.eq(zero));
321 |
322 | BigNumber memory a = a_val.init(false);
323 | (bool valid, BigNumber memory a_inv ) = invMod(a, m);
324 | vm.assume(valid); // we don't continue if there is no modular multiplicative inverse for a
325 |
326 | BigNumber memory e = e_val.init(true);
327 |
328 | BigNumber memory res = a.modexp(a_inv, e, m);
329 |
330 | string[] memory runJsInputs = new string[](10);
331 |
332 | // build ffi command string
333 | runJsInputs[0] = 'npm';
334 | runJsInputs[1] = '--prefix';
335 | runJsInputs[2] = 'test/differential/scripts/';
336 | runJsInputs[3] = '--silent';
337 | runJsInputs[4] = 'run';
338 | runJsInputs[5] = 'differential';
339 | runJsInputs[6] = 'modexp';
340 | runJsInputs[7] = a_inv.val.toHexString();
341 | runJsInputs[8] = e_val.toHexString();
342 | runJsInputs[9] = m_val.toHexString();
343 |
344 | // run and captures output
345 | bytes memory jsResult = vm.ffi(runJsInputs);
346 | (bool neg, bytes memory js_res_val ) = abi.decode(jsResult, (bool, bytes));
347 |
348 | BigNumber memory js_res = js_res_val.init(neg);
349 |
350 | assertEq(res.eq(js_res), true);
351 | }
352 |
353 | function invMod(BigNumber memory a, BigNumber memory m) public returns(bool, BigNumber memory) {
354 | string[] memory runJsInputs = new string[](11);
355 |
356 | // build ffi command string
357 | runJsInputs[0] = 'npm';
358 | runJsInputs[1] = '--prefix';
359 | runJsInputs[2] = 'test/differential/scripts/';
360 | runJsInputs[3] = '--silent';
361 | runJsInputs[4] = 'run';
362 | runJsInputs[5] = 'differential';
363 | runJsInputs[6] = 'invmod';
364 | runJsInputs[7] = a.val.toHexString();
365 | runJsInputs[8] = m.val.toHexString();
366 |
367 | // run and captures output
368 | bytes memory jsResult = vm.ffi(runJsInputs);
369 | (bool valid, bool neg, bytes memory val ) = abi.decode(jsResult, (bool, bool, bytes));
370 | BigNumber memory res = val.init(neg);
371 |
372 | return (valid, res);
373 | }
374 |
375 | // write a test case for divmod
376 |
377 | // write a test case for div
378 |
379 | // write a test case for mulmod
380 |
381 | // write a test case for powmod
382 |
383 | // write a test case for exp
384 |
385 | // write a test case for invmod
386 |
387 | // write a test case for inv
388 |
389 | // write a test case for sqrt
390 |
391 | }
392 |
--------------------------------------------------------------------------------
/test/differential/README.md:
--------------------------------------------------------------------------------
1 | ## Differential Testing
2 | Differential testing is used to compare solidity-BigNumber's implementation to reference implementations in other languages. This directory contains the scripts needed to support this testing, as well as the differential tests themselves.
3 |
4 | Currently, the only reference implementation is adapted from the [indutny/bn.js](https://github.com/indutny/bn.js/) implementation (The same BigNumber library used in the popular Ethereum TypeScript utilities library, [ethers.js](https://docs.ethers.io/v5/)). It is written in javascript.
5 |
6 |
7 | ### Node Version
8 | `>=14.17`
9 |
10 | ### Setup
11 | From the [scripts directory](./scripts/), run
12 | ```sh
13 | npm install
14 | npm run compile
15 | ```
16 |
17 | ### Run the differential test using foundry
18 | Now you can run the tests.
19 | From the root of the solidity-BigNumber repo, run:
20 | ```sh
21 | forge test -vvvv --ffi --mc BigNumbersDifferentialTest
22 | ```
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/test/differential/scripts/differential.ts:
--------------------------------------------------------------------------------
1 | import { BN } from 'bn.js';
2 | import { ethers } from 'ethers';
3 |
4 | const func = process.argv[2];
5 | switch(func){
6 | case "add": {
7 | const a_val = process.argv[3].substring(2);
8 | const b_val = process.argv[4].substring(2);
9 | const a_neg = (process.argv[5] === 'true');
10 | const b_neg = (process.argv[6] === 'true');
11 | let a = new BN(a_val, 16)
12 | let b = new BN(b_val, 16)
13 | if(a_neg) a = a.mul(new BN(-1));
14 | if(b_neg) b = b.mul(new BN(-1));
15 | let res = a.add(b)
16 | const neg = res.isNeg()
17 | if(neg) res = res.abs()
18 | process.stdout.write(ethers.utils.defaultAbiCoder.encode(['bool', 'bytes'], [neg, ethers.BigNumber.from(res.toString())]));
19 | break;
20 | }
21 | case "sub": {
22 | const a_val = process.argv[3].substring(2);
23 | const b_val = process.argv[4].substring(2);
24 | const a_neg = (process.argv[5] === 'true');
25 | const b_neg = (process.argv[6] === 'true');
26 | let a = new BN(a_val, 16)
27 | let b = new BN(b_val, 16)
28 | if(a_neg) a = a.mul(new BN(-1));
29 | if(b_neg) b = b.mul(new BN(-1));
30 | let res = a.sub(b)
31 | const neg = res.isNeg()
32 | if(neg) res = res.abs()
33 | process.stdout.write(ethers.utils.defaultAbiCoder.encode(['bool', 'bytes'], [neg, ethers.BigNumber.from(res.toString())]));
34 | break;
35 | }
36 | case "mul": {
37 | const a_val = process.argv[3].substring(2);
38 | const b_val = process.argv[4].substring(2);
39 | const a_neg = (process.argv[5] === 'true');
40 | const b_neg = (process.argv[6] === 'true');
41 | let a = new BN(a_val, 16)
42 | let b = new BN(b_val, 16)
43 | if(a_neg) a = a.mul(new BN(-1));
44 | if(b_neg) b = b.mul(new BN(-1));
45 | let res = a.mul(b)
46 | const neg = res.isNeg()
47 | if(neg) res = res.abs()
48 | process.stdout.write(ethers.utils.defaultAbiCoder.encode(['bool', 'bytes'], [neg, ethers.BigNumber.from(res.toString())]));
49 | break;
50 | }
51 | case "div": {
52 | const a_val = process.argv[3].substring(2);
53 | const b_val = process.argv[4].substring(2);
54 | const a_neg = (process.argv[5] === 'true');
55 | const b_neg = (process.argv[6] === 'true');
56 | let a = new BN(a_val, 16)
57 | let b = new BN(b_val, 16)
58 | if(a_neg) a = a.mul(new BN(-1));
59 | if(b_neg) b = b.mul(new BN(-1));
60 | let res = a.div(b)
61 | const neg = res.isNeg()
62 | if(neg) res = res.abs()
63 | process.stdout.write(ethers.utils.defaultAbiCoder.encode(['bool', 'bytes'], [neg, ethers.BigNumber.from(res.toString())]));
64 | break;
65 | }
66 | case "invmod": {
67 | const a_val = process.argv[3].substring(2);
68 | const m_val = process.argv[4].substring(2);
69 | let a = new BN(a_val, 16)
70 | let m = new BN(m_val, 16)
71 | let res = a.invm(m)
72 | const neg = res.isNeg()
73 | if(neg) res = res.mul(new BN(-1))
74 | let valid = a.mul(res).mod(m).eq(new BN(1));
75 | process.stdout.write(ethers.utils.defaultAbiCoder.encode(['bool', 'bool', 'bytes'], [valid, neg, ethers.BigNumber.from(res.toString())]));
76 | break;
77 | }
78 | case "mod": {
79 | const a_val = process.argv[3].substring(2);
80 | const n_val = process.argv[4].substring(2);
81 | const a_neg = (process.argv[5] === 'true');
82 | let a = new BN(a_val, 16)
83 | let n = new BN(n_val, 16)
84 | if(a_neg) a = a.mul(new BN(-1));
85 | let res = a.umod(n)
86 | const neg = res.isNeg()
87 | if(neg) res = res.abs()
88 | process.stdout.write(ethers.utils.defaultAbiCoder.encode(['bool', 'bytes'], [neg, ethers.BigNumber.from(res.toString())]));
89 | break;
90 | }
91 | case "shl": {
92 | const a_val = process.argv[3].substring(2);
93 | const bits = Number(process.argv[4]);
94 | let a = new BN(a_val, 16);
95 | let res = a.shln(bits)
96 | const neg = res.isNeg()
97 | process.stdout.write(ethers.utils.defaultAbiCoder.encode(['bool', 'bytes'], [neg, ethers.BigNumber.from(res.toString())]));
98 | break;
99 | }
100 | case "shr": {
101 | const a_val = process.argv[3].substring(2);
102 | const bits = Number(process.argv[4]);
103 | let a = new BN(a_val, 16);
104 | let res = a.shrn(bits)
105 | const neg = res.isNeg()
106 | process.stdout.write(ethers.utils.defaultAbiCoder.encode(['bool', 'bytes'], [neg, ethers.BigNumber.from(res.toString())]));
107 | break;
108 | }
109 | case "cmp": {
110 | const a_val = process.argv[3].substring(2);
111 | const b_val = process.argv[4].substring(2);
112 | const a_neg = (process.argv[5] === 'true');
113 | const b_neg = (process.argv[6] === 'true');
114 | const signed = (process.argv[7] === 'true');
115 |
116 | let a = new BN(a_val, 16);
117 | let b = new BN(b_val, 16);
118 | if(signed){
119 | if(a_neg) a = a.mul(new BN(-1));
120 | if(b_neg) b = b.mul(new BN(-1));
121 | }
122 | let res = 0;
123 | if(a.gt(b)) res = 1;
124 | else if(a.lt(b)) res = -1;
125 | process.stdout.write(ethers.utils.defaultAbiCoder.encode(['int'], [res]));
126 | break;
127 | }
128 | case "modmul": {
129 | const a_val = process.argv[3].substring(2);
130 | const b_val = process.argv[4].substring(2);
131 | const n_val = process.argv[5].substring(2);
132 | const a_neg = (process.argv[6] === 'true');
133 | const b_neg = (process.argv[7] === 'true');
134 | let a = new BN(a_val, 16)
135 | let b = new BN(b_val, 16)
136 | let n = new BN(n_val, 16)
137 | if(a_neg) a = a.mul(new BN(-1));
138 | if(b_neg) b = b.mul(new BN(-1));
139 | let res = a.mul(b).umod(n)
140 | const neg = res.isNeg()
141 | if(neg) res = res.abs()
142 | process.stdout.write(ethers.utils.defaultAbiCoder.encode(['bool', 'bytes'], [neg, ethers.BigNumber.from(res.toString())]));
143 | break;
144 | }
145 | case "modexp": {
146 | const a_val = process.argv[3].substring(2);
147 | const e_val = process.argv[4].substring(2);
148 | const m_val = process.argv[5].substring(2);
149 | let a = new BN(a_val, 16)
150 | let e = new BN(e_val, 16)
151 | let m = new BN(m_val, 16)
152 | var reducedA = a.toRed(BN.red(m));
153 | var reducedRes = reducedA.redPow(e);
154 | var res = reducedRes.fromRed();
155 | const neg = res.isNeg()
156 | if(neg) res = res.abs()
157 | process.stdout.write(ethers.utils.defaultAbiCoder.encode(['bool', 'bytes'], [neg, ethers.BigNumber.from(res.toString())]));
158 | break;
159 | }
160 | case "iszero": {
161 | const a_val = process.argv[3];
162 | const a_neg = (process.argv[4] === 'true');
163 | let a = new BN(a_val, 16)
164 | if(a_neg) a = a.mul(new BN(-1));
165 | let res = a.isZero()
166 | process.stdout.write(ethers.utils.defaultAbiCoder.encode(['bool'], [ethers.BigNumber.from(res.toString())]));
167 | break;
168 | }
169 | }
170 |
--------------------------------------------------------------------------------
/test/differential/scripts/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "solidity-BigNumber-differential",
3 | "version": "1.0.0",
4 | "description": "Scripts to perform solidity bignumber testing",
5 | "main": "generate.js",
6 | "author": "",
7 | "license": "MIT",
8 | "devDependencies": {
9 | "bn.js": "^5.2.1",
10 | "ethereumjs-util": "^7.1.4",
11 | "rlp": "^3.0.0",
12 | "typescript": "^4.8.4",
13 | "ethers": "^5.7.1"
14 | },
15 | "scripts": {
16 | "compile": "npx tsc --esModuleInterop ./*.ts",
17 | "differential": "node differential.js"
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/test/differential/util/Strings.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.8.4;
2 |
3 | library Strings {
4 | bytes16 private constant _SYMBOLS = "0123456789abcdef";
5 |
6 | /**
7 | * @dev Return the log in base 10, rounded down, of a positive value.
8 | * Returns 0 if given 0.
9 | */
10 | function log10(uint256 value) internal pure returns (uint256) {
11 | uint256 result = 0;
12 | unchecked {
13 | if (value >= 10**64) {
14 | value /= 10**64;
15 | result += 64;
16 | }
17 | if (value >= 10**32) {
18 | value /= 10**32;
19 | result += 32;
20 | }
21 | if (value >= 10**16) {
22 | value /= 10**16;
23 | result += 16;
24 | }
25 | if (value >= 10**8) {
26 | value /= 10**8;
27 | result += 8;
28 | }
29 | if (value >= 10**4) {
30 | value /= 10**4;
31 | result += 4;
32 | }
33 | if (value >= 10**2) {
34 | value /= 10**2;
35 | result += 2;
36 | }
37 | if (value >= 10**1) {
38 | result += 1;
39 | }
40 | }
41 | return result;
42 | }
43 |
44 | /**
45 | * @dev Converts a `bool` to its ASCII `string` decimal representation.
46 | */
47 | function toString(bool value) internal pure returns (string memory) {
48 | return (value ? "true" : "false");
49 | }
50 |
51 | /**
52 | * @dev Converts a `uint256` to its ASCII `string` decimal representation.
53 | */
54 | function toString(uint256 value) internal pure returns (string memory) {
55 | unchecked {
56 | uint256 length = log10(value) + 1;
57 | string memory buffer = new string(length);
58 | uint256 ptr;
59 | /// @solidity memory-safe-assembly
60 | assembly {
61 | ptr := add(buffer, add(32, length))
62 | }
63 | while (true) {
64 | ptr--;
65 | /// @solidity memory-safe-assembly
66 | assembly {
67 | mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
68 | }
69 | value /= 10;
70 | if (value == 0) break;
71 | }
72 | return buffer;
73 | }
74 | }
75 |
76 | ///@dev converts bytes array to its ASCII hex string representation
77 | /// TODO: Definitely more efficient way to do this by processing multiple (16?) bytes at once
78 | /// but really a helper function for the tests, efficiency not key.
79 | function toHexString(bytes memory input) public pure returns (string memory) {
80 | require(input.length < type(uint256).max / 2 - 1);
81 | bytes16 symbols = "0123456789abcdef";
82 | bytes memory hex_buffer = new bytes(2 * input.length + 2);
83 | hex_buffer[0] = "0";
84 | hex_buffer[1] = "x";
85 |
86 | uint pos = 2;
87 | uint256 length = input.length;
88 | for (uint i = 0; i < length; ++i) {
89 | uint _byte = uint8(input[i]);
90 | hex_buffer[pos++] = symbols[_byte >> 4];
91 | hex_buffer[pos++] = symbols[_byte & 0xf];
92 | }
93 | return string(hex_buffer);
94 | }
95 | }
96 |
--------------------------------------------------------------------------------