├── .env.example
├── .gas-snapshot
├── .github
└── workflows
│ └── ci.yml
├── .gitignore
├── .gitmodules
├── LICENSE
├── README.md
├── assets
└── readme.jpg
├── foundry.toml
├── script
└── Deploy.s.sol
├── src
├── BytesAux.sol
└── BytesLib.sol
├── test
└── BytesAux.t.sol
└── utils
├── flatten.sh
├── rename.sh
├── run_script.sh
└── run_script_local.sh
/.env.example:
--------------------------------------------------------------------------------
1 | # RPC URL sourced by scripts
2 | RPC_URL=
3 |
4 | # The deployment private key sourced by scripts
5 | DEPLOYER_KEY=
--------------------------------------------------------------------------------
/.gas-snapshot:
--------------------------------------------------------------------------------
1 | BytesAuxTest:testWriteAndReadNoOffset(uint128) (runs: 256, μ: 27074, ~: 28862)
2 | BytesAuxTest:testWriteAndReadWithOffset(uint128,uint64) (runs: 256, μ: 34014, ~: 34014)
3 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: ci
2 |
3 | on: [push]
4 |
5 | jobs:
6 | tests:
7 | name: Forge Testing
8 | runs-on: ubuntu-latest
9 | steps:
10 | - uses: actions/checkout@v2
11 |
12 | - name: Install Foundry
13 | uses: onbjerg/foundry-toolchain@v1
14 | with:
15 | version: nightly
16 |
17 | - name: Install Dependencies
18 | run: forge install
19 |
20 | - name: Run Tests
21 | run: FOUNDRY_PROFILE=ci forge test
22 |
23 | snapshot:
24 | runs-on: ubuntu-latest
25 | steps:
26 | - uses: actions/checkout@v2
27 |
28 | - name: Install Foundry
29 | uses: foundry-rs/foundry-toolchain@v1
30 | with:
31 | version: nightly
32 |
33 | - name: Install deps
34 | run: forge install
35 |
36 | - name: Check contract sizes
37 | run: forge build --sizes
38 |
39 |
40 | slither:
41 | runs-on: ubuntu-latest
42 | strategy:
43 | matrix:
44 | node-version: [16.x]
45 | steps:
46 | - uses: actions/checkout@v2
47 |
48 | - name: Install Foundry
49 | uses: foundry-rs/foundry-toolchain@v1
50 | with:
51 | version: nightly
52 |
53 | - name: Install deps
54 | run: forge install
55 |
56 | - name: Check contract sizes
57 | run: forge build --sizes
58 |
59 |
60 | scripts:
61 | strategy:
62 | fail-fast: true
63 | name: Run Unix Scripts
64 | runs-on: ubuntu-latest
65 | steps:
66 | - uses: actions/checkout@v3
67 | with:
68 | submodules: recursive
69 |
70 | - name: Install Foundry
71 | uses: foundry-rs/foundry-toolchain@v1
72 | with:
73 | version: nightly
74 |
75 | - name: Run Forge build
76 | run: |
77 | forge --version
78 | forge build --sizes
79 | id: build
80 | continue-on-error: true
81 |
82 | - name: Run scripts
83 | run: |
84 | ls -lsa
85 | ls script/
86 | for file in script/*; do
87 | forge script $file
88 | done
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | cache/
2 | out/
3 |
4 | # Ignore Environment Variables!
5 | .env
6 | .env.prod
7 |
8 | # Ignore all vscode settings
9 | .vscode/
10 |
11 | # Ignore flattened files
12 | flattened.txt
13 |
14 | broadcast
15 | .DS_Store
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "lib/solmate"]
2 | path = lib/solmate
3 | url = https://github.com/rari-capital/solmate
4 | [submodule "lib/forge-std"]
5 | path = lib/forge-std
6 | url = https://github.com/foundry-rs/forge-std
7 |
--------------------------------------------------------------------------------
/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
637 | by 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 | # BytesAux / Aux Bytes Example
2 |
3 | ### This example shows you how to store uint as bytes in aux and retrieve the value you've stored.
4 |
5 | It does use assembly so shoutout to @vectorized for helping me figure out exactly what to do. I'm not trying to be optimised here I just realised that this would be very painful in Solidity.
6 |
7 | ### What is in here?
8 |
9 | 1) An example of storing a uint128 in a bytes24 object as well as a way to retrieve this value
10 |
11 |
12 | 2) An example of storing a uint128 and a uint64 inside a bytes24 object as well as a way to retrieve both values at once and a way to retrieve only the latter value
13 |
14 |
15 | *This should teach you how we can use bytes to store information in `aux` and retrieve it later.*
16 |
17 | Arby
--------------------------------------------------------------------------------
/assets/readme.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/The-Arbiter/Aux-Bytes-Example/e41813eb5b398e2194ffd7db7e1884e6c2ea31ac/assets/readme.jpg
--------------------------------------------------------------------------------
/foundry.toml:
--------------------------------------------------------------------------------
1 | # Foundry Configuration File
2 | # Default definitions: https://github.com/gakonst/foundry/blob/b7917fa8491aedda4dd6db53fbb206ea233cd531/config/src/lib.rs#L782
3 | # See more config options at: https://github.com/gakonst/foundry/tree/master/config
4 |
5 | # The Default Profile
6 | [profile.default]
7 | solc_version = '0.8.15'
8 | auto_detect_solc = false
9 | optimizer = true
10 | optimizer_runs = 1_000
11 | fuzz_runs = 256
12 | remappings = [
13 | "forge-std=lib/forge-std/src/",
14 | "solmate=lib/solmate/src/",
15 | ]
16 |
17 | # Extreme Fuzzing CI Profile :P
18 | [profile.ci]
19 | fuzz_runs = 100_000
--------------------------------------------------------------------------------
/script/Deploy.s.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-only
2 | pragma solidity ^0.8.13;
3 |
4 | import {Script} from 'forge-std/Script.sol';
5 |
6 |
7 |
8 | /// @notice A very simple deployment script
9 | contract Deploy is Script {
10 |
11 | /// @notice The main script entrypoint
12 |
13 | function run() external {
14 |
15 | }
16 | }
--------------------------------------------------------------------------------
/src/BytesAux.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-only
2 | pragma solidity ^0.8.13;
3 |
4 | import "src/BytesLib.sol";
5 |
6 | /// @title Store uint as bytes and recover it
7 | contract BytesAux{
8 |
9 | // We use BytesLib since I am not comfortable dealing with bytes in assembly right now.
10 | using BytesLib for bytes;
11 |
12 | struct DemoStruct{
13 | uint64 number;
14 | bytes24 aux;
15 | }
16 |
17 | DemoStruct demo;
18 |
19 | constructor() {}
20 |
21 | function _uint128ToBytes24(uint128 value_) internal pure returns (bytes24 result) {
22 | assembly {
23 | // `bytes24` is left aligned.
24 | // We shift `value` left by 128, which left aligns it,
25 | // and also cleans out the upper 128 bits if they aren't clean.
26 | result := shl(128, value_)
27 | }
28 | }
29 |
30 | function _uint128And64ToBytes24(uint128 firstValue_, uint64 secondValue_)
31 | internal
32 | pure
33 | returns
34 | (bytes24 result)
35 | {
36 | assembly {
37 | // `bytes24` is left aligned.
38 | result := or(
39 | // We shift `firstValue_` left by 128, which left aligns it,
40 | // and also cleans out the upper 128 bits if they aren't clean.
41 | shl(128, firstValue_),
42 | // We shift `secondValue_` left by 192 to clean up any upper bits,
43 | // and shift it back by 128 into position in the `bytes24`.
44 | shr(128, shl(192, secondValue_))
45 | )
46 | }
47 | }
48 |
49 | function _bytes24ToUint128And64(bytes24 value_)
50 | internal
51 | pure
52 | returns
53 | (uint128 firstValue, uint64 secondValue)
54 | {
55 | assembly {
56 | firstValue := shr(128, value_)
57 | secondValue := shr(192, shl(128, value_))
58 | }
59 | }
60 |
61 | function _bytes24OffsetValueToUint128(bytes24 value, uint8 offset) internal pure returns (uint128 result) {
62 | assembly {
63 | result := shr(add(128, offset), shl(offset, value))
64 | }
65 | }
66 |
67 | function _bytes24OffsetValueToUint64(bytes24 value, uint8 offset) internal pure returns (uint64 result) {
68 | assembly {
69 | result := shr(add(192, offset), shl(offset, value))
70 | }
71 | }
72 |
73 | // Sets the aux bytes to a uint value
74 | function setAux(uint128 value_) external returns (bool status){
75 | demo.aux = _uint128ToBytes24(value_);
76 | status = true;
77 | }
78 |
79 | // Sets the aux bytes to two uint values of different sizes
80 | function setAuxMultiple(uint128 firstValue_, uint64 secondValue_) external returns (bool status){
81 | demo.aux = _uint128And64ToBytes24(firstValue_, secondValue_);
82 | status = true;
83 | }
84 |
85 | // Gets the uint value based on the aux bytes
86 | function getAuxFirstValueOnly() external view returns (uint128 firstValue){
87 | (firstValue, ) = _bytes24ToUint128And64(demo.aux);
88 | }
89 |
90 | /// @dev Gets the uint value based on the aux bytes
91 | function getAuxMultiple() external view returns (uint128 firstValue, uint64 secondValue){
92 | return _bytes24ToUint128And64(demo.aux);
93 | }
94 |
95 | // Gets the second uint value based on the aux bytes and an offset
96 | function getAuxSecondValueOnly() external view returns (uint64 secondValue){
97 | (, secondValue) = _bytes24ToUint128And64(demo.aux);
98 | }
99 |
100 |
101 | }
102 |
--------------------------------------------------------------------------------
/src/BytesLib.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: Unlicense
2 | /*
3 | * @title Solidity Bytes Arrays Utils
4 | * @author Gonçalo Sá
5 | *
6 | * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
7 | * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
8 | */
9 | pragma solidity >=0.8.0 <0.9.0;
10 |
11 |
12 | library BytesLib {
13 | function concat(
14 | bytes memory _preBytes,
15 | bytes memory _postBytes
16 | )
17 | internal
18 | pure
19 | returns (bytes memory)
20 | {
21 | bytes memory tempBytes;
22 |
23 | assembly {
24 | // Get a location of some free memory and store it in tempBytes as
25 | // Solidity does for memory variables.
26 | tempBytes := mload(0x40)
27 |
28 | // Store the length of the first bytes array at the beginning of
29 | // the memory for tempBytes.
30 | let length := mload(_preBytes)
31 | mstore(tempBytes, length)
32 |
33 | // Maintain a memory counter for the current write location in the
34 | // temp bytes array by adding the 32 bytes for the array length to
35 | // the starting location.
36 | let mc := add(tempBytes, 0x20)
37 | // Stop copying when the memory counter reaches the length of the
38 | // first bytes array.
39 | let end := add(mc, length)
40 |
41 | for {
42 | // Initialize a copy counter to the start of the _preBytes data,
43 | // 32 bytes into its memory.
44 | let cc := add(_preBytes, 0x20)
45 | } lt(mc, end) {
46 | // Increase both counters by 32 bytes each iteration.
47 | mc := add(mc, 0x20)
48 | cc := add(cc, 0x20)
49 | } {
50 | // Write the _preBytes data into the tempBytes memory 32 bytes
51 | // at a time.
52 | mstore(mc, mload(cc))
53 | }
54 |
55 | // Add the length of _postBytes to the current length of tempBytes
56 | // and store it as the new length in the first 32 bytes of the
57 | // tempBytes memory.
58 | length := mload(_postBytes)
59 | mstore(tempBytes, add(length, mload(tempBytes)))
60 |
61 | // Move the memory counter back from a multiple of 0x20 to the
62 | // actual end of the _preBytes data.
63 | mc := end
64 | // Stop copying when the memory counter reaches the new combined
65 | // length of the arrays.
66 | end := add(mc, length)
67 |
68 | for {
69 | let cc := add(_postBytes, 0x20)
70 | } lt(mc, end) {
71 | mc := add(mc, 0x20)
72 | cc := add(cc, 0x20)
73 | } {
74 | mstore(mc, mload(cc))
75 | }
76 |
77 | // Update the free-memory pointer by padding our last write location
78 | // to 32 bytes: add 31 bytes to the end of tempBytes to move to the
79 | // next 32 byte block, then round down to the nearest multiple of
80 | // 32. If the sum of the length of the two arrays is zero then add
81 | // one before rounding down to leave a blank 32 bytes (the length block with 0).
82 | mstore(0x40, and(
83 | add(add(end, iszero(add(length, mload(_preBytes)))), 31),
84 | not(31) // Round down to the nearest 32 bytes.
85 | ))
86 | }
87 |
88 | return tempBytes;
89 | }
90 |
91 | function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
92 | assembly {
93 | // Read the first 32 bytes of _preBytes storage, which is the length
94 | // of the array. (We don't need to use the offset into the slot
95 | // because arrays use the entire slot.)
96 | let fslot := sload(_preBytes.slot)
97 | // Arrays of 31 bytes or less have an even value in their slot,
98 | // while longer arrays have an odd value. The actual length is
99 | // the slot divided by two for odd values, and the lowest order
100 | // byte divided by two for even values.
101 | // If the slot is even, bitwise and the slot with 255 and divide by
102 | // two to get the length. If the slot is odd, bitwise and the slot
103 | // with -1 and divide by two.
104 | let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
105 | let mlength := mload(_postBytes)
106 | let newlength := add(slength, mlength)
107 | // slength can contain both the length and contents of the array
108 | // if length < 32 bytes so let's prepare for that
109 | // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
110 | switch add(lt(slength, 32), lt(newlength, 32))
111 | case 2 {
112 | // Since the new array still fits in the slot, we just need to
113 | // update the contents of the slot.
114 | // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
115 | sstore(
116 | _preBytes.slot,
117 | // all the modifications to the slot are inside this
118 | // next block
119 | add(
120 | // we can just add to the slot contents because the
121 | // bytes we want to change are the LSBs
122 | fslot,
123 | add(
124 | mul(
125 | div(
126 | // load the bytes from memory
127 | mload(add(_postBytes, 0x20)),
128 | // zero all bytes to the right
129 | exp(0x100, sub(32, mlength))
130 | ),
131 | // and now shift left the number of bytes to
132 | // leave space for the length in the slot
133 | exp(0x100, sub(32, newlength))
134 | ),
135 | // increase length by the double of the memory
136 | // bytes length
137 | mul(mlength, 2)
138 | )
139 | )
140 | )
141 | }
142 | case 1 {
143 | // The stored value fits in the slot, but the combined value
144 | // will exceed it.
145 | // get the keccak hash to get the contents of the array
146 | mstore(0x0, _preBytes.slot)
147 | let sc := add(keccak256(0x0, 0x20), div(slength, 32))
148 |
149 | // save new length
150 | sstore(_preBytes.slot, add(mul(newlength, 2), 1))
151 |
152 | // The contents of the _postBytes array start 32 bytes into
153 | // the structure. Our first read should obtain the `submod`
154 | // bytes that can fit into the unused space in the last word
155 | // of the stored array. To get this, we read 32 bytes starting
156 | // from `submod`, so the data we read overlaps with the array
157 | // contents by `submod` bytes. Masking the lowest-order
158 | // `submod` bytes allows us to add that value directly to the
159 | // stored value.
160 |
161 | let submod := sub(32, slength)
162 | let mc := add(_postBytes, submod)
163 | let end := add(_postBytes, mlength)
164 | let mask := sub(exp(0x100, submod), 1)
165 |
166 | sstore(
167 | sc,
168 | add(
169 | and(
170 | fslot,
171 | 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
172 | ),
173 | and(mload(mc), mask)
174 | )
175 | )
176 |
177 | for {
178 | mc := add(mc, 0x20)
179 | sc := add(sc, 1)
180 | } lt(mc, end) {
181 | sc := add(sc, 1)
182 | mc := add(mc, 0x20)
183 | } {
184 | sstore(sc, mload(mc))
185 | }
186 |
187 | mask := exp(0x100, sub(mc, end))
188 |
189 | sstore(sc, mul(div(mload(mc), mask), mask))
190 | }
191 | default {
192 | // get the keccak hash to get the contents of the array
193 | mstore(0x0, _preBytes.slot)
194 | // Start copying to the last used word of the stored array.
195 | let sc := add(keccak256(0x0, 0x20), div(slength, 32))
196 |
197 | // save new length
198 | sstore(_preBytes.slot, add(mul(newlength, 2), 1))
199 |
200 | // Copy over the first `submod` bytes of the new data as in
201 | // case 1 above.
202 | let slengthmod := mod(slength, 32)
203 | let mlengthmod := mod(mlength, 32)
204 | let submod := sub(32, slengthmod)
205 | let mc := add(_postBytes, submod)
206 | let end := add(_postBytes, mlength)
207 | let mask := sub(exp(0x100, submod), 1)
208 |
209 | sstore(sc, add(sload(sc), and(mload(mc), mask)))
210 |
211 | for {
212 | sc := add(sc, 1)
213 | mc := add(mc, 0x20)
214 | } lt(mc, end) {
215 | sc := add(sc, 1)
216 | mc := add(mc, 0x20)
217 | } {
218 | sstore(sc, mload(mc))
219 | }
220 |
221 | mask := exp(0x100, sub(mc, end))
222 |
223 | sstore(sc, mul(div(mload(mc), mask), mask))
224 | }
225 | }
226 | }
227 |
228 | function slice(
229 | bytes memory _bytes,
230 | uint256 _start,
231 | uint256 _length
232 | )
233 | internal
234 | pure
235 | returns (bytes memory)
236 | {
237 | require(_length + 31 >= _length, "slice_overflow");
238 | require(_bytes.length >= _start + _length, "slice_outOfBounds");
239 |
240 | bytes memory tempBytes;
241 |
242 | assembly {
243 | switch iszero(_length)
244 | case 0 {
245 | // Get a location of some free memory and store it in tempBytes as
246 | // Solidity does for memory variables.
247 | tempBytes := mload(0x40)
248 |
249 | // The first word of the slice result is potentially a partial
250 | // word read from the original array. To read it, we calculate
251 | // the length of that partial word and start copying that many
252 | // bytes into the array. The first word we copy will start with
253 | // data we don't care about, but the last `lengthmod` bytes will
254 | // land at the beginning of the contents of the new array. When
255 | // we're done copying, we overwrite the full first word with
256 | // the actual length of the slice.
257 | let lengthmod := and(_length, 31)
258 |
259 | // The multiplication in the next line is necessary
260 | // because when slicing multiples of 32 bytes (lengthmod == 0)
261 | // the following copy loop was copying the origin's length
262 | // and then ending prematurely not copying everything it should.
263 | let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
264 | let end := add(mc, _length)
265 |
266 | for {
267 | // The multiplication in the next line has the same exact purpose
268 | // as the one above.
269 | let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
270 | } lt(mc, end) {
271 | mc := add(mc, 0x20)
272 | cc := add(cc, 0x20)
273 | } {
274 | mstore(mc, mload(cc))
275 | }
276 |
277 | mstore(tempBytes, _length)
278 |
279 | //update free-memory pointer
280 | //allocating the array padded to 32 bytes like the compiler does now
281 | mstore(0x40, and(add(mc, 31), not(31)))
282 | }
283 | //if we want a zero-length slice let's just return a zero-length array
284 | default {
285 | tempBytes := mload(0x40)
286 | //zero out the 32 bytes slice we are about to return
287 | //we need to do it because Solidity does not garbage collect
288 | mstore(tempBytes, 0)
289 |
290 | mstore(0x40, add(tempBytes, 0x20))
291 | }
292 | }
293 |
294 | return tempBytes;
295 | }
296 |
297 | function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
298 | require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
299 | address tempAddress;
300 |
301 | assembly {
302 | tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
303 | }
304 |
305 | return tempAddress;
306 | }
307 |
308 | function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {
309 | require(_bytes.length >= _start + 1 , "toUint8_outOfBounds");
310 | uint8 tempUint;
311 |
312 | assembly {
313 | tempUint := mload(add(add(_bytes, 0x1), _start))
314 | }
315 |
316 | return tempUint;
317 | }
318 |
319 | function toUint16(bytes memory _bytes, uint256 _start) internal pure returns (uint16) {
320 | require(_bytes.length >= _start + 2, "toUint16_outOfBounds");
321 | uint16 tempUint;
322 |
323 | assembly {
324 | tempUint := mload(add(add(_bytes, 0x2), _start))
325 | }
326 |
327 | return tempUint;
328 | }
329 |
330 | function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32) {
331 | require(_bytes.length >= _start + 4, "toUint32_outOfBounds");
332 | uint32 tempUint;
333 |
334 | assembly {
335 | tempUint := mload(add(add(_bytes, 0x4), _start))
336 | }
337 |
338 | return tempUint;
339 | }
340 |
341 | function toUint64(bytes memory _bytes, uint256 _start) internal pure returns (uint64) {
342 | require(_bytes.length >= _start + 8, "toUint64_outOfBounds");
343 | uint64 tempUint;
344 |
345 | assembly {
346 | tempUint := mload(add(add(_bytes, 0x8), _start))
347 | }
348 |
349 | return tempUint;
350 | }
351 |
352 | function toUint96(bytes memory _bytes, uint256 _start) internal pure returns (uint96) {
353 | require(_bytes.length >= _start + 12, "toUint96_outOfBounds");
354 | uint96 tempUint;
355 |
356 | assembly {
357 | tempUint := mload(add(add(_bytes, 0xc), _start))
358 | }
359 |
360 | return tempUint;
361 | }
362 |
363 | function toUint128(bytes memory _bytes, uint256 _start) internal pure returns (uint128) {
364 | require(_bytes.length >= _start + 16, "toUint128_outOfBounds");
365 | uint128 tempUint;
366 |
367 | assembly {
368 | tempUint := mload(add(add(_bytes, 0x10), _start))
369 | }
370 |
371 | return tempUint;
372 | }
373 |
374 | function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {
375 | require(_bytes.length >= _start + 32, "toUint256_outOfBounds");
376 | uint256 tempUint;
377 |
378 | assembly {
379 | tempUint := mload(add(add(_bytes, 0x20), _start))
380 | }
381 |
382 | return tempUint;
383 | }
384 |
385 | function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) {
386 | require(_bytes.length >= _start + 32, "toBytes32_outOfBounds");
387 | bytes32 tempBytes32;
388 |
389 | assembly {
390 | tempBytes32 := mload(add(add(_bytes, 0x20), _start))
391 | }
392 |
393 | return tempBytes32;
394 | }
395 |
396 | function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
397 | bool success = true;
398 |
399 | assembly {
400 | let length := mload(_preBytes)
401 |
402 | // if lengths don't match the arrays are not equal
403 | switch eq(length, mload(_postBytes))
404 | case 1 {
405 | // cb is a circuit breaker in the for loop since there's
406 | // no said feature for inline assembly loops
407 | // cb = 1 - don't breaker
408 | // cb = 0 - break
409 | let cb := 1
410 |
411 | let mc := add(_preBytes, 0x20)
412 | let end := add(mc, length)
413 |
414 | for {
415 | let cc := add(_postBytes, 0x20)
416 | // the next line is the loop condition:
417 | // while(uint256(mc < end) + cb == 2)
418 | } eq(add(lt(mc, end), cb), 2) {
419 | mc := add(mc, 0x20)
420 | cc := add(cc, 0x20)
421 | } {
422 | // if any of these checks fails then arrays are not equal
423 | if iszero(eq(mload(mc), mload(cc))) {
424 | // unsuccess:
425 | success := 0
426 | cb := 0
427 | }
428 | }
429 | }
430 | default {
431 | // unsuccess:
432 | success := 0
433 | }
434 | }
435 |
436 | return success;
437 | }
438 |
439 | function equalStorage(
440 | bytes storage _preBytes,
441 | bytes memory _postBytes
442 | )
443 | internal
444 | view
445 | returns (bool)
446 | {
447 | bool success = true;
448 |
449 | assembly {
450 | // we know _preBytes_offset is 0
451 | let fslot := sload(_preBytes.slot)
452 | // Decode the length of the stored array like in concatStorage().
453 | let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
454 | let mlength := mload(_postBytes)
455 |
456 | // if lengths don't match the arrays are not equal
457 | switch eq(slength, mlength)
458 | case 1 {
459 | // slength can contain both the length and contents of the array
460 | // if length < 32 bytes so let's prepare for that
461 | // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
462 | if iszero(iszero(slength)) {
463 | switch lt(slength, 32)
464 | case 1 {
465 | // blank the last byte which is the length
466 | fslot := mul(div(fslot, 0x100), 0x100)
467 |
468 | if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
469 | // unsuccess:
470 | success := 0
471 | }
472 | }
473 | default {
474 | // cb is a circuit breaker in the for loop since there's
475 | // no said feature for inline assembly loops
476 | // cb = 1 - don't breaker
477 | // cb = 0 - break
478 | let cb := 1
479 |
480 | // get the keccak hash to get the contents of the array
481 | mstore(0x0, _preBytes.slot)
482 | let sc := keccak256(0x0, 0x20)
483 |
484 | let mc := add(_postBytes, 0x20)
485 | let end := add(mc, mlength)
486 |
487 | // the next line is the loop condition:
488 | // while(uint256(mc < end) + cb == 2)
489 | for {} eq(add(lt(mc, end), cb), 2) {
490 | sc := add(sc, 1)
491 | mc := add(mc, 0x20)
492 | } {
493 | if iszero(eq(sload(sc), mload(mc))) {
494 | // unsuccess:
495 | success := 0
496 | cb := 0
497 | }
498 | }
499 | }
500 | }
501 | }
502 | default {
503 | // unsuccess:
504 | success := 0
505 | }
506 | }
507 |
508 | return success;
509 | }
510 | }
--------------------------------------------------------------------------------
/test/BytesAux.t.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-only
2 | pragma solidity ^0.8.13;
3 |
4 | import "forge-std/Test.sol";
5 |
6 | import {BytesAux} from "src/BytesAux.sol";
7 |
8 | contract BytesAuxTest is Test {
9 |
10 | BytesAux bytesAux;
11 |
12 | function setUp() external {
13 | bytesAux = new BytesAux();
14 | }
15 |
16 | // Check that we can use the bytes24 to store a uint128
17 | function testWriteAndReadNoOffset(uint128 value_) public {
18 | // Set the AUX
19 | bool setStatus = bytesAux.setAux(value_);
20 | if(setStatus!=true){
21 | revert("Setter did not return true");
22 | }
23 | // Get the AUX
24 | uint128 storedValue = bytesAux.getAuxFirstValueOnly();
25 | if(storedValue!=value_){
26 | revert("Stored value is not equal to the initial value!");
27 | }
28 | }
29 |
30 | // Check that we can use the bytes24 to store a uint128 (16 bytes) and a uint64 (8 bytes) separately
31 | // We also retrieve them independently
32 | function testWriteAndReadWithOffset(uint128 firstValue_, uint64 secondValue_) public {
33 |
34 | // Set the AUX
35 | bool setStatus = bytesAux.setAuxMultiple(firstValue_,secondValue_);
36 | if(setStatus!=true){
37 | revert("Setter did not return true");
38 | }
39 | // Get the AUX
40 | uint128 storedFirstValue;
41 | uint64 storedSecondValue;
42 | (storedFirstValue, storedSecondValue) = bytesAux.getAuxMultiple();
43 |
44 | console2.log("Stored first value is",storedFirstValue);
45 | console2.log("Stored second value is",storedSecondValue);
46 |
47 | // Check the values
48 | if(storedFirstValue!=firstValue_){
49 | revert("Stored value is not equal to the initial value!");
50 | }
51 | if(storedSecondValue!=secondValue_){
52 | revert("Stored value is not equal to the initial value!");
53 | }
54 |
55 | // Try and get the second value *only* using our custom function
56 | uint64 storedSecondValueAgain = bytesAux.getAuxSecondValueOnly();
57 | if(storedSecondValue!=storedSecondValueAgain){
58 | revert("Stored value is not equal to the second stored value!");
59 | }
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/utils/flatten.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Read the contract name
4 | echo Which contract do you want to flatten \(eg Greeter\)?
5 | read contract
6 |
7 | # Remove an existing flattened contracts
8 | rm -rf flattened.txt
9 |
10 | # FLATTEN
11 | forge flatten ./src/${contract}.sol > flattened.txt
--------------------------------------------------------------------------------
/utils/rename.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Make sed command compatible in both Mac and Linux environments
4 | # Reference: https://stackoverflow.com/a/38595160/8696958
5 | sedi () {
6 | sed --version >/dev/null 2>&1 && sed -i -- "$@" || sed -i "" "$@"
7 | }
8 |
9 | # Read the new repo name
10 | echo Enter your new repo name:
11 | read repo
12 |
13 | # Rename instances of "femplate" to the new repo name in README.md
14 | sedi 's/femplate/'${repo}'/g' 'README.md'
15 | sedi 's/.'${repo}'..https:\/\/github.com\/abigger87\/'${repo}'./[femplate](https:\/\/github.com\/abigger87\/femplate)/g' 'README.md'
16 |
--------------------------------------------------------------------------------
/utils/run_script.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Read the RPC URL
4 | source .env
5 |
6 | # Read script
7 | echo Which script do you want to run?
8 | read script
9 |
10 | # Read script arguments
11 | echo Enter script arguments, or press enter if none:
12 | read -ra args
13 |
14 | # Run the script
15 | echo Running Script: $script...
16 |
17 | # Run the script with interactive inputs
18 | forge script $script \
19 | --rpc-url $RPC_URL \
20 | --broadcast \
21 | -vvvv \
22 | --private-key $DEPLOYER_KEY \
23 | $args
24 |
--------------------------------------------------------------------------------
/utils/run_script_local.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Read the RPC URL
4 | source .env
5 |
6 | ## Fork Mainnet
7 | echo Please wait a few seconds for anvil to fork mainnet and run locally...
8 | anvil --fork-url $RPC_URL &
9 |
10 | # Wait for anvil to fork
11 | sleep 5
12 |
13 | # Read script
14 | echo Which script do you want to run?
15 | read script
16 |
17 | # Read script arguments
18 | echo Enter script arguments, or press enter if none:
19 | read -ra args
20 |
21 | # Run the script
22 | echo Running Script: $script...
23 |
24 | # We specify the anvil url as http://localhost:8545
25 | # We need to specify the sender for our local anvil node
26 | forge script $script \
27 | --fork-url http://localhost:8545 \
28 | --broadcast \
29 | -vvvv \
30 | --sender 0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266 \
31 | --private-key 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 \
32 | $args
33 |
34 | # Once finished, we want to kill our anvil instance running in the background
35 | trap "exit" INT TERM
36 | trap "kill 0" EXIT
37 |
--------------------------------------------------------------------------------