├── .gas-snapshot
├── .github
└── workflows
│ └── ci.yaml
├── .gitignore
├── .gitmodules
├── .husky
├── .gitignore
└── pre-commit
├── .nvmrc
├── .prettierignore
├── .prettierrc.json
├── LICENSE
├── README.md
├── cli
└── cli.ts
├── foundry.toml
├── gaussian
├── package.json
├── src
├── Gaussian.sol
├── Invariant.sol
├── Units.sol
├── reference
│ ├── ReferenceGaussian.sol
│ └── ReferenceInvariant.sol
└── test
│ ├── Cdf.t.sol
│ ├── DifferentialTests.t.sol
│ ├── Erfc.t.sol
│ ├── Gaussian.t.sol
│ ├── HelperInvariant.sol
│ ├── Ierfc.t.sol
│ ├── Invariant.t.sol
│ ├── Pdf.t.sol
│ └── Ppf.t.sol
├── test
└── differential
│ └── scripts
│ ├── gaussian-extended.ts
│ ├── generate.ts
│ ├── generate_erfc.ts
│ ├── invariant.ts
│ ├── package.json
│ └── yarn.lock
├── tsconfig.json
└── yarn.lock
/.gas-snapshot:
--------------------------------------------------------------------------------
1 | TestExample:testReceive() (gas: 12157)
2 | TestRaw:testAbs() (gas: 2291)
3 | TestSMath:testAbs() (gas: 2357)
4 | TestSMath:testAbs02() (gas: 604)
5 | TestSMath:testRaw() (gas: 2401)
6 | TestSMath:testUnwrap() (gas: 626)
7 | TestTypes:test00():(bool) (gas: 760)
8 | TestTypes:test01():(bool) (gas: 210)
9 | TestTypes:testAddGas() (gas: 2726)
10 | TestTypes:testAddRawGas() (gas: 2445)
11 | TestTypes:testAddUncheckedGas() (gas: 2269)
12 | TestTypes:testLt() (gas: 142)
13 | TestTypes:testUnwrapGas() (gas: 2357)
14 | TestTypes:testWrapGas() (gas: 2115)
15 | TestTypes:testWrapUnwrapGas() (gas: 2137)
16 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yaml:
--------------------------------------------------------------------------------
1 | on: [push]
2 |
3 | name: test
4 |
5 | jobs:
6 | check:
7 | name: Foundry project
8 | runs-on: ubuntu-latest
9 | steps:
10 | - uses: actions/checkout@v3
11 | with:
12 | submodules: recursive
13 |
14 | - name: Install Foundry
15 | uses: foundry-rs/foundry-toolchain@v1
16 | with:
17 | version: nightly
18 |
19 | - name: Install deps
20 | run: yarn install
21 |
22 | - name: Build
23 | run: yarn build
24 |
25 | - name: Run tests
26 | run: forge test
27 | env:
28 | FOUNDRY_FUZZ_RUNS: 10000
29 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | docs
2 | node_modules
3 | .env
4 | coverage
5 | coverage.json
6 | typechain-types
7 | yarn-error.log
8 | dist/
9 |
10 | # Foundry
11 | cache
12 | out
13 | optimized-out
14 |
15 | .DS_Store
16 |
17 | # VScode
18 | .vscode
19 |
20 | # Differential testing
21 | test/differential/data
22 | test/differential/scripts/node_modules
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "lib/forge-std"]
2 | path = lib/forge-std
3 | url = https://github.com/foundry-rs/forge-std
4 | branch = v1.2.0
5 | [submodule "lib/solmate"]
6 | path = lib/solmate
7 | url = https://github.com/transmissions11/solmate
8 | branch = v7
9 |
--------------------------------------------------------------------------------
/.husky/.gitignore:
--------------------------------------------------------------------------------
1 | _
2 |
--------------------------------------------------------------------------------
/.husky/pre-commit:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | . "$(dirname "$0")/_/husky.sh"
3 |
4 | npx lint-staged
5 |
--------------------------------------------------------------------------------
/.nvmrc:
--------------------------------------------------------------------------------
1 | 16.11.0
--------------------------------------------------------------------------------
/.prettierignore:
--------------------------------------------------------------------------------
1 | cache
2 |
--------------------------------------------------------------------------------
/.prettierrc.json:
--------------------------------------------------------------------------------
1 | {
2 | "semi": false,
3 | "singleQuote": true,
4 | "printWidth": 120,
5 | "overrides": [
6 | {
7 | "files": "*.sol",
8 | "options": {
9 | "printWidth": 80,
10 | "tabWidth": 4,
11 | "useTabs": false,
12 | "singleQuote": false,
13 | "bracketSpacing": false,
14 | "explicitTypes": "always"
15 | }
16 | }
17 | ]
18 | }
19 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published by
637 | the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Beta
2 |
3 | > This library is in beta. It's not ready for production.
4 |
5 |  [](https://github.com/primitivefinance/solstat/actions/workflows/ci.yaml) [](https://discord.gg/primitive) [](https://twitter.com/primitivefi)
6 |
7 | # SolStat
8 |
9 | SolStat is a Math library written in solidity for statistical function approximations. The library is composed of two core libraries; Gaussian.sol, and Invariant.sol. We will go over each of these libraries and their testing suites. We at Primitive use these libraries to support development with RMM-01s unique trading function, which utilizes the cumulative distribution function (CDF) of the normal distribution denoted by the greek capital letter Phi($\Phi$) in the literature [1,2]. You may recognize the normal or Gaussian distribution as the bell curve. This distribution is significant in modeling real-valued random numbers of unknown distributions. Within the RMM-01 trading function and options pricing, the CDF is used to model random price movement of a Markov process. Since price paths are commonly modeled with markovian proccesses, we believe that the greater community will find value in this library.
10 |
11 | ## How to use
12 |
13 | Requirements: forge, node >=v16.0.0
14 |
15 | ```
16 | yarn install
17 | forge install
18 | yarn build
19 | forge test
20 | ```
21 |
22 | To compute values using the gaussian.js library, you can use this commmand in the cli:
23 |
24 | ```
25 | yarn cli --cdf {value}
26 | yarn cli --pdf {value}
27 | yarn cli --ppf {value}
28 | ```
29 |
30 | ## Irrational Functions
31 |
32 | The primary reason for utilizing these approximation algorithms is that computers have trouble expressing irrational functions. This is because irrational numbers have an infinite number of decimals. Some examples of irrational numbers are $\pi$ and $\sqrt(2)$. This only becomes a challenge when we try to compute these numbers. This is because computers don't have an infinite amount of memory. Thus mathematicians and computer scientists have developed a variety of approximation algorithms to achieve varying degrees of speed and accuracy when approximating these irrational functions. These algorithms are commonly iterative and achieve greater accuracy with more iterations.
33 |
34 | ## Computational Constraints
35 |
36 | In classical computing, our computational resources have become [abundant](https://en.wikipedia.org/wiki/Moore%27s_law), allowing us the liberty to iterate these algorithms to achieve our desired accuracy. However, the [Ethereum Virtual Machine (EVM)](https://ethereum.org/en/developers/docs/evm/) has a necessary monetary cost of computation. This computational environment has monetarily motivated developers to find efficient algorithms and hacks to reduce their applications' computational overhead (and thus the cost of computation).
37 |
38 | ## `Gaussian.sol`
39 |
40 | This contract implements a number of functions important to the gaussian distributions. Importantly all these implementations are only for a mean $\mu = 0$ and variance $\sigma = 1$. These implementations are based on the [Numerical Recipes](https://e-maxx.ru/bookz/files/numerical_recipes.pdf) textbook and its C implementation. [Numerical Recipes](https://e-maxx.ru/bookz/files/numerical_recipes.pdf) cites the original text by Abramowitz and Stegun, "[Handbook of Mathematical Functions](https://personal.math.ubc.ca/~cbm/aands/abramowitz_and_stegun.pdf)," which should be read to understand these unique functions and the implications of their numerical approximations. This implementation was also inspired by the [javascript Gausian library](https://github.com/errcw/gaussian), which implements the same algorithm.
41 |
42 | ### Cumulative Distribution Function
43 |
44 | The implementation of the CDF aproximation algorithm takes in a random variable $x$ as a single parameter. The function depends on a special helper functions known as the error function `erf`. The error function’s identity is `erfc(-x) = 2 - erfc(x)` and has a small collection of unique properties:
45 |
46 | erfc(-infinity) = 2
47 |
48 | erfc(0) = 1
49 |
50 | erfc(infinity) = 0
51 |
52 | The reference implementation for the error function is on p221 of Numerical Recipes in section C 2e. A helpful resource is this [wolfram notebook](https://mathworld.wolfram.com/Erfc.html).
53 |
54 | ### Probability Density Function
55 |
56 | The library also supports an approximation of the Probability Density Function(PPF) which is mathematically interpeted as $Z(x) = \frac{1}{\sigma\sqrt{2\pi}}e^{\frac{-(x - \mu)^2}{2\sigma^2}}$. This implementation has a maximum error bound of of $1.2e-7$ and can be refrenced in this [wofram notebook](https://mathworld.wolfram.com/ProbabilityDensityFunction.html).
57 |
58 | ### Percent Point Function / Quantile Function
59 |
60 | Furthermore we implemented aproximation algorithms for the Percent Point Function(PPF) sometimes known as the inverse CDF or the quantile function. The function is mathmatically defined as $D(x) = \mu - \sigma\sqrt{2}(ierfc(2x))$, has a maximum error of `1.2e-7`, and depends on the inverse error function `ierf` which satisfies `ierfc(erfc(x)) = erfc(ierfc(x))`. The invers error function, defined as `ierfc(1 - x) = ierf(x)`, has a domain of in the interval $0 < x < 2$ and has some unique properties:
61 |
62 | ierfc(0) = infinity
63 |
64 | ierfc(1) = 0
65 |
66 | ierfc(2) = - infinity
67 |
68 | ## `Invariant.sol`
69 |
70 | `Invariant.sol` is a contract used to compute the invariant of the RMM-01 trading function such that we compute $y$ in $y = K\Phi(\Phi^{⁻¹}(1-x) - \sigma\sqrt(\tau)) + k$. Notice how we need to compute the normal CDF of a quantity. For a more detailed perspective on the trading function, please see the whitepaper. This is an example of how we have used this library for our research, development, and testing of RMM-01. The function reverts if $x$ is greater than one and simplifies to $K(1+x) + k$ when $\tau$ is zero (at expiry). The function takes in five parameters
71 | `R_x`: The reserves of token $x$ per unit of liquidity, always within the bounds of $[0,1]$.
72 | `stk`: The strike price of the pool.
73 | `vol`: the implied volatility of the pool denoted by the lowercase greek letter sigma in finance literature.
74 | `tau`: The time until the pool expires. Once expired, there can be no swaps.
75 | `inv`: The current invariant given `R_x`.
76 | The function then returns the quantity of token y per unit of liquidity denoted `R_y`, which is always within the bounds of $[0, stk]$. This is a clear example of how one would use this library.
77 |
78 | ## Differential Testing with Foundry
79 |
80 | We leveraged foundry's support of differential testing for this library. Differential testing is a popular technique that seeds inputs to different implementations of the same application and detects differences in their execution. Differential testing is an excellent complement to traditional software testing as it is well suited to detect semantic errors. This library used differential testing against the javascript gaussian library to detect anomalies and varying bugs. This helped us to be confident in the performance and implementation of the library.
81 |
82 | [1]: [Replicating Market Makers](https://arxiv.org/pdf/2103.14769.pdf)
83 |
84 | [2]: [Replicating Portfolios: Contstructing Permissionless Derivatives](https://arxiv.org/pdf/2205.09890.pdf)
85 |
--------------------------------------------------------------------------------
/cli/cli.ts:
--------------------------------------------------------------------------------
1 | import gaussian from 'gaussian'
2 |
3 | var erfc = function (x) {
4 | var z = Math.abs(x)
5 | var t = 1 / (1 + z / 2)
6 | var r =
7 | t *
8 | Math.exp(
9 | -z * z -
10 | 1.26551223 +
11 | t *
12 | (1.00002368 +
13 | t *
14 | (0.37409196 +
15 | t *
16 | (0.09678418 +
17 | t *
18 | (-0.18628806 +
19 | t * (0.27886807 + t * (-1.13520398 + t * (1.48851587 + t * (-0.82215223 + t * 0.17087277))))))))
20 | )
21 | return x >= 0 ? r : 2 - r
22 | }
23 |
24 | var ierfc = function (x) {
25 | if (x >= 2) {
26 | return -100
27 | }
28 | if (x <= 0) {
29 | return 100
30 | }
31 |
32 | var xx = x < 1 ? x : 2 - x
33 | var t = Math.sqrt(-2 * Math.log(xx / 2))
34 |
35 | var r = -0.70711 * ((2.30753 + t * 0.27061) / (1 + t * (0.99229 + t * 0.04481)) - t)
36 |
37 | for (var j = 0; j < 2; j++) {
38 | var err = erfc(r) - xx
39 | r += err / (1.12837916709551257 * Math.exp(-(r * r)) - r * err)
40 | }
41 |
42 | return x < 1 ? r : -r
43 | }
44 |
45 | const cdf = (x) => {
46 | return gaussian(0, 1).cdf(x)
47 | }
48 |
49 | const ppf = (x) => {
50 | return gaussian(0, 1).ppf(x)
51 | }
52 |
53 | const pdf = (x) => {
54 | return gaussian(0, 1).pdf(x)
55 | }
56 |
57 | async function main() {
58 | const args = process.argv
59 | const [, , flag, value] = args
60 |
61 | if (value) {
62 | if (flag && flag === '--cdf') {
63 | console.log(`cdf: ${cdf(value)}`)
64 | } else if (flag && flag === '--ppf') {
65 | console.log(`ppf: ${ppf(value)}`)
66 | } else if (flag && flag === '--pdf') {
67 | console.log(`pdf: ${pdf(value)}`)
68 | } else if (flag && flag === '--erfc') {
69 | console.log(`erfc: ${erfc(value)}`)
70 | } else if (flag && flag === '--ierfc') {
71 | console.log(`ierfc: ${ierfc(value)}`)
72 | } else {
73 | console.log(`Unknown operation: ${flag}`)
74 | }
75 | } else {
76 | console.log('No value supplied...')
77 | }
78 | }
79 |
80 | main().catch((err) => {
81 | console.error(err)
82 | process.exit(1)
83 | })
84 |
--------------------------------------------------------------------------------
/foundry.toml:
--------------------------------------------------------------------------------
1 | [profile.default]
2 | solc = "0.8.13"
3 | via_ir = true
4 | optimizer_runs = 15000
5 | ffi = true # important!
6 | remappings = [
7 | 'solmate/=lib/solmate/src/'
8 | ]
9 |
10 | [profile.test]
11 | via_ir = false
12 |
13 | [fuzz]
14 | runs = 100000
15 | max_test_rejects = 4000000
16 |
--------------------------------------------------------------------------------
/gaussian:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/primitivefinance/solstat/80c603f8d1b2f527a98c08e7efc02ba9d8629f2d/gaussian
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "solstat",
3 | "license": "AGPL-3.0-only",
4 | "version": "1.0.0-beta",
5 | "description": "Solidity library for statistical function approximations.",
6 | "files": [
7 | "src/**/*.sol"
8 | ],
9 | "scripts": {
10 | "cli": "npx ts-node ./cli/cli.ts",
11 | "build": "yarn generate",
12 | "lint": "prettier --write **.sol && prettier --write **.ts",
13 | "prepare": "husky install",
14 | "generate": "cd ./test/differential/scripts/ && npm run generate"
15 | },
16 | "repository": {
17 | "type": "git",
18 | "url": "git+https://github.com/primitivefinance/solstat.git"
19 | },
20 | "keywords": [
21 | "hardhat",
22 | "solidity",
23 | "primitive",
24 | "foundry"
25 | ],
26 | "devDependencies": {
27 | "@types/node": "^17.0.24",
28 | "dotenv": "^16.0.0",
29 | "ethers": "^5.6.4",
30 | "gaussian": "^1.2.0",
31 | "husky": ">=6",
32 | "lint-staged": ">=10",
33 | "prettier": "2.6.2",
34 | "prettier-plugin-solidity": "^1.0.0-beta.19",
35 | "ts-node": "^10.7.0",
36 | "typescript": "^4.6.3"
37 | },
38 | "engines": {
39 | "node": ">=16.0.0"
40 | },
41 | "lint-staged": {
42 | "*.ts": "prettier --write"
43 | },
44 | "publishConfig": {
45 | "access": "public"
46 | },
47 | "resolutions": {
48 | "async": ">=2.6.4",
49 | "cross-fetch": ">=3.1.5",
50 | "lodash": ">=4.17.21",
51 | "node-fetch": ">=2.6.7",
52 | "underscore": ">=1.12.1",
53 | "yargs-parser": ">=5.0.1"
54 | },
55 | "dependencies": {
56 | "evm-bn": "^1.1.2"
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/src/Gaussian.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.4;
3 |
4 | import "solmate/utils/FixedPointMathLib.sol";
5 | import "./Units.sol";
6 |
7 | /**
8 | * @title Gaussian Math Library.
9 | * @author @alexangelj
10 | * @custom:coauthor @0xjepsen
11 | * @custom:coauthor @autoparallel
12 | *
13 | * @notice Models the normal distribution using the special Complimentary Error Function.
14 | *
15 | * @dev Only implements a distribution with mean (µ) = 0 and variance (σ) = 1.
16 | * Uses Numerical Recipes as a framework and reference C implemenation.
17 | * Numerical Recipes cites the original textbook written by Abramowitz and Stegun,
18 | * "Handbook of Mathematical Functions", which should be read to understand these
19 | * special functions and the implications of their numerical approximations.
20 | *
21 | * @custom:source Handbook of Mathematical Functions https://personal.math.ubc.ca/~cbm/aands/abramowitz_and_stegun.pdf.
22 | * @custom:source Numerical Recipes https://e-maxx.ru/bookz/files/numerical_recipes.pdf.
23 | * @custom:source Inspired by https://github.com/errcw/gaussian.
24 | */
25 | library Gaussian {
26 | using {abs, diviWad} for int256;
27 | using FixedPointMathLib for int256;
28 | using FixedPointMathLib for uint256;
29 |
30 | error Infinity();
31 | error NegativeInfinity();
32 | error OutOfBounds();
33 |
34 | uint256 internal constant WAD = 1 ether;
35 | uint256 internal constant HALF_WAD = 0.5 ether;
36 | uint256 internal constant DOUBLE_WAD = 2 ether;
37 | uint256 internal constant PI = 3_141592653589793238;
38 | int256 internal constant ERFC_DOMAIN_UPPER = int256(6.24 ether);
39 | int256 internal constant ERFC_DOMAIN_LOWER = -ERFC_DOMAIN_UPPER;
40 | int256 internal constant SQRT_2PI = 2_506628274631000502;
41 | int256 internal constant SIGN = -1;
42 | int256 internal constant SCALAR = 1 ether;
43 | int256 internal constant HALF_SCALAR = 1e9;
44 | int256 internal constant SCALAR_SQRD = 1e36;
45 | int256 internal constant HALF = 5e17;
46 | int256 internal constant ONE = 1 ether;
47 | int256 internal constant TWO = 2 ether;
48 | int256 internal constant NEGATIVE_TWO = -2e18;
49 | int256 internal constant SQRT2 = 1_414213562373095048; // √2 with 18 decimals of precision.
50 | int256 internal constant ERFC_A = 1_265512230000000000;
51 | int256 internal constant ERFC_B = 1_000023680000000000;
52 | int256 internal constant ERFC_C = 374091960000000000; // 1e-1
53 | int256 internal constant ERFC_D = 96784180000000000; // 1e-2
54 | int256 internal constant ERFC_E = -186288060000000000; // 1e-1
55 | int256 internal constant ERFC_F = 278868070000000000; // 1e-1
56 | int256 internal constant ERFC_G = -1_135203980000000000;
57 | int256 internal constant ERFC_H = 1_488515870000000000;
58 | int256 internal constant ERFC_I = -822152230000000000; // 1e-1
59 | int256 internal constant ERFC_J = 170872770000000000; // 1e-1
60 | int256 internal constant IERFC_A = -707110000000000000; // 1e-1
61 | int256 internal constant IERFC_B = 2_307530000000000000;
62 | int256 internal constant IERFC_C = 270610000000000000; // 1e-1
63 | int256 internal constant IERFC_D = 992290000000000000; // 1e-1
64 | int256 internal constant IERFC_E = 44810000000000000; // 1e-2
65 | int256 internal constant IERFC_F = 1_128379167095512570;
66 |
67 | /**
68 | * @notice Approximation of the Complimentary Error Function.
69 | * Related to the Error Function: `erfc(x) = 1 - erf(x)`.
70 | * Both cumulative distribution and error functions are integrals
71 | * which cannot be expressed in elementary terms. They are called special functions.
72 | * The error and complimentary error functions have numerical approximations
73 | * which is what is used in this library to compute the cumulative distribution function.
74 | *
75 | * @dev This is a special function with its own identities.
76 | * As `input` approaches ∞ or -∞, `output` returns 0 or 2 wad respectively.
77 | * Once `input` is ~6.24 wad, it returns these values because of only having 15 decimals of precision.
78 | * Identity: `erfc(-x) = 2 - erfc(x)`.
79 | * Special Values:
80 | * erfc(-∞) = 2
81 | * erfc(0) = 1
82 | * erfc(∞) = 0
83 | *
84 | * @custom:epsilon Fractional error less than 1.2e-7.
85 | * @custom:error Maximum error of 1e-15 compared to Gaussian.js library.
86 | * @custom:source Numerical Recipes in C 2e p221.
87 | * @custom:source https://mathworld.wolfram.com/Erfc.html.
88 | */
89 | function erfc(int256 input) internal pure returns (int256 output) {
90 | if (input == 0) return ONE;
91 | if (input >= ERFC_DOMAIN_UPPER) return 0;
92 | if (input <= ERFC_DOMAIN_LOWER) return TWO;
93 |
94 | uint256 z = input.abs(); // |z|
95 | int256 t = diviWad(ONE, (ONE + int256(z.divWadDown(DOUBLE_WAD)))); // 1 / (1 + z / 2)
96 |
97 | int256 k;
98 | int256 step;
99 |
100 | {
101 | // Avoids stack too deep.
102 | int256 _t = t;
103 |
104 | step =
105 | (ERFC_F + muliWad(_t, (ERFC_G + muliWad(_t, (ERFC_H + muliWad(_t, (ERFC_I + muliWad(_t, ERFC_J))))))));
106 | }
107 |
108 | {
109 | int256 _t = t;
110 | step = muliWad(
111 | _t, (ERFC_B + muliWad(_t, (ERFC_C + muliWad(_t, (ERFC_D + muliWad(_t, (ERFC_E + muliWad(_t, step))))))))
112 | );
113 |
114 | k = (int256(-1) * muliWad(int256(z), int256(z)) - ERFC_A) + step;
115 | }
116 |
117 | int256 exp = k.expWad();
118 | int256 r = muliWad(t, exp);
119 | output = (input < 0) ? TWO - r : r;
120 | }
121 |
122 | /**
123 | * @notice Approximation of the Inverse Complimentary Error Function - erfc^(-1).
124 | *
125 | * @dev Equal to `ierfc(erfc(x)) = erfc(ierfc(x))` for 0 < x < 2.
126 | * Related to the Inverse Error Function: `ierfc(1 - x) = ierf(x)`.
127 | * This is a special function with its own identities.
128 | * Domain: 0 < x < 2
129 | * Special values:
130 | * ierfc(0) = ∞
131 | * ierfc(1) = 0
132 | * ierfc(2) = -∞
133 | *
134 | * @custom:error Maximum error of 1e-15 compared to Gaussian.js library.
135 | * @custom:source Numerical Recipes 3e p265.
136 | * @custom:source https://mathworld.wolfram.com/InverseErfc.html.
137 | */
138 | function ierfc(int256 x) internal pure returns (int256 z) {
139 | if (x < 0 || x > 2 ether) revert OutOfBounds();
140 | if (x == 0) revert Infinity();
141 | if (x == 2 ether) revert NegativeInfinity();
142 | if (z != 0) return z;
143 |
144 | int256 xx = (x < ONE) ? x : TWO - x;
145 | int256 logInput = xx.diviWad(TWO);
146 | if (logInput == 0) revert Infinity();
147 | int256 ln = logInput.lnWad(); // ln( xx / 2)
148 | int256 t = int256(uint256(muliWad(-TWO, ln)).sqrt()) * HALF_SCALAR;
149 |
150 | int256 r;
151 | {
152 | int256 numerator = (IERFC_B + muliWad(t, IERFC_C));
153 | int256 denominator = (ONE + muliWad(t, (IERFC_D + muliWad(t, IERFC_E))));
154 | r = muliWad(IERFC_A, diviWad(numerator, denominator) - t);
155 | }
156 |
157 | uint256 i;
158 | while (i < 2) {
159 | int256 err = erfc(r) - xx;
160 | int256 input = -(muliWad(r, r)); // -(r * r)
161 | int256 expWad = input.expWad();
162 | int256 denom = muliWad(IERFC_F, expWad) - muliWad(r, err);
163 | r = r + diviWad(err, denom);
164 | unchecked {
165 | ++i;
166 | }
167 | }
168 |
169 | z = x < ONE ? r : -r;
170 | }
171 |
172 | /**
173 | * @notice Approximation of the Cumulative Distribution Function.
174 | *
175 | * @dev Equal to `D(x) = 0.5[ 1 + erf((x - µ) / σ√2)]`.
176 | * Only computes cdf of a distribution with µ = 0 and σ = 1.
177 | *
178 | * @custom:rounding Rounds down via truncation from division.
179 | * @custom:error Maximum error of 1.2e-7 compared to theoretical cdf.
180 | * @custom:error Maximum error of 1e-15 compared to Gaussian.js library.
181 | * @custom:source https://mathworld.wolfram.com/NormalDistribution.html.
182 | */
183 | function cdf(int256 x) internal pure returns (int256 z) {
184 | int256 input = (x * ONE) / SQRT2;
185 | int256 negated = -input;
186 | int256 _erfc = erfc(negated);
187 | z = (_erfc * ONE) / TWO;
188 | }
189 |
190 | /**
191 | * @notice Approximation of the Probability Density Function.
192 | *
193 | * @dev Equal to `Z(x) = (1 / σ√2π)e^( (-(x - µ)^2) / 2σ^2 )`.
194 | * Only computes pdf of a distribution with µ = 0 and σ = 1.
195 | *
196 | * @custom:rounding Rounds down via truncation from division.
197 | * @custom:error Maximum error of 1.2e-7 compared to theoretical pdf.
198 | * @custom:error Maximum error of 1e-15 compared to Gaussian.js library.
199 | * @custom:source https://mathworld.wolfram.com/ProbabilityDensityFunction.html.
200 | */
201 | function pdf(int256 x) internal pure returns (int256 z) {
202 | int256 e = (-x * x) / TWO;
203 | e = e.expWad();
204 | z = (e * ONE) / SQRT_2PI;
205 | }
206 |
207 | /**
208 | * @notice Approximation of the Percent Point Function.
209 | *
210 | * @dev Equal to `D(x)^(-1) = µ - σ√2(ierfc(2x))`.
211 | * Only computes ppf of a distribution with µ = 0 and σ = 1.
212 | *
213 | * @custom:error Maximum error of 1.2e-7 compared to theoretical ierfc.
214 | * @custom:error Maximum error of 1e-14 in differential tests vs. javscript implementation.
215 | * This error is for inputs near the upper bound >= 0.99 wad.
216 | * JS uses 64bit floats naturally. 12 bits are assigned to the sign and exponent.
217 | * This leaves 52bit to represent the decimal.
218 | * Taking log_10(2^52) gives roughly 15.65.
219 | * This means that we can really only get 15 digits of accuracy from JS itself.
220 | * The error is in this conversion from fixed point to floating point.
221 | * @custom:source https://mathworld.wolfram.com/NormalDistribution.html.
222 | */
223 | function ppf(int256 x) internal pure returns (int256 z) {
224 | if (x == int256(HALF_WAD)) return int256(0);
225 | if (x >= ONE) revert Infinity();
226 | if (x == 0) revert NegativeInfinity();
227 | int256 double = x * 2;
228 | int256 _ierfc = ierfc(double);
229 | int256 res = muliWad(SQRT2, _ierfc);
230 | z = -res;
231 | }
232 | }
233 |
--------------------------------------------------------------------------------
/src/Invariant.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.4;
3 |
4 | import "./Gaussian.sol";
5 |
6 | /**
7 | * @title Invariant of Primitive RMM.
8 | * @author @alexangelj
9 | * @notice Invariant is `k` with the trading function `k = y - KΦ(Φ⁻¹(1-x) - σ√τ)`.
10 | *
11 | * @dev Terms which can potentially be ambiguous are given discrete names.
12 | * This makes it easier to search for terms and update terms.
13 | * Variables can sometimes not be trusted to be or act like their names.
14 | * This naming scheme avoids this problem using a glossary to define them.
15 | *
16 | * // -------------------- Glossary --------------------- //
17 | *
18 | * `R_x` - Amount of asset token reserves per single unit of liquidity.
19 | * `R_y` - Amount of quote token reserves per single unit of liquidity.
20 | * `stk` - Strike price of the pool. The terminal price of each asset token.
21 | * `vol` - Implied volatility of the pool. Higher vol = higher price impact on swaps.
22 | * `tau` - Time until the pool expires. Amount of seconds until the pool's curve becomes flat around `stk`.
23 | * `inv` - Invariant of the pool. Difference between theoretical $ value and actual $ value per liquidity.
24 | *
25 | * `WAD` - Signed or unsigned fixed point number with up to 18 decimals and up to 256 total bits wide.
26 | * `YEAR`- Equal to the amount of seconds in a year. Used in `invariant` function.
27 | *
28 | * // -------------------- Units ------------------------ //
29 | *
30 | * `R_x` - Units are unsigned WAD. Represents value of tokens, decimals matter.
31 | * `R_y` - Units are unsigned WAD. Represents value of tokens, decimals matter.
32 | * `stk` - Units are unsigned WAD. Represents value of tokens, decimals matter.
33 | * `vol` - Units are unsigned WAD. Represents a percentage in which 100% = WAD.
34 | * `tau` - Units are YEAR. Represents a time unit which `1.0` is equal to YEAR.
35 | * `inv` - Units are signed WAD. Initial value of zero and decreases over time.
36 | *
37 | * // -------------------- Denoted By ----------------- //
38 | *
39 | * `R_x` - Denoted by `x`.
40 | * `R_y` - Denoted by `y`.
41 | * `stk` - Denoted by `K`.
42 | * `vol` - Denoted by `σ`.
43 | * `tau` - Denoted by `τ`.
44 | * `inv` - Denoted by `k`.
45 | *
46 | * // -------------------- Error Bounds ----------------- //
47 | *
48 | * `inv` - Up to 1e-9.
49 | *
50 | * // ------------------------ ~ ------------------------ //
51 | */
52 | library Invariant {
53 | using Gaussian for int256;
54 | using FixedPointMathLib for uint256;
55 |
56 | uint256 internal constant WAD = 1 ether;
57 | int256 internal constant ONE = 1 ether;
58 | int256 internal constant YEAR = 31556952;
59 | int256 internal constant HALF_SCALAR = 1e9;
60 |
61 | /**
62 | * @dev Reverts when an input value is out of bounds of its acceptable range.
63 | */
64 | error OOB();
65 |
66 | /**
67 | * @notice Uses reserves `R_x` to compute reserves `R_y`.
68 | *
69 | * @dev Computes `y` in `y = KΦ(Φ⁻¹(1-x) - σ√τ) + k`.
70 | * Primary function use to compute the invariant.
71 | * Simplifies to `K(1 -x) + k` when time to expiry is zero.
72 | * Reverts if `R_x` is greater than one. Units are a fixed point number with 18 decimals.
73 | *
74 | * We handle some special cases, try this:
75 | * `normalcd(normalicd(1) - 0.1)` in https://keisan.casio.com/calculator
76 | * Gaussian.sol reverts for `ppf(1)` and `ppf(0)`, so we handle those cases.
77 | *
78 | * @param R_x Quantity of token reserve `x` within the bounds of [0, 1].
79 | * @param stk Strike price of the pool. Terminal price of asset `x` in the pool denominated in asset `y`.
80 | * @param vol Implied volatility of the pool. Higher implied volatility = higher price impact on swaps.
81 | * @param tau Time until the pool expires. Once expired, no swaps can happen. Scaled to units of `Invariant.YEAR`.
82 | * @param inv Current invariant given the actual `R_x`. Zero if computing invariant itself.
83 | * @return R_y Quantity of token reserve `y` within the bounds of [0, stk].
84 | *
85 | * @custom:error Technically, none. This is the source of truth for the trading function.
86 | * @custom:source https://primitive.xyz/whitepaper
87 | */
88 | function getY(uint256 R_x, uint256 stk, uint256 vol, uint256 tau, int256 inv) internal pure returns (uint256 R_y) {
89 | if (R_x > WAD) revert OOB(); // Negative input for `ppf` is invalid.
90 | if (R_x == WAD) return uint256(inv); // For `ppf(0)` case, because 1 - 1 == 0, cdf(ppf(0)) == 0, and `y = K * 0 + k` simplifies to `y = k`.
91 | if (R_x == 0) return uint256(int256(stk) + inv); // For `ppf(1)` case, because 1 - 0 == 1, cdf(ppf(1)) == 1, and `y = K * 1 + k` simplifies to `y = K + k`.
92 | if (tau != 0) {
93 | // short circuit
94 | uint256 sec = tau.divWadDown(uint256(YEAR));
95 | uint256 sdr = sec.sqrt();
96 | sdr = sdr * uint256(HALF_SCALAR);
97 | sdr = vol.mulWadDown(sdr);
98 |
99 | int256 phi = ONE - int256(R_x);
100 | phi = phi.ppf();
101 |
102 | int256 input = phi - int256(sdr);
103 | input = input.cdf();
104 |
105 | R_y = uint256(muliWad(int256(stk), input) + inv);
106 | } else {
107 | R_y = uint256(muliWad(int256(stk), ONE - int256(R_x)) + inv);
108 | }
109 | }
110 |
111 | /**
112 | * @notice Uses reserves `R_y` to compute reserves `R_x`.
113 | *
114 | * @dev Computes `x` in `x = 1 - Φ(Φ⁻¹( (y + k) / K ) + σ√τ)`.
115 | * Not used in invariant function. Used for computing swap outputs.
116 | * Simplifies to `1 - ( (y + k) / K )` when time to expiry is zero.
117 | * Reverts if `R_y` is greater than one. Units are WAD.
118 | *
119 | * Dangerous! There are important bounds to using this function.
120 | *
121 | * @param R_y Quantity of token reserve `y` within the bounds of [0, stk].
122 | * @param stk Strike price of the pool. Terminal price of asset `x` in the pool denominated in asset `y`.
123 | * @param vol Implied volatility of the pool. Higher implied volatility = higher price impact on swaps.
124 | * @param tau Time until the pool expires. Once expired, no swaps can happen. Scaled to units of `Invariant.YEAR`.
125 | * @param inv Current invariant given the actual reserves `R_y`.
126 | * @return R_x Quantity of token reserve `x` within the bounds of [0, 1].
127 | *
128 | * @custom:error Up to 1e-6. This an **approximated** "inverse" of the `getY` function.
129 | * @custom:source https://primitive.xyz/whitepaper
130 | */
131 | function getX(uint256 R_y, uint256 stk, uint256 vol, uint256 tau, int256 inv) internal pure returns (uint256 R_x) {
132 | // Short circuits because tau != 0 is more likely.
133 | if (tau != 0) {
134 | uint256 sec = tau.divWadDown(uint256(YEAR));
135 |
136 | uint256 sdr = sec.sqrt();
137 | sdr = sdr * uint256(HALF_SCALAR);
138 | sdr = vol.mulWadDown(sdr);
139 |
140 | int256 phi = diviWad(int256(R_y) + inv, int256(stk));
141 |
142 | if (phi < 0) revert OOB(); // Negative input for `ppf` is invalid.
143 | if (phi > ONE) revert OOB();
144 | if (phi == ONE) return 0; // `x = 1 - Φ(Φ⁻¹( 1 ) + σ√τ)` simplifies to `x = 0`.
145 | if (phi == 0) return WAD; // `x = 1 - Φ(Φ⁻¹( 0 ) + σ√τ)` simplifies to `x = 1`.
146 |
147 | phi = phi.ppf();
148 |
149 | int256 input = phi + int256(sdr);
150 | input = input.cdf();
151 | R_x = uint256(ONE - input);
152 | } else {
153 | int256 numerator = int256(R_y) + inv;
154 | int256 denominator = int256(stk);
155 | R_x = uint256(ONE - diviWad(numerator, denominator));
156 | }
157 | }
158 |
159 | /**
160 | * @notice Computes the invariant of the RMM trading function.
161 | *
162 | * @dev Computes `k` in `k = y - KΦ(Φ⁻¹(1-x) - σ√τ)`.
163 | * Used to validate swaps, the most critical function.
164 | *
165 | * @custom:source https://rmm.eth.xyz
166 | */
167 | function invariant(uint256 R_y, uint256 R_x, uint256 stk, uint256 vol, uint256 tau)
168 | internal
169 | pure
170 | returns (int256 inv)
171 | {
172 | uint256 y = getY(R_x, stk, vol, tau, inv); // `inv` is 0 because we are solving `inv`, aka `k`.
173 | assembly {
174 | inv := sub(R_y, y)
175 | }
176 | }
177 | }
178 |
--------------------------------------------------------------------------------
/src/Units.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.4;
3 |
4 | error Min();
5 |
6 | function abs(int256 input) pure returns (uint256 output) {
7 | if (input == type(int256).min) revert Min();
8 | if (input < 0) {
9 | assembly {
10 | output := add(not(input), 1)
11 | }
12 | } else {
13 | assembly {
14 | output := input
15 | }
16 | }
17 | }
18 |
19 | /// @dev From solmate@v7, changes last `div` to `sdiv`.
20 | function muli(
21 | int256 x,
22 | int256 y,
23 | int256 denominator
24 | ) pure returns (int256 z) {
25 | assembly {
26 | // Store x * y in z for now.
27 | z := mul(x, y)
28 |
29 | // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
30 | if iszero(
31 | and(iszero(iszero(denominator)), or(iszero(x), eq(sdiv(z, x), y)))
32 | ) {
33 | revert(0, 0)
34 | }
35 |
36 | // Divide z by the denominator.
37 | z := sdiv(z, denominator)
38 | }
39 | }
40 |
41 | function muliWad(int256 x, int256 y) pure returns (int256 z) {
42 | z = muli(x, y, 1 ether);
43 | }
44 |
45 | function diviWad(int256 x, int256 y) pure returns (int256 z) {
46 | z = muli(x, 1 ether, y);
47 | }
48 |
--------------------------------------------------------------------------------
/src/reference/ReferenceGaussian.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.4;
3 |
4 | import "solmate/utils/FixedPointMathLib.sol";
5 | import "../Units.sol";
6 |
7 | /**
8 | * @title Gaussian Math Library.
9 | * @author @alexangelj
10 | *
11 | * @notice Models the normal distribution using the special Complimentary Error Function.
12 | *
13 | * @dev Only implements a distribution with mean (µ) = 0 and variance (σ) = 1.
14 | * Uses Numerical Recipes as a framework and reference C implemenation.
15 | * Numerical Recipes cites the original textbook written by Abramowitz and Stegun,
16 | * "Handbook of Mathematical Functions", which should be read to understand these
17 | * special functions and the implications of their numerical approximations.
18 | *
19 | * @custom:source Handbook of Mathematical Functions https://personal.math.ubc.ca/~cbm/aands/abramowitz_and_stegun.pdf.
20 | * @custom:source Numerical Recipes https://e-maxx.ru/bookz/files/numerical_recipes.pdf.
21 | * @custom:source Inspired by https://github.com/errcw/gaussian.
22 | */
23 | library Gaussian {
24 | using FixedPointMathLib for int256;
25 | using FixedPointMathLib for uint256;
26 |
27 | error Infinity();
28 | error NegativeInfinity();
29 | error Overflow();
30 | error OutOfBounds();
31 |
32 | uint256 internal constant HALF_WAD = 0.5 ether;
33 | uint256 internal constant PI = 3_141592653589793238;
34 | int256 internal constant SQRT_2PI = 2_506628274631000502;
35 | int256 internal constant SIGN = -1;
36 | int256 internal constant SCALAR = 1e18;
37 | int256 internal constant HALF_SCALAR = 1e9;
38 | int256 internal constant SCALAR_SQRD = 1e36;
39 | int256 internal constant HALF = 5e17;
40 | int256 internal constant ONE = 1e18;
41 | int256 internal constant TWO = 2e18;
42 | int256 internal constant NEGATIVE_TWO = -2e18;
43 | int256 internal constant SQRT2 = 1_414213562373095048; // √2 with 18 decimals of precision.
44 | int256 internal constant ERFC_A = 1_265512230000000000;
45 | int256 internal constant ERFC_B = 1_000023680000000000;
46 | int256 internal constant ERFC_C = 374091960000000000; // 1e-1
47 | int256 internal constant ERFC_D = 96784180000000000; // 1e-2
48 | int256 internal constant ERFC_E = -186288060000000000; // 1e-1
49 | int256 internal constant ERFC_F = 278868070000000000; // 1e-1
50 | int256 internal constant ERFC_G = -1_135203980000000000;
51 | int256 internal constant ERFC_H = 1_488515870000000000;
52 | int256 internal constant ERFC_I = -822152230000000000; // 1e-1
53 | int256 internal constant ERFC_J = 170872770000000000; // 1e-1
54 | int256 internal constant IERFC_A = -707110000000000000; // 1e-1
55 | int256 internal constant IERFC_B = 2_307530000000000000;
56 | int256 internal constant IERFC_C = 270610000000000000; // 1e-1
57 | int256 internal constant IERFC_D = 992290000000000000; // 1e-1
58 | int256 internal constant IERFC_E = 44810000000000000; // 1e-2
59 | int256 internal constant IERFC_F = 1_128379167095512570;
60 |
61 | /**
62 | * @notice Approximation of the Complimentary Error Function.
63 | * Related to the Error Function: `erfc(x) = 1 - erf(x)`.
64 | * Both cumulative distribution and error functions are integrals
65 | * which cannot be expressed in elementary terms. They are called special functions.
66 | * The error and complimentary error functions have numerical approximations
67 | * which is what is used in this library to compute the cumulative distribution function.
68 | *
69 | * @dev This is a special function with its own identities.
70 | * Identity: `erfc(-x) = 2 - erfc(x)`.
71 | * Special Values:
72 | * erfc(-infinity) = 2
73 | * erfc(0) = 1
74 | * erfc(infinity) = 0
75 | *
76 | * @custom:epsilon Fractional error less than 1.2e-7.
77 | * @custom:source Numerical Recipes in C 2e p221.
78 | * @custom:source https://mathworld.wolfram.com/Erfc.html.
79 | */
80 | function erfc(int256 input) internal pure returns (int256 output) {
81 | if (input == 0) {
82 | return 1 ether;
83 | }
84 |
85 | uint256 z = abs(input);
86 | int256 t;
87 | int256 step;
88 | int256 k;
89 |
90 | assembly {
91 | let quo := sdiv(mul(z, ONE), TWO) // 1 / (1 + z / 2).
92 | let den := add(ONE, quo)
93 | t := sdiv(SCALAR_SQRD, den)
94 |
95 | function muli(pxn, pxd) -> res {
96 | res := mul(pxn, pxd)
97 |
98 | if iszero(eq(sdiv(res, pxn), pxd)) {
99 | mstore(0, 0x35278d1200000000000000000000000000000000000000000000000000000000)
100 | revert(0, 4)
101 | }
102 |
103 | res := sdiv(res, ONE)
104 | }
105 |
106 | {
107 | step := add(
108 | ERFC_F,
109 | muli(
110 | t,
111 | add(
112 | ERFC_G,
113 | muli(
114 | t,
115 | add(
116 | ERFC_H,
117 | muli(t, add(ERFC_I, muli(t, ERFC_J)))
118 | )
119 | )
120 | )
121 | )
122 | )
123 | }
124 | {
125 | step := muli(
126 | t,
127 | add(
128 | ERFC_B,
129 | muli(
130 | t,
131 | add(
132 | ERFC_C,
133 | muli(
134 | t,
135 | add(
136 | ERFC_D,
137 | muli(t, add(ERFC_E, muli(t, step)))
138 | )
139 | )
140 | )
141 | )
142 | )
143 | )
144 | }
145 |
146 | k := add(sub(mul(SIGN, muli(z, z)), ERFC_A), step)
147 | }
148 |
149 | int256 expWad = FixedPointMathLib.expWad(k);
150 | int256 r;
151 | assembly {
152 | r := sdiv(mul(t, expWad), ONE)
153 | switch iszero(slt(input, 0))
154 | case 0 {
155 | output := sub(TWO, r)
156 | }
157 | case 1 {
158 | output := r
159 | }
160 | }
161 | }
162 |
163 | /**
164 | * @notice Approximation of the Inverse Complimentary Error Function - erfc^(-1).
165 | *
166 | * @dev Equal to `ierfc(erfc(x)) = erfc(ierfc(x))` for 0 < x < 2.
167 | * Related to the Inverse Error Function: `ierfc(1 - x) = ierf(x)`.
168 | * This is a special function with its own identities.
169 | * Domain: 0 < x < 2
170 | * Special values:
171 | * ierfc(0) = infinity
172 | * ierfc(1) = 0
173 | * ierfc(2) = -infinity
174 | *
175 | * @custom:source Numerical Recipes 3e p265.
176 | * @custom:source https://mathworld.wolfram.com/InverseErfc.html.
177 | */
178 | function ierfc(int256 x) internal pure returns (int256 z) {
179 | if (x == 0 || x == 2 ether) revert Infinity();
180 | if (x < 0 || x > 2 ether) revert OutOfBounds();
181 |
182 | assembly {
183 | // x >= 2, iszero(x < 2 ? 1 : 0) ? 1 : 0.
184 | if iszero(slt(x, TWO)) {
185 | z := mul(add(not(100), 1), SCALAR)
186 | }
187 |
188 | // x <= 0.
189 | if iszero(sgt(x, 0)) {
190 | z := mul(100, SCALAR)
191 | }
192 | }
193 |
194 | if (z != 0) return z;
195 |
196 | int256 xx; // (x < ONE) ? x : TWO - x.
197 | assembly {
198 | switch iszero(slt(x, ONE))
199 | case 0 {
200 | xx := x
201 | }
202 | case 1 {
203 | xx := sub(TWO, x)
204 | }
205 | }
206 |
207 | int256 logInput = diviWad(xx, TWO);
208 | if (logInput == 0) revert Infinity();
209 | int256 ln = FixedPointMathLib.lnWad(logInput);
210 | uint256 t = uint256(muliWad(NEGATIVE_TWO, ln)).sqrt();
211 | assembly {
212 | t := mul(t, HALF_SCALAR)
213 | }
214 |
215 | int256 r;
216 | assembly {
217 | function muli(pxn, pxd) -> res {
218 | res := mul(pxn, pxd)
219 |
220 | if iszero(eq(sdiv(res, pxn), pxd)) {
221 | mstore(0, 0x35278d1200000000000000000000000000000000000000000000000000000000)
222 | revert(0, 4)
223 | }
224 |
225 | res := sdiv(res, ONE)
226 | }
227 |
228 | r := muli(
229 | IERFC_A,
230 | sub(
231 | sdiv(
232 | mul(add(IERFC_B, muli(t, IERFC_C)), ONE),
233 | add(ONE, muli(t, add(IERFC_D, muli(t, IERFC_E))))
234 | ),
235 | t
236 | )
237 | )
238 | }
239 |
240 | uint256 itr;
241 | while (itr < 2) {
242 | int256 err = erfc(r);
243 | assembly {
244 | err := sub(err, xx)
245 | }
246 |
247 | int256 input;
248 | assembly {
249 | input := add(not(sdiv(mul(r, r), ONE)), 1) // -(r * r).
250 | }
251 |
252 | int256 expWad = input.expWad();
253 |
254 | assembly {
255 | function muli(pxn, pxd) -> res {
256 | res := sdiv(mul(pxn, pxd), ONE)
257 | }
258 |
259 | r := add(
260 | r,
261 | sdiv(
262 | mul(err, ONE),
263 | sub(muli(IERFC_F, expWad), muli(r, err))
264 | )
265 | )
266 |
267 | itr := add(itr, 1)
268 | }
269 | }
270 |
271 | assembly {
272 | switch iszero(slt(x, ONE)) // x < ONE ? r : -r.
273 | case 0 {
274 | z := r
275 | }
276 | case 1 {
277 | z := add(not(r), 1)
278 | }
279 | }
280 | }
281 |
282 | /**
283 | * @notice Approximation of the Cumulative Distribution Function.
284 | *
285 | * @dev Equal to `D(x) = 0.5[ 1 + erf((x - µ) / σ√2)]`.
286 | * Only computes cdf of a distribution with µ = 0 and σ = 1.
287 | *
288 | * @custom:error Maximum error of 1.2e-7.
289 | * @custom:source https://mathworld.wolfram.com/NormalDistribution.html.
290 | */
291 | function cdf(int256 x) internal pure returns (int256 z) {
292 | int256 negated;
293 |
294 | assembly {
295 | let res := sdiv(mul(x, ONE), SQRT2)
296 | negated := add(not(res), 1)
297 | }
298 |
299 | int256 _erfc = erfc(negated);
300 |
301 | assembly {
302 | z := sdiv(mul(ONE, _erfc), TWO)
303 | }
304 | }
305 |
306 | /**
307 | * @notice Approximation of the Probability Density Function.
308 | *
309 | * @dev Equal to `Z(x) = (1 / σ√2π)e^( (-(x - µ)^2) / 2σ^2 )`.
310 | * Only computes pdf of a distribution with µ = 0 and σ = 1.
311 | *
312 | * @custom:error Maximum error of 1.2e-7.
313 | * @custom:source https://mathworld.wolfram.com/ProbabilityDensityFunction.html.
314 | */
315 | function pdf(int256 x) internal pure returns (int256 z) {
316 | int256 e;
317 |
318 | assembly {
319 | e := sdiv(mul(add(not(x), 1), x), TWO) // (-x * x) / 2.
320 | }
321 |
322 | e = FixedPointMathLib.expWad(e);
323 |
324 | assembly {
325 | z := sdiv(mul(e, ONE), SQRT_2PI)
326 | }
327 | }
328 |
329 | /**
330 | * @notice Approximation of the Percent Point Function.
331 | *
332 | * @dev Equal to `D(x)^(-1) = µ - σ√2(ierfc(2x))`.
333 | * Only computes ppf of a distribution with µ = 0 and σ = 1.
334 | *
335 | * @custom:error Maximum error of 1.2e-7 compared to "real" ierfc.
336 | * @custom:error Maximum error of 1e-14 in differential tests vs. javscript implementation.
337 | * This error is for inputs near the upper bound >= 0.99 wad.
338 | * JS uses 64bit floats naturally. 12 bits are assigned to the sign and exponent.
339 | * This leaves 52bit to represent the decimal.
340 | * Taking log_10(2^52) gives roughly 15.65.
341 | * This means that we can really only get 15 digits of accuracy from JS itself.
342 | * The error is in this conversion from fixed point to floating point.
343 | * @custom:source https://mathworld.wolfram.com/NormalDistribution.html.
344 | */
345 | function ppf(int256 x) internal pure returns (int256 z) {
346 | if (x == int256(HALF_WAD)) return int256(0); // returns 3.75e-8, but we know it's zero.
347 | if (x >= ONE) revert Infinity();
348 | if (x == 0) revert NegativeInfinity();
349 | assembly {
350 | x := mul(x, 2)
351 | }
352 |
353 | int256 _ierfc = ierfc(x);
354 |
355 | assembly {
356 | let res := sdiv(mul(SQRT2, _ierfc), ONE)
357 | z := add(not(res), 1) // -res.
358 | }
359 | }
360 | }
361 |
--------------------------------------------------------------------------------
/src/reference/ReferenceInvariant.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.4;
3 |
4 | import "./ReferenceGaussian.sol";
5 |
6 | /**
7 | * @title Invariant of Primitive RMM.
8 | * @author @alexangelj
9 | * @notice Invariant is `k` with the trading function `k = y - KΦ(Φ⁻¹(1-x) - σ√τ)`.
10 | *
11 | * @dev Terms which can potentially be ambiguous are given discrete names.
12 | * This makes it easier to search for terms and update terms.
13 | * Variables can sometimes not be trusted to be or act like their names.
14 | * This naming scheme avoids this problem using a glossary to define them.
15 | *
16 | * // -------------------- Glossary --------------------- //
17 | *
18 | * `R_x` - Amount of asset token reserves per single unit of liquidity.
19 | * `R_y` - Amount of quote token reserves per single unit of liquidity.
20 | * `stk` - Strike price of the pool. The terminal price of each asset token.
21 | * `vol` - Implied volatility of the pool. Higher vol = higher price impact on swaps.
22 | * `tau` - Time until the pool expires. Amount of seconds until the pool's curve becomes flat around `stk`.
23 | * `inv` - Invariant of the pool. Difference between theoretical $ value and actual $ value per liquidity.
24 | *
25 | * `WAD` - Signed or unsigned fixed point number with up to 18 decimals and up to 256 total bits wide.
26 | * `YEAR`- Equal to the amount of seconds in a year. Used in `invariant` function.
27 | *
28 | * // -------------------- Units ------------------------ //
29 | *
30 | * `R_x` - Units are unsigned WAD. Represents value of tokens, decimals matter.
31 | * `R_y` - Units are unsigned WAD. Represents value of tokens, decimals matter.
32 | * `stk` - Units are unsigned WAD. Represents value of tokens, decimals matter.
33 | * `vol` - Units are unsigned WAD. Represents a percentage in which 100% = WAD.
34 | * `tau` - Units are YEAR. Represents a time unit which `1.0` is equal to YEAR.
35 | * `inv` - Units are signed WAD. Initial value of zero and decreases over time.
36 | *
37 | * // -------------------- Denoted By ----------------- //
38 | *
39 | * `R_x` - Denoted by `x`.
40 | * `R_y` - Denoted by `y`.
41 | * `stk` - Denoted by `K`.
42 | * `vol` - Denoted by `σ`.
43 | * `tau` - Denoted by `τ`.
44 | * `inv` - Denoted by `k`.
45 | *
46 | * // -------------------- Error Bounds ----------------- //
47 | *
48 | * `inv` - Up to 1e-9.
49 | *
50 | * // ------------------------ ~ ------------------------ //
51 | */
52 | library Invariant {
53 | using Gaussian for int256; // Uses the `cdf` and `pdf` functions.
54 | using FixedPointMathLib for uint256; // Uses the `sqrt` function.
55 |
56 | uint256 internal constant WAD = 1 ether;
57 | uint256 internal constant DOUBLE_WAD = 2 ether;
58 | int256 internal constant ONE = 1 ether;
59 | int256 internal constant YEAR = 31556952;
60 | int256 internal constant HALF_SCALAR = 1e9;
61 |
62 | /**
63 | * @dev Reverts when an input value is out of bounds of its acceptable range.
64 | */
65 | error OOB();
66 |
67 | /**
68 | * @notice Uses reserves `R_x` to compute reserves `R_y`.
69 | *
70 | * @dev Computes `y` in `y = KΦ(Φ⁻¹(1-x) - σ√τ) + k`.
71 | * Primary function use to compute the invariant.
72 | * Simplifies to `K(1 -x) + k` when time to expiry is zero.
73 | * Reverts if `R_x` is greater than one. Units are a fixed point number with 18 decimals.
74 | *
75 | * We handle some special cases, try this:
76 | * `normalcd(normalicd(1) - 0.1)` in https://keisan.casio.com/calculator
77 | * Gaussian.sol reverts for `ppf(1)` and `ppf(0)`, so we handle those cases.
78 | *
79 | * @param R_x Quantity of token reserve `x` within the bounds of [0, 1].
80 | * @param stk Strike price of the pool. Terminal price of asset `x` in the pool denominated in asset `y`.
81 | * @param vol Implied volatility of the pool. Higher implied volatility = higher price impact on swaps.
82 | * @param tau Time until the pool expires. Once expired, no swaps can happen. Scaled to units of `Invariant.YEAR`.
83 | * @param inv Current invariant given the actual `R_x`. Zero if computing invariant itself.
84 | * @return R_y Quantity of token reserve `y` within the bounds of [0, stk].
85 | *
86 | * @custom:error Technically, none. This is the source of truth for the trading function.
87 | * @custom:source https://primitive.xyz/whitepaper
88 | */
89 | function getY(
90 | uint256 R_x,
91 | uint256 stk,
92 | uint256 vol,
93 | uint256 tau,
94 | int256 inv
95 | ) internal pure returns (uint256 R_y) {
96 | if (R_x > WAD) revert OOB(); // Negative input for `ppf` is invalid.
97 | if (R_x == WAD) return uint256(inv); // For `ppf(0)` case, because 1 - 1 == 0, cdf(ppf(0)) == 0, and `y = K * 0 + k` simplifies to `y = k`.
98 | if (R_x == 0) return uint256(int256(stk) + inv); // For `ppf(1)` case, because 1 - 0 == 1, cdf(ppf(1)) == 1, and `y = K * 1 + k` simplifies to `y = K + k`.
99 | if (tau != 0) {
100 | // Short circuits because tau != 0 is more likely.
101 | uint256 sec;
102 | assembly {
103 | sec := sdiv(mul(tau, ONE), YEAR) // Unit math: YEAR * SCALAR / YEAR = SCALAR.
104 | }
105 |
106 | uint256 sdr = sec.sqrt(); // √τ.
107 | assembly {
108 | sdr := mul(sdr, HALF_SCALAR) // Unit math: sdr * HALF_SCALAR = SCALAR.
109 | sdr := sdiv(mul(vol, sdr), ONE) // σ√τ.
110 | }
111 |
112 | int256 phi;
113 | assembly {
114 | phi := sub(ONE, R_x)
115 | }
116 | phi = phi.ppf(); // Φ⁻¹(1-x).
117 |
118 | int256 cdf;
119 | assembly {
120 | cdf := sub(phi, sdr) // Φ⁻¹(1-x) - σ√τ.
121 | }
122 | cdf = cdf.cdf(); // Φ(Φ⁻¹(1-x) - σ√τ).
123 |
124 | assembly {
125 | R_y := add(sdiv(mul(stk, cdf), ONE), inv)
126 | }
127 | } else {
128 | assembly {
129 | R_y := add(sdiv(mul(stk, sub(ONE, R_x)), ONE), inv)
130 | }
131 | }
132 | }
133 |
134 | /**
135 | * @notice Uses reserves `R_y` to compute reserves `R_x`.
136 | *
137 | * @dev Computes `x` in `x = 1 - Φ(Φ⁻¹( (y + k) / K ) + σ√τ)`.
138 | * Not used in invariant function. Used for computing swap outputs.
139 | * Simplifies to `1 - ( (y + k) / K )` when time to expiry is zero.
140 | * Reverts if `R_y` is greater than one. Units are WAD.
141 | *
142 | * Dangerous! There are important bounds to using this function.
143 | *
144 | * @param R_y Quantity of token reserve `y` within the bounds of [0, stk].
145 | * @param stk Strike price of the pool. Terminal price of asset `x` in the pool denominated in asset `y`.
146 | * @param vol Implied volatility of the pool. Higher implied volatility = higher price impact on swaps.
147 | * @param tau Time until the pool expires. Once expired, no swaps can happen. Scaled to units of `Invariant.YEAR`.
148 | * @param inv Current invariant given the actual reserves `R_y`.
149 | * @return R_x Quantity of token reserve `x` within the bounds of [0, 1].
150 | *
151 | * @custom:error Up to 1e-6. This an **approximated** "inverse" of the `getY` function.
152 | * @custom:source https://primitive.xyz/whitepaper
153 | */
154 | function getX(
155 | uint256 R_y,
156 | uint256 stk,
157 | uint256 vol,
158 | uint256 tau,
159 | int256 inv
160 | ) internal pure returns (uint256 R_x) {
161 | // Short circuits because tau != 0 is more likely.
162 | if (tau != 0) {
163 | uint256 sec;
164 | assembly {
165 | sec := div(mul(tau, ONE), YEAR) // Unit math: YEAR * SCALAR / YEAR = SCALAR.
166 | }
167 |
168 | uint256 sdr = sec.sqrt(); // √τ.
169 | assembly {
170 | sdr := mul(sdr, HALF_SCALAR) // Unit math: HALF_SCALAR * HALF_SCALAR = SCALAR.
171 | sdr := div(mul(vol, sdr), ONE) // σ√τ.
172 | }
173 |
174 | int256 phi;
175 | assembly {
176 | phi := sdiv(mul(add(R_y, inv), ONE), stk) // (y + k) / K.
177 | }
178 |
179 | if (phi < 0) revert OOB(); // Negative input for `ppf` is invalid.
180 | if (phi > ONE) revert OOB();
181 | if (phi == ONE) return 0; // `x = 1 - Φ(Φ⁻¹( 1 ) + σ√τ)` simplifies to `x = 0`.
182 | if (phi == 0) return WAD; // `x = 1 - Φ(Φ⁻¹( 0 ) + σ√τ)` simplifies to `x = 1`.
183 |
184 | phi = phi.ppf(); // Φ⁻¹( (y + k) / K ).
185 |
186 | int256 cdf;
187 | assembly {
188 | cdf := add(phi, sdr) // Φ⁻¹( (y + k) / K ) + σ√τ.
189 | }
190 | cdf = cdf.cdf(); // Φ(Φ⁻¹( (y + k) / K ) + σ√τ).
191 |
192 | assembly {
193 | R_x := sub(ONE, cdf)
194 | }
195 | } else {
196 | assembly {
197 | R_x := sub(ONE, sdiv(mul(add(R_y, inv), ONE), stk))
198 | }
199 | }
200 | }
201 |
202 | /**
203 | * @notice Computes the invariant of the RMM trading function.
204 | *
205 | * @dev Computes `k` in `k = y - KΦ(Φ⁻¹(1-x) - σ√τ)`.
206 | * Used to validate swaps, the most critical function.
207 | *
208 | * @custom:source https://rmm.eth.xyz
209 | */
210 | function invariant(
211 | uint256 R_y,
212 | uint256 R_x,
213 | uint256 stk,
214 | uint256 vol,
215 | uint256 tau
216 | ) internal pure returns (int256 inv) {
217 | uint256 y = getY(R_x, stk, vol, tau, inv); // `inv` is 0 because we are solving `inv`, aka `k`.
218 | assembly {
219 | inv := sub(R_y, y)
220 | }
221 | }
222 | }
223 |
--------------------------------------------------------------------------------
/src/test/Cdf.t.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.13;
3 |
4 | import "forge-std/Test.sol";
5 |
6 | import {Gaussian} from "../Gaussian.sol";
7 |
8 | contract TestCdf is Test {
9 | // todo: fix these tests!! @clemlak
10 | /* function testDiff_cdf(int256 x) public {
11 | vm.assume(x > -2828427124746190093171572875253809907);
12 | vm.assume(x < 2828427124746190093171572875253809907);
13 | string[] memory inputs = new string[](3);
14 | inputs[0] = "./gaussian";
15 | inputs[1] = "cdf";
16 | inputs[2] = vm.toString(x);
17 | bytes memory res = vm.ffi(inputs);
18 | uint256 ref = abi.decode(res, (uint256));
19 | int256 y = Gaussian.cdf(x);
20 |
21 | // When outputs are very small, we tolerate a larger error
22 | if (ref < 1_000_000_000 && y < 1_000_000_000) {
23 | // 0.1% of difference
24 | assertApproxEqRel(ref, uint256(y), 0.001 ether);
25 | } else {
26 | // 0.00005% of difference
27 | assertApproxEqRel(ref, uint256(y), 0.0000005 ether);
28 | }
29 | } */
30 | }
31 |
--------------------------------------------------------------------------------
/src/test/DifferentialTests.t.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.8.13;
2 |
3 | import "forge-std/Test.sol";
4 |
5 | import "../Gaussian.sol";
6 | import "./HelperInvariant.sol";
7 |
8 | contract DifferentialTests is Test {
9 | enum DifferentialFunctions {
10 | erfc,
11 | ierfc,
12 | cdf,
13 | ppf,
14 | invariant
15 | }
16 |
17 | string internal constant DATA_DIR = "test/differential/data/";
18 | uint256 internal constant EPSILON = 1e3;
19 |
20 | uint256 _epsilon;
21 | int256[129] _inputs;
22 | int256[129] _outputs;
23 | uint256[5][129] _invariantInputs;
24 |
25 | function setUp() public {
26 | generate();
27 | }
28 |
29 | function generate() public {
30 | // Run the reference implementation in javascript
31 | string[] memory runJsInputs = new string[](6);
32 | runJsInputs[0] = "npm";
33 | runJsInputs[1] = "--prefix";
34 | runJsInputs[2] = "test/differential/scripts/";
35 | runJsInputs[3] = "--silent";
36 | runJsInputs[4] = "run";
37 | runJsInputs[5] = "generate"; // Generates length 129 by default
38 | vm.ffi(runJsInputs);
39 | }
40 |
41 | function load(string memory key)
42 | public
43 | returns (int256[129] memory inputs, int256[129] memory outputs)
44 | {
45 | string[] memory cmds = new string[](2);
46 | // Get inputs.
47 | cmds[0] = "cat";
48 | cmds[1] = string(abi.encodePacked(DATA_DIR, key, "/input"));
49 | bytes memory result = vm.ffi(cmds);
50 | if (keccak256(abi.encodePacked(key)) == keccak256("invariant")) {
51 | _invariantInputs = abi.decode(result, (uint256[5][129]));
52 | } else {
53 | inputs = abi.decode(result, (int256[129]));
54 | }
55 | _inputs = inputs;
56 | // Get outputs.
57 | cmds[0] = "cat";
58 | cmds[1] = string(abi.encodePacked(DATA_DIR, key, "/output"));
59 | result = vm.ffi(cmds);
60 | outputs = abi.decode(result, (int256[129]));
61 | _outputs = outputs;
62 | }
63 |
64 | function testDifferentialERFC() public {
65 | _epsilon = EPSILON;
66 | load("erfc");
67 | run(DifferentialFunctions.erfc);
68 | }
69 |
70 | function testDifferentialIERFC() public {
71 | _epsilon = EPSILON;
72 | load("ierfc");
73 | run(DifferentialFunctions.ierfc);
74 | }
75 |
76 | function testDifferentialCDF() public {
77 | _epsilon = EPSILON;
78 | load("cdf");
79 | run(DifferentialFunctions.cdf);
80 | }
81 |
82 | function testDifferentialPPF() public {
83 | _epsilon = EPSILON * 10;
84 | load("ppf");
85 | run(DifferentialFunctions.ppf);
86 | }
87 |
88 | function testDifferentialInvariant() public {
89 | _epsilon = 1e9; // todo: fix/investigate
90 | load("invariant");
91 | run(DifferentialFunctions.invariant);
92 | }
93 |
94 | function run(DifferentialFunctions fn) public {
95 | if (fn == DifferentialFunctions.erfc) {
96 | _run(Gaussian.erfc);
97 | } else if (fn == DifferentialFunctions.ierfc) {
98 | _run(Gaussian.ierfc);
99 | } else if (fn == DifferentialFunctions.cdf) {
100 | _run(Gaussian.cdf);
101 | } else if (fn == DifferentialFunctions.ppf) {
102 | _run(Gaussian.ppf);
103 | } else if (fn == DifferentialFunctions.invariant) {
104 | _run(customInvariant);
105 | } else {
106 | revert();
107 | }
108 | }
109 |
110 | function customInvariant(uint256[5] memory args)
111 | internal
112 | pure
113 | returns (int256 k)
114 | {
115 | HelperInvariant.Args memory invariantInputs;
116 | uint256 y = args[0];
117 | invariantInputs.x = args[1];
118 | invariantInputs.K = args[2];
119 | invariantInputs.o = args[3];
120 | invariantInputs.t = args[4];
121 | k = HelperInvariant.invariant(invariantInputs, y);
122 | }
123 |
124 | function _run(function(int256) view returns (int256) method) internal {
125 | uint256 length = _inputs.length;
126 | for (uint256 i = 0; i < length; ++i) {
127 | int256 input = _inputs[i];
128 | int256 output = _outputs[i];
129 | int256 computed = method(input);
130 | assertApproxEqAbs(
131 | computed,
132 | output,
133 | _epsilon,
134 | vm.toString(input)
135 | );
136 | }
137 | }
138 |
139 | function _run(function(uint256[5] memory) view returns (int256) method)
140 | internal
141 | {
142 | uint256 length = _invariantInputs.length;
143 | for (uint256 i = 0; i < length; ++i) {
144 | uint256[5] memory input = _invariantInputs[i];
145 | int256 output = _outputs[i];
146 | int256 computed = method(input);
147 | assertApproxEqAbs(
148 | computed,
149 | output,
150 | _epsilon,
151 | "computed-output-mismatch"
152 | );
153 | }
154 | }
155 | }
156 |
--------------------------------------------------------------------------------
/src/test/Erfc.t.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.13;
3 |
4 | import "forge-std/Test.sol";
5 |
6 | import {Gaussian} from "../Gaussian.sol";
7 |
8 | contract TestErfc is Test {
9 | function testFuzz_erfc_ReturnsTwoWhenInputIsTooLow(int256 x) public {
10 | vm.assume(x <= Gaussian.ERFC_DOMAIN_LOWER);
11 |
12 | // TODO: Investigate why the error selector is 0x4d2d75b1
13 | // instead of 0x35278d12
14 | int256 y = Gaussian.erfc(x);
15 | assertEq(y, int256(2 ether), "erfc-not-two");
16 | }
17 |
18 | function testFuzz_erfc_ReturnsZeroWhenInputIsTooHigh(int256 x) public {
19 | vm.assume(x >= Gaussian.ERFC_DOMAIN_UPPER);
20 | int256 y = Gaussian.erfc(x);
21 | assertEq(y, 0, "erfc-not-zero");
22 | }
23 |
24 | function testFuzz_erfc_NegativeInputIsBounded(int256 x) public {
25 | vm.assume(x > -1999999999999999998000000000000000002);
26 | vm.assume(x < -0.0000001 ether);
27 | int256 y = Gaussian.erfc(x);
28 | assertGe(y, 1 ether);
29 | assertLe(y, 2 ether);
30 | }
31 |
32 | function testFuzz_erfc_PositiveInputIsBounded(int256 x) public {
33 | vm.assume(x > 0.0000001 ether);
34 | vm.assume(x < 1999999999999999998000000000000000002);
35 | int256 y = Gaussian.erfc(x);
36 | assertGe(y, 0 ether);
37 | assertLe(y, 1 ether);
38 | }
39 |
40 | function test_erfc_zero_input_returns_one() public {
41 | assertEq(Gaussian.erfc(0), 1 ether);
42 | }
43 |
44 | // todo: fix these tests!! @clemlak
45 | /* function testDiff_erfc(int256 x) public {
46 | vm.assume(x < 1999999999999999998000000000000000002);
47 | vm.assume(x > -1999999999999999998000000000000000002);
48 | string[] memory inputs = new string[](3);
49 | inputs[0] = "./gaussian";
50 | inputs[1] = "erfc";
51 | inputs[2] = vm.toString(x);
52 | bytes memory res = vm.ffi(inputs);
53 | uint256 ref = abi.decode(res, (uint256));
54 | int256 y = Gaussian.erfc(x);
55 | // Results have a 0.0001% difference
56 | assertApproxEqRel(ref, uint256(y), 0.000001 ether);
57 | } */
58 | }
59 |
--------------------------------------------------------------------------------
/src/test/Gaussian.t.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.13;
3 |
4 | import "forge-std/Test.sol";
5 |
6 | import {Gaussian} from "../Gaussian.sol";
7 | import {Gaussian as Ref} from "../reference/ReferenceGaussian.sol";
8 |
9 | int256 constant HIGH = int256(10 ether);
10 | int256 constant LOW = -int256(10 ether);
11 |
12 | // 1e18 == 100%
13 | uint256 constant CDF_ERROR_REL = 0.0000001 ether; // 0.0000001 ether = 0.00001%
14 |
15 | contract TestGaussian is Test {
16 | /// @dev https://keisan.casio.com/calculator
17 | function test_cdf() public {
18 | assertApproxEqRel(
19 | Ref.cdf(1 ether),
20 | int256(0.841344746068542949 ether),
21 | CDF_ERROR_REL,
22 | "cdf-1"
23 | );
24 | assertApproxEqRel(
25 | Ref.cdf(1.5 ether),
26 | int256(0.933192798731141934 ether),
27 | CDF_ERROR_REL,
28 | "cdf-1.5"
29 | );
30 | assertApproxEqRel(
31 | Ref.cdf(2 ether),
32 | int256(0.977249868051820793 ether),
33 | CDF_ERROR_REL,
34 | "cdf-2"
35 | );
36 | assertApproxEqRel(
37 | Ref.cdf(10 ether),
38 | int256(1 ether),
39 | CDF_ERROR_REL,
40 | "cdf-10"
41 | );
42 |
43 | assertApproxEqRel(
44 | Ref.cdf(0.0000001 ether),
45 | int256(0.50000003989422804 ether),
46 | CDF_ERROR_REL,
47 | "cdf-0.0000001"
48 | );
49 |
50 | assertApproxEqRel(
51 | Ref.cdf(0.01 ether),
52 | int256(0.503989356314631604 ether),
53 | CDF_ERROR_REL,
54 | "cdf-0.01"
55 | );
56 |
57 | // negative
58 | assertApproxEqRel(
59 | Ref.cdf(-int256(0.0000001 ether)),
60 | int256(0.49999996010577196 ether),
61 | CDF_ERROR_REL,
62 | "cdf-negative-0.0000001"
63 | );
64 | assertApproxEqRel(
65 | Ref.cdf(-int256(0.1 ether)),
66 | int256(0.460172162722971019 ether),
67 | CDF_ERROR_REL,
68 | "cdf-negative-0.1"
69 | );
70 | assertApproxEqRel(
71 | Ref.cdf(-int256(0.5 ether)),
72 | int256(0.308537538725986896 ether),
73 | CDF_ERROR_REL,
74 | "cdf-negative-0.5"
75 | );
76 | assertApproxEqRel(
77 | Ref.cdf(-int256(0.99 ether)),
78 | int256(0.161087059510830911 ether),
79 | CDF_ERROR_REL,
80 | "cdf-negative-0.99"
81 | );
82 | assertApproxEqRel(
83 | Ref.cdf(-int256(1 ether)),
84 | int256(0.158655253931457051 ether),
85 | CDF_ERROR_REL,
86 | "cdf-negative-1"
87 | );
88 | assertApproxEqRel(
89 | Ref.cdf(-int256(2 ether)),
90 | int256(0.022750131948179207 ether),
91 | CDF_ERROR_REL,
92 | "cdf-negative-2"
93 | );
94 | }
95 |
96 | function test_ppf_one_reverts() public {
97 | vm.expectRevert(Gaussian.Infinity.selector);
98 | assertApproxEqRel(
99 | Ref.ppf(1 ether),
100 | int256(0 ether),
101 | CDF_ERROR_REL,
102 | "ppf-1"
103 | );
104 | }
105 |
106 | function test_ppf_zero_reverts() public {
107 | vm.expectRevert(Gaussian.NegativeInfinity.selector);
108 | assertApproxEqRel(
109 | Ref.ppf(0 ether),
110 | int256(0 ether),
111 | CDF_ERROR_REL,
112 | "ppf-0"
113 | );
114 | }
115 |
116 | function test_ppf() public {
117 | assertApproxEqRel(
118 | Ref.ppf(0.5 ether),
119 | int256(0 ether),
120 | CDF_ERROR_REL,
121 | "ppf-0.5"
122 | );
123 | assertApproxEqRel(
124 | Ref.ppf(0.99 ether),
125 | int256(2.3263478740408411 ether),
126 | CDF_ERROR_REL,
127 | "ppf-0.99"
128 | );
129 | assertApproxEqRel(
130 | Ref.ppf(0.01 ether),
131 | -int256(2.3263478740408411 ether),
132 | CDF_ERROR_REL,
133 | "ppf-0.01"
134 | );
135 | assertApproxEqRel(
136 | Ref.ppf(0.999999 ether),
137 | int256(4.75342430882289895 ether),
138 | CDF_ERROR_REL,
139 | "ppf-0.999999"
140 | );
141 | assertApproxEqRel(
142 | Ref.ppf(0.000001 ether),
143 | -int256(4.753424308822899 ether),
144 | CDF_ERROR_REL,
145 | "ppf-0.000001"
146 | );
147 |
148 | uint256 ppfRelErr = 0.000001 ether; // todo: rel error goes up as input precision increases.
149 | assertApproxEqRel(
150 | Ref.ppf(0.3222222 ether),
151 | -int256(0.461493756180050379 ether),
152 | ppfRelErr,
153 | "ppf-0.3222222"
154 | );
155 | }
156 |
157 | function testReference_erfc_Equality(int256 input) public {
158 | vm.assume(input < HIGH);
159 | vm.assume(input > LOW);
160 | vm.assume(input != 0);
161 | int256 actual = Gaussian.erfc(input);
162 | int256 expected = Ref.erfc(input);
163 | assertEq(actual, expected, "erfc-inequality");
164 | }
165 |
166 | // todo: investigate, reverts with Infinity() if input is 1 because of rounding down?
167 | function testReference_ierfc_Equality(int256 input) public {
168 | vm.assume(input < 2 ether);
169 | vm.assume(input > 1);
170 | int256 actual = Gaussian.ierfc(input);
171 | int256 expected = Ref.ierfc(input);
172 | assertEq(actual, expected, "ierfc-inequality");
173 | }
174 |
175 | function testReference_cdf_Equality(int256 input) public {
176 | vm.assume(input < HIGH);
177 | vm.assume(input > LOW);
178 | vm.assume(input != 0);
179 | int256 actual = Gaussian.cdf(input);
180 | int256 expected = Ref.cdf(input);
181 | console.logInt(actual);
182 | console.logInt(expected);
183 | // assertEq(actual, expected, "cdf-inequality");
184 | assertApproxEqRel(actual, expected, 0.0015 ether);
185 | }
186 |
187 | function testReference_pdf_Equality(int256 input) public {
188 | vm.assume(input < HIGH);
189 | vm.assume(input > LOW);
190 | int256 actual = Gaussian.pdf(input);
191 | int256 expected = Ref.pdf(input);
192 | assertEq(actual, expected, "pdf-inequality");
193 | }
194 |
195 | function testReference_ppf_Equality(int256 input) public {
196 | vm.assume(input > 0);
197 | vm.assume(input < 1 ether);
198 | int256 actual = Gaussian.ppf(input);
199 | int256 expected = Ref.ppf(input);
200 | assertEq(actual, expected, "ppf-inequality");
201 | }
202 |
203 | function testERFC() public {
204 | int256 actual = Gaussian.erfc(-1e18);
205 | int256 expected = 1842700787760006725;
206 | assertEq(actual, expected, "erfc");
207 | }
208 |
209 | function testERFCGas() public logs_gas {
210 | int256 actual = Gaussian.erfc(-1);
211 | actual;
212 | }
213 |
214 | function testIERFCGas() public logs_gas {
215 | int256 actual = Gaussian.ierfc(5e17);
216 | actual;
217 | }
218 |
219 | function testCDFGas() public logs_gas {
220 | int256 actual = Gaussian.cdf(-5e17);
221 | actual;
222 | }
223 |
224 | function testPPFGas() public logs_gas {
225 | int256 actual = Gaussian.ppf(5e17);
226 | actual;
227 | }
228 |
229 | function testPDFGas() public logs_gas {
230 | int256 actual = Gaussian.pdf(5e17);
231 | actual;
232 | }
233 |
234 | function testFuzz_ERFC_Bounds_positive(int256 x) public {
235 | vm.assume(x >= 0 && x < 1999999999999999998000000000000000002);
236 | int256 y = Gaussian.erfc(x);
237 | assertLe(y, 2 ether);
238 | assertGe(y, 0);
239 | }
240 |
241 | function testFuzz_ERFC_Bounds_negative(int256 x) public {
242 | vm.assume(x <= 0 && x > -1999999999999999998000000000000000002);
243 | int256 y = Gaussian.erfc(x);
244 | assertLe(y, 2 ether);
245 | assertGe(y, 0);
246 | }
247 | }
248 |
--------------------------------------------------------------------------------
/src/test/HelperInvariant.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.13;
3 |
4 | import "../Invariant.sol";
5 |
6 | library HelperInvariant {
7 | struct Args {
8 | uint256 x;
9 | uint256 K;
10 | uint256 o;
11 | uint256 t;
12 | }
13 |
14 | function getY(Args memory args) public pure returns (uint256 y) {
15 | y = Invariant.getY(args.x, args.K, args.o, args.t, 0);
16 | }
17 |
18 | function getX(Args memory args) public pure returns (uint256 x) {
19 | x = Invariant.getX(args.x, args.K, args.o, args.t, 0);
20 | }
21 |
22 | function invariant(Args memory args, uint256 R_y)
23 | public
24 | pure
25 | returns (int256 inv)
26 | {
27 | inv = Invariant.invariant(R_y, args.x, args.K, args.o, args.t);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/test/Ierfc.t.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.13;
3 |
4 | import "forge-std/Test.sol";
5 |
6 | import {Gaussian} from "../Gaussian.sol";
7 |
8 | contract TestIerfc is Test {
9 | function testFuzz_ierfc_RevertWhenInputIsOutOfBounds(int256 x) public {
10 | vm.assume(x < 0 || x > 2 ether);
11 | vm.expectRevert(Gaussian.OutOfBounds.selector);
12 | int256 y = Gaussian.ierfc(x);
13 | y;
14 | }
15 |
16 | function test_ierfc_InputOneWillTriggerInfinity() public {
17 | vm.expectRevert(Gaussian.Infinity.selector);
18 | int256 y = Gaussian.ierfc(1);
19 | console.logInt(y);
20 | }
21 |
22 | function test_ierfc_ZeroTriggersInfinity() public {
23 | vm.expectRevert(Gaussian.Infinity.selector);
24 | int256 y = Gaussian.ierfc(0);
25 | y;
26 | }
27 |
28 | function test_ierfc_TwoTriggersNegativeInfinity() public {
29 | vm.expectRevert(Gaussian.NegativeInfinity.selector);
30 | int256 y = Gaussian.ierfc(2 ether);
31 | y;
32 | }
33 |
34 | // todo: fix these tests!! @clemlak
35 | /* function testDiff_ierfc(int64 x) public {
36 | vm.assume(x > 0.00001 ether);
37 | vm.assume(x < 2 ether);
38 | string[] memory inputs = new string[](3);
39 | inputs[0] = "./gaussian";
40 | inputs[1] = "ierfc";
41 | inputs[2] = vm.toString(x);
42 | bytes memory res = vm.ffi(inputs);
43 | int256 ref = abi.decode(res, (int256));
44 | int256 y = Gaussian.ierfc(int256(x));
45 |
46 | // When inputs are very close to 1, we tolerate a larger error
47 | if (x > 0.99 ether && x < 1.05 ether) {
48 | // 0.15% of difference
49 | assertApproxEqRel(ref, y, 0.0015 ether);
50 | } else {
51 | // 0.0003% of difference
52 | assertApproxEqRel(ref, y, 0.000003 ether);
53 | }
54 | } */
55 | }
56 |
--------------------------------------------------------------------------------
/src/test/Invariant.t.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.13;
3 |
4 | import "forge-std/Test.sol";
5 |
6 | import "../Gaussian.sol";
7 | import {Invariant} from "../Invariant.sol";
8 | import {Invariant as Ref} from "../reference/ReferenceInvariant.sol";
9 | import {HelperInvariant} from "./HelperInvariant.sol";
10 |
11 | uint256 constant GET_REVERSE_ERROR_REL = 0.000000988606022657 ether; //0.038844859616646632 ether; // highest % error found in test
12 | uint256 constant GET_Y_ERROR_REL = 0.000000059885406089 ether; // highest % error found in test getY-0.5-365-days.
13 | uint256 constant GET_X_ERROR_REL = 0.000000059885406087 ether; // highest % error found in test getX-0.5-365-days.
14 |
15 | /// @dev for making test cases with different days, compute years in wad, then pass into calculator.
16 | function debugDays(uint256 amountTime) pure returns (uint256 yearsWad) {
17 | yearsWad = (uint256(amountTime) * Invariant.WAD) / uint256(Invariant.YEAR);
18 | }
19 |
20 | function debugVol(uint256 amountVol) pure returns (uint256 yearsWad) {
21 | yearsWad = (uint256(amountVol) * Invariant.WAD) / 10_000;
22 | }
23 |
24 | function convertSecondsToWadYears(uint256 sec) pure returns (uint256 yrsWad) {
25 | uint256 wad = Invariant.WAD;
26 | uint256 yr = uint256(Invariant.YEAR);
27 | assembly {
28 | yrsWad := div(mul(sec, wad), yr)
29 | }
30 | }
31 |
32 | /**
33 | * @notice Changes percentage into WAD units then cancels the percentage units.
34 | */
35 | function convertPercentageToWad(uint256 pct) pure returns (uint256 pctWad) {
36 | uint256 wad = Invariant.WAD;
37 | assembly {
38 | pctWad := div(mul(pct, wad), 10000)
39 | }
40 | }
41 |
42 | contract TestInvariant is Test {
43 | function testReverse() public {
44 | uint256 R_x = 0.460185342615210335 ether;
45 | uint256 stk = 10 ether;
46 | uint256 vol = 0.1 ether;
47 | uint256 tau = 365 days;
48 | int256 inv = 0;
49 | uint256 R_y = Ref.getY({
50 | R_x: R_x,
51 | stk: stk,
52 | vol: vol,
53 | tau: tau,
54 | inv: inv
55 | });
56 |
57 | uint256 expected = Ref.getX({
58 | R_y: R_y,
59 | stk: stk,
60 | vol: vol,
61 | tau: tau,
62 | inv: inv
63 | });
64 |
65 | assertApproxEqRel(
66 | R_y,
67 | 5 ether,
68 | GET_REVERSE_ERROR_REL,
69 | "R_x-equals-strike"
70 | );
71 | assertApproxEqRel(
72 | R_x,
73 | expected,
74 | GET_REVERSE_ERROR_REL,
75 | "getY-getX-reverse"
76 | );
77 | }
78 |
79 | function testFuzzReverse(
80 | uint256 R_x,
81 | uint256 stk,
82 | uint256 vol,
83 | uint256 tau
84 | ) public {
85 | R_x = bound(R_x, 1_000_000_000_000 wei, 1 ether);
86 | stk = bound(stk, 1_000_000_000_000 wei, type(uint128).max - 1);
87 | vol = bound(vol, 0.01 ether, 2.5 ether); // 1% and 250%
88 | tau = bound(tau, 1 days, 500 days);
89 |
90 | uint256 R_y = Invariant.getY({
91 | R_x: R_x,
92 | stk: stk,
93 | vol: vol,
94 | tau: tau,
95 | inv: 0
96 | });
97 | vm.assume(R_y > 0);
98 |
99 | console.log("R_y", R_y);
100 | console.log("R_x", R_x);
101 | console.log("stk", stk);
102 | console.log("vol", vol);
103 | console.log("tau", tau);
104 |
105 | int256 phi;
106 | int256 one = 1 ether;
107 | assembly {
108 | phi := sdiv(mul(add(R_y, 0), one), stk) // (y + k) / K.
109 | }
110 | console.logInt(phi);
111 |
112 | uint256 expected = Invariant.getX({
113 | R_y: R_y,
114 | stk: stk,
115 | vol: vol,
116 | tau: tau,
117 | inv: 0
118 | });
119 |
120 | if (R_y == 0) expected = R_x;
121 | if (phi == Invariant.ONE) expected = 0;
122 | vm.assume(phi != Invariant.ONE);
123 | if (phi == 0) expected = Invariant.WAD;
124 |
125 | assertApproxEqRel(
126 | R_x,
127 | expected,
128 | GET_REVERSE_ERROR_REL,
129 | "getY-getX-equality"
130 | );
131 | }
132 |
133 | /// @dev `x = 1 - Φ(Φ⁻¹( (y + k) / K ) + σ√τ)`
134 | /// calculator: 1 - normalcdlower(normalicdlower({R_y} / {stk}) + {vol}sqrt({debugDays(tau)}))
135 | /// https://keisan.casio.com/calculator
136 | function test_getX() public {
137 | int256 inv = 0;
138 | assertApproxEqRel(
139 | Invariant.getX({
140 | R_y: 5 ether,
141 | stk: 10 ether,
142 | vol: 0.1 ether,
143 | tau: 365 days, // 0.999336057550805286 years
144 | inv: inv
145 | }),
146 | 0.460185342615210335 ether,
147 | GET_X_ERROR_REL,
148 | "getX-365-days"
149 | );
150 | assertApproxEqRel(
151 | Invariant.getX({
152 | R_y: 5 ether,
153 | stk: 10 ether,
154 | vol: 0.1 ether,
155 | tau: 1 days, // 0.002737907006988507 years
156 | inv: inv
157 | }),
158 | 0.497912543516404356 ether,
159 | GET_X_ERROR_REL,
160 | "getX-1-days"
161 | );
162 | assertApproxEqRel(
163 | Invariant.getX({
164 | R_y: 5 ether,
165 | stk: 10 ether,
166 | vol: 0.1 ether,
167 | tau: 1 hours, // 0.000114079458624521 years
168 | inv: inv
169 | }),
170 | 0.499573897866220608 ether,
171 | GET_X_ERROR_REL,
172 | "getX-1-hours"
173 | );
174 | assertApproxEqRel(
175 | Invariant.getX({
176 | R_y: 5 ether,
177 | stk: 10 ether,
178 | vol: 0.1 ether,
179 | tau: 10 minutes, // 0.000019013243104086 years
180 | inv: inv
181 | }),
182 | 0.499826044504759416 ether,
183 | GET_X_ERROR_REL,
184 | "getX-10-minutes"
185 | );
186 |
187 | assertApproxEqRel(
188 | Invariant.getX({
189 | R_y: 0.000001 ether,
190 | stk: 10 ether,
191 | vol: 0.1 ether,
192 | tau: 182.5 days, // 0.499668028775402643 years
193 | inv: inv
194 | }),
195 | 0.9999998540866343 ether,
196 | GET_X_ERROR_REL,
197 | "getX-0.000001"
198 | );
199 | assertApproxEqRel(
200 | Invariant.getX({
201 | R_y: 1.923115 ether,
202 | stk: 10 ether,
203 | vol: 0.1 ether,
204 | tau: 182.5 days, // 0.499668028775402643 years
205 | inv: inv
206 | }),
207 | 0.787774373410884564 ether,
208 | GET_X_ERROR_REL,
209 | "getX-1.923115"
210 | );
211 | assertApproxEqRel(
212 | Invariant.getX({
213 | R_y: 8.125266343 ether,
214 | stk: 10 ether,
215 | vol: 0.1 ether,
216 | tau: 182.5 days, // 0.499668028775402643 years
217 | inv: inv
218 | }),
219 | 0.16904834360300908 ether,
220 | GET_X_ERROR_REL,
221 | "getX-8.125266343"
222 | );
223 | assertApproxEqRel(
224 | Invariant.getX({
225 | R_y: 0.9888888888888 ether,
226 | stk: 10 ether,
227 | vol: 0.1 ether,
228 | tau: 182.5 days, // 0.499668028775402643 years
229 | inv: inv
230 | }),
231 | 0.888240006888906376 ether,
232 | GET_X_ERROR_REL,
233 | "getX-0.9888888888888"
234 | );
235 | }
236 |
237 | /// @dev `y = KΦ(Φ⁻¹(1-x) - σ√τ) + k`
238 | /// calculator: {stk}*normalcdlower(normalicdlower(1-{R_x}) - {vol}sqrt({debugDays(tau)}))
239 | /// https://keisan.casio.com/calculator
240 | function test_getY() public {
241 | int256 inv = 0;
242 | assertApproxEqRel(
243 | Invariant.getY({
244 | R_x: 0.5 ether,
245 | stk: 10 ether,
246 | vol: 0.1 ether,
247 | tau: 365 days, // 0.999336057550805286 years
248 | inv: inv
249 | }),
250 | 4.60185342615210335 ether,
251 | GET_Y_ERROR_REL,
252 | "getY-365-days"
253 | );
254 | assertApproxEqRel(
255 | Invariant.getY({
256 | R_x: 0.5 ether,
257 | stk: 10 ether,
258 | vol: 0.1 ether,
259 | tau: 1 days, // 0.002737907006988507 years
260 | inv: inv
261 | }),
262 | 4.97912543516404356 ether,
263 | GET_Y_ERROR_REL,
264 | "getY-1-days"
265 | );
266 | assertApproxEqRel(
267 | Invariant.getY({
268 | R_x: 0.5 ether,
269 | stk: 10 ether,
270 | vol: 0.1 ether,
271 | tau: 1 hours, // 0.000114079458624521 years
272 | inv: inv
273 | }),
274 | 4.99573897866220608 ether,
275 | GET_Y_ERROR_REL,
276 | "getY-1-hours"
277 | );
278 | assertApproxEqRel(
279 | Invariant.getY({
280 | R_x: 0.5 ether,
281 | stk: 10 ether,
282 | vol: 0.1 ether,
283 | tau: 10 minutes, // 0.000019013243104086 years
284 | inv: inv
285 | }),
286 | 4.99826044504759416 ether,
287 | GET_Y_ERROR_REL,
288 | "getY-10-minutes"
289 | );
290 |
291 | assertApproxEqRel(
292 | Invariant.getY({
293 | R_x: 0.234235235 ether,
294 | stk: 10 ether,
295 | vol: 0.1 ether,
296 | tau: 182.5 days, // 0.499668028775402643 years
297 | inv: inv
298 | }),
299 | 7.43535169031051685 ether,
300 | GET_Y_ERROR_REL,
301 | "getY-0.234235235"
302 | );
303 | assertApproxEqRel(
304 | Invariant.getY({
305 | R_x: 0.155634675745745 ether,
306 | stk: 10 ether,
307 | vol: 0.1 ether,
308 | tau: 182.5 days, // 0.499668028775402643 years
309 | inv: inv
310 | }),
311 | 8.2687166403107352 ether,
312 | GET_Y_ERROR_REL,
313 | "getY-0.155634675745745"
314 | );
315 | assertApproxEqRel(
316 | Invariant.getY({
317 | R_x: 0.8125266343 ether,
318 | stk: 10 ether,
319 | vol: 0.1 ether,
320 | tau: 182.5 days, // 0.499668028775402643 years
321 | inv: inv
322 | }),
323 | 1.6904834360300908 ether,
324 | GET_Y_ERROR_REL,
325 | "getY-0.8125266343"
326 | );
327 | assertApproxEqRel(
328 | Invariant.getY({
329 | R_x: 0.9888888888888 ether,
330 | stk: 10 ether,
331 | vol: 0.1 ether,
332 | tau: 182.5 days, // 0.499668028775402643 years
333 | inv: inv
334 | }),
335 | 0.092057918358111211 ether,
336 | GET_Y_ERROR_REL,
337 | "getY-0.9888888888888"
338 | );
339 |
340 | assertApproxEqRel(
341 | Invariant.getY({
342 | R_x: 0.00000000002 ether,
343 | stk: 10 ether,
344 | vol: 0.1 ether,
345 | tau: 182.5 days, // 0.499668028775402643 years
346 | inv: inv
347 | }),
348 | 9.99999999967851372 ether,
349 | GET_Y_ERROR_REL,
350 | "getY-0.00000000002"
351 | );
352 | }
353 |
354 | function testReference_getY_Equality(
355 | uint256 asset,
356 | uint256 strike,
357 | uint256 sigma,
358 | uint256 tau
359 | ) public {
360 | HelperInvariant.Args memory args = HelperInvariant.Args(
361 | _base(asset),
362 | _strike(strike),
363 | _sigma(sigma),
364 | _tau(tau, block.timestamp)
365 | );
366 |
367 | uint256 actual = Invariant.getY(args.x, args.K, args.o, args.t, 0);
368 | uint256 expected = Ref.getY(args.x, args.K, args.o, args.t, 0);
369 | assertEq(actual, expected, "getY-inequality");
370 | }
371 |
372 | function testReference_getX_Equality(
373 | uint256 quote,
374 | uint256 strike,
375 | uint256 sigma,
376 | uint256 tau
377 | ) public {
378 | strike = _strike(strike);
379 | sigma = _sigma(sigma);
380 | tau = _tau(tau, block.timestamp);
381 | quote = _quote(quote, strike);
382 | HelperInvariant.Args memory args = HelperInvariant.Args(
383 | quote,
384 | strike,
385 | sigma,
386 | tau
387 | );
388 |
389 | uint256 actual = Invariant.getX(args.x, args.K, args.o, args.t, 0);
390 | uint256 expected = Ref.getX(args.x, args.K, args.o, args.t, 0);
391 | assertApproxEqAbs(actual, expected, 1 ether - 1e6, "getX-inequality");
392 | }
393 |
394 | function testReference_invariant_Equality(
395 | uint256 quote,
396 | uint256 asset,
397 | uint256 strike,
398 | uint256 sigma,
399 | uint256 tau
400 | ) public {
401 | HelperInvariant.Args memory args = HelperInvariant.Args(
402 | _base(asset),
403 | _strike(strike),
404 | _sigma(sigma),
405 | _tau(tau, block.timestamp)
406 | );
407 |
408 | quote = _quote(quote, strike);
409 |
410 | int256 actual = Invariant.invariant(
411 | quote,
412 | args.x,
413 | args.K,
414 | args.o,
415 | args.t
416 | );
417 | int256 expected = Ref.invariant(quote, args.x, args.K, args.o, args.t);
418 | assertEq(actual, expected, "invariant-inequality");
419 | }
420 |
421 | function _base(uint256 asset) internal view returns (uint256) {
422 | return bound(asset, 0, uint256(Invariant.ONE)); // Between 0 and 1e18. Todo: fix for token decimals.
423 | }
424 |
425 | function _quote(uint256 quote, uint256 strike)
426 | internal
427 | view
428 | returns (uint256)
429 | {
430 | return bound(quote, 0, strike); // Between 0 and strike.
431 | }
432 |
433 | function _strike(uint256 strike) internal view returns (uint256) {
434 | return bound(strike, 1, type(uint128).max - 1); // Between 1 and 2^128 - 1.
435 | }
436 |
437 | function _sigma(uint256 sigma) internal view returns (uint256) {
438 | return bound(sigma, 1, type(uint24).max - 1); // Between 1 and (2^24 - 1).
439 | }
440 |
441 | function _tau(uint256 tau, uint256 time) internal view returns (uint256) {
442 | return bound(tau, time, (type(uint32).max - 1)); // Between block.timestamp and 2^32 - 1, in units of years.
443 | }
444 |
445 | function getArgs() internal pure returns (HelperInvariant.Args memory) {
446 | HelperInvariant.Args memory args = HelperInvariant.Args(
447 | 308537538726e6,
448 | 1e18,
449 | 1e18,
450 | 1e18
451 | );
452 | return args;
453 | }
454 |
455 | function testGetYGas() public logs_gas {
456 | uint256 actual = HelperInvariant.getY(getArgs());
457 | actual;
458 | }
459 |
460 | function testGetXGas() public logs_gas {
461 | uint256 y = 308537538726e6;
462 | HelperInvariant.Args memory args = getArgs();
463 | args.x = y;
464 | uint256 actual = HelperInvariant.getX(args);
465 | actual;
466 | }
467 |
468 | function testHelperInvariantGas() public logs_gas {
469 | uint256 y = 308537538726e6;
470 | int256 actual = HelperInvariant.invariant(getArgs(), y);
471 | actual;
472 | y;
473 | }
474 |
475 | function testReferenceGetYGas() public logs_gas {
476 | HelperInvariant.Args memory args = getArgs();
477 | uint256 actual = Ref.getY(args.x, args.K, args.o, args.t, 0);
478 | actual;
479 | }
480 |
481 | function testReferenceGetXGas() public logs_gas {
482 | uint256 y = 308537538726e6;
483 | HelperInvariant.Args memory args = getArgs();
484 | uint256 actual = Ref.getX(y, args.K, args.o, args.t, 0);
485 | actual;
486 | }
487 |
488 | function testReferenceHelperInvariantGas() public logs_gas {
489 | uint256 y = 308537538726e6;
490 | HelperInvariant.Args memory args = getArgs();
491 | int256 actual = Ref.invariant(y, args.x, args.K, args.o, args.t);
492 | actual;
493 | y;
494 | }
495 |
496 | function testFuzzInvariant(
497 | uint256 quote,
498 | uint256 asset,
499 | uint256 strike,
500 | uint256 sigma,
501 | uint256 tau
502 | ) public {
503 | console.log("block time", block.timestamp);
504 | HelperInvariant.Args memory args = HelperInvariant.Args(
505 | _base(asset),
506 | _strike(strike),
507 | _sigma(sigma),
508 | _tau(tau, block.timestamp)
509 | );
510 |
511 | console.log(args.x);
512 | console.log(args.K);
513 | console.log(args.o);
514 | console.log(args.t);
515 | int256 k = HelperInvariant.invariant(args, _quote(quote, args.K));
516 | if (args.t == 0) {
517 | int256 expected = int256(
518 | (args.K * (uint256(Invariant.ONE) - args.x)) / 1e18
519 | );
520 | assertEq(k, expected);
521 | }
522 | emit log_int(k);
523 | }
524 |
525 | function test_getY_upper_bound_returns_zero() public {
526 | HelperInvariant.Args memory args = HelperInvariant.Args({
527 | x: Invariant.WAD,
528 | K: 10e18,
529 | o: 1e4,
530 | t: 365 days
531 | });
532 | uint256 actual = Invariant.getY(args.x, args.K, args.o, args.t, 0);
533 | assertEq(actual, 0, "not-zero");
534 | }
535 |
536 | function test_getY_lower_bound_returns_strike() public {
537 | HelperInvariant.Args memory args = HelperInvariant.Args({
538 | x: 0,
539 | K: 10e18,
540 | o: 1e4,
541 | t: 365 days
542 | });
543 | uint256 actual = Invariant.getY(args.x, args.K, args.o, args.t, 0);
544 | assertEq(actual, args.K, "not-strike");
545 | }
546 | }
547 |
--------------------------------------------------------------------------------
/src/test/Pdf.t.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.13;
3 |
4 | import "forge-std/Test.sol";
5 |
6 | import {Gaussian} from "../Gaussian.sol";
7 |
8 | contract TestPdf is Test {
9 | // todo: fix these tests!! @clemlak
10 | /* function testDiff_pdf(int256 x) public {
11 | vm.assume(x > -2828427124746190093171572875253809907);
12 | vm.assume(x < 2828427124746190093171572875253809907);
13 | string[] memory inputs = new string[](3);
14 | inputs[0] = "./gaussian";
15 | inputs[1] = "pdf";
16 | inputs[2] = vm.toString(x);
17 | bytes memory res = vm.ffi(inputs);
18 | int256 ref = abi.decode(res, (int256));
19 | int256 y = Gaussian.pdf(x);
20 |
21 | // When outputs are very small, we tolerate a larger error
22 | if (ref < 1_000_000_000 && y < 1_000_000_000) {
23 | // 0.1% of difference
24 | assertApproxEqRel(ref, y, 0.001 ether);
25 | } else {
26 | // 0.00005% of difference
27 | assertApproxEqRel(ref, y, 0.0000005 ether);
28 | }
29 | } */
30 | }
31 |
--------------------------------------------------------------------------------
/src/test/Ppf.t.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.13;
3 |
4 | import "forge-std/Test.sol";
5 |
6 | import {Gaussian} from "../Gaussian.sol";
7 |
8 | contract TestPpf is Test {
9 | // todo: fix these tests!! @clemlak
10 | /* function testDiff_ppf(int64 x) public {
11 | vm.assume(x > 0.0000001 ether);
12 | vm.assume(x < 1 ether);
13 | string[] memory inputs = new string[](3);
14 | inputs[0] = "./gaussian";
15 | inputs[1] = "ppf";
16 | inputs[2] = vm.toString(x);
17 | bytes memory res = vm.ffi(inputs);
18 | int256 ref = abi.decode(res, (int256));
19 | int256 y = Gaussian.ppf(int256(x));
20 | // Results have a 0.00165% difference
21 | assertApproxEqRel(ref, y, 0.001 ether);
22 | } */
23 | }
24 |
--------------------------------------------------------------------------------
/test/differential/scripts/gaussian-extended.ts:
--------------------------------------------------------------------------------
1 | export const erfc = function (x) {
2 | var z = Math.abs(x)
3 | var t = 1 / (1 + z / 2)
4 | var r =
5 | t *
6 | Math.exp(
7 | -z * z -
8 | 1.26551223 +
9 | t *
10 | (1.00002368 +
11 | t *
12 | (0.37409196 +
13 | t *
14 | (0.09678418 +
15 | t *
16 | (-0.18628806 +
17 | t * (0.27886807 + t * (-1.13520398 + t * (1.48851587 + t * (-0.82215223 + t * 0.17087277))))))))
18 | )
19 | return x >= 0 ? r : 2 - r
20 | }
21 |
22 | export const ierfc = function (x) {
23 | if (x >= 2) {
24 | return -100
25 | }
26 | if (x <= 0) {
27 | return 100
28 | }
29 |
30 | var xx = x < 1 ? x : 2 - x
31 | var t = Math.sqrt(-2 * Math.log(xx / 2))
32 |
33 | var r = -0.70711 * ((2.30753 + t * 0.27061) / (1 + t * (0.99229 + t * 0.04481)) - t)
34 |
35 | for (var j = 0; j < 2; j++) {
36 | var err = erfc(r) - xx
37 | r += err / (1.12837916709551257 * Math.exp(-(r * r)) - r * err)
38 | }
39 |
40 | var output = x < 1 ? r : -r
41 | return output
42 | }
43 |
--------------------------------------------------------------------------------
/test/differential/scripts/generate.ts:
--------------------------------------------------------------------------------
1 | import * as fs from 'fs'
2 | import { BigNumber, ethers } from 'ethers'
3 | import { formatEther, parseEther } from 'ethers/lib/utils'
4 | import { erfc, ierfc } from './gaussian-extended'
5 | import gaussian from 'gaussian'
6 | import { toBn } from 'evm-bn'
7 | import {
8 | Args,
9 | ArgsBig,
10 | parse as parseArgs,
11 | format as formatInvariant,
12 | formatArgs,
13 | getY,
14 | getX,
15 | invariant,
16 | } from './invariant'
17 |
18 | const cdf = (x) => {
19 | return gaussian(0, 1).cdf(x)
20 | }
21 |
22 | const ppf = (x) => {
23 | return gaussian(0, 1).ppf(x)
24 | }
25 |
26 | function parse(x) {
27 | return toBn(x.toString())._hex
28 | }
29 |
30 | function format(x) {
31 | return +formatEther(x)
32 | }
33 |
34 | const DIFFERENTIAL_FUNCTIONS: Key[] = ['erfc', 'ierfc', 'cdf', 'ppf', 'invariant']
35 | type Key = 'erfc' | 'ierfc' | 'cdf' | 'ppf' | 'invariant'
36 |
37 | type ArgsInputs = [bigint, bigint, bigint, bigint]
38 |
39 | const COMPUTE_FN_INPUTS = {
40 | erfc: function (x) {
41 | if (typeof x === 'undefined') throw new Error(`Value ${x} is undefined`)
42 | return toBn(Math.random().toString())._hex
43 | },
44 | ierfc: function (x) {
45 | if (typeof x === 'undefined') throw new Error(`Value ${x} is undefined`)
46 | return toBn(Math.random().toString())._hex
47 | },
48 | cdf: function (x) {
49 | if (typeof x === 'undefined') throw new Error(`Value ${x} is undefined`)
50 | return toBn(Math.random().toString())._hex
51 | },
52 | ppf: function (x) {
53 | if (typeof x === 'undefined') throw new Error(`Value ${x} is undefined`)
54 | return toBn(Math.random().toString())._hex
55 | },
56 | invariant: function (x): InvariantInput {
57 | x = Math.random()
58 | let K = getStrike(x)
59 | let o = getSigma(x)
60 | let t = getTau(x)
61 | let y = parse(getQuote(x))
62 | let args = parseArgs({ x, K, o, t })
63 | if (typeof x === 'undefined') throw new Error(`Value ${x} is undefined`)
64 | let argsArray: ArgsInputs = Object.keys(args).map((key) => args[key] as bigint) as ArgsInputs
65 | return [y, ...argsArray]
66 | },
67 | }
68 |
69 | type InvariantInput = [string, bigint, bigint, bigint, bigint]
70 |
71 | function getQuote(x: number): number {
72 | return x % (Math.pow(2, 128) - 1)
73 | }
74 |
75 | function getSigma(x: number): number {
76 | return 1 + (x % (Math.pow(2, 24) - 1))
77 | }
78 |
79 | function getStrike(x: number): number {
80 | return 1 + (x % (Math.pow(2, 128) - 1))
81 | }
82 |
83 | function getTau(x: number): number {
84 | return x % (Math.pow(2, 32) - 1)
85 | }
86 |
87 | const COMPUTE_FN_OUTPUTS = {
88 | erfc: function (x) {
89 | return parse(erfc(format(x)))
90 | },
91 | ierfc: function (x) {
92 | return parse(ierfc(format(x)))
93 | },
94 | cdf: function (x) {
95 | return parse(cdf(format(x)))
96 | },
97 | ppf: function (x) {
98 | return parse(ppf(format(x)))
99 | },
100 | invariant: function (x: InvariantInput): string {
101 | let args = { x: x[1], K: x[2], o: x[3], t: x[4] }
102 | return parse(invariant(format(x[0]), formatArgs(args)))
103 | },
104 | }
105 |
106 | COMPUTE_FN_INPUTS['erfc'].bind(COMPUTE_FN_INPUTS)
107 | COMPUTE_FN_OUTPUTS['erfc'].bind(COMPUTE_FN_OUTPUTS)
108 | COMPUTE_FN_INPUTS['ierfc'].bind(COMPUTE_FN_INPUTS)
109 | COMPUTE_FN_OUTPUTS['ierfc'].bind(COMPUTE_FN_OUTPUTS)
110 | COMPUTE_FN_INPUTS['cdf'].bind(COMPUTE_FN_INPUTS)
111 | COMPUTE_FN_OUTPUTS['cdf'].bind(COMPUTE_FN_OUTPUTS)
112 | COMPUTE_FN_INPUTS['ppf'].bind(COMPUTE_FN_INPUTS)
113 | COMPUTE_FN_OUTPUTS['ppf'].bind(COMPUTE_FN_OUTPUTS)
114 | COMPUTE_FN_INPUTS['invariant'].bind(COMPUTE_FN_INPUTS)
115 | COMPUTE_FN_OUTPUTS['invariant'].bind(COMPUTE_FN_OUTPUTS)
116 |
117 | const DEFAULT_START_INDEX = 1
118 | const DEFAULT_END_INDEX = 130
119 | const DEFAULT_ENCODING_TYPE = ['int256[129]']
120 | const INVARIANT_ENCODING_TYPE = ['uint256[5][129]']
121 | const encode = (data: string[], encodeType: string[]) => ethers.utils.defaultAbiCoder.encode(encodeType, [data])
122 |
123 | function writeInput(data: string, key: string) {
124 | if (!fs.existsSync(`../data/${key}/`)) {
125 | fs.mkdirSync(`../data/${key}/`)
126 | }
127 | fs.writeFileSync(`../data/${key}/input`, data)
128 | }
129 |
130 | function writeOutput(data: string, key: string) {
131 | if (!fs.existsSync(`../data/${key}/`)) {
132 | fs.mkdirSync(`../data/${key}/`)
133 | }
134 | fs.writeFileSync(`../data/${key}/output`, data)
135 | }
136 |
137 | function checkSynced() {
138 | if (!fs.existsSync('../data/')) {
139 | fs.mkdirSync('../data/')
140 | }
141 | }
142 |
143 | checkSynced()
144 |
145 | for (const i in DIFFERENTIAL_FUNCTIONS) {
146 | const key = DIFFERENTIAL_FUNCTIONS[i]
147 |
148 | if (!(key in COMPUTE_FN_INPUTS)) continue
149 | if (!(key in COMPUTE_FN_OUTPUTS)) continue
150 |
151 | const inputs: string[] = []
152 | const outputs: string[] = []
153 | for (let i = DEFAULT_START_INDEX; i < DEFAULT_END_INDEX; ++i) {
154 | const inputFunction = COMPUTE_FN_INPUTS[key] as Function
155 | const outputFunction = COMPUTE_FN_OUTPUTS[key] as Function
156 |
157 | const input = inputFunction(i)
158 | const output = outputFunction(input)
159 |
160 | inputs.push(input)
161 | outputs.push(output)
162 | }
163 |
164 | let encodingTypes: string[][] = [] // [input encoding, output encoding]
165 | switch (key) {
166 | case 'invariant':
167 | encodingTypes = [INVARIANT_ENCODING_TYPE, DEFAULT_ENCODING_TYPE]
168 | break
169 | default:
170 | encodingTypes = [DEFAULT_ENCODING_TYPE, DEFAULT_ENCODING_TYPE]
171 | break
172 | }
173 |
174 | const encodedIn = encode(inputs, encodingTypes[0])
175 | const encodedOut = encode(outputs, encodingTypes[1])
176 |
177 | writeInput(encodedIn, key)
178 | writeOutput(encodedOut, key)
179 | }
180 |
--------------------------------------------------------------------------------
/test/differential/scripts/generate_erfc.ts:
--------------------------------------------------------------------------------
1 | import * as fs from 'fs'
2 | import { BigNumber, ethers } from 'ethers'
3 | import { formatEther, parseEther } from 'ethers/lib/utils'
4 | import { erfc, ierfc } from './gaussian-extended'
5 | import gaussian from 'gaussian'
6 |
7 | const cdf = (x) => {
8 | return gaussian(0, 1).cdf(x)
9 | }
10 |
11 | const ppf = (x) => {
12 | return gaussian(0, 1).ppf(x)
13 | }
14 |
15 | function parse(x) {
16 | return parseEther(x.toString())._hex
17 | }
18 |
19 | function format(x) {
20 | return +formatEther(x)
21 | }
22 |
23 | const DIFFERENTIAL_FUNCTIONS: Key[] = ['erfc', 'ierfc', 'cdf', 'pdf']
24 | type Key = 'erfc' | 'ierfc' | 'cdf' | 'pdf'
25 |
26 | const COMPUTE_FN_INPUTS = {
27 | erfc: function (x) {
28 | if (typeof x === 'undefined') throw new Error(`Value ${x} is undefined`)
29 | return parseEther(Math.floor((Math.random() * x) % 2).toString())._hex
30 | },
31 | }
32 |
33 | const COMPUTE_FN_OUTPUTS = {
34 | erfc: function (x) {
35 | return parse(erfc(format(x)))
36 | },
37 | }
38 |
39 | COMPUTE_FN_INPUTS['erfc'].bind(COMPUTE_FN_INPUTS)
40 | COMPUTE_FN_OUTPUTS['erfc'].bind(COMPUTE_FN_OUTPUTS)
41 |
42 | const DEFAULT_START_INDEX = 1
43 | const DEFAULT_END_INDEX = 130
44 | const DEFAULT_ENCODING_TYPE = ['int256[129]']
45 | const encode = (data: string[]) => ethers.utils.defaultAbiCoder.encode(DEFAULT_ENCODING_TYPE, [data])
46 |
47 | function writeInput(data: string, key: string) {
48 | if (!fs.existsSync(`../data/${key}/`)) {
49 | fs.mkdirSync(`../data/${key}/`)
50 | }
51 | fs.writeFileSync(`../data/${key}/input`, data)
52 | }
53 |
54 | function writeOutput(data: string, key: string) {
55 | if (!fs.existsSync(`../data/${key}/`)) {
56 | fs.mkdirSync(`../data/${key}/`)
57 | }
58 | fs.writeFileSync(`../data/${key}/output`, data)
59 | }
60 |
61 | function checkSynced() {
62 | if (!fs.existsSync('../data/')) {
63 | fs.mkdirSync('../data/')
64 | }
65 | }
66 |
67 | checkSynced()
68 |
69 | for (const i in DIFFERENTIAL_FUNCTIONS) {
70 | const key = DIFFERENTIAL_FUNCTIONS[i]
71 |
72 | if (!(key in COMPUTE_FN_INPUTS)) continue
73 | if (!(key in COMPUTE_FN_OUTPUTS)) continue
74 |
75 | const inputs: string[] = []
76 | const outputs: string[] = []
77 | for (let i = DEFAULT_START_INDEX; i < DEFAULT_END_INDEX; ++i) {
78 | const inputFunction = COMPUTE_FN_INPUTS[key] as Function
79 | const outputFunction = COMPUTE_FN_OUTPUTS[key] as Function
80 |
81 | const input = inputFunction(i)
82 | const output = outputFunction(input)
83 |
84 | inputs.push(input)
85 | outputs.push(output)
86 | }
87 |
88 | const encodedIn = encode(inputs)
89 | const encodedOut = encode(outputs)
90 |
91 | writeInput(encodedIn, key)
92 | writeOutput(encodedOut, key)
93 | }
94 |
95 | /* var data: string[] = []
96 | for (var i = 1; i < 130; ++i) {
97 | const random = (Math.random() * i) % 2
98 | const input = parseEther(Math.floor(random).toString())
99 | data.push(input._hex)
100 | }
101 | var outputData = data.map((b) => parse(erfc(format(b))))
102 |
103 | const encodedOutputs = ethers.utils.defaultAbiCoder.encode(['int256[129]'], [outputData])
104 | process.stdout.write(encodedOutputs)
105 |
106 | const encodedInputs = ethers.utils.defaultAbiCoder.encode(['int256[129]'], [data])
107 | if (!fs.existsSync('../data/')) {
108 | fs.mkdirSync('../data/')
109 | }
110 | fs.writeFileSync('../data/output', encodedOutputs)
111 | fs.writeFileSync('../data/input', encodedInputs) */
112 |
--------------------------------------------------------------------------------
/test/differential/scripts/invariant.ts:
--------------------------------------------------------------------------------
1 | import { BigNumberish } from 'ethers'
2 | import { formatEther } from 'ethers/lib/utils'
3 | import gaussian from 'gaussian'
4 |
5 | export interface Args {
6 | x: number
7 | K: number
8 | o: number
9 | t: number
10 | }
11 |
12 | export interface ArgsBig {
13 | x: bigint
14 | K: bigint
15 | o: bigint
16 | t: bigint
17 | }
18 |
19 | export const YEAR = 31556952
20 |
21 | export function parse(args: Args): ArgsBig {
22 | return {
23 | x: BigInt(Math.floor((args.x as number) * 1e18)),
24 | K: BigInt(Math.floor((args.K as number) * 1e18)),
25 | o: BigInt(Math.floor((args.o as number) * 1e18)),
26 | t: BigInt(Math.floor((args.t as number) * YEAR)),
27 | }
28 | }
29 |
30 | export function format(x: BigNumberish | bigint): number {
31 | return +formatEther(x)
32 | }
33 |
34 | export function formatArgs(args: ArgsBig): Args {
35 | return {
36 | x: +formatEther(args.x),
37 | K: +formatEther(args.K),
38 | o: +formatEther(args.o),
39 | t: parseInt(args.t.toString(16), 16) / YEAR,
40 | }
41 | }
42 |
43 | export function getY(args: Args): number {
44 | if (args.t != 0) {
45 | const y = args.K * gaussian(0, 1).cdf(gaussian(0, 1).ppf(1 - args.x) - args.o * Math.sqrt(args.t))
46 | return y
47 | } else {
48 | return args.K * (1 - args.x)
49 | }
50 | }
51 |
52 | export function getX(args: Args): number {
53 | const y = args.x
54 | const x = 1 - gaussian(0, 1).cdf(gaussian(0, 1).ppf((y - 0) / args.K) + args.o * Math.sqrt(args.t))
55 | return x
56 | }
57 |
58 | export function invariant(y: number, args: Args): number {
59 | const y0 = getY(args)
60 | const k = y - y0
61 | return k
62 | }
63 |
--------------------------------------------------------------------------------
/test/differential/scripts/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "solstat-differential",
3 | "version": "1.0.0",
4 | "description": "Scripts to perform solidity/ts gaussian testing.",
5 | "main": "generate.ts",
6 | "author": "",
7 | "license": "MIT",
8 | "dependencies": {
9 | "ethereumjs-util": "^7.1.4",
10 | "ethers": "^5.6.4",
11 | "rlp": "^3.0.0"
12 | },
13 | "devDependencies": {
14 | "evm-bn": "^1.1.1",
15 | "typescript": "^4.6.3"
16 | },
17 | "scripts": {
18 | "generate": "ts-node generate.ts",
19 | "generate-erfc": "ts-node generate_erfc.ts",
20 | "generate-erfc-129": "ts-node generate_erfc.ts"
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/test/differential/scripts/yarn.lock:
--------------------------------------------------------------------------------
1 | # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
2 | # yarn lockfile v1
3 |
4 |
5 | "@ethersproject/abi@5.6.3", "@ethersproject/abi@^5.6.3":
6 | version "5.6.3"
7 | resolved "https://registry.yarnpkg.com/@ethersproject/abi/-/abi-5.6.3.tgz#2d643544abadf6e6b63150508af43475985c23db"
8 | integrity sha512-CxKTdoZY4zDJLWXG6HzNH6znWK0M79WzzxHegDoecE3+K32pzfHOzuXg2/oGSTecZynFgpkjYXNPOqXVJlqClw==
9 | dependencies:
10 | "@ethersproject/address" "^5.6.1"
11 | "@ethersproject/bignumber" "^5.6.2"
12 | "@ethersproject/bytes" "^5.6.1"
13 | "@ethersproject/constants" "^5.6.1"
14 | "@ethersproject/hash" "^5.6.1"
15 | "@ethersproject/keccak256" "^5.6.1"
16 | "@ethersproject/logger" "^5.6.0"
17 | "@ethersproject/properties" "^5.6.0"
18 | "@ethersproject/strings" "^5.6.1"
19 |
20 | "@ethersproject/abstract-provider@5.6.1", "@ethersproject/abstract-provider@^5.6.1":
21 | version "5.6.1"
22 | resolved "https://registry.yarnpkg.com/@ethersproject/abstract-provider/-/abstract-provider-5.6.1.tgz#02ddce150785caf0c77fe036a0ebfcee61878c59"
23 | integrity sha512-BxlIgogYJtp1FS8Muvj8YfdClk3unZH0vRMVX791Z9INBNT/kuACZ9GzaY1Y4yFq+YSy6/w4gzj3HCRKrK9hsQ==
24 | dependencies:
25 | "@ethersproject/bignumber" "^5.6.2"
26 | "@ethersproject/bytes" "^5.6.1"
27 | "@ethersproject/logger" "^5.6.0"
28 | "@ethersproject/networks" "^5.6.3"
29 | "@ethersproject/properties" "^5.6.0"
30 | "@ethersproject/transactions" "^5.6.2"
31 | "@ethersproject/web" "^5.6.1"
32 |
33 | "@ethersproject/abstract-signer@5.6.2", "@ethersproject/abstract-signer@^5.6.2":
34 | version "5.6.2"
35 | resolved "https://registry.yarnpkg.com/@ethersproject/abstract-signer/-/abstract-signer-5.6.2.tgz#491f07fc2cbd5da258f46ec539664713950b0b33"
36 | integrity sha512-n1r6lttFBG0t2vNiI3HoWaS/KdOt8xyDjzlP2cuevlWLG6EX0OwcKLyG/Kp/cuwNxdy/ous+R/DEMdTUwWQIjQ==
37 | dependencies:
38 | "@ethersproject/abstract-provider" "^5.6.1"
39 | "@ethersproject/bignumber" "^5.6.2"
40 | "@ethersproject/bytes" "^5.6.1"
41 | "@ethersproject/logger" "^5.6.0"
42 | "@ethersproject/properties" "^5.6.0"
43 |
44 | "@ethersproject/address@5.6.1", "@ethersproject/address@^5.6.1":
45 | version "5.6.1"
46 | resolved "https://registry.yarnpkg.com/@ethersproject/address/-/address-5.6.1.tgz#ab57818d9aefee919c5721d28cd31fd95eff413d"
47 | integrity sha512-uOgF0kS5MJv9ZvCz7x6T2EXJSzotiybApn4XlOgoTX0xdtyVIJ7pF+6cGPxiEq/dpBiTfMiw7Yc81JcwhSYA0Q==
48 | dependencies:
49 | "@ethersproject/bignumber" "^5.6.2"
50 | "@ethersproject/bytes" "^5.6.1"
51 | "@ethersproject/keccak256" "^5.6.1"
52 | "@ethersproject/logger" "^5.6.0"
53 | "@ethersproject/rlp" "^5.6.1"
54 |
55 | "@ethersproject/base64@5.6.1", "@ethersproject/base64@^5.6.1":
56 | version "5.6.1"
57 | resolved "https://registry.yarnpkg.com/@ethersproject/base64/-/base64-5.6.1.tgz#2c40d8a0310c9d1606c2c37ae3092634b41d87cb"
58 | integrity sha512-qB76rjop6a0RIYYMiB4Eh/8n+Hxu2NIZm8S/Q7kNo5pmZfXhHGHmS4MinUainiBC54SCyRnwzL+KZjj8zbsSsw==
59 | dependencies:
60 | "@ethersproject/bytes" "^5.6.1"
61 |
62 | "@ethersproject/basex@5.6.1", "@ethersproject/basex@^5.6.1":
63 | version "5.6.1"
64 | resolved "https://registry.yarnpkg.com/@ethersproject/basex/-/basex-5.6.1.tgz#badbb2f1d4a6f52ce41c9064f01eab19cc4c5305"
65 | integrity sha512-a52MkVz4vuBXR06nvflPMotld1FJWSj2QT0985v7P/emPZO00PucFAkbcmq2vpVU7Ts7umKiSI6SppiLykVWsA==
66 | dependencies:
67 | "@ethersproject/bytes" "^5.6.1"
68 | "@ethersproject/properties" "^5.6.0"
69 |
70 | "@ethersproject/bignumber@5.6.2", "@ethersproject/bignumber@^5.5.0", "@ethersproject/bignumber@^5.6.2":
71 | version "5.6.2"
72 | resolved "https://registry.yarnpkg.com/@ethersproject/bignumber/-/bignumber-5.6.2.tgz#72a0717d6163fab44c47bcc82e0c550ac0315d66"
73 | integrity sha512-v7+EEUbhGqT3XJ9LMPsKvXYHFc8eHxTowFCG/HgJErmq4XHJ2WR7aeyICg3uTOAQ7Icn0GFHAohXEhxQHq4Ubw==
74 | dependencies:
75 | "@ethersproject/bytes" "^5.6.1"
76 | "@ethersproject/logger" "^5.6.0"
77 | bn.js "^5.2.1"
78 |
79 | "@ethersproject/bytes@5.6.1", "@ethersproject/bytes@^5.6.1":
80 | version "5.6.1"
81 | resolved "https://registry.yarnpkg.com/@ethersproject/bytes/-/bytes-5.6.1.tgz#24f916e411f82a8a60412344bf4a813b917eefe7"
82 | integrity sha512-NwQt7cKn5+ZE4uDn+X5RAXLp46E1chXoaMmrxAyA0rblpxz8t58lVkrHXoRIn0lz1joQElQ8410GqhTqMOwc6g==
83 | dependencies:
84 | "@ethersproject/logger" "^5.6.0"
85 |
86 | "@ethersproject/constants@5.6.1", "@ethersproject/constants@^5.6.1":
87 | version "5.6.1"
88 | resolved "https://registry.yarnpkg.com/@ethersproject/constants/-/constants-5.6.1.tgz#e2e974cac160dd101cf79fdf879d7d18e8cb1370"
89 | integrity sha512-QSq9WVnZbxXYFftrjSjZDUshp6/eKp6qrtdBtUCm0QxCV5z1fG/w3kdlcsjMCQuQHUnAclKoK7XpXMezhRDOLg==
90 | dependencies:
91 | "@ethersproject/bignumber" "^5.6.2"
92 |
93 | "@ethersproject/contracts@5.6.2":
94 | version "5.6.2"
95 | resolved "https://registry.yarnpkg.com/@ethersproject/contracts/-/contracts-5.6.2.tgz#20b52e69ebc1b74274ff8e3d4e508de971c287bc"
96 | integrity sha512-hguUA57BIKi6WY0kHvZp6PwPlWF87MCeB4B7Z7AbUpTxfFXFdn/3b0GmjZPagIHS+3yhcBJDnuEfU4Xz+Ks/8g==
97 | dependencies:
98 | "@ethersproject/abi" "^5.6.3"
99 | "@ethersproject/abstract-provider" "^5.6.1"
100 | "@ethersproject/abstract-signer" "^5.6.2"
101 | "@ethersproject/address" "^5.6.1"
102 | "@ethersproject/bignumber" "^5.6.2"
103 | "@ethersproject/bytes" "^5.6.1"
104 | "@ethersproject/constants" "^5.6.1"
105 | "@ethersproject/logger" "^5.6.0"
106 | "@ethersproject/properties" "^5.6.0"
107 | "@ethersproject/transactions" "^5.6.2"
108 |
109 | "@ethersproject/hash@5.6.1", "@ethersproject/hash@^5.6.1":
110 | version "5.6.1"
111 | resolved "https://registry.yarnpkg.com/@ethersproject/hash/-/hash-5.6.1.tgz#224572ea4de257f05b4abf8ae58b03a67e99b0f4"
112 | integrity sha512-L1xAHurbaxG8VVul4ankNX5HgQ8PNCTrnVXEiFnE9xoRnaUcgfD12tZINtDinSllxPLCtGwguQxJ5E6keE84pA==
113 | dependencies:
114 | "@ethersproject/abstract-signer" "^5.6.2"
115 | "@ethersproject/address" "^5.6.1"
116 | "@ethersproject/bignumber" "^5.6.2"
117 | "@ethersproject/bytes" "^5.6.1"
118 | "@ethersproject/keccak256" "^5.6.1"
119 | "@ethersproject/logger" "^5.6.0"
120 | "@ethersproject/properties" "^5.6.0"
121 | "@ethersproject/strings" "^5.6.1"
122 |
123 | "@ethersproject/hdnode@5.6.2", "@ethersproject/hdnode@^5.6.2":
124 | version "5.6.2"
125 | resolved "https://registry.yarnpkg.com/@ethersproject/hdnode/-/hdnode-5.6.2.tgz#26f3c83a3e8f1b7985c15d1db50dc2903418b2d2"
126 | integrity sha512-tERxW8Ccf9CxW2db3WsN01Qao3wFeRsfYY9TCuhmG0xNpl2IO8wgXU3HtWIZ49gUWPggRy4Yg5axU0ACaEKf1Q==
127 | dependencies:
128 | "@ethersproject/abstract-signer" "^5.6.2"
129 | "@ethersproject/basex" "^5.6.1"
130 | "@ethersproject/bignumber" "^5.6.2"
131 | "@ethersproject/bytes" "^5.6.1"
132 | "@ethersproject/logger" "^5.6.0"
133 | "@ethersproject/pbkdf2" "^5.6.1"
134 | "@ethersproject/properties" "^5.6.0"
135 | "@ethersproject/sha2" "^5.6.1"
136 | "@ethersproject/signing-key" "^5.6.2"
137 | "@ethersproject/strings" "^5.6.1"
138 | "@ethersproject/transactions" "^5.6.2"
139 | "@ethersproject/wordlists" "^5.6.1"
140 |
141 | "@ethersproject/json-wallets@5.6.1", "@ethersproject/json-wallets@^5.6.1":
142 | version "5.6.1"
143 | resolved "https://registry.yarnpkg.com/@ethersproject/json-wallets/-/json-wallets-5.6.1.tgz#3f06ba555c9c0d7da46756a12ac53483fe18dd91"
144 | integrity sha512-KfyJ6Zwz3kGeX25nLihPwZYlDqamO6pfGKNnVMWWfEVVp42lTfCZVXXy5Ie8IZTN0HKwAngpIPi7gk4IJzgmqQ==
145 | dependencies:
146 | "@ethersproject/abstract-signer" "^5.6.2"
147 | "@ethersproject/address" "^5.6.1"
148 | "@ethersproject/bytes" "^5.6.1"
149 | "@ethersproject/hdnode" "^5.6.2"
150 | "@ethersproject/keccak256" "^5.6.1"
151 | "@ethersproject/logger" "^5.6.0"
152 | "@ethersproject/pbkdf2" "^5.6.1"
153 | "@ethersproject/properties" "^5.6.0"
154 | "@ethersproject/random" "^5.6.1"
155 | "@ethersproject/strings" "^5.6.1"
156 | "@ethersproject/transactions" "^5.6.2"
157 | aes-js "3.0.0"
158 | scrypt-js "3.0.1"
159 |
160 | "@ethersproject/keccak256@5.6.1", "@ethersproject/keccak256@^5.6.1":
161 | version "5.6.1"
162 | resolved "https://registry.yarnpkg.com/@ethersproject/keccak256/-/keccak256-5.6.1.tgz#b867167c9b50ba1b1a92bccdd4f2d6bd168a91cc"
163 | integrity sha512-bB7DQHCTRDooZZdL3lk9wpL0+XuG3XLGHLh3cePnybsO3V0rdCAOQGpn/0R3aODmnTOOkCATJiD2hnL+5bwthA==
164 | dependencies:
165 | "@ethersproject/bytes" "^5.6.1"
166 | js-sha3 "0.8.0"
167 |
168 | "@ethersproject/logger@5.6.0", "@ethersproject/logger@^5.6.0":
169 | version "5.6.0"
170 | resolved "https://registry.yarnpkg.com/@ethersproject/logger/-/logger-5.6.0.tgz#d7db1bfcc22fd2e4ab574cba0bb6ad779a9a3e7a"
171 | integrity sha512-BiBWllUROH9w+P21RzoxJKzqoqpkyM1pRnEKG69bulE9TSQD8SAIvTQqIMZmmCO8pUNkgLP1wndX1gKghSpBmg==
172 |
173 | "@ethersproject/networks@5.6.3", "@ethersproject/networks@^5.6.3":
174 | version "5.6.3"
175 | resolved "https://registry.yarnpkg.com/@ethersproject/networks/-/networks-5.6.3.tgz#3ee3ab08f315b433b50c99702eb32e0cf31f899f"
176 | integrity sha512-QZxRH7cA5Ut9TbXwZFiCyuPchdWi87ZtVNHWZd0R6YFgYtes2jQ3+bsslJ0WdyDe0i6QumqtoYqvY3rrQFRZOQ==
177 | dependencies:
178 | "@ethersproject/logger" "^5.6.0"
179 |
180 | "@ethersproject/pbkdf2@5.6.1", "@ethersproject/pbkdf2@^5.6.1":
181 | version "5.6.1"
182 | resolved "https://registry.yarnpkg.com/@ethersproject/pbkdf2/-/pbkdf2-5.6.1.tgz#f462fe320b22c0d6b1d72a9920a3963b09eb82d1"
183 | integrity sha512-k4gRQ+D93zDRPNUfmduNKq065uadC2YjMP/CqwwX5qG6R05f47boq6pLZtV/RnC4NZAYOPH1Cyo54q0c9sshRQ==
184 | dependencies:
185 | "@ethersproject/bytes" "^5.6.1"
186 | "@ethersproject/sha2" "^5.6.1"
187 |
188 | "@ethersproject/properties@5.6.0", "@ethersproject/properties@^5.6.0":
189 | version "5.6.0"
190 | resolved "https://registry.yarnpkg.com/@ethersproject/properties/-/properties-5.6.0.tgz#38904651713bc6bdd5bdd1b0a4287ecda920fa04"
191 | integrity sha512-szoOkHskajKePTJSZ46uHUWWkbv7TzP2ypdEK6jGMqJaEt2sb0jCgfBo0gH0m2HBpRixMuJ6TBRaQCF7a9DoCg==
192 | dependencies:
193 | "@ethersproject/logger" "^5.6.0"
194 |
195 | "@ethersproject/providers@5.6.8":
196 | version "5.6.8"
197 | resolved "https://registry.yarnpkg.com/@ethersproject/providers/-/providers-5.6.8.tgz#22e6c57be215ba5545d3a46cf759d265bb4e879d"
198 | integrity sha512-Wf+CseT/iOJjrGtAOf3ck9zS7AgPmr2fZ3N97r4+YXN3mBePTG2/bJ8DApl9mVwYL+RpYbNxMEkEp4mPGdwG/w==
199 | dependencies:
200 | "@ethersproject/abstract-provider" "^5.6.1"
201 | "@ethersproject/abstract-signer" "^5.6.2"
202 | "@ethersproject/address" "^5.6.1"
203 | "@ethersproject/base64" "^5.6.1"
204 | "@ethersproject/basex" "^5.6.1"
205 | "@ethersproject/bignumber" "^5.6.2"
206 | "@ethersproject/bytes" "^5.6.1"
207 | "@ethersproject/constants" "^5.6.1"
208 | "@ethersproject/hash" "^5.6.1"
209 | "@ethersproject/logger" "^5.6.0"
210 | "@ethersproject/networks" "^5.6.3"
211 | "@ethersproject/properties" "^5.6.0"
212 | "@ethersproject/random" "^5.6.1"
213 | "@ethersproject/rlp" "^5.6.1"
214 | "@ethersproject/sha2" "^5.6.1"
215 | "@ethersproject/strings" "^5.6.1"
216 | "@ethersproject/transactions" "^5.6.2"
217 | "@ethersproject/web" "^5.6.1"
218 | bech32 "1.1.4"
219 | ws "7.4.6"
220 |
221 | "@ethersproject/random@5.6.1", "@ethersproject/random@^5.6.1":
222 | version "5.6.1"
223 | resolved "https://registry.yarnpkg.com/@ethersproject/random/-/random-5.6.1.tgz#66915943981bcd3e11bbd43733f5c3ba5a790255"
224 | integrity sha512-/wtPNHwbmng+5yi3fkipA8YBT59DdkGRoC2vWk09Dci/q5DlgnMkhIycjHlavrvrjJBkFjO/ueLyT+aUDfc4lA==
225 | dependencies:
226 | "@ethersproject/bytes" "^5.6.1"
227 | "@ethersproject/logger" "^5.6.0"
228 |
229 | "@ethersproject/rlp@5.6.1", "@ethersproject/rlp@^5.6.1":
230 | version "5.6.1"
231 | resolved "https://registry.yarnpkg.com/@ethersproject/rlp/-/rlp-5.6.1.tgz#df8311e6f9f24dcb03d59a2bac457a28a4fe2bd8"
232 | integrity sha512-uYjmcZx+DKlFUk7a5/W9aQVaoEC7+1MOBgNtvNg13+RnuUwT4F0zTovC0tmay5SmRslb29V1B7Y5KCri46WhuQ==
233 | dependencies:
234 | "@ethersproject/bytes" "^5.6.1"
235 | "@ethersproject/logger" "^5.6.0"
236 |
237 | "@ethersproject/sha2@5.6.1", "@ethersproject/sha2@^5.6.1":
238 | version "5.6.1"
239 | resolved "https://registry.yarnpkg.com/@ethersproject/sha2/-/sha2-5.6.1.tgz#211f14d3f5da5301c8972a8827770b6fd3e51656"
240 | integrity sha512-5K2GyqcW7G4Yo3uenHegbXRPDgARpWUiXc6RiF7b6i/HXUoWlb7uCARh7BAHg7/qT/Q5ydofNwiZcim9qpjB6g==
241 | dependencies:
242 | "@ethersproject/bytes" "^5.6.1"
243 | "@ethersproject/logger" "^5.6.0"
244 | hash.js "1.1.7"
245 |
246 | "@ethersproject/signing-key@5.6.2", "@ethersproject/signing-key@^5.6.2":
247 | version "5.6.2"
248 | resolved "https://registry.yarnpkg.com/@ethersproject/signing-key/-/signing-key-5.6.2.tgz#8a51b111e4d62e5a62aee1da1e088d12de0614a3"
249 | integrity sha512-jVbu0RuP7EFpw82vHcL+GP35+KaNruVAZM90GxgQnGqB6crhBqW/ozBfFvdeImtmb4qPko0uxXjn8l9jpn0cwQ==
250 | dependencies:
251 | "@ethersproject/bytes" "^5.6.1"
252 | "@ethersproject/logger" "^5.6.0"
253 | "@ethersproject/properties" "^5.6.0"
254 | bn.js "^5.2.1"
255 | elliptic "6.5.4"
256 | hash.js "1.1.7"
257 |
258 | "@ethersproject/solidity@5.6.1":
259 | version "5.6.1"
260 | resolved "https://registry.yarnpkg.com/@ethersproject/solidity/-/solidity-5.6.1.tgz#5845e71182c66d32e6ec5eefd041fca091a473e2"
261 | integrity sha512-KWqVLkUUoLBfL1iwdzUVlkNqAUIFMpbbeH0rgCfKmJp0vFtY4AsaN91gHKo9ZZLkC4UOm3cI3BmMV4N53BOq4g==
262 | dependencies:
263 | "@ethersproject/bignumber" "^5.6.2"
264 | "@ethersproject/bytes" "^5.6.1"
265 | "@ethersproject/keccak256" "^5.6.1"
266 | "@ethersproject/logger" "^5.6.0"
267 | "@ethersproject/sha2" "^5.6.1"
268 | "@ethersproject/strings" "^5.6.1"
269 |
270 | "@ethersproject/strings@5.6.1", "@ethersproject/strings@^5.6.1":
271 | version "5.6.1"
272 | resolved "https://registry.yarnpkg.com/@ethersproject/strings/-/strings-5.6.1.tgz#dbc1b7f901db822b5cafd4ebf01ca93c373f8952"
273 | integrity sha512-2X1Lgk6Jyfg26MUnsHiT456U9ijxKUybz8IM1Vih+NJxYtXhmvKBcHOmvGqpFSVJ0nQ4ZCoIViR8XlRw1v/+Cw==
274 | dependencies:
275 | "@ethersproject/bytes" "^5.6.1"
276 | "@ethersproject/constants" "^5.6.1"
277 | "@ethersproject/logger" "^5.6.0"
278 |
279 | "@ethersproject/transactions@5.6.2", "@ethersproject/transactions@^5.6.2":
280 | version "5.6.2"
281 | resolved "https://registry.yarnpkg.com/@ethersproject/transactions/-/transactions-5.6.2.tgz#793a774c01ced9fe7073985bb95a4b4e57a6370b"
282 | integrity sha512-BuV63IRPHmJvthNkkt9G70Ullx6AcM+SDc+a8Aw/8Yew6YwT51TcBKEp1P4oOQ/bP25I18JJr7rcFRgFtU9B2Q==
283 | dependencies:
284 | "@ethersproject/address" "^5.6.1"
285 | "@ethersproject/bignumber" "^5.6.2"
286 | "@ethersproject/bytes" "^5.6.1"
287 | "@ethersproject/constants" "^5.6.1"
288 | "@ethersproject/keccak256" "^5.6.1"
289 | "@ethersproject/logger" "^5.6.0"
290 | "@ethersproject/properties" "^5.6.0"
291 | "@ethersproject/rlp" "^5.6.1"
292 | "@ethersproject/signing-key" "^5.6.2"
293 |
294 | "@ethersproject/units@5.6.1":
295 | version "5.6.1"
296 | resolved "https://registry.yarnpkg.com/@ethersproject/units/-/units-5.6.1.tgz#ecc590d16d37c8f9ef4e89e2005bda7ddc6a4e6f"
297 | integrity sha512-rEfSEvMQ7obcx3KWD5EWWx77gqv54K6BKiZzKxkQJqtpriVsICrktIQmKl8ReNToPeIYPnFHpXvKpi068YFZXw==
298 | dependencies:
299 | "@ethersproject/bignumber" "^5.6.2"
300 | "@ethersproject/constants" "^5.6.1"
301 | "@ethersproject/logger" "^5.6.0"
302 |
303 | "@ethersproject/wallet@5.6.2":
304 | version "5.6.2"
305 | resolved "https://registry.yarnpkg.com/@ethersproject/wallet/-/wallet-5.6.2.tgz#cd61429d1e934681e413f4bc847a5f2f87e3a03c"
306 | integrity sha512-lrgh0FDQPuOnHcF80Q3gHYsSUODp6aJLAdDmDV0xKCN/T7D99ta1jGVhulg3PY8wiXEngD0DfM0I2XKXlrqJfg==
307 | dependencies:
308 | "@ethersproject/abstract-provider" "^5.6.1"
309 | "@ethersproject/abstract-signer" "^5.6.2"
310 | "@ethersproject/address" "^5.6.1"
311 | "@ethersproject/bignumber" "^5.6.2"
312 | "@ethersproject/bytes" "^5.6.1"
313 | "@ethersproject/hash" "^5.6.1"
314 | "@ethersproject/hdnode" "^5.6.2"
315 | "@ethersproject/json-wallets" "^5.6.1"
316 | "@ethersproject/keccak256" "^5.6.1"
317 | "@ethersproject/logger" "^5.6.0"
318 | "@ethersproject/properties" "^5.6.0"
319 | "@ethersproject/random" "^5.6.1"
320 | "@ethersproject/signing-key" "^5.6.2"
321 | "@ethersproject/transactions" "^5.6.2"
322 | "@ethersproject/wordlists" "^5.6.1"
323 |
324 | "@ethersproject/web@5.6.1", "@ethersproject/web@^5.6.1":
325 | version "5.6.1"
326 | resolved "https://registry.yarnpkg.com/@ethersproject/web/-/web-5.6.1.tgz#6e2bd3ebadd033e6fe57d072db2b69ad2c9bdf5d"
327 | integrity sha512-/vSyzaQlNXkO1WV+RneYKqCJwualcUdx/Z3gseVovZP0wIlOFcCE1hkRhKBH8ImKbGQbMl9EAAyJFrJu7V0aqA==
328 | dependencies:
329 | "@ethersproject/base64" "^5.6.1"
330 | "@ethersproject/bytes" "^5.6.1"
331 | "@ethersproject/logger" "^5.6.0"
332 | "@ethersproject/properties" "^5.6.0"
333 | "@ethersproject/strings" "^5.6.1"
334 |
335 | "@ethersproject/wordlists@5.6.1", "@ethersproject/wordlists@^5.6.1":
336 | version "5.6.1"
337 | resolved "https://registry.yarnpkg.com/@ethersproject/wordlists/-/wordlists-5.6.1.tgz#1e78e2740a8a21e9e99947e47979d72e130aeda1"
338 | integrity sha512-wiPRgBpNbNwCQFoCr8bcWO8o5I810cqO6mkdtKfLKFlLxeCWcnzDi4Alu8iyNzlhYuS9npCwivMbRWF19dyblw==
339 | dependencies:
340 | "@ethersproject/bytes" "^5.6.1"
341 | "@ethersproject/hash" "^5.6.1"
342 | "@ethersproject/logger" "^5.6.0"
343 | "@ethersproject/properties" "^5.6.0"
344 | "@ethersproject/strings" "^5.6.1"
345 |
346 | "@types/bn.js@^5.1.0":
347 | version "5.1.0"
348 | resolved "https://registry.yarnpkg.com/@types/bn.js/-/bn.js-5.1.0.tgz#32c5d271503a12653c62cf4d2b45e6eab8cebc68"
349 | integrity sha512-QSSVYj7pYFN49kW77o2s9xTCwZ8F2xLbjLLSEVh8D2F4JUhZtPAGOFLTD+ffqksBx/u4cE/KImFjyhqCjn/LIA==
350 | dependencies:
351 | "@types/node" "*"
352 |
353 | "@types/node@*":
354 | version "17.0.35"
355 | resolved "https://registry.yarnpkg.com/@types/node/-/node-17.0.35.tgz#635b7586086d51fb40de0a2ec9d1014a5283ba4a"
356 | integrity sha512-vu1SrqBjbbZ3J6vwY17jBs8Sr/BKA+/a/WtjRG+whKg1iuLFOosq872EXS0eXWILdO36DHQQeku/ZcL6hz2fpg==
357 |
358 | "@types/pbkdf2@^3.0.0":
359 | version "3.1.0"
360 | resolved "https://registry.yarnpkg.com/@types/pbkdf2/-/pbkdf2-3.1.0.tgz#039a0e9b67da0cdc4ee5dab865caa6b267bb66b1"
361 | integrity sha512-Cf63Rv7jCQ0LaL8tNXmEyqTHuIJxRdlS5vMh1mj5voN4+QFhVZnlZruezqpWYDiJ8UTzhP0VmeLXCmBk66YrMQ==
362 | dependencies:
363 | "@types/node" "*"
364 |
365 | "@types/secp256k1@^4.0.1":
366 | version "4.0.3"
367 | resolved "https://registry.yarnpkg.com/@types/secp256k1/-/secp256k1-4.0.3.tgz#1b8e55d8e00f08ee7220b4d59a6abe89c37a901c"
368 | integrity sha512-Da66lEIFeIz9ltsdMZcpQvmrmmoqrfju8pm1BH8WbYjZSwUgCwXLb9C+9XYogwBITnbsSaMdVPb2ekf7TV+03w==
369 | dependencies:
370 | "@types/node" "*"
371 |
372 | aes-js@3.0.0:
373 | version "3.0.0"
374 | resolved "https://registry.yarnpkg.com/aes-js/-/aes-js-3.0.0.tgz#e21df10ad6c2053295bcbb8dab40b09dbea87e4d"
375 | integrity sha512-H7wUZRn8WpTq9jocdxQ2c8x2sKo9ZVmzfRE13GiNJXfp7NcKYEdvl3vspKjXox6RIG2VtaRe4JFvxG4rqp2Zuw==
376 |
377 | base-x@^3.0.2:
378 | version "3.0.9"
379 | resolved "https://registry.yarnpkg.com/base-x/-/base-x-3.0.9.tgz#6349aaabb58526332de9f60995e548a53fe21320"
380 | integrity sha512-H7JU6iBHTal1gp56aKoaa//YUxEaAOUiydvrV/pILqIHXTtqxSkATOnDA2u+jZ/61sD+L/412+7kzXRtWukhpQ==
381 | dependencies:
382 | safe-buffer "^5.0.1"
383 |
384 | bech32@1.1.4:
385 | version "1.1.4"
386 | resolved "https://registry.yarnpkg.com/bech32/-/bech32-1.1.4.tgz#e38c9f37bf179b8eb16ae3a772b40c356d4832e9"
387 | integrity sha512-s0IrSOzLlbvX7yp4WBfPITzpAU8sqQcpsmwXDiKwrG4r491vwCO/XpejasRNl0piBMe/DvP4Tz0mIS/X1DPJBQ==
388 |
389 | blakejs@^1.1.0:
390 | version "1.2.1"
391 | resolved "https://registry.yarnpkg.com/blakejs/-/blakejs-1.2.1.tgz#5057e4206eadb4a97f7c0b6e197a505042fc3814"
392 | integrity sha512-QXUSXI3QVc/gJME0dBpXrag1kbzOqCjCX8/b54ntNyW6sjtoqxqRk3LTmXzaJoh71zMsDCjM+47jS7XiwN/+fQ==
393 |
394 | bn.js@^4.11.9:
395 | version "4.12.0"
396 | resolved "https://registry.yarnpkg.com/bn.js/-/bn.js-4.12.0.tgz#775b3f278efbb9718eec7361f483fb36fbbfea88"
397 | integrity sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==
398 |
399 | bn.js@^5.1.2, bn.js@^5.2.0, bn.js@^5.2.1:
400 | version "5.2.1"
401 | resolved "https://registry.yarnpkg.com/bn.js/-/bn.js-5.2.1.tgz#0bc527a6a0d18d0aa8d5b0538ce4a77dccfa7b70"
402 | integrity sha512-eXRvHzWyYPBuB4NBy0cmYQjGitUrtqwbvlzP3G6VFnNRbsZQIxQ10PbKKHt8gZ/HW/D/747aDl+QkDqg3KQLMQ==
403 |
404 | brorand@^1.1.0:
405 | version "1.1.0"
406 | resolved "https://registry.yarnpkg.com/brorand/-/brorand-1.1.0.tgz#12c25efe40a45e3c323eb8675a0a0ce57b22371f"
407 | integrity sha512-cKV8tMCEpQs4hK/ik71d6LrPOnpkpGBR0wzxqr68g2m/LB2GxVYQroAjMJZRVM1Y4BCjCKc3vAamxSzOY2RP+w==
408 |
409 | browserify-aes@^1.2.0:
410 | version "1.2.0"
411 | resolved "https://registry.yarnpkg.com/browserify-aes/-/browserify-aes-1.2.0.tgz#326734642f403dabc3003209853bb70ad428ef48"
412 | integrity sha512-+7CHXqGuspUn/Sl5aO7Ea0xWGAtETPXNSAjHo48JfLdPWcMng33Xe4znFvQweqc/uzk5zSOI3H52CYnjCfb5hA==
413 | dependencies:
414 | buffer-xor "^1.0.3"
415 | cipher-base "^1.0.0"
416 | create-hash "^1.1.0"
417 | evp_bytestokey "^1.0.3"
418 | inherits "^2.0.1"
419 | safe-buffer "^5.0.1"
420 |
421 | bs58@^4.0.0:
422 | version "4.0.1"
423 | resolved "https://registry.yarnpkg.com/bs58/-/bs58-4.0.1.tgz#be161e76c354f6f788ae4071f63f34e8c4f0a42a"
424 | integrity sha512-Ok3Wdf5vOIlBrgCvTq96gBkJw+JUEzdBgyaza5HLtPm7yTHkjRy8+JzNyHF7BHa0bNWOQIp3m5YF0nnFcOIKLw==
425 | dependencies:
426 | base-x "^3.0.2"
427 |
428 | bs58check@^2.1.2:
429 | version "2.1.2"
430 | resolved "https://registry.yarnpkg.com/bs58check/-/bs58check-2.1.2.tgz#53b018291228d82a5aa08e7d796fdafda54aebfc"
431 | integrity sha512-0TS1jicxdU09dwJMNZtVAfzPi6Q6QeN0pM1Fkzrjn+XYHvzMKPU3pHVpva+769iNVSfIYWf7LJ6WR+BuuMf8cA==
432 | dependencies:
433 | bs58 "^4.0.0"
434 | create-hash "^1.1.0"
435 | safe-buffer "^5.1.2"
436 |
437 | buffer-xor@^1.0.3:
438 | version "1.0.3"
439 | resolved "https://registry.yarnpkg.com/buffer-xor/-/buffer-xor-1.0.3.tgz#26e61ed1422fb70dd42e6e36729ed51d855fe8d9"
440 | integrity sha512-571s0T7nZWK6vB67HI5dyUF7wXiNcfaPPPTl6zYCNApANjIvYJTg7hlud/+cJpdAhS7dVzqMLmfhfHR3rAcOjQ==
441 |
442 | cipher-base@^1.0.0, cipher-base@^1.0.1, cipher-base@^1.0.3:
443 | version "1.0.4"
444 | resolved "https://registry.yarnpkg.com/cipher-base/-/cipher-base-1.0.4.tgz#8760e4ecc272f4c363532f926d874aae2c1397de"
445 | integrity sha512-Kkht5ye6ZGmwv40uUDZztayT2ThLQGfnj/T71N/XzeZeo3nf8foyW7zGTsPYkEya3m5f3cAypH+qe7YOrM1U2Q==
446 | dependencies:
447 | inherits "^2.0.1"
448 | safe-buffer "^5.0.1"
449 |
450 | create-hash@^1.1.0, create-hash@^1.1.2, create-hash@^1.2.0:
451 | version "1.2.0"
452 | resolved "https://registry.yarnpkg.com/create-hash/-/create-hash-1.2.0.tgz#889078af11a63756bcfb59bd221996be3a9ef196"
453 | integrity sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg==
454 | dependencies:
455 | cipher-base "^1.0.1"
456 | inherits "^2.0.1"
457 | md5.js "^1.3.4"
458 | ripemd160 "^2.0.1"
459 | sha.js "^2.4.0"
460 |
461 | create-hmac@^1.1.4, create-hmac@^1.1.7:
462 | version "1.1.7"
463 | resolved "https://registry.yarnpkg.com/create-hmac/-/create-hmac-1.1.7.tgz#69170c78b3ab957147b2b8b04572e47ead2243ff"
464 | integrity sha512-MJG9liiZ+ogc4TzUwuvbER1JRdgvUFSB5+VR/g5h82fGaIRWMWddtKBHi7/sVhfjQZ6SehlyhvQYrcYkaUIpLg==
465 | dependencies:
466 | cipher-base "^1.0.3"
467 | create-hash "^1.1.0"
468 | inherits "^2.0.1"
469 | ripemd160 "^2.0.0"
470 | safe-buffer "^5.0.1"
471 | sha.js "^2.4.8"
472 |
473 | elliptic@6.5.4, elliptic@^6.5.4:
474 | version "6.5.4"
475 | resolved "https://registry.yarnpkg.com/elliptic/-/elliptic-6.5.4.tgz#da37cebd31e79a1367e941b592ed1fbebd58abbb"
476 | integrity sha512-iLhC6ULemrljPZb+QutR5TQGB+pdW6KGD5RSegS+8sorOZT+rdQFbsQFJgvN3eRqNALqJer4oQ16YvJHlU8hzQ==
477 | dependencies:
478 | bn.js "^4.11.9"
479 | brorand "^1.1.0"
480 | hash.js "^1.0.0"
481 | hmac-drbg "^1.0.1"
482 | inherits "^2.0.4"
483 | minimalistic-assert "^1.0.1"
484 | minimalistic-crypto-utils "^1.0.1"
485 |
486 | ethereum-cryptography@^0.1.3:
487 | version "0.1.3"
488 | resolved "https://registry.yarnpkg.com/ethereum-cryptography/-/ethereum-cryptography-0.1.3.tgz#8d6143cfc3d74bf79bbd8edecdf29e4ae20dd191"
489 | integrity sha512-w8/4x1SGGzc+tO97TASLja6SLd3fRIK2tLVcV2Gx4IB21hE19atll5Cq9o3d0ZmAYC/8aw0ipieTSiekAea4SQ==
490 | dependencies:
491 | "@types/pbkdf2" "^3.0.0"
492 | "@types/secp256k1" "^4.0.1"
493 | blakejs "^1.1.0"
494 | browserify-aes "^1.2.0"
495 | bs58check "^2.1.2"
496 | create-hash "^1.2.0"
497 | create-hmac "^1.1.7"
498 | hash.js "^1.1.7"
499 | keccak "^3.0.0"
500 | pbkdf2 "^3.0.17"
501 | randombytes "^2.1.0"
502 | safe-buffer "^5.1.2"
503 | scrypt-js "^3.0.0"
504 | secp256k1 "^4.0.1"
505 | setimmediate "^1.0.5"
506 |
507 | ethereumjs-util@^7.1.4:
508 | version "7.1.4"
509 | resolved "https://registry.yarnpkg.com/ethereumjs-util/-/ethereumjs-util-7.1.4.tgz#a6885bcdd92045b06f596c7626c3e89ab3312458"
510 | integrity sha512-p6KmuPCX4mZIqsQzXfmSx9Y0l2hqf+VkAiwSisW3UKUFdk8ZkAt+AYaor83z2nSi6CU2zSsXMlD80hAbNEGM0A==
511 | dependencies:
512 | "@types/bn.js" "^5.1.0"
513 | bn.js "^5.1.2"
514 | create-hash "^1.1.2"
515 | ethereum-cryptography "^0.1.3"
516 | rlp "^2.2.4"
517 |
518 | ethers@^5.6.4:
519 | version "5.6.8"
520 | resolved "https://registry.yarnpkg.com/ethers/-/ethers-5.6.8.tgz#d36b816b4896341a80a8bbd2a44e8cb6e9b98dd4"
521 | integrity sha512-YxIGaltAOdvBFPZwIkyHnXbW40f1r8mHUgapW6dxkO+6t7H6wY8POUn0Kbxrd/N7I4hHxyi7YCddMAH/wmho2w==
522 | dependencies:
523 | "@ethersproject/abi" "5.6.3"
524 | "@ethersproject/abstract-provider" "5.6.1"
525 | "@ethersproject/abstract-signer" "5.6.2"
526 | "@ethersproject/address" "5.6.1"
527 | "@ethersproject/base64" "5.6.1"
528 | "@ethersproject/basex" "5.6.1"
529 | "@ethersproject/bignumber" "5.6.2"
530 | "@ethersproject/bytes" "5.6.1"
531 | "@ethersproject/constants" "5.6.1"
532 | "@ethersproject/contracts" "5.6.2"
533 | "@ethersproject/hash" "5.6.1"
534 | "@ethersproject/hdnode" "5.6.2"
535 | "@ethersproject/json-wallets" "5.6.1"
536 | "@ethersproject/keccak256" "5.6.1"
537 | "@ethersproject/logger" "5.6.0"
538 | "@ethersproject/networks" "5.6.3"
539 | "@ethersproject/pbkdf2" "5.6.1"
540 | "@ethersproject/properties" "5.6.0"
541 | "@ethersproject/providers" "5.6.8"
542 | "@ethersproject/random" "5.6.1"
543 | "@ethersproject/rlp" "5.6.1"
544 | "@ethersproject/sha2" "5.6.1"
545 | "@ethersproject/signing-key" "5.6.2"
546 | "@ethersproject/solidity" "5.6.1"
547 | "@ethersproject/strings" "5.6.1"
548 | "@ethersproject/transactions" "5.6.2"
549 | "@ethersproject/units" "5.6.1"
550 | "@ethersproject/wallet" "5.6.2"
551 | "@ethersproject/web" "5.6.1"
552 | "@ethersproject/wordlists" "5.6.1"
553 |
554 | evm-bn@^1.1.1:
555 | version "1.1.1"
556 | resolved "https://registry.yarnpkg.com/evm-bn/-/evm-bn-1.1.1.tgz#ebb0f4ad50294ff5920b0bef5371023ff57a735b"
557 | integrity sha512-Ou+Y5WgoUnjRZjXYpKBTs3orakrpCw6rvj1jiOp2e1kBLVxpnxDywlO1N6hrCbYguPbFlbEWqo0OLzuFXp+UDw==
558 | dependencies:
559 | "@ethersproject/bignumber" "^5.5.0"
560 | from-exponential "^1.1.1"
561 |
562 | evp_bytestokey@^1.0.3:
563 | version "1.0.3"
564 | resolved "https://registry.yarnpkg.com/evp_bytestokey/-/evp_bytestokey-1.0.3.tgz#7fcbdb198dc71959432efe13842684e0525acb02"
565 | integrity sha512-/f2Go4TognH/KvCISP7OUsHn85hT9nUkxxA9BEWxFn+Oj9o8ZNLm/40hdlgSLyuOimsrTKLUMEorQexp/aPQeA==
566 | dependencies:
567 | md5.js "^1.3.4"
568 | safe-buffer "^5.1.1"
569 |
570 | from-exponential@^1.1.1:
571 | version "1.1.1"
572 | resolved "https://registry.yarnpkg.com/from-exponential/-/from-exponential-1.1.1.tgz#41caff748d22e9c195713802cdac31acbe4b1b83"
573 | integrity sha512-VBE7f5OVnYwdgB3LHa+Qo29h8qVpxhVO9Trlc+AWm+/XNAgks1tAwMFHb33mjeiof77GglsJzeYF7OqXrROP/A==
574 |
575 | hash-base@^3.0.0:
576 | version "3.1.0"
577 | resolved "https://registry.yarnpkg.com/hash-base/-/hash-base-3.1.0.tgz#55c381d9e06e1d2997a883b4a3fddfe7f0d3af33"
578 | integrity sha512-1nmYp/rhMDiE7AYkDw+lLwlAzz0AntGIe51F3RfFfEqyQ3feY2eI/NcwC6umIQVOASPMsWJLJScWKSSvzL9IVA==
579 | dependencies:
580 | inherits "^2.0.4"
581 | readable-stream "^3.6.0"
582 | safe-buffer "^5.2.0"
583 |
584 | hash.js@1.1.7, hash.js@^1.0.0, hash.js@^1.0.3, hash.js@^1.1.7:
585 | version "1.1.7"
586 | resolved "https://registry.yarnpkg.com/hash.js/-/hash.js-1.1.7.tgz#0babca538e8d4ee4a0f8988d68866537a003cf42"
587 | integrity sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA==
588 | dependencies:
589 | inherits "^2.0.3"
590 | minimalistic-assert "^1.0.1"
591 |
592 | hmac-drbg@^1.0.1:
593 | version "1.0.1"
594 | resolved "https://registry.yarnpkg.com/hmac-drbg/-/hmac-drbg-1.0.1.tgz#d2745701025a6c775a6c545793ed502fc0c649a1"
595 | integrity sha1-0nRXAQJabHdabFRXk+1QL8DGSaE=
596 | dependencies:
597 | hash.js "^1.0.3"
598 | minimalistic-assert "^1.0.0"
599 | minimalistic-crypto-utils "^1.0.1"
600 |
601 | inherits@^2.0.1, inherits@^2.0.3, inherits@^2.0.4:
602 | version "2.0.4"
603 | resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c"
604 | integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==
605 |
606 | js-sha3@0.8.0:
607 | version "0.8.0"
608 | resolved "https://registry.yarnpkg.com/js-sha3/-/js-sha3-0.8.0.tgz#b9b7a5da73afad7dedd0f8c463954cbde6818840"
609 | integrity sha512-gF1cRrHhIzNfToc802P800N8PpXS+evLLXfsVpowqmAFR9uwbi89WvXg2QspOmXL8QL86J4T1EpFu+yUkwJY3Q==
610 |
611 | keccak@^3.0.0:
612 | version "3.0.2"
613 | resolved "https://registry.yarnpkg.com/keccak/-/keccak-3.0.2.tgz#4c2c6e8c54e04f2670ee49fa734eb9da152206e0"
614 | integrity sha512-PyKKjkH53wDMLGrvmRGSNWgmSxZOUqbnXwKL9tmgbFYA1iAYqW21kfR7mZXV0MlESiefxQQE9X9fTa3X+2MPDQ==
615 | dependencies:
616 | node-addon-api "^2.0.0"
617 | node-gyp-build "^4.2.0"
618 | readable-stream "^3.6.0"
619 |
620 | md5.js@^1.3.4:
621 | version "1.3.5"
622 | resolved "https://registry.yarnpkg.com/md5.js/-/md5.js-1.3.5.tgz#b5d07b8e3216e3e27cd728d72f70d1e6a342005f"
623 | integrity sha512-xitP+WxNPcTTOgnTJcrhM0xvdPepipPSf3I8EIpGKeFLjt3PlJLIDG3u8EX53ZIubkb+5U2+3rELYpEhHhzdkg==
624 | dependencies:
625 | hash-base "^3.0.0"
626 | inherits "^2.0.1"
627 | safe-buffer "^5.1.2"
628 |
629 | minimalistic-assert@^1.0.0, minimalistic-assert@^1.0.1:
630 | version "1.0.1"
631 | resolved "https://registry.yarnpkg.com/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz#2e194de044626d4a10e7f7fbc00ce73e83e4d5c7"
632 | integrity sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==
633 |
634 | minimalistic-crypto-utils@^1.0.1:
635 | version "1.0.1"
636 | resolved "https://registry.yarnpkg.com/minimalistic-crypto-utils/-/minimalistic-crypto-utils-1.0.1.tgz#f6c00c1c0b082246e5c4d99dfb8c7c083b2b582a"
637 | integrity sha1-9sAMHAsIIkblxNmd+4x8CDsrWCo=
638 |
639 | node-addon-api@^2.0.0:
640 | version "2.0.2"
641 | resolved "https://registry.yarnpkg.com/node-addon-api/-/node-addon-api-2.0.2.tgz#432cfa82962ce494b132e9d72a15b29f71ff5d32"
642 | integrity sha512-Ntyt4AIXyaLIuMHF6IOoTakB3K+RWxwtsHNRxllEoA6vPwP9o4866g6YWDLUdnucilZhmkxiHwHr11gAENw+QA==
643 |
644 | node-gyp-build@^4.2.0:
645 | version "4.4.0"
646 | resolved "https://registry.yarnpkg.com/node-gyp-build/-/node-gyp-build-4.4.0.tgz#42e99687ce87ddeaf3a10b99dc06abc11021f3f4"
647 | integrity sha512-amJnQCcgtRVw9SvoebO3BKGESClrfXGCUTX9hSn1OuGQTQBOZmVd0Z0OlecpuRksKvbsUqALE8jls/ErClAPuQ==
648 |
649 | pbkdf2@^3.0.17:
650 | version "3.1.2"
651 | resolved "https://registry.yarnpkg.com/pbkdf2/-/pbkdf2-3.1.2.tgz#dd822aa0887580e52f1a039dc3eda108efae3075"
652 | integrity sha512-iuh7L6jA7JEGu2WxDwtQP1ddOpaJNC4KlDEFfdQajSGgGPNi4OyDc2R7QnbY2bR9QjBVGwgvTdNJZoE7RaxUMA==
653 | dependencies:
654 | create-hash "^1.1.2"
655 | create-hmac "^1.1.4"
656 | ripemd160 "^2.0.1"
657 | safe-buffer "^5.0.1"
658 | sha.js "^2.4.8"
659 |
660 | randombytes@^2.1.0:
661 | version "2.1.0"
662 | resolved "https://registry.yarnpkg.com/randombytes/-/randombytes-2.1.0.tgz#df6f84372f0270dc65cdf6291349ab7a473d4f2a"
663 | integrity sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==
664 | dependencies:
665 | safe-buffer "^5.1.0"
666 |
667 | readable-stream@^3.6.0:
668 | version "3.6.0"
669 | resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-3.6.0.tgz#337bbda3adc0706bd3e024426a286d4b4b2c9198"
670 | integrity sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==
671 | dependencies:
672 | inherits "^2.0.3"
673 | string_decoder "^1.1.1"
674 | util-deprecate "^1.0.1"
675 |
676 | ripemd160@^2.0.0, ripemd160@^2.0.1:
677 | version "2.0.2"
678 | resolved "https://registry.yarnpkg.com/ripemd160/-/ripemd160-2.0.2.tgz#a1c1a6f624751577ba5d07914cbc92850585890c"
679 | integrity sha512-ii4iagi25WusVoiC4B4lq7pbXfAp3D9v5CwfkY33vffw2+pkDjY1D8GaN7spsxvCSx8dkPqOZCEZyfxcmJG2IA==
680 | dependencies:
681 | hash-base "^3.0.0"
682 | inherits "^2.0.1"
683 |
684 | rlp@^2.2.4:
685 | version "2.2.7"
686 | resolved "https://registry.yarnpkg.com/rlp/-/rlp-2.2.7.tgz#33f31c4afac81124ac4b283e2bd4d9720b30beaf"
687 | integrity sha512-d5gdPmgQ0Z+AklL2NVXr/IoSjNZFfTVvQWzL/AM2AOcSzYP2xjlb0AC8YyCLc41MSNf6P6QVtjgPdmVtzb+4lQ==
688 | dependencies:
689 | bn.js "^5.2.0"
690 |
691 | rlp@^3.0.0:
692 | version "3.0.0"
693 | resolved "https://registry.yarnpkg.com/rlp/-/rlp-3.0.0.tgz#5a60725ca4314a3a165feecca1836e4f2c1e2343"
694 | integrity sha512-PD6U2PGk6Vq2spfgiWZdomLvRGDreBLxi5jv5M8EpRo3pU6VEm31KO+HFxE18Q3vgqfDrQ9pZA3FP95rkijNKw==
695 |
696 | safe-buffer@^5.0.1, safe-buffer@^5.1.0, safe-buffer@^5.1.1, safe-buffer@^5.1.2, safe-buffer@^5.2.0, safe-buffer@~5.2.0:
697 | version "5.2.1"
698 | resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6"
699 | integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==
700 |
701 | scrypt-js@3.0.1, scrypt-js@^3.0.0:
702 | version "3.0.1"
703 | resolved "https://registry.yarnpkg.com/scrypt-js/-/scrypt-js-3.0.1.tgz#d314a57c2aef69d1ad98a138a21fe9eafa9ee312"
704 | integrity sha512-cdwTTnqPu0Hyvf5in5asVdZocVDTNRmR7XEcJuIzMjJeSHybHl7vpB66AzwTaIg6CLSbtjcxc8fqcySfnTkccA==
705 |
706 | secp256k1@^4.0.1:
707 | version "4.0.3"
708 | resolved "https://registry.yarnpkg.com/secp256k1/-/secp256k1-4.0.3.tgz#c4559ecd1b8d3c1827ed2d1b94190d69ce267303"
709 | integrity sha512-NLZVf+ROMxwtEj3Xa562qgv2BK5e2WNmXPiOdVIPLgs6lyTzMvBq0aWTYMI5XCP9jZMVKOcqZLw/Wc4vDkuxhA==
710 | dependencies:
711 | elliptic "^6.5.4"
712 | node-addon-api "^2.0.0"
713 | node-gyp-build "^4.2.0"
714 |
715 | setimmediate@^1.0.5:
716 | version "1.0.5"
717 | resolved "https://registry.yarnpkg.com/setimmediate/-/setimmediate-1.0.5.tgz#290cbb232e306942d7d7ea9b83732ab7856f8285"
718 | integrity sha1-KQy7Iy4waULX1+qbg3Mqt4VvgoU=
719 |
720 | sha.js@^2.4.0, sha.js@^2.4.8:
721 | version "2.4.11"
722 | resolved "https://registry.yarnpkg.com/sha.js/-/sha.js-2.4.11.tgz#37a5cf0b81ecbc6943de109ba2960d1b26584ae7"
723 | integrity sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ==
724 | dependencies:
725 | inherits "^2.0.1"
726 | safe-buffer "^5.0.1"
727 |
728 | string_decoder@^1.1.1:
729 | version "1.3.0"
730 | resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.3.0.tgz#42f114594a46cf1a8e30b0a84f56c78c3edac21e"
731 | integrity sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==
732 | dependencies:
733 | safe-buffer "~5.2.0"
734 |
735 | typescript@^4.6.3:
736 | version "4.7.2"
737 | resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.7.2.tgz#1f9aa2ceb9af87cca227813b4310fff0b51593c4"
738 | integrity sha512-Mamb1iX2FDUpcTRzltPxgWMKy3fhg0TN378ylbktPGPK/99KbDtMQ4W1hwgsbPAsG3a0xKa1vmw4VKZQbkvz5A==
739 |
740 | util-deprecate@^1.0.1:
741 | version "1.0.2"
742 | resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf"
743 | integrity sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=
744 |
745 | ws@7.4.6:
746 | version "7.4.6"
747 | resolved "https://registry.yarnpkg.com/ws/-/ws-7.4.6.tgz#5654ca8ecdeee47c33a9a4bf6d28e2be2980377c"
748 | integrity sha512-YmhHDO4MzaDLB+M9ym/mDA5z0naX8j7SIlT8f8z+I0VtzsRbekxEutHSme7NPS2qE8StCYQNUnfWdXta/Yu85A==
749 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es2018",
4 | "module": "commonjs",
5 | "strict": true,
6 | "esModuleInterop": true,
7 | "resolveJsonModule": true,
8 | "preserveSymlinks": true,
9 | "outDir": "dist",
10 | "noImplicitAny": false
11 | },
12 | "ts-node": {
13 | "files": true
14 | },
15 | "include": ["./test/**/*.ts", "./scripts", "./types"],
16 | "exclude": ["./test/differential/scripts/node_modules"]
17 | }
18 |
--------------------------------------------------------------------------------