{"owner":"argotorg","repo":"solidity","hasSkills":true,"totalSkillsCount":3,"totalTokensCount":3744,"categories":["plugin-manifest","cursor-rule"],"hasMcp":false,"mcpConfig":null,"found":["tools/yulPhaser/README.md","test/tools/ossfuzz/README.md",".cursorrules (solidity-foundry-cursorrules-prompt-file.mdc)"],"skills":{"tools/yulPhaser/README.md":"## yul-phaser\n`yul-phaser` is an internal tool for finding good sequences of [optimisation steps](/libyul/optimiser/README.md) for Yul optimiser.\n\n### How it works\nThe space of possible solutions to this problem (usually referred to as _phase-ordering problem_) is extremely large and there may even be no single sequence that produces optimal results for all possible programs.\n\nThe tool uses genetic algorithms to find sequences that result in better programs than others and to iteratively refine them.\nThe input is a set of one or more [Yul](/docs/yul.rst) programs and each sequence is applied to all of these programs.\nOptimised programs are given numeric scores according to the selected metric.\n\nOptimisation step sequences are presented in an abbreviated form - as strings of letters where each character represents one step.\nThere's a [table listing available abbreviations in the optimiser docs](/docs/yul.rst#optimization-step-sequence).\n\n### How to use it\nThe application has sensible defaults for most parameters.\nAn invocation can be as simple as:\n\n``` bash\ntools/yul-phaser ../test/libyul/yulOptimizerTests/fullSuite/*.yul \\\n    --random-population 100\n```\n\nThis assumes that you have a working copy of the Solidity repository and you're in the build directory within that working copy.\n\nRun `yul-phaser --help` for a full list of available options.\n\n#### Restarting from a previous state\n`yul-phaser` can save the list of sequences found after each round:\n\n``` bash\ntools/yul-phaser *.yul        \\\n    --random-population   100 \\\n    --population-autosave /tmp/population.txt\n```\n\nIf you stop the application, you can later use the file to continue the search from the point you left off:\n\n``` bash\ntools/yul-phaser *.yul                         \\\n    --population-from-file /tmp/population.txt \\\n    --population-autosave  /tmp/population.txt\n```\n\n#### Analysing a sequence\nApart from running the genetic algorithm, `yul-phaser` can also provide useful information about a particular sequence.\n\nFor example, to see the value of a particular metric for a given sequence and program run:\n``` bash\ntools/yul-phaser *.yul            \\\n    --show-initial-population     \\\n    --rounds            0         \\\n    --metric            code-size \\\n    --metric-aggregator sum       \\\n    --population        <your sequence>\n```\n\nYou can also easily see program code after being optimised using that sequence:\n``` bash\ntools/yul-phaser *.yul                    \\\n    --rounds     0                        \\\n    --mode       print-optimised-programs \\\n    --population <your sequence>\n```\n\n#### Using output from Solidity compiler\n`yul-phaser` can process the intermediate representation produced by `solc`:\n\n``` bash\nsolc/solc <sol file> --ir --output-dir <output directory>\n```\n\nAfter running this command you'll find one or more .yul files in the output directory.\nThese files contain whole Yul objects rather than just raw Yul programs but `yul-phaser` is prepared to handle them too.\n\n#### Using optimisation step sequences with the compiler\nYou can tell Yul optimiser to use a specific sequence for your code by passing `--yul-optimizations` option to `solc`:\n\n``` bash\nsolc/solc <sol file> --optimize --ir-optimized --yul-optimizations <sequence>\n```\n\n### How to choose good parameters\nChoosing good parameters for a genetic algorithm is not a trivial task but phaser's defaults are generally enough to find a sequence that gives results comparable or better than one hand-crafted by an experienced developer for a given set of programs.\nThe difficult part is providing a fairly representative set of input files.\nIf the files you give do not need certain optimisations the tool will find sequences that do not use these optimisations and perform badly for programs that could benefit from them.\nIf all the provided files greatly benefit from a specific optimisation, the sequence may not work well for programs that do not.\n\nWe have conducted [a set of rough experiments](https://github.com/argotorg/solidity/issues/7806#issuecomment-598644491) to evaluate some combinations of parameter values.\nThe conclusions were used to adjust the defaults but you might still benefit from some general observations:\n\n1. The algorithm that performed the best was `GEWEP`.\n2. Using longer sequences in the initial population yields better results. The algorithm is good at removing superfluous steps.\n3. Preserving the top sequences from previous rounds improves results. Elite should contain at least a few individuals, especially when using the `classic` algorithm.\n4. Do not set mutation/deletion/addition chance too high. It makes results worse because it destroys the good patterns preserved by crossover. Values around 1-5% seem to work best.\n5. Keep the algorithm running for 1000 rounds or more. It usually finds good sequences faster than that but it can shorten them significantly if you let it run longer. This is especially important when starting with long sequences.\n","test/tools/ossfuzz/README.md":"## Intro\n\n[oss-fuzz][1] is Google's fuzzing infrastructure that performs continuous fuzzing. What this means is that, each and every upstream commit is automatically fetched by the infrastructure and fuzzed on a daily basis.\n\n## How to build fuzzers?\n\nWe have multiple fuzzers, some based on string input and others on protobuf input. To build them, please do the following:\n\n- Create a local docker image from `Dockerfile.ubuntu.clang.ossfuzz` in the `.circleci/docker` sub-directory. Please note that this step is likely to take at least an hour to complete. Therefore, it is recommended to do it when you are away from the computer (and the computer is plugged to power since we do not want a battery drain).\n\n```\n$ cd .circleci/docker\n$ docker build -t solidity-ossfuzz-local -f Dockerfile.ubuntu.clang.ossfuzz .\n```\n\n- Login to the docker container sourced from the image built in the previous step from the solidity parent directory\n\n```\n## Host\n$ cd solidity\n$ docker run -v `pwd`:/src/solidity -ti solidity-ossfuzz-local /bin/bash\n## Docker shell\n$ cd /src/solidity\n```\n\n- Run cmake and build fuzzer harnesses\n\n```\n## Docker shell\n$ cd /src/solidity\n$ rm -rf fuzzer-build && mkdir fuzzer-build && cd fuzzer-build\n## Compile protobuf C++ bindings\n$ protoc --proto_path=../test/tools/ossfuzz yulProto.proto --cpp_out=../test/tools/ossfuzz\n$ protoc --proto_path=../test/tools/ossfuzz abiV2Proto.proto --cpp_out=../test/tools/ossfuzz\n$ protoc --proto_path=../test/tools/ossfuzz solProto.proto --cpp_out=../test/tools/ossfuzz\n## Run cmake\n$ export CC=clang CXX=clang++\n$ cmake -DCMAKE_TOOLCHAIN_FILE=cmake/toolchains/libfuzzer.cmake -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE:-Release} ..\n$ make ossfuzz ossfuzz_proto ossfuzz_abiv2 -j\n```\n\n## Why the elaborate docker image to build fuzzers?\n\nFor the following reasons:\n\n- Fuzzing binaries **must** link against libc++ and not libstdc++\n  - This is [because][2] (1) MemorySanitizer (which flags uses of uninitialized memory) depends on libc++; and (2) because libc++ is instrumented (to check for memory and type errors) and libstdc++ not, the former may find more bugs.\n\n- Linking against libc++ requires us to compile everything solidity depends on from source (and link these against libc++ as well)\n\n- To reproduce the compiler versions used by upstream oss-fuzz bots, we need to reuse their docker image containing the said compiler versions\n\n- Some fuzzers depend on libprotobuf, libprotobuf-mutator, libevmone etc. which may not be available locally; even if they were they might not be the right versions\n\n## What is LIB\\_FUZZING\\_ENGINE?\n\noss-fuzz contains multiple fuzzer back-ends i.e., fuzzers. Each back-end may require different linker flags. oss-fuzz builder bot defines the correct linker flags via a bash environment variable called `LIB_FUZZING_ENGINE`.\n\nFor the solidity ossfuzz CI build, we use the libFuzzer back-end. This back-end requires us to manually set the `LIB_FUZZING_ENGINE` to `-fsanitize=fuzzer`.\n\n## What does the ossfuzz directory contain?\n\nTo help oss-fuzz do this, we (as project maintainers) need to provide the following:\n\n- test harnesses: C/C++ tests that define the `LLVMFuzzerTestOneInput` API. This determines what is to be fuzz tested.\n- build infrastructure: (c)make targets per fuzzing binary. Fuzzing requires coverage and memory instrumentation of the code to be fuzzed.\n- configuration files: These are files with the `.options` extension that are parsed by oss-fuzz. The only option that we use currently is the `dictionary` option that asks the fuzzing engines behind oss-fuzz to use the specified dictionary. The specified dictionary happens to be `solidity.dict.`\n\n`solidity.dict` contains Solidity-specific syntactical tokens that are more likely to guide the fuzzer towards generating parseable and varied Solidity input.\n\nTo be consistent and aid better evaluation of the utility of the fuzzing dictionary, we stick to the following rules-of-thumb:\n  - Full tokens such as `block.number` are preceded and followed by a whitespace\n  - Incomplete tokens including function calls such as `msg.sender.send()` are abbreviated `.send(` to provide some leeway to the fuzzer to synthesize variants such as `address(this).send()`\n  - Language keywords are suffixed by a whitespace with the exception of those that end a line of code such as `break;` and `continue;`\n\n[1]: https://github.com/google/oss-fuzz\n[2]: https://github.com/google/oss-fuzz/issues/1114#issuecomment-360660201\n",".cursorrules (solidity-foundry-cursorrules-prompt-file.mdc)":"---\ndescription: \"Cursor rules for Solidity development with Foundry integration.\"\nglobs: **/*\nalwaysApply: false\n---\nYou are an expert in Solidity and smart contract security.\n\nGeneral Rules\n\n- Cut the fluff. Code or detailed explanations only.\n- Keep it casual and brief.\n- Accuracy and depth matter.\n- Answer first, explain later if needed.\n- Logic trumps authority. Don't care about sources.\n- Embrace new tech and unconventional ideas.\n- Wild speculation's fine, just flag it.\n- Save the ethics talk.\n- Only mention safety for non-obvious, critical issues.\n- Push content limits if needed, explain after.\n- Sources at the end, not mid-text.\n- Skip the AI self-references and knowledge date stuff.\n- Stick to my code style.\n- Use multiple responses for complex answers.\n- For code tweaks, show minimal context - a few lines around changes max.\n- Don't be lazy, write all the code to implement features I ask for.\n- Warn users if they add a private key directly into a non-environment file and replace with an env reference.\n\nSolidity Best Practices\n\n- Use explicit function visibility modifiers and appropriate natspec comments.\n- Utilize function modifiers for common checks, enhancing readability and reducing redundancy.\n- Follow consistent naming: CamelCase for contracts, PascalCase for interfaces (prefixed with \"I\").\n- Implement the Interface Segregation Principle for flexible and maintainable contracts.\n- Design upgradeable contracts using proven patterns like the proxy pattern when necessary.\n- Implement comprehensive events for all significant state changes.\n- Follow the Checks-Effects-Interactions pattern to prevent reentrancy and other vulnerabilities.\n- Use static analysis tools like Slither and Mythril in the development workflow.\n- Implement timelocks and multisig controls for sensitive operations in production.\n- Conduct thorough gas optimization, considering both deployment and runtime costs.\n- Use OpenZeppelin's AccessControl for fine-grained permissions.\n- Use Solidity 0.8.0+ for built-in overflow/underflow protection.\n- Implement circuit breakers (pause functionality) using OpenZeppelin's Pausable when appropriate.\n- Use pull over push payment patterns to mitigate reentrancy and denial of service attacks.\n- Implement rate limiting for sensitive functions to prevent abuse.\n- Use OpenZeppelin's SafeERC20 for interacting with ERC20 tokens.\n- Implement proper randomness using Chainlink VRF or similar oracle solutions.\n- Use assembly for gas-intensive operations, but document extensively and use with caution.\n  - If Solady has an implementation built already, use that instead of writing assembly from scratch.\n- Implement effective state machine patterns for complex contract logic.\n- Use OpenZeppelin's ReentrancyGuard as an additional layer of protection against reentrancy.\n- Implement proper access control for initializers in upgradeable contracts.\n- Use OpenZeppelin's ERC20Snapshot for token balances requiring historical lookups.\n- Implement timelocks for sensitive operations using OpenZeppelin's TimelockController.\n- Use OpenZeppelin's ERC20Permit for gasless approvals in token contracts.\n- Implement proper slippage protection for DEX-like functionalities.\n- Use OpenZeppelin's ERC20Votes for governance token implementations.\n- Implement effective storage patterns to optimize gas costs (e.g., packing variables).\n- Use libraries for complex operations to reduce contract size and improve reusability.\n- Implement proper access control for self-destruct functionality, if used.\n  - Use freezable patterns instead of depricated `selfdestruct`.\n- Use OpenZeppelin's Address library for safe interactions with external contracts.\n- Use custom errors instead of revert strings for gas efficiency and better error handling.\n- Implement NatSpec comments for all public and external functions.\n- Use immutable variables for values set once at construction time.\n- Implement proper inheritance patterns, favoring composition over deep inheritance chains.\n- Use events for off-chain logging and indexing of important state changes.\n- Implement fallback and receive functions with caution, clearly documenting their purpose.\n- Use view and pure function modifiers appropriately to signal state access patterns.\n- Implement proper decimal handling for financial calculations, using fixed-point arithmetic libraries when necessary.\n- Use assembly sparingly and only when necessary for optimizations, with thorough documentation.\n- Implement effective error propagation patterns in internal functions.\n\nTesting and Quality Assurance\n\n- Implement a comprehensive testing strategy including unit, integration, and end-to-end tests.\n- Use a `setup` function in test files to set default state and initialize variables.\n- Use Foundry's fuzzing capabilities to uncover edge cases with property-based testing.\n- Take advantage of Foundry's test cheatcodes for advanced testing scenarios.\n- Write invariant tests for critical contract properties using Foundry's invariant testing features.\n- Use Foundry's Fuzz testing to automatically generate test cases and find edge case bugs.\n- Implement stateful fuzzing tests for complex state transitions.\n- Implement gas usage tests to ensure operations remain efficient.\n- Use Foundry's fork testing capabilities to test against live environments.\n- Implement differential testing by comparing implementations.\n- Conduct regular security audits and bug bounties for production-grade contracts.\n- Use test coverage tools and aim for high test coverage, especially for critical paths.\n- Write appropriate test fixtures using Foundry's standard libraries.\n- Use Foundry's vm.startPrank/vm.stopPrank for testing access control mechanisms.\n- Implement proper setup and teardown in test files.\n- If deterministic testing is being done, ensure that the `foundry.toml` file has `block_number` and `block_timestamp` values.\n\nPerformance Optimization\n\n- Optimize contracts for gas efficiency, considering storage layout and function optimization.\n- Implement efficient indexing and querying strategies for off-chain data.\n\nDevelopment Workflow\n\n- Utilize Foundry's forge for compilation, testing, and deployment.\n- Use Foundry's cast for command-line interaction with contracts.\n- Implement comprehensive Foundry scripts for deployment and verification.\n- Use Foundry's script capabilities for complex deployment sequences.\n- Implement a robust CI/CD pipeline for smart contract deployments.\n- Use static type checking and linting tools in pre-commit hooks.\n- Utilize `forge fmt` if prompted about consistent code formatting.\n\nDocumentation\n\n- Document code thoroughly, focusing on why rather than what.\n- Maintain up-to-date API documentation for smart contracts.\n- Create and maintain comprehensive project documentation, including architecture diagrams and decision logs.\n- Document test scenarios and their purpose clearly.\n- Document any assumptions made in the contract design.\n\nDependencies\n\n- Use OpenZeppelin (openzeppelin/openzeppelin-contracts) as the main source of dependencies.\n- Use Solady (vectorized/solady) when gas optimization is crucial.\n- Ensure that any libraries used are installed with forge, and remappings are set.\n- Place remappings in `foundry.toml` instead of a `remappings.txt` file.\n\nConfiguring Environment\n\nOne or more of the following profiles can be added to `foundry.toml` as needed for the project.\n\n- When via_ir is required:\n\n```\n# via_ir pipeline is very slow - use a separate profile to pre-compile and then use vm.getCode to deploy\n[profile.via_ir]\nvia_ir = true\n# do not compile tests when compiling via-ir\ntest = 'src'\nout = 'via_ir-out'\n```\n\n- When deterministic deployment is required:\n\n```\n[profile.deterministic]\n# ensure that block number + timestamp are realistic when running tests\nblock_number = 17722462\nblock_timestamp = 1689711647\n# don't pollute bytecode with metadata\nbytecode_hash = 'none'\ncbor_metadata = false\n```\n"},"files":{"tools/yulPhaser/README.md":"## yul-phaser\n`yul-phaser` is an internal tool for finding good sequences of [optimisation steps](/libyul/optimiser/README.md) for Yul optimiser.\n\n### How it works\nThe space of possible solutions to this problem (usually referred to as _phase-ordering problem_) is extremely large and there may even be no single sequence that produces optimal results for all possible programs.\n\nThe tool uses genetic algorithms to find sequences that result in better programs than others and to iteratively refine them.\nThe input is a set of one or more [Yul](/docs/yul.rst) programs and each sequence is applied to all of these programs.\nOptimised programs are given numeric scores according to the selected metric.\n\nOptimisation step sequences are presented in an abbreviated form - as strings of letters where each character represents one step.\nThere's a [table listing available abbreviations in the optimiser docs](/docs/yul.rst#optimization-step-sequence).\n\n### How to use it\nThe application has sensible defaults for most parameters.\nAn invocation can be as simple as:\n\n``` bash\ntools/yul-phaser ../test/libyul/yulOptimizerTests/fullSuite/*.yul \\\n    --random-population 100\n```\n\nThis assumes that you have a working copy of the Solidity repository and you're in the build directory within that working copy.\n\nRun `yul-phaser --help` for a full list of available options.\n\n#### Restarting from a previous state\n`yul-phaser` can save the list of sequences found after each round:\n\n``` bash\ntools/yul-phaser *.yul        \\\n    --random-population   100 \\\n    --population-autosave /tmp/population.txt\n```\n\nIf you stop the application, you can later use the file to continue the search from the point you left off:\n\n``` bash\ntools/yul-phaser *.yul                         \\\n    --population-from-file /tmp/population.txt \\\n    --population-autosave  /tmp/population.txt\n```\n\n#### Analysing a sequence\nApart from running the genetic algorithm, `yul-phaser` can also provide useful information about a particular sequence.\n\nFor example, to see the value of a particular metric for a given sequence and program run:\n``` bash\ntools/yul-phaser *.yul            \\\n    --show-initial-population     \\\n    --rounds            0         \\\n    --metric            code-size \\\n    --metric-aggregator sum       \\\n    --population        <your sequence>\n```\n\nYou can also easily see program code after being optimised using that sequence:\n``` bash\ntools/yul-phaser *.yul                    \\\n    --rounds     0                        \\\n    --mode       print-optimised-programs \\\n    --population <your sequence>\n```\n\n#### Using output from Solidity compiler\n`yul-phaser` can process the intermediate representation produced by `solc`:\n\n``` bash\nsolc/solc <sol file> --ir --output-dir <output directory>\n```\n\nAfter running this command you'll find one or more .yul files in the output directory.\nThese files contain whole Yul objects rather than just raw Yul programs but `yul-phaser` is prepared to handle them too.\n\n#### Using optimisation step sequences with the compiler\nYou can tell Yul optimiser to use a specific sequence for your code by passing `--yul-optimizations` option to `solc`:\n\n``` bash\nsolc/solc <sol file> --optimize --ir-optimized --yul-optimizations <sequence>\n```\n\n### How to choose good parameters\nChoosing good parameters for a genetic algorithm is not a trivial task but phaser's defaults are generally enough to find a sequence that gives results comparable or better than one hand-crafted by an experienced developer for a given set of programs.\nThe difficult part is providing a fairly representative set of input files.\nIf the files you give do not need certain optimisations the tool will find sequences that do not use these optimisations and perform badly for programs that could benefit from them.\nIf all the provided files greatly benefit from a specific optimisation, the sequence may not work well for programs that do not.\n\nWe have conducted [a set of rough experiments](https://github.com/argotorg/solidity/issues/7806#issuecomment-598644491) to evaluate some combinations of parameter values.\nThe conclusions were used to adjust the defaults but you might still benefit from some general observations:\n\n1. The algorithm that performed the best was `GEWEP`.\n2. Using longer sequences in the initial population yields better results. The algorithm is good at removing superfluous steps.\n3. Preserving the top sequences from previous rounds improves results. Elite should contain at least a few individuals, especially when using the `classic` algorithm.\n4. Do not set mutation/deletion/addition chance too high. It makes results worse because it destroys the good patterns preserved by crossover. Values around 1-5% seem to work best.\n5. Keep the algorithm running for 1000 rounds or more. It usually finds good sequences faster than that but it can shorten them significantly if you let it run longer. This is especially important when starting with long sequences.\n","test/tools/ossfuzz/README.md":"## Intro\n\n[oss-fuzz][1] is Google's fuzzing infrastructure that performs continuous fuzzing. What this means is that, each and every upstream commit is automatically fetched by the infrastructure and fuzzed on a daily basis.\n\n## How to build fuzzers?\n\nWe have multiple fuzzers, some based on string input and others on protobuf input. To build them, please do the following:\n\n- Create a local docker image from `Dockerfile.ubuntu.clang.ossfuzz` in the `.circleci/docker` sub-directory. Please note that this step is likely to take at least an hour to complete. Therefore, it is recommended to do it when you are away from the computer (and the computer is plugged to power since we do not want a battery drain).\n\n```\n$ cd .circleci/docker\n$ docker build -t solidity-ossfuzz-local -f Dockerfile.ubuntu.clang.ossfuzz .\n```\n\n- Login to the docker container sourced from the image built in the previous step from the solidity parent directory\n\n```\n## Host\n$ cd solidity\n$ docker run -v `pwd`:/src/solidity -ti solidity-ossfuzz-local /bin/bash\n## Docker shell\n$ cd /src/solidity\n```\n\n- Run cmake and build fuzzer harnesses\n\n```\n## Docker shell\n$ cd /src/solidity\n$ rm -rf fuzzer-build && mkdir fuzzer-build && cd fuzzer-build\n## Compile protobuf C++ bindings\n$ protoc --proto_path=../test/tools/ossfuzz yulProto.proto --cpp_out=../test/tools/ossfuzz\n$ protoc --proto_path=../test/tools/ossfuzz abiV2Proto.proto --cpp_out=../test/tools/ossfuzz\n$ protoc --proto_path=../test/tools/ossfuzz solProto.proto --cpp_out=../test/tools/ossfuzz\n## Run cmake\n$ export CC=clang CXX=clang++\n$ cmake -DCMAKE_TOOLCHAIN_FILE=cmake/toolchains/libfuzzer.cmake -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE:-Release} ..\n$ make ossfuzz ossfuzz_proto ossfuzz_abiv2 -j\n```\n\n## Why the elaborate docker image to build fuzzers?\n\nFor the following reasons:\n\n- Fuzzing binaries **must** link against libc++ and not libstdc++\n  - This is [because][2] (1) MemorySanitizer (which flags uses of uninitialized memory) depends on libc++; and (2) because libc++ is instrumented (to check for memory and type errors) and libstdc++ not, the former may find more bugs.\n\n- Linking against libc++ requires us to compile everything solidity depends on from source (and link these against libc++ as well)\n\n- To reproduce the compiler versions used by upstream oss-fuzz bots, we need to reuse their docker image containing the said compiler versions\n\n- Some fuzzers depend on libprotobuf, libprotobuf-mutator, libevmone etc. which may not be available locally; even if they were they might not be the right versions\n\n## What is LIB\\_FUZZING\\_ENGINE?\n\noss-fuzz contains multiple fuzzer back-ends i.e., fuzzers. Each back-end may require different linker flags. oss-fuzz builder bot defines the correct linker flags via a bash environment variable called `LIB_FUZZING_ENGINE`.\n\nFor the solidity ossfuzz CI build, we use the libFuzzer back-end. This back-end requires us to manually set the `LIB_FUZZING_ENGINE` to `-fsanitize=fuzzer`.\n\n## What does the ossfuzz directory contain?\n\nTo help oss-fuzz do this, we (as project maintainers) need to provide the following:\n\n- test harnesses: C/C++ tests that define the `LLVMFuzzerTestOneInput` API. This determines what is to be fuzz tested.\n- build infrastructure: (c)make targets per fuzzing binary. Fuzzing requires coverage and memory instrumentation of the code to be fuzzed.\n- configuration files: These are files with the `.options` extension that are parsed by oss-fuzz. The only option that we use currently is the `dictionary` option that asks the fuzzing engines behind oss-fuzz to use the specified dictionary. The specified dictionary happens to be `solidity.dict.`\n\n`solidity.dict` contains Solidity-specific syntactical tokens that are more likely to guide the fuzzer towards generating parseable and varied Solidity input.\n\nTo be consistent and aid better evaluation of the utility of the fuzzing dictionary, we stick to the following rules-of-thumb:\n  - Full tokens such as `block.number` are preceded and followed by a whitespace\n  - Incomplete tokens including function calls such as `msg.sender.send()` are abbreviated `.send(` to provide some leeway to the fuzzer to synthesize variants such as `address(this).send()`\n  - Language keywords are suffixed by a whitespace with the exception of those that end a line of code such as `break;` and `continue;`\n\n[1]: https://github.com/google/oss-fuzz\n[2]: https://github.com/google/oss-fuzz/issues/1114#issuecomment-360660201\n",".cursorrules (solidity-foundry-cursorrules-prompt-file.mdc)":"---\ndescription: \"Cursor rules for Solidity development with Foundry integration.\"\nglobs: **/*\nalwaysApply: false\n---\nYou are an expert in Solidity and smart contract security.\n\nGeneral Rules\n\n- Cut the fluff. Code or detailed explanations only.\n- Keep it casual and brief.\n- Accuracy and depth matter.\n- Answer first, explain later if needed.\n- Logic trumps authority. Don't care about sources.\n- Embrace new tech and unconventional ideas.\n- Wild speculation's fine, just flag it.\n- Save the ethics talk.\n- Only mention safety for non-obvious, critical issues.\n- Push content limits if needed, explain after.\n- Sources at the end, not mid-text.\n- Skip the AI self-references and knowledge date stuff.\n- Stick to my code style.\n- Use multiple responses for complex answers.\n- For code tweaks, show minimal context - a few lines around changes max.\n- Don't be lazy, write all the code to implement features I ask for.\n- Warn users if they add a private key directly into a non-environment file and replace with an env reference.\n\nSolidity Best Practices\n\n- Use explicit function visibility modifiers and appropriate natspec comments.\n- Utilize function modifiers for common checks, enhancing readability and reducing redundancy.\n- Follow consistent naming: CamelCase for contracts, PascalCase for interfaces (prefixed with \"I\").\n- Implement the Interface Segregation Principle for flexible and maintainable contracts.\n- Design upgradeable contracts using proven patterns like the proxy pattern when necessary.\n- Implement comprehensive events for all significant state changes.\n- Follow the Checks-Effects-Interactions pattern to prevent reentrancy and other vulnerabilities.\n- Use static analysis tools like Slither and Mythril in the development workflow.\n- Implement timelocks and multisig controls for sensitive operations in production.\n- Conduct thorough gas optimization, considering both deployment and runtime costs.\n- Use OpenZeppelin's AccessControl for fine-grained permissions.\n- Use Solidity 0.8.0+ for built-in overflow/underflow protection.\n- Implement circuit breakers (pause functionality) using OpenZeppelin's Pausable when appropriate.\n- Use pull over push payment patterns to mitigate reentrancy and denial of service attacks.\n- Implement rate limiting for sensitive functions to prevent abuse.\n- Use OpenZeppelin's SafeERC20 for interacting with ERC20 tokens.\n- Implement proper randomness using Chainlink VRF or similar oracle solutions.\n- Use assembly for gas-intensive operations, but document extensively and use with caution.\n  - If Solady has an implementation built already, use that instead of writing assembly from scratch.\n- Implement effective state machine patterns for complex contract logic.\n- Use OpenZeppelin's ReentrancyGuard as an additional layer of protection against reentrancy.\n- Implement proper access control for initializers in upgradeable contracts.\n- Use OpenZeppelin's ERC20Snapshot for token balances requiring historical lookups.\n- Implement timelocks for sensitive operations using OpenZeppelin's TimelockController.\n- Use OpenZeppelin's ERC20Permit for gasless approvals in token contracts.\n- Implement proper slippage protection for DEX-like functionalities.\n- Use OpenZeppelin's ERC20Votes for governance token implementations.\n- Implement effective storage patterns to optimize gas costs (e.g., packing variables).\n- Use libraries for complex operations to reduce contract size and improve reusability.\n- Implement proper access control for self-destruct functionality, if used.\n  - Use freezable patterns instead of depricated `selfdestruct`.\n- Use OpenZeppelin's Address library for safe interactions with external contracts.\n- Use custom errors instead of revert strings for gas efficiency and better error handling.\n- Implement NatSpec comments for all public and external functions.\n- Use immutable variables for values set once at construction time.\n- Implement proper inheritance patterns, favoring composition over deep inheritance chains.\n- Use events for off-chain logging and indexing of important state changes.\n- Implement fallback and receive functions with caution, clearly documenting their purpose.\n- Use view and pure function modifiers appropriately to signal state access patterns.\n- Implement proper decimal handling for financial calculations, using fixed-point arithmetic libraries when necessary.\n- Use assembly sparingly and only when necessary for optimizations, with thorough documentation.\n- Implement effective error propagation patterns in internal functions.\n\nTesting and Quality Assurance\n\n- Implement a comprehensive testing strategy including unit, integration, and end-to-end tests.\n- Use a `setup` function in test files to set default state and initialize variables.\n- Use Foundry's fuzzing capabilities to uncover edge cases with property-based testing.\n- Take advantage of Foundry's test cheatcodes for advanced testing scenarios.\n- Write invariant tests for critical contract properties using Foundry's invariant testing features.\n- Use Foundry's Fuzz testing to automatically generate test cases and find edge case bugs.\n- Implement stateful fuzzing tests for complex state transitions.\n- Implement gas usage tests to ensure operations remain efficient.\n- Use Foundry's fork testing capabilities to test against live environments.\n- Implement differential testing by comparing implementations.\n- Conduct regular security audits and bug bounties for production-grade contracts.\n- Use test coverage tools and aim for high test coverage, especially for critical paths.\n- Write appropriate test fixtures using Foundry's standard libraries.\n- Use Foundry's vm.startPrank/vm.stopPrank for testing access control mechanisms.\n- Implement proper setup and teardown in test files.\n- If deterministic testing is being done, ensure that the `foundry.toml` file has `block_number` and `block_timestamp` values.\n\nPerformance Optimization\n\n- Optimize contracts for gas efficiency, considering storage layout and function optimization.\n- Implement efficient indexing and querying strategies for off-chain data.\n\nDevelopment Workflow\n\n- Utilize Foundry's forge for compilation, testing, and deployment.\n- Use Foundry's cast for command-line interaction with contracts.\n- Implement comprehensive Foundry scripts for deployment and verification.\n- Use Foundry's script capabilities for complex deployment sequences.\n- Implement a robust CI/CD pipeline for smart contract deployments.\n- Use static type checking and linting tools in pre-commit hooks.\n- Utilize `forge fmt` if prompted about consistent code formatting.\n\nDocumentation\n\n- Document code thoroughly, focusing on why rather than what.\n- Maintain up-to-date API documentation for smart contracts.\n- Create and maintain comprehensive project documentation, including architecture diagrams and decision logs.\n- Document test scenarios and their purpose clearly.\n- Document any assumptions made in the contract design.\n\nDependencies\n\n- Use OpenZeppelin (openzeppelin/openzeppelin-contracts) as the main source of dependencies.\n- Use Solady (vectorized/solady) when gas optimization is crucial.\n- Ensure that any libraries used are installed with forge, and remappings are set.\n- Place remappings in `foundry.toml` instead of a `remappings.txt` file.\n\nConfiguring Environment\n\nOne or more of the following profiles can be added to `foundry.toml` as needed for the project.\n\n- When via_ir is required:\n\n```\n# via_ir pipeline is very slow - use a separate profile to pre-compile and then use vm.getCode to deploy\n[profile.via_ir]\nvia_ir = true\n# do not compile tests when compiling via-ir\ntest = 'src'\nout = 'via_ir-out'\n```\n\n- When deterministic deployment is required:\n\n```\n[profile.deterministic]\n# ensure that block number + timestamp are realistic when running tests\nblock_number = 17722462\nblock_timestamp = 1689711647\n# don't pollute bytecode with metadata\nbytecode_hash = 'none'\ncbor_metadata = false\n```\n"},"items":[{"name":"README.md","path":"test/tools/ossfuzz/README.md","rawUrl":"https://raw.githubusercontent.com/argotorg/solidity/HEAD/test/tools/ossfuzz/README.md","title":"ossfuzz Documentation","category":"plugin-manifest","format":"markdown","content":"## Intro\n\n[oss-fuzz][1] is Google's fuzzing infrastructure that performs continuous fuzzing. What this means is that, each and every upstream commit is automatically fetched by the infrastructure and fuzzed on a daily basis.\n\n## How to build fuzzers?\n\nWe have multiple fuzzers, some based on string input and others on protobuf input. To build them, please do the following:\n\n- Create a local docker image from `Dockerfile.ubuntu.clang.ossfuzz` in the `.circleci/docker` sub-directory. Please note that this step is likely to take at least an hour to complete. Therefore, it is recommended to do it when you are away from the computer (and the computer is plugged to power since we do not want a battery drain).\n\n```\n$ cd .circleci/docker\n$ docker build -t solidity-ossfuzz-local -f Dockerfile.ubuntu.clang.ossfuzz .\n```\n\n- Login to the docker container sourced from the image built in the previous step from the solidity parent directory\n\n```\n## Host\n$ cd solidity\n$ docker run -v `pwd`:/src/solidity -ti solidity-ossfuzz-local /bin/bash\n## Docker shell\n$ cd /src/solidity\n```\n\n- Run cmake and build fuzzer harnesses\n\n```\n## Docker shell\n$ cd /src/solidity\n$ rm -rf fuzzer-build && mkdir fuzzer-build && cd fuzzer-build\n## Compile protobuf C++ bindings\n$ protoc --proto_path=../test/tools/ossfuzz yulProto.proto --cpp_out=../test/tools/ossfuzz\n$ protoc --proto_path=../test/tools/ossfuzz abiV2Proto.proto --cpp_out=../test/tools/ossfuzz\n$ protoc --proto_path=../test/tools/ossfuzz solProto.proto --cpp_out=../test/tools/ossfuzz\n## Run cmake\n$ export CC=clang CXX=clang++\n$ cmake -DCMAKE_TOOLCHAIN_FILE=cmake/toolchains/libfuzzer.cmake -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE:-Release} ..\n$ make ossfuzz ossfuzz_proto ossfuzz_abiv2 -j\n```\n\n## Why the elaborate docker image to build fuzzers?\n\nFor the following reasons:\n\n- Fuzzing binaries **must** link against libc++ and not libstdc++\n  - This is [because][2] (1) MemorySanitizer (which flags uses of uninitialized memory) depends on libc++; and (2) because libc++ is instrumented (to check for memory and type errors) and libstdc++ not, the former may find more bugs.\n\n- Linking against libc++ requires us to compile everything solidity depends on from source (and link these against libc++ as well)\n\n- To reproduce the compiler versions used by upstream oss-fuzz bots, we need to reuse their docker image containing the said compiler versions\n\n- Some fuzzers depend on libprotobuf, libprotobuf-mutator, libevmone etc. which may not be available locally; even if they were they might not be the right versions\n\n## What is LIB\\_FUZZING\\_ENGINE?\n\noss-fuzz contains multiple fuzzer back-ends i.e., fuzzers. Each back-end may require different linker flags. oss-fuzz builder bot defines the correct linker flags via a bash environment variable called `LIB_FUZZING_ENGINE`.\n\nFor the solidity ossfuzz CI build, we use the libFuzzer back-end. This back-end requires us to manually set the `LIB_FUZZING_ENGINE` to `-fsanitize=fuzzer`.\n\n## What does the ossfuzz directory contain?\n\nTo help oss-fuzz do this, we (as project maintainers) need to provide the following:\n\n- test harnesses: C/C++ tests that define the `LLVMFuzzerTestOneInput` API. This determines what is to be fuzz tested.\n- build infrastructure: (c)make targets per fuzzing binary. Fuzzing requires coverage and memory instrumentation of the code to be fuzzed.\n- configuration files: These are files with the `.options` extension that are parsed by oss-fuzz. The only option that we use currently is the `dictionary` option that asks the fuzzing engines behind oss-fuzz to use the specified dictionary. The specified dictionary happens to be `solidity.dict.`\n\n`solidity.dict` contains Solidity-specific syntactical tokens that are more likely to guide the fuzzer towards generating parseable and varied Solidity input.\n\nTo be consistent and aid better evaluation of the utility of the fuzzing dictionary, we stick to the following rules-of-thumb:\n  - Full tokens such as `block.number` are preceded and followed by a whitespace\n  - Incomplete tokens including function calls such as `msg.sender.send()` are abbreviated `.send(` to provide some leeway to the fuzzer to synthesize variants such as `address(this).send()`\n  - Language keywords are suffixed by a whitespace with the exception of those that end a line of code such as `break;` and `continue;`\n\n[1]: https://github.com/google/oss-fuzz\n[2]: https://github.com/google/oss-fuzz/issues/1114#issuecomment-360660201\n","isInternal":false,"tokens":1096,"sizeBytes":4478},{"name":"README.md","path":"tools/yulPhaser/README.md","rawUrl":"https://raw.githubusercontent.com/argotorg/solidity/HEAD/tools/yulPhaser/README.md","title":"yulPhaser Documentation","category":"plugin-manifest","format":"markdown","content":"## yul-phaser\n`yul-phaser` is an internal tool for finding good sequences of [optimisation steps](/libyul/optimiser/README.md) for Yul optimiser.\n\n### How it works\nThe space of possible solutions to this problem (usually referred to as _phase-ordering problem_) is extremely large and there may even be no single sequence that produces optimal results for all possible programs.\n\nThe tool uses genetic algorithms to find sequences that result in better programs than others and to iteratively refine them.\nThe input is a set of one or more [Yul](/docs/yul.rst) programs and each sequence is applied to all of these programs.\nOptimised programs are given numeric scores according to the selected metric.\n\nOptimisation step sequences are presented in an abbreviated form - as strings of letters where each character represents one step.\nThere's a [table listing available abbreviations in the optimiser docs](/docs/yul.rst#optimization-step-sequence).\n\n### How to use it\nThe application has sensible defaults for most parameters.\nAn invocation can be as simple as:\n\n``` bash\ntools/yul-phaser ../test/libyul/yulOptimizerTests/fullSuite/*.yul \\\n    --random-population 100\n```\n\nThis assumes that you have a working copy of the Solidity repository and you're in the build directory within that working copy.\n\nRun `yul-phaser --help` for a full list of available options.\n\n#### Restarting from a previous state\n`yul-phaser` can save the list of sequences found after each round:\n\n``` bash\ntools/yul-phaser *.yul        \\\n    --random-population   100 \\\n    --population-autosave /tmp/population.txt\n```\n\nIf you stop the application, you can later use the file to continue the search from the point you left off:\n\n``` bash\ntools/yul-phaser *.yul                         \\\n    --population-from-file /tmp/population.txt \\\n    --population-autosave  /tmp/population.txt\n```\n\n#### Analysing a sequence\nApart from running the genetic algorithm, `yul-phaser` can also provide useful information about a particular sequence.\n\nFor example, to see the value of a particular metric for a given sequence and program run:\n``` bash\ntools/yul-phaser *.yul            \\\n    --show-initial-population     \\\n    --rounds            0         \\\n    --metric            code-size \\\n    --metric-aggregator sum       \\\n    --population        <your sequence>\n```\n\nYou can also easily see program code after being optimised using that sequence:\n``` bash\ntools/yul-phaser *.yul                    \\\n    --rounds     0                        \\\n    --mode       print-optimised-programs \\\n    --population <your sequence>\n```\n\n#### Using output from Solidity compiler\n`yul-phaser` can process the intermediate representation produced by `solc`:\n\n``` bash\nsolc/solc <sol file> --ir --output-dir <output directory>\n```\n\nAfter running this command you'll find one or more .yul files in the output directory.\nThese files contain whole Yul objects rather than just raw Yul programs but `yul-phaser` is prepared to handle them too.\n\n#### Using optimisation step sequences with the compiler\nYou can tell Yul optimiser to use a specific sequence for your code by passing `--yul-optimizations` option to `solc`:\n\n``` bash\nsolc/solc <sol file> --optimize --ir-optimized --yul-optimizations <sequence>\n```\n\n### How to choose good parameters\nChoosing good parameters for a genetic algorithm is not a trivial task but phaser's defaults are generally enough to find a sequence that gives results comparable or better than one hand-crafted by an experienced developer for a given set of programs.\nThe difficult part is providing a fairly representative set of input files.\nIf the files you give do not need certain optimisations the tool will find sequences that do not use these optimisations and perform badly for programs that could benefit from them.\nIf all the provided files greatly benefit from a specific optimisation, the sequence may not work well for programs that do not.\n\nWe have conducted [a set of rough experiments](https://github.com/argotorg/solidity/issues/7806#issuecomment-598644491) to evaluate some combinations of parameter values.\nThe conclusions were used to adjust the defaults but you might still benefit from some general observations:\n\n1. The algorithm that performed the best was `GEWEP`.\n2. Using longer sequences in the initial population yields better results. The algorithm is good at removing superfluous steps.\n3. Preserving the top sequences from previous rounds improves results. Elite should contain at least a few individuals, especially when using the `classic` algorithm.\n4. Do not set mutation/deletion/addition chance too high. It makes results worse because it destroys the good patterns preserved by crossover. Values around 1-5% seem to work best.\n5. Keep the algorithm running for 1000 rounds or more. It usually finds good sequences faster than that but it can shorten them significantly if you let it run longer. This is especially important when starting with long sequences.\n","isInternal":false,"tokens":1093,"sizeBytes":4983},{"name":".cursorrules","path":".cursorrules (solidity-foundry-cursorrules-prompt-file.mdc)","rawUrl":"https://raw.githubusercontent.com/PatrickJS/awesome-cursorrules/main/rules/solidity-foundry-cursorrules-prompt-file.mdc","title":"Awesome Cursorrules: solidity foundry","category":"cursor-rule","format":"markdown","content":"---\ndescription: \"Cursor rules for Solidity development with Foundry integration.\"\nglobs: **/*\nalwaysApply: false\n---\nYou are an expert in Solidity and smart contract security.\n\nGeneral Rules\n\n- Cut the fluff. Code or detailed explanations only.\n- Keep it casual and brief.\n- Accuracy and depth matter.\n- Answer first, explain later if needed.\n- Logic trumps authority. Don't care about sources.\n- Embrace new tech and unconventional ideas.\n- Wild speculation's fine, just flag it.\n- Save the ethics talk.\n- Only mention safety for non-obvious, critical issues.\n- Push content limits if needed, explain after.\n- Sources at the end, not mid-text.\n- Skip the AI self-references and knowledge date stuff.\n- Stick to my code style.\n- Use multiple responses for complex answers.\n- For code tweaks, show minimal context - a few lines around changes max.\n- Don't be lazy, write all the code to implement features I ask for.\n- Warn users if they add a private key directly into a non-environment file and replace with an env reference.\n\nSolidity Best Practices\n\n- Use explicit function visibility modifiers and appropriate natspec comments.\n- Utilize function modifiers for common checks, enhancing readability and reducing redundancy.\n- Follow consistent naming: CamelCase for contracts, PascalCase for interfaces (prefixed with \"I\").\n- Implement the Interface Segregation Principle for flexible and maintainable contracts.\n- Design upgradeable contracts using proven patterns like the proxy pattern when necessary.\n- Implement comprehensive events for all significant state changes.\n- Follow the Checks-Effects-Interactions pattern to prevent reentrancy and other vulnerabilities.\n- Use static analysis tools like Slither and Mythril in the development workflow.\n- Implement timelocks and multisig controls for sensitive operations in production.\n- Conduct thorough gas optimization, considering both deployment and runtime costs.\n- Use OpenZeppelin's AccessControl for fine-grained permissions.\n- Use Solidity 0.8.0+ for built-in overflow/underflow protection.\n- Implement circuit breakers (pause functionality) using OpenZeppelin's Pausable when appropriate.\n- Use pull over push payment patterns to mitigate reentrancy and denial of service attacks.\n- Implement rate limiting for sensitive functions to prevent abuse.\n- Use OpenZeppelin's SafeERC20 for interacting with ERC20 tokens.\n- Implement proper randomness using Chainlink VRF or similar oracle solutions.\n- Use assembly for gas-intensive operations, but document extensively and use with caution.\n  - If Solady has an implementation built already, use that instead of writing assembly from scratch.\n- Implement effective state machine patterns for complex contract logic.\n- Use OpenZeppelin's ReentrancyGuard as an additional layer of protection against reentrancy.\n- Implement proper access control for initializers in upgradeable contracts.\n- Use OpenZeppelin's ERC20Snapshot for token balances requiring historical lookups.\n- Implement timelocks for sensitive operations using OpenZeppelin's TimelockController.\n- Use OpenZeppelin's ERC20Permit for gasless approvals in token contracts.\n- Implement proper slippage protection for DEX-like functionalities.\n- Use OpenZeppelin's ERC20Votes for governance token implementations.\n- Implement effective storage patterns to optimize gas costs (e.g., packing variables).\n- Use libraries for complex operations to reduce contract size and improve reusability.\n- Implement proper access control for self-destruct functionality, if used.\n  - Use freezable patterns instead of depricated `selfdestruct`.\n- Use OpenZeppelin's Address library for safe interactions with external contracts.\n- Use custom errors instead of revert strings for gas efficiency and better error handling.\n- Implement NatSpec comments for all public and external functions.\n- Use immutable variables for values set once at construction time.\n- Implement proper inheritance patterns, favoring composition over deep inheritance chains.\n- Use events for off-chain logging and indexing of important state changes.\n- Implement fallback and receive functions with caution, clearly documenting their purpose.\n- Use view and pure function modifiers appropriately to signal state access patterns.\n- Implement proper decimal handling for financial calculations, using fixed-point arithmetic libraries when necessary.\n- Use assembly sparingly and only when necessary for optimizations, with thorough documentation.\n- Implement effective error propagation patterns in internal functions.\n\nTesting and Quality Assurance\n\n- Implement a comprehensive testing strategy including unit, integration, and end-to-end tests.\n- Use a `setup` function in test files to set default state and initialize variables.\n- Use Foundry's fuzzing capabilities to uncover edge cases with property-based testing.\n- Take advantage of Foundry's test cheatcodes for advanced testing scenarios.\n- Write invariant tests for critical contract properties using Foundry's invariant testing features.\n- Use Foundry's Fuzz testing to automatically generate test cases and find edge case bugs.\n- Implement stateful fuzzing tests for complex state transitions.\n- Implement gas usage tests to ensure operations remain efficient.\n- Use Foundry's fork testing capabilities to test against live environments.\n- Implement differential testing by comparing implementations.\n- Conduct regular security audits and bug bounties for production-grade contracts.\n- Use test coverage tools and aim for high test coverage, especially for critical paths.\n- Write appropriate test fixtures using Foundry's standard libraries.\n- Use Foundry's vm.startPrank/vm.stopPrank for testing access control mechanisms.\n- Implement proper setup and teardown in test files.\n- If deterministic testing is being done, ensure that the `foundry.toml` file has `block_number` and `block_timestamp` values.\n\nPerformance Optimization\n\n- Optimize contracts for gas efficiency, considering storage layout and function optimization.\n- Implement efficient indexing and querying strategies for off-chain data.\n\nDevelopment Workflow\n\n- Utilize Foundry's forge for compilation, testing, and deployment.\n- Use Foundry's cast for command-line interaction with contracts.\n- Implement comprehensive Foundry scripts for deployment and verification.\n- Use Foundry's script capabilities for complex deployment sequences.\n- Implement a robust CI/CD pipeline for smart contract deployments.\n- Use static type checking and linting tools in pre-commit hooks.\n- Utilize `forge fmt` if prompted about consistent code formatting.\n\nDocumentation\n\n- Document code thoroughly, focusing on why rather than what.\n- Maintain up-to-date API documentation for smart contracts.\n- Create and maintain comprehensive project documentation, including architecture diagrams and decision logs.\n- Document test scenarios and their purpose clearly.\n- Document any assumptions made in the contract design.\n\nDependencies\n\n- Use OpenZeppelin (openzeppelin/openzeppelin-contracts) as the main source of dependencies.\n- Use Solady (vectorized/solady) when gas optimization is crucial.\n- Ensure that any libraries used are installed with forge, and remappings are set.\n- Place remappings in `foundry.toml` instead of a `remappings.txt` file.\n\nConfiguring Environment\n\nOne or more of the following profiles can be added to `foundry.toml` as needed for the project.\n\n- When via_ir is required:\n\n```\n# via_ir pipeline is very slow - use a separate profile to pre-compile and then use vm.getCode to deploy\n[profile.via_ir]\nvia_ir = true\n# do not compile tests when compiling via-ir\ntest = 'src'\nout = 'via_ir-out'\n```\n\n- When deterministic deployment is required:\n\n```\n[profile.deterministic]\n# ensure that block number + timestamp are realistic when running tests\nblock_number = 17722462\nblock_timestamp = 1689711647\n# don't pollute bytecode with metadata\nbytecode_hash = 'none'\ncbor_metadata = false\n```\n","tokens":1555,"sizeBytes":7946}],"systemPromptSnippet":"<yakaai_skills repo=\"argotorg/solidity\">\n<!-- File: test/tools/ossfuzz/README.md (Tokens: ~1096 | Category: plugin-manifest) -->\n## Intro\n\n[oss-fuzz][1] is Google's fuzzing infrastructure that performs continuous fuzzing. What this means is that, each and every upstream commit is automatically fetched by the infrastructure and fuzzed on a daily basis.\n\n## How to build fuzzers?\n\nWe have multiple fuzzers, some based on string input and others on protobuf input. To build them, please do the following:\n\n- Create a local docker image from `Dockerfile.ubuntu.clang.ossfuzz` in the `.circleci/docker` sub-directory. Please note that this step is likely to take at least an hour to complete. Therefore, it is recommended to do it when you are away from the computer (and the computer is plugged to power since we do not want a battery drain).\n\n```\n$ cd .circleci/docker\n$ docker build -t solidity-ossfuzz-local -f Dockerfile.ubuntu.clang.ossfuzz .\n```\n\n- Login to the docker container sourced from the image built in the previous step from the solidity parent directory\n\n```\n## Host\n$ cd solidity\n$ docker run -v `pwd`:/src/solidity -ti solidity-ossfuzz-local /bin/bash\n## Docker shell\n$ cd /src/solidity\n```\n\n- Run cmake and build fuzzer harnesses\n\n```\n## Docker shell\n$ cd /src/solidity\n$ rm -rf fuzzer-build && mkdir fuzzer-build && cd fuzzer-build\n## Compile protobuf C++ bindings\n$ protoc --proto_path=../test/tools/ossfuzz yulProto.proto --cpp_out=../test/tools/ossfuzz\n$ protoc --proto_path=../test/tools/ossfuzz abiV2Proto.proto --cpp_out=../test/tools/ossfuzz\n$ protoc --proto_path=../test/tools/ossfuzz solProto.proto --cpp_out=../test/tools/ossfuzz\n## Run cmake\n$ export CC=clang CXX=clang++\n$ cmake -DCMAKE_TOOLCHAIN_FILE=cmake/toolchains/libfuzzer.cmake -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE:-Release} ..\n$ make ossfuzz ossfuzz_proto ossfuzz_abiv2 -j\n```\n\n## Why the elaborate docker image to build fuzzers?\n\nFor the following reasons:\n\n- Fuzzing binaries **must** link against libc++ and not libstdc++\n  - This is [because][2] (1) MemorySanitizer (which flags uses of uninitialized memory) depends on libc++; and (2) because libc++ is instrumented (to check for memory and type errors) and libstdc++ not, the former may find more bugs.\n\n- Linking against libc++ requires us to compile everything solidity depends on from source (and link these against libc++ as well)\n\n- To reproduce the compiler versions used by upstream oss-fuzz bots, we need to reuse their docker image containing the said compiler versions\n\n- Some fuzzers depend on libprotobuf, libprotobuf-mutator, libevmone etc. which may not be available locally; even if they were they might not be the right versions\n\n## What is LIB\\_FUZZING\\_ENGINE?\n\noss-fuzz contains multiple fuzzer back-ends i.e., fuzzers. Each back-end may require different linker flags. oss-fuzz builder bot defines the correct linker flags via a bash environment variable called `LIB_FUZZING_ENGINE`.\n\nFor the solidity ossfuzz CI build, we use the libFuzzer back-end. This back-end requires us to manually set the `LIB_FUZZING_ENGINE` to `-fsanitize=fuzzer`.\n\n## What does the ossfuzz directory contain?\n\nTo help oss-fuzz do this, we (as project maintainers) need to provide the following:\n\n- test harnesses: C/C++ tests that define the `LLVMFuzzerTestOneInput` API. This determines what is to be fuzz tested.\n- build infrastructure: (c)make targets per fuzzing binary. Fuzzing requires coverage and memory instrumentation of the code to be fuzzed.\n- configuration files: These are files with the `.options` extension that are parsed by oss-fuzz. The only option that we use currently is the `dictionary` option that asks the fuzzing engines behind oss-fuzz to use the specified dictionary. The specified dictionary happens to be `solidity.dict.`\n\n`solidity.dict` contains Solidity-specific syntactical tokens that are more likely to guide the fuzzer towards generating parseable and varied Solidity input.\n\nTo be consistent and aid better evaluation of the utility of the fuzzing dictionary, we stick to the following rules-of-thumb:\n  - Full tokens such as `block.number` are preceded and followed by a whitespace\n  - Incomplete tokens including function calls such as `msg.sender.send()` are abbreviated `.send(` to provide some leeway to the fuzzer to synthesize variants such as `address(this).send()`\n  - Language keywords are suffixed by a whitespace with the exception of those that end a line of code such as `break;` and `continue;`\n\n[1]: https://github.com/google/oss-fuzz\n[2]: https://github.com/google/oss-fuzz/issues/1114#issuecomment-360660201\n\n<!-- File: tools/yulPhaser/README.md (Tokens: ~1093 | Category: plugin-manifest) -->\n## yul-phaser\n`yul-phaser` is an internal tool for finding good sequences of [optimisation steps](/libyul/optimiser/README.md) for Yul optimiser.\n\n### How it works\nThe space of possible solutions to this problem (usually referred to as _phase-ordering problem_) is extremely large and there may even be no single sequence that produces optimal results for all possible programs.\n\nThe tool uses genetic algorithms to find sequences that result in better programs than others and to iteratively refine them.\nThe input is a set of one or more [Yul](/docs/yul.rst) programs and each sequence is applied to all of these programs.\nOptimised programs are given numeric scores according to the selected metric.\n\nOptimisation step sequences are presented in an abbreviated form - as strings of letters where each character represents one step.\nThere's a [table listing available abbreviations in the optimiser docs](/docs/yul.rst#optimization-step-sequence).\n\n### How to use it\nThe application has sensible defaults for most parameters.\nAn invocation can be as simple as:\n\n``` bash\ntools/yul-phaser ../test/libyul/yulOptimizerTests/fullSuite/*.yul \\\n    --random-population 100\n```\n\nThis assumes that you have a working copy of the Solidity repository and you're in the build directory within that working copy.\n\nRun `yul-phaser --help` for a full list of available options.\n\n#### Restarting from a previous state\n`yul-phaser` can save the list of sequences found after each round:\n\n``` bash\ntools/yul-phaser *.yul        \\\n    --random-population   100 \\\n    --population-autosave /tmp/population.txt\n```\n\nIf you stop the application, you can later use the file to continue the search from the point you left off:\n\n``` bash\ntools/yul-phaser *.yul                         \\\n    --population-from-file /tmp/population.txt \\\n    --population-autosave  /tmp/population.txt\n```\n\n#### Analysing a sequence\nApart from running the genetic algorithm, `yul-phaser` can also provide useful information about a particular sequence.\n\nFor example, to see the value of a particular metric for a given sequence and program run:\n``` bash\ntools/yul-phaser *.yul            \\\n    --show-initial-population     \\\n    --rounds            0         \\\n    --metric            code-size \\\n    --metric-aggregator sum       \\\n    --population        <your sequence>\n```\n\nYou can also easily see program code after being optimised using that sequence:\n``` bash\ntools/yul-phaser *.yul                    \\\n    --rounds     0                        \\\n    --mode       print-optimised-programs \\\n    --population <your sequence>\n```\n\n#### Using output from Solidity compiler\n`yul-phaser` can process the intermediate representation produced by `solc`:\n\n``` bash\nsolc/solc <sol file> --ir --output-dir <output directory>\n```\n\nAfter running this command you'll find one or more .yul files in the output directory.\nThese files contain whole Yul objects rather than just raw Yul programs but `yul-phaser` is prepared to handle them too.\n\n#### Using optimisation step sequences with the compiler\nYou can tell Yul optimiser to use a specific sequence for your code by passing `--yul-optimizations` option to `solc`:\n\n``` bash\nsolc/solc <sol file> --optimize --ir-optimized --yul-optimizations <sequence>\n```\n\n### How to choose good parameters\nChoosing good parameters for a genetic algorithm is not a trivial task but phaser's defaults are generally enough to find a sequence that gives results comparable or better than one hand-crafted by an experienced developer for a given set of programs.\nThe difficult part is providing a fairly representative set of input files.\nIf the files you give do not need certain optimisations the tool will find sequences that do not use these optimisations and perform badly for programs that could benefit from them.\nIf all the provided files greatly benefit from a specific optimisation, the sequence may not work well for programs that do not.\n\nWe have conducted [a set of rough experiments](https://github.com/argotorg/solidity/issues/7806#issuecomment-598644491) to evaluate some combinations of parameter values.\nThe conclusions were used to adjust the defaults but you might still benefit from some general observations:\n\n1. The algorithm that performed the best was `GEWEP`.\n2. Using longer sequences in the initial population yields better results. The algorithm is good at removing superfluous steps.\n3. Preserving the top sequences from previous rounds improves results. Elite should contain at least a few individuals, especially when using the `classic` algorithm.\n4. Do not set mutation/deletion/addition chance too high. It makes results worse because it destroys the good patterns preserved by crossover. Values around 1-5% seem to work best.\n5. Keep the algorithm running for 1000 rounds or more. It usually finds good sequences faster than that but it can shorten them significantly if you let it run longer. This is especially important when starting with long sequences.\n\n<!-- File: .cursorrules (solidity-foundry-cursorrules-prompt-file.mdc) (Tokens: ~1555 | Category: cursor-rule) -->\n---\ndescription: \"Cursor rules for Solidity development with Foundry integration.\"\nglobs: **/*\nalwaysApply: false\n---\nYou are an expert in Solidity and smart contract security.\n\nGeneral Rules\n\n- Cut the fluff. Code or detailed explanations only.\n- Keep it casual and brief.\n- Accuracy and depth matter.\n- Answer first, explain later if needed.\n- Logic trumps authority. Don't care about sources.\n- Embrace new tech and unconventional ideas.\n- Wild speculation's fine, just flag it.\n- Save the ethics talk.\n- Only mention safety for non-obvious, critical issues.\n- Push content limits if needed, explain after.\n- Sources at the end, not mid-text.\n- Skip the AI self-references and knowledge date stuff.\n- Stick to my code style.\n- Use multiple responses for complex answers.\n- For code tweaks, show minimal context - a few lines around changes max.\n- Don't be lazy, write all the code to implement features I ask for.\n- Warn users if they add a private key directly into a non-environment file and replace with an env reference.\n\nSolidity Best Practices\n\n- Use explicit function visibility modifiers and appropriate natspec comments.\n- Utilize function modifiers for common checks, enhancing readability and reducing redundancy.\n- Follow consistent naming: CamelCase for contracts, PascalCase for interfaces (prefixed with \"I\").\n- Implement the Interface Segregation Principle for flexible and maintainable contracts.\n- Design upgradeable contracts using proven patterns like the proxy pattern when necessary.\n- Implement comprehensive events for all significant state changes.\n- Follow the Checks-Effects-Interactions pattern to prevent reentrancy and other vulnerabilities.\n- Use static analysis tools like Slither and Mythril in the development workflow.\n- Implement timelocks and multisig controls for sensitive operations in production.\n- Conduct thorough gas optimization, considering both deployment and runtime costs.\n- Use OpenZeppelin's AccessControl for fine-grained permissions.\n- Use Solidity 0.8.0+ for built-in overflow/underflow protection.\n- Implement circuit breakers (pause functionality) using OpenZeppelin's Pausable when appropriate.\n- Use pull over push payment patterns to mitigate reentrancy and denial of service attacks.\n- Implement rate limiting for sensitive functions to prevent abuse.\n- Use OpenZeppelin's SafeERC20 for interacting with ERC20 tokens.\n- Implement proper randomness using Chainlink VRF or similar oracle solutions.\n- Use assembly for gas-intensive operations, but document extensively and use with caution.\n  - If Solady has an implementation built already, use that instead of writing assembly from scratch.\n- Implement effective state machine patterns for complex contract logic.\n- Use OpenZeppelin's ReentrancyGuard as an additional layer of protection against reentrancy.\n- Implement proper access control for initializers in upgradeable contracts.\n- Use OpenZeppelin's ERC20Snapshot for token balances requiring historical lookups.\n- Implement timelocks for sensitive operations using OpenZeppelin's TimelockController.\n- Use OpenZeppelin's ERC20Permit for gasless approvals in token contracts.\n- Implement proper slippage protection for DEX-like functionalities.\n- Use OpenZeppelin's ERC20Votes for governance token implementations.\n- Implement effective storage patterns to optimize gas costs (e.g., packing variables).\n- Use libraries for complex operations to reduce contract size and improve reusability.\n- Implement proper access control for self-destruct functionality, if used.\n  - Use freezable patterns instead of depricated `selfdestruct`.\n- Use OpenZeppelin's Address library for safe interactions with external contracts.\n- Use custom errors instead of revert strings for gas efficiency and better error handling.\n- Implement NatSpec comments for all public and external functions.\n- Use immutable variables for values set once at construction time.\n- Implement proper inheritance patterns, favoring composition over deep inheritance chains.\n- Use events for off-chain logging and indexing of important state changes.\n- Implement fallback and receive functions with caution, clearly documenting their purpose.\n- Use view and pure function modifiers appropriately to signal state access patterns.\n- Implement proper decimal handling for financial calculations, using fixed-point arithmetic libraries when necessary.\n- Use assembly sparingly and only when necessary for optimizations, with thorough documentation.\n- Implement effective error propagation patterns in internal functions.\n\nTesting and Quality Assurance\n\n- Implement a comprehensive testing strategy including unit, integration, and end-to-end tests.\n- Use a `setup` function in test files to set default state and initialize variables.\n- Use Foundry's fuzzing capabilities to uncover edge cases with property-based testing.\n- Take advantage of Foundry's test cheatcodes for advanced testing scenarios.\n- Write invariant tests for critical contract properties using Foundry's invariant testing features.\n- Use Foundry's Fuzz testing to automatically generate test cases and find edge case bugs.\n- Implement stateful fuzzing tests for complex state transitions.\n- Implement gas usage tests to ensure operations remain efficient.\n- Use Foundry's fork testing capabilities to test against live environments.\n- Implement differential testing by comparing implementations.\n- Conduct regular security audits and bug bounties for production-grade contracts.\n- Use test coverage tools and aim for high test coverage, especially for critical paths.\n- Write appropriate test fixtures using Foundry's standard libraries.\n- Use Foundry's vm.startPrank/vm.stopPrank for testing access control mechanisms.\n- Implement proper setup and teardown in test files.\n- If deterministic testing is being done, ensure that the `foundry.toml` file has `block_number` and `block_timestamp` values.\n\nPerformance Optimization\n\n- Optimize contracts for gas efficiency, considering storage layout and function optimization.\n- Implement efficient indexing and querying strategies for off-chain data.\n\nDevelopment Workflow\n\n- Utilize Foundry's forge for compilation, testing, and deployment.\n- Use Foundry's cast for command-line interaction with contracts.\n- Implement comprehensive Foundry scripts for deployment and verification.\n- Use Foundry's script capabilities for complex deployment sequences.\n- Implement a robust CI/CD pipeline for smart contract deployments.\n- Use static type checking and linting tools in pre-commit hooks.\n- Utilize `forge fmt` if prompted about consistent code formatting.\n\nDocumentation\n\n- Document code thoroughly, focusing on why rather than what.\n- Maintain up-to-date API documentation for smart contracts.\n- Create and maintain comprehensive project documentation, including architecture diagrams and decision logs.\n- Document test scenarios and their purpose clearly.\n- Document any assumptions made in the contract design.\n\nDependencies\n\n- Use OpenZeppelin (openzeppelin/openzeppelin-contracts) as the main source of dependencies.\n- Use Solady (vectorized/solady) when gas optimization is crucial.\n- Ensure that any libraries used are installed with forge, and remappings are set.\n- Place remappings in `foundry.toml` instead of a `remappings.txt` file.\n\nConfiguring Environment\n\nOne or more of the following profiles can be added to `foundry.toml` as needed for the project.\n\n- When via_ir is required:\n\n```\n# via_ir pipeline is very slow - use a separate profile to pre-compile and then use vm.getCode to deploy\n[profile.via_ir]\nvia_ir = true\n# do not compile tests when compiling via-ir\ntest = 'src'\nout = 'via_ir-out'\n```\n\n- When deterministic deployment is required:\n\n```\n[profile.deterministic]\n# ensure that block number + timestamp are realistic when running tests\nblock_number = 17722462\nblock_timestamp = 1689711647\n# don't pollute bytecode with metadata\nbytecode_hash = 'none'\ncbor_metadata = false\n```\n</yakaai_skills>"}