From 0751d0001634194c83aa8f18c5ff6956c1f51c7a Mon Sep 17 00:00:00 2001 From: unarbos Date: Fri, 21 Aug 2026 20:28:40 -0300 Subject: [PATCH 1/2] Add canonical rails: buy staked subnet alpha from MetaMask with USDC. One ERC-20 per subnet on an EVM chain (demo: fake Base on anvil), each backed 1:1 by staked alpha in a hub escrow on Bittensor. Buys lock USDC, mint tUSD, swap through a protocol-owned pool, and stake; balances rebase as emissions accrue; sells unwind back to USDC. Ships pallet-usd-psm, the USD precompile, Gateway/Portal/share-token contracts, a Hyperlane-based local rig (8 subnets with real mainnet identities), a MetaMask demo page, and an e2e suite. See swapdemo.md to run it. Co-authored-by: Cursor --- .gitignore | 6 + Cargo.lock | 52 + Cargo.toml | 3 + common/Cargo.toml | 4 + common/src/lib.rs | 1 + common/src/rails.rs | 490 + contracts/evm/export-artifacts.sh | 29 + contracts/evm/foundry.toml | 15 + contracts/evm/lib/forge-std/.gitattributes | 1 + contracts/evm/lib/forge-std/.gitignore | 4 + contracts/evm/lib/forge-std/CONTRIBUTING.md | 193 + contracts/evm/lib/forge-std/LICENSE-APACHE | 203 + contracts/evm/lib/forge-std/LICENSE-MIT | 25 + contracts/evm/lib/forge-std/README.md | 314 + .../evm/lib/forge-std/RELEASE_CHECKLIST.md | 12 + contracts/evm/lib/forge-std/foundry.toml | 18 + contracts/evm/lib/forge-std/package.json | 16 + contracts/evm/lib/forge-std/scripts/vm.py | 655 + contracts/evm/lib/forge-std/src/Base.sol | 48 + contracts/evm/lib/forge-std/src/Config.sol | 60 + .../evm/lib/forge-std/src/LibVariable.sol | 477 + contracts/evm/lib/forge-std/src/Script.sol | 30 + .../evm/lib/forge-std/src/StdAssertions.sol | 1300 ++ contracts/evm/lib/forge-std/src/StdChains.sol | 316 + contracts/evm/lib/forge-std/src/StdCheats.sol | 922 ++ contracts/evm/lib/forge-std/src/StdConfig.sol | 632 + .../evm/lib/forge-std/src/StdConstants.sol | 30 + contracts/evm/lib/forge-std/src/StdError.sol | 33 + .../evm/lib/forge-std/src/StdInvariant.sol | 161 + contracts/evm/lib/forge-std/src/StdJson.sol | 327 + contracts/evm/lib/forge-std/src/StdMath.sol | 68 + .../evm/lib/forge-std/src/StdStorage.sol | 582 + contracts/evm/lib/forge-std/src/StdStyle.sol | 410 + contracts/evm/lib/forge-std/src/StdToml.sol | 323 + contracts/evm/lib/forge-std/src/StdUtils.sol | 247 + contracts/evm/lib/forge-std/src/Test.sol | 34 + contracts/evm/lib/forge-std/src/Vm.sol | 2700 ++++ contracts/evm/lib/forge-std/src/console.sol | 1599 ++ contracts/evm/lib/forge-std/src/console2.sol | 4 + .../lib/forge-std/src/interfaces/IERC1155.sol | 105 + .../lib/forge-std/src/interfaces/IERC165.sol | 12 + .../lib/forge-std/src/interfaces/IERC20.sol | 43 + .../lib/forge-std/src/interfaces/IERC4626.sol | 190 + .../lib/forge-std/src/interfaces/IERC6909.sol | 72 + .../lib/forge-std/src/interfaces/IERC721.sol | 164 + .../lib/forge-std/src/interfaces/IERC7540.sol | 145 + .../lib/forge-std/src/interfaces/IERC7575.sol | 241 + .../forge-std/src/interfaces/IMulticall3.sol | 68 + .../evm/lib/forge-std/src/safeconsole.sol | 13248 ++++++++++++++++ .../evm/lib/forge-std/test/CommonBase.t.sol | 44 + contracts/evm/lib/forge-std/test/Config.t.sol | 381 + .../evm/lib/forge-std/test/LibVariable.t.sol | 452 + .../lib/forge-std/test/StdAssertions.t.sol | 141 + .../evm/lib/forge-std/test/StdChains.t.sol | 227 + .../evm/lib/forge-std/test/StdCheats.t.sol | 695 + .../evm/lib/forge-std/test/StdConstants.t.sol | 38 + .../evm/lib/forge-std/test/StdError.t.sol | 119 + .../evm/lib/forge-std/test/StdJson.t.sol | 49 + .../evm/lib/forge-std/test/StdMath.t.sol | 202 + .../evm/lib/forge-std/test/StdStorage.t.sol | 589 + .../evm/lib/forge-std/test/StdStyle.t.sol | 110 + .../evm/lib/forge-std/test/StdToml.t.sol | 49 + .../evm/lib/forge-std/test/StdUtils.t.sol | 342 + contracts/evm/lib/forge-std/test/Vm.t.sol | 18 + .../test/compilation/CompilationScript.sol | 8 + .../compilation/CompilationScriptBase.sol | 8 + .../test/compilation/CompilationTest.sol | 8 + .../test/compilation/CompilationTestBase.sol | 8 + .../test/fixtures/broadcast.log.json | 187 + .../lib/forge-std/test/fixtures/config.toml | 81 + .../evm/lib/forge-std/test/fixtures/test.json | 8 + .../evm/lib/forge-std/test/fixtures/test.toml | 6 + contracts/evm/script/DeployBase.s.sol | 82 + contracts/evm/script/DeployBittensor.s.sol | 30 + contracts/evm/src/BaseERC20.sol | 76 + contracts/evm/src/CanonicalShareToken.sol | 92 + contracts/evm/src/Chutes.sol | 204 + contracts/evm/src/EnvelopeLib.sol | 94 + contracts/evm/src/Gateway.sol | 72 + contracts/evm/src/MockUSDC.sol | 15 + contracts/evm/src/RailsPortal.sol | 138 + contracts/evm/src/RateLimits.sol | 60 + contracts/evm/src/interfaces/IMailbox.sol | 17 + .../evm/src/interfaces/IMessageRecipient.sol | 7 + contracts/evm/src/interfaces/IUsdRails.sol | 38 + contracts/evm/test/CanonicalShareToken.t.sol | 50 + contracts/evm/test/Chutes.t.sol | 139 + contracts/evm/test/GatewayPortal.t.sol | 150 + contracts/evm/test/RateLimits.t.sol | 55 + contracts/evm/test/mocks/MockMailbox.sol | 47 + contracts/evm/test/mocks/MockUsdRails.sol | 23 + demo/index.html | 1061 ++ docs/canonical-rails-design.md | 284 + justfile | 30 + node/Cargo.toml | 2 + node/src/rpc.rs | 4 + pallets/admin-utils/src/lib.rs | 2 + pallets/usd-psm/Cargo.toml | 39 + pallets/usd-psm/rpc/Cargo.toml | 17 + pallets/usd-psm/rpc/src/lib.rs | 159 + pallets/usd-psm/runtime-api/Cargo.toml | 33 + pallets/usd-psm/runtime-api/src/lib.rs | 89 + pallets/usd-psm/src/lib.rs | 1292 ++ pallets/usd-psm/src/mock.rs | 222 + pallets/usd-psm/src/tests.rs | 565 + precompiles/Cargo.toml | 2 + precompiles/src/lib.rs | 28 +- precompiles/src/mock.rs | 15 + precompiles/src/registry.rs | 2 + precompiles/src/solidity/usd.abi | 151 + precompiles/src/solidity/usd.sol | 35 + precompiles/src/usd.rs | 124 + runtime/Cargo.toml | 6 + runtime/src/lib.rs | 225 + runtime/tests/rails_evm_pool_validation.rs | 178 + scripts/localnet.sh | 10 + scripts/rails/agents.sh | 88 + scripts/rails/demo.sh | 17 + scripts/rails/deploy-contracts.sh | 194 + scripts/rails/down.sh | 44 + scripts/rails/env.sh | 73 + scripts/rails/hyperlane-deploy.sh | 54 + .../rails/hyperlane/baselocal.metadata.yaml | 18 + scripts/rails/hyperlane/btlocal.metadata.yaml | 18 + scripts/rails/hyperlane/core-config.yaml | 17 + scripts/rails/manifest.sh | 64 + scripts/rails/ping.sh | 64 + scripts/rails/subnets.json | 66 + scripts/rails/up.sh | 56 + swapdemo.md | 82 + ts-tests/moonwall.config.json | 28 +- ts-tests/scripts/rails-bootstrap.ts | 89 + ts-tests/scripts/rails-check-emissions.ts | 23 + ts-tests/scripts/rails-check-nonce.ts | 18 + ts-tests/scripts/rails-configure-pallet.ts | 305 + ts-tests/scripts/rails-debug-alpha.ts | 35 + ts-tests/scripts/rails-debug-balance.ts | 23 + ts-tests/scripts/rails-envelope.ts | 90 + .../rails/fixtures/golden-envelopes.json | 66 + ts-tests/suites/rails/test-rails-buy-sell.ts | 195 + ts-tests/suites/rails/test-rails-failures.ts | 194 + ts-tests/suites/rails/test-rails-golden.ts | 118 + ts-tests/utils/rails-artifacts.json | 12 + ts-tests/utils/rails.ts | 375 + 144 files changed, 38789 insertions(+), 3 deletions(-) create mode 100644 common/src/rails.rs create mode 100755 contracts/evm/export-artifacts.sh create mode 100644 contracts/evm/foundry.toml create mode 100644 contracts/evm/lib/forge-std/.gitattributes create mode 100644 contracts/evm/lib/forge-std/.gitignore create mode 100644 contracts/evm/lib/forge-std/CONTRIBUTING.md create mode 100644 contracts/evm/lib/forge-std/LICENSE-APACHE create mode 100644 contracts/evm/lib/forge-std/LICENSE-MIT create mode 100644 contracts/evm/lib/forge-std/README.md create mode 100644 contracts/evm/lib/forge-std/RELEASE_CHECKLIST.md create mode 100644 contracts/evm/lib/forge-std/foundry.toml create mode 100644 contracts/evm/lib/forge-std/package.json create mode 100755 contracts/evm/lib/forge-std/scripts/vm.py create mode 100644 contracts/evm/lib/forge-std/src/Base.sol create mode 100644 contracts/evm/lib/forge-std/src/Config.sol create mode 100644 contracts/evm/lib/forge-std/src/LibVariable.sol create mode 100644 contracts/evm/lib/forge-std/src/Script.sol create mode 100644 contracts/evm/lib/forge-std/src/StdAssertions.sol create mode 100644 contracts/evm/lib/forge-std/src/StdChains.sol create mode 100644 contracts/evm/lib/forge-std/src/StdCheats.sol create mode 100644 contracts/evm/lib/forge-std/src/StdConfig.sol create mode 100644 contracts/evm/lib/forge-std/src/StdConstants.sol create mode 100644 contracts/evm/lib/forge-std/src/StdError.sol create mode 100644 contracts/evm/lib/forge-std/src/StdInvariant.sol create mode 100644 contracts/evm/lib/forge-std/src/StdJson.sol create mode 100644 contracts/evm/lib/forge-std/src/StdMath.sol create mode 100644 contracts/evm/lib/forge-std/src/StdStorage.sol create mode 100644 contracts/evm/lib/forge-std/src/StdStyle.sol create mode 100644 contracts/evm/lib/forge-std/src/StdToml.sol create mode 100644 contracts/evm/lib/forge-std/src/StdUtils.sol create mode 100644 contracts/evm/lib/forge-std/src/Test.sol create mode 100644 contracts/evm/lib/forge-std/src/Vm.sol create mode 100644 contracts/evm/lib/forge-std/src/console.sol create mode 100644 contracts/evm/lib/forge-std/src/console2.sol create mode 100644 contracts/evm/lib/forge-std/src/interfaces/IERC1155.sol create mode 100644 contracts/evm/lib/forge-std/src/interfaces/IERC165.sol create mode 100644 contracts/evm/lib/forge-std/src/interfaces/IERC20.sol create mode 100644 contracts/evm/lib/forge-std/src/interfaces/IERC4626.sol create mode 100644 contracts/evm/lib/forge-std/src/interfaces/IERC6909.sol create mode 100644 contracts/evm/lib/forge-std/src/interfaces/IERC721.sol create mode 100644 contracts/evm/lib/forge-std/src/interfaces/IERC7540.sol create mode 100644 contracts/evm/lib/forge-std/src/interfaces/IERC7575.sol create mode 100644 contracts/evm/lib/forge-std/src/interfaces/IMulticall3.sol create mode 100644 contracts/evm/lib/forge-std/src/safeconsole.sol create mode 100644 contracts/evm/lib/forge-std/test/CommonBase.t.sol create mode 100644 contracts/evm/lib/forge-std/test/Config.t.sol create mode 100644 contracts/evm/lib/forge-std/test/LibVariable.t.sol create mode 100644 contracts/evm/lib/forge-std/test/StdAssertions.t.sol create mode 100644 contracts/evm/lib/forge-std/test/StdChains.t.sol create mode 100644 contracts/evm/lib/forge-std/test/StdCheats.t.sol create mode 100644 contracts/evm/lib/forge-std/test/StdConstants.t.sol create mode 100644 contracts/evm/lib/forge-std/test/StdError.t.sol create mode 100644 contracts/evm/lib/forge-std/test/StdJson.t.sol create mode 100644 contracts/evm/lib/forge-std/test/StdMath.t.sol create mode 100644 contracts/evm/lib/forge-std/test/StdStorage.t.sol create mode 100644 contracts/evm/lib/forge-std/test/StdStyle.t.sol create mode 100644 contracts/evm/lib/forge-std/test/StdToml.t.sol create mode 100644 contracts/evm/lib/forge-std/test/StdUtils.t.sol create mode 100644 contracts/evm/lib/forge-std/test/Vm.t.sol create mode 100644 contracts/evm/lib/forge-std/test/compilation/CompilationScript.sol create mode 100644 contracts/evm/lib/forge-std/test/compilation/CompilationScriptBase.sol create mode 100644 contracts/evm/lib/forge-std/test/compilation/CompilationTest.sol create mode 100644 contracts/evm/lib/forge-std/test/compilation/CompilationTestBase.sol create mode 100644 contracts/evm/lib/forge-std/test/fixtures/broadcast.log.json create mode 100644 contracts/evm/lib/forge-std/test/fixtures/config.toml create mode 100644 contracts/evm/lib/forge-std/test/fixtures/test.json create mode 100644 contracts/evm/lib/forge-std/test/fixtures/test.toml create mode 100644 contracts/evm/script/DeployBase.s.sol create mode 100644 contracts/evm/script/DeployBittensor.s.sol create mode 100644 contracts/evm/src/BaseERC20.sol create mode 100644 contracts/evm/src/CanonicalShareToken.sol create mode 100644 contracts/evm/src/Chutes.sol create mode 100644 contracts/evm/src/EnvelopeLib.sol create mode 100644 contracts/evm/src/Gateway.sol create mode 100644 contracts/evm/src/MockUSDC.sol create mode 100644 contracts/evm/src/RailsPortal.sol create mode 100644 contracts/evm/src/RateLimits.sol create mode 100644 contracts/evm/src/interfaces/IMailbox.sol create mode 100644 contracts/evm/src/interfaces/IMessageRecipient.sol create mode 100644 contracts/evm/src/interfaces/IUsdRails.sol create mode 100644 contracts/evm/test/CanonicalShareToken.t.sol create mode 100644 contracts/evm/test/Chutes.t.sol create mode 100644 contracts/evm/test/GatewayPortal.t.sol create mode 100644 contracts/evm/test/RateLimits.t.sol create mode 100644 contracts/evm/test/mocks/MockMailbox.sol create mode 100644 contracts/evm/test/mocks/MockUsdRails.sol create mode 100644 demo/index.html create mode 100644 docs/canonical-rails-design.md create mode 100644 pallets/usd-psm/Cargo.toml create mode 100644 pallets/usd-psm/rpc/Cargo.toml create mode 100644 pallets/usd-psm/rpc/src/lib.rs create mode 100644 pallets/usd-psm/runtime-api/Cargo.toml create mode 100644 pallets/usd-psm/runtime-api/src/lib.rs create mode 100644 pallets/usd-psm/src/lib.rs create mode 100644 pallets/usd-psm/src/mock.rs create mode 100644 pallets/usd-psm/src/tests.rs create mode 100644 precompiles/src/solidity/usd.abi create mode 100644 precompiles/src/solidity/usd.sol create mode 100644 precompiles/src/usd.rs create mode 100644 runtime/tests/rails_evm_pool_validation.rs create mode 100755 scripts/rails/agents.sh create mode 100755 scripts/rails/demo.sh create mode 100755 scripts/rails/deploy-contracts.sh create mode 100755 scripts/rails/down.sh create mode 100755 scripts/rails/env.sh create mode 100755 scripts/rails/hyperlane-deploy.sh create mode 100644 scripts/rails/hyperlane/baselocal.metadata.yaml create mode 100644 scripts/rails/hyperlane/btlocal.metadata.yaml create mode 100644 scripts/rails/hyperlane/core-config.yaml create mode 100755 scripts/rails/manifest.sh create mode 100755 scripts/rails/ping.sh create mode 100644 scripts/rails/subnets.json create mode 100755 scripts/rails/up.sh create mode 100644 swapdemo.md create mode 100644 ts-tests/scripts/rails-bootstrap.ts create mode 100644 ts-tests/scripts/rails-check-emissions.ts create mode 100644 ts-tests/scripts/rails-check-nonce.ts create mode 100644 ts-tests/scripts/rails-configure-pallet.ts create mode 100644 ts-tests/scripts/rails-debug-alpha.ts create mode 100644 ts-tests/scripts/rails-debug-balance.ts create mode 100644 ts-tests/scripts/rails-envelope.ts create mode 100644 ts-tests/suites/rails/fixtures/golden-envelopes.json create mode 100644 ts-tests/suites/rails/test-rails-buy-sell.ts create mode 100644 ts-tests/suites/rails/test-rails-failures.ts create mode 100644 ts-tests/suites/rails/test-rails-golden.ts create mode 100644 ts-tests/utils/rails-artifacts.json create mode 100644 ts-tests/utils/rails.ts diff --git a/.gitignore b/.gitignore index 95e13311e5..682ba847aa 100644 --- a/.gitignore +++ b/.gitignore @@ -91,3 +91,9 @@ sdk/python/dist/ .github/scripts/deploy/proxy_proxy_blob.hex .github/scripts/deploy/pending-release.json .github/scripts/deploy/deployment-multisig-proposal.hex + +# Canonical rails local rig state and foundry build outputs +.rails/ +contracts/evm/out/ +contracts/evm/cache/ +contracts/evm/broadcast/ diff --git a/Cargo.lock b/Cargo.lock index 80d546694e..0d130c6992 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8711,6 +8711,8 @@ dependencies = [ "pallet-transaction-payment", "pallet-transaction-payment-rpc", "pallet-transaction-payment-rpc-runtime-api", + "pallet-usd-psm-rpc", + "pallet-usd-psm-runtime-api", "polkadot-sdk", "sc-basic-authorship", "sc-chain-spec", @@ -8793,6 +8795,7 @@ dependencies = [ "frame-system-rpc-runtime-api", "frame-try-runtime", "hex", + "libsecp256k1", "log", "pallet-admin-utils", "pallet-alpha-assets", @@ -8841,6 +8844,8 @@ dependencies = [ "pallet-timestamp", "pallet-transaction-payment", "pallet-transaction-payment-rpc-runtime-api", + "pallet-usd-psm", + "pallet-usd-psm-runtime-api", "parity-scale-codec", "polkadot-runtime-common", "precompile-utils", @@ -11531,6 +11536,50 @@ dependencies = [ "sp-runtime", ] +[[package]] +name = "pallet-usd-psm" +version = "0.1.0" +dependencies = [ + "frame-support", + "frame-system", + "log", + "pallet-balances", + "parity-scale-codec", + "scale-info", + "sp-core", + "sp-io", + "sp-runtime", + "subtensor-macros", + "subtensor-runtime-common", +] + +[[package]] +name = "pallet-usd-psm-rpc" +version = "0.1.0" +dependencies = [ + "jsonrpsee", + "pallet-usd-psm-runtime-api", + "sp-api", + "sp-blockchain", + "sp-core", + "sp-runtime", +] + +[[package]] +name = "pallet-usd-psm-runtime-api" +version = "0.1.0" +dependencies = [ + "frame-support", + "parity-scale-codec", + "scale-info", + "serde", + "sp-api", + "sp-core", + "sp-std", + "subtensor-macros", + "subtensor-runtime-common", +] + [[package]] name = "pallet-utility" version = "41.0.0" @@ -18992,6 +19041,7 @@ dependencies = [ "pallet-subtensor-proxy", "pallet-subtensor-swap", "pallet-timestamp", + "pallet-usd-psm", "parity-scale-codec", "precompile-utils", "scale-info", @@ -19011,6 +19061,8 @@ dependencies = [ "approx", "environmental", "frame-support", + "hex", + "hex-literal", "impl-trait-for-tuples", "num-traits", "parity-scale-codec", diff --git a/Cargo.toml b/Cargo.toml index c65e70952e..928120f1a1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -58,6 +58,9 @@ useless_conversion = "allow" # until polkadot is patched [workspace.dependencies] pallet-alpha-assets = { path = "pallets/alpha-assets", default-features = false } +pallet-usd-psm = { path = "pallets/usd-psm", default-features = false } +pallet-usd-psm-runtime-api = { path = "pallets/usd-psm/runtime-api", default-features = false } +pallet-usd-psm-rpc = { path = "pallets/usd-psm/rpc", default-features = false } node-subtensor-runtime = { path = "runtime", default-features = false } pallet-admin-utils = { path = "pallets/admin-utils", default-features = false } pallet-limit-orders = { path = "pallets/limit-orders", default-features = false } diff --git a/common/Cargo.toml b/common/Cargo.toml index 6188c966a2..84d7a13cf7 100644 --- a/common/Cargo.toml +++ b/common/Cargo.toml @@ -28,6 +28,10 @@ runtime-common.workspace = true impl-trait-for-tuples.workspace = true approx = { workspace = true, optional = true } +[dev-dependencies] +hex.workspace = true +hex-literal.workspace = true + [lints] workspace = true diff --git a/common/src/lib.rs b/common/src/lib.rs index aa92e318ee..bbf99881c4 100644 --- a/common/src/lib.rs +++ b/common/src/lib.rs @@ -26,6 +26,7 @@ use frame_support::weights::WeightMeter; mod currency; mod evm_context; mod proxy; +pub mod rails; mod transaction_error; /// Balance of an account. diff --git a/common/src/rails.rs b/common/src/rails.rs new file mode 100644 index 0000000000..16192ea684 --- /dev/null +++ b/common/src/rails.rs @@ -0,0 +1,490 @@ +//! Shared types for the canonical rails: the USD -> TAO -> alpha settlement +//! pipeline (tUSD ledger, PSM, canonical pool, gateway envelope wire format). +//! +//! The [`GatewayEnvelope`] byte format is the only cross-chain wire contract: +//! clients (SDK / btcli) SCALE-encode an envelope, bridge message bodies carry +//! it opaquely through Solidity, and the runtime decodes it in +//! `gateway_execute`. Solidity never parses envelope internals, so this module +//! is the single source of truth for the format. +//! +//! Versioning: the first byte of the wire format is a version tag. New +//! envelope layouts get a new version byte and a new decoder arm; existing +//! versions are never reinterpreted. + +use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen}; +use frame_support::pallet_prelude::*; +use scale_info::TypeInfo; +use serde::{Deserialize, Serialize}; +use sp_runtime::AccountId32; +use sp_runtime::Vec; +use subtensor_macros::freeze_struct; + +use crate::currency::AlphaBalance; +use crate::NetUid; + +/// Version tag for [`GatewayEnvelope`] wire encoding. +pub const ENVELOPE_VERSION_V1: u8 = 1; + +/// Number of decimals used by every rails asset on every chain (matches rao). +pub const RAILS_DECIMALS: u8 = 9; + +/// Identifier of an external USD-like asset registered in the PSM +/// (peg stability module) registry. +pub type UsdAssetId = u32; + +/// Canonical asset identifier used across runtime, precompiles, SDK and CLI. +/// +/// Non-exhaustive with explicit codec indices: new variants can be appended +/// without a storage migration and without disturbing existing encodings. +#[non_exhaustive] +#[derive( + Deserialize, + Serialize, + Clone, + Copy, + Decode, + DecodeWithMemTracking, + Encode, + Eq, + MaxEncodedLen, + PartialEq, + RuntimeDebug, + TypeInfo, +)] +pub enum AssetId { + /// Native TAO. + #[codec(index = 0)] + Tao, + /// Internal USD accounting unit. Never leaves the runtime. + #[codec(index = 1)] + TUsd, + /// Subnet alpha for a given netuid. + #[codec(index = 2)] + Alpha(NetUid), + /// An external USD asset registered in the PSM. + #[codec(index = 3)] + Usd(UsdAssetId), +} + +/// Action requested by an inbound gateway envelope, executed atomically by +/// the runtime after the deposited funds are secured. +/// +/// Action failures never revert the delivery: the fallback credits tUSD to +/// the destination account instead (see [`FallbackReason`]). +#[non_exhaustive] +#[derive( + Deserialize, + Serialize, + Clone, + Decode, + DecodeWithMemTracking, + Encode, + Eq, + MaxEncodedLen, + PartialEq, + RuntimeDebug, + TypeInfo, +)] +pub enum GatewayAction { + /// Credit tUSD to the destination account and stop. Also the fallback + /// outcome of every failed deposit-side action. + #[codec(index = 0)] + CreditTUsd, + // index 1 retired: SwapToTao (hub-side product, cut). + /// Swap for TAO, then stake into `netuid` under `hotkey`. + #[codec(index = 2)] + Stake { + netuid: NetUid, + hotkey: AccountId32, + min_alpha: AlphaBalance, + }, + // index 3 retired: ReleaseAlpha (unwrap-to-hub, cut). + /// Buy canonical shares: USD deposit -> pool swap -> stake into the hub + /// escrow -> mint shares (at the current index) to `recipient` on + /// `domain`. The envelope `amount` is the USD amount. + #[codec(index = 4)] + BuyShares { + netuid: NetUid, + /// EVM address receiving the share mint on the spoke chain. + recipient: [u8; 20], + min_alpha: AlphaBalance, + /// Hyperlane domain of the spoke chain (where the shares mint). + domain: u32, + }, + /// Sell canonical shares that were already burned on the spoke: unstake + /// escrowed alpha -> pool swap -> release `usd_asset` from PSM reserves + /// to `recipient` on `domain`. The envelope `amount` is the share count. + #[codec(index = 5)] + SellShares { + netuid: NetUid, + /// EVM address receiving the released USD on the spoke chain. + recipient: [u8; 20], + /// PSM asset to release reserves from. + usd_asset: UsdAssetId, + min_usd: u64, + /// Hyperlane domain of the spoke chain (where the USD releases). + domain: u32, + }, +} + +/// The v1 gateway envelope: the payload carried in bridge message bodies. +#[freeze_struct("73fb42f814f9019d")] +#[derive( + Deserialize, + Serialize, + Clone, + Decode, + DecodeWithMemTracking, + Encode, + Eq, + MaxEncodedLen, + PartialEq, + RuntimeDebug, + TypeInfo, +)] +pub struct GatewayEnvelope { + /// Asset being deposited (v1: always `AssetId::Usd(_)`). + pub asset: AssetId, + /// Amount in rails units (9 decimals). + pub amount: u64, + /// Destination account on the runtime. + pub dest: AccountId32, + /// What to do with the deposit once secured. + pub action: GatewayAction, + /// Origin-assigned sequential nonce. The runtime keeps a `NextNonce` + /// counter: an envelope executes only when its nonce equals the counter, + /// so deliveries are strictly ordered and replays are rejected. + pub nonce: u64, +} + +/// Why an envelope's requested action could not be executed. In every case +/// the deposit was still secured and tUSD was credited to `dest`. +#[non_exhaustive] +#[derive( + Deserialize, + Serialize, + Clone, + Copy, + Decode, + DecodeWithMemTracking, + Encode, + Eq, + MaxEncodedLen, + PartialEq, + RuntimeDebug, + TypeInfo, +)] +pub enum FallbackReason { + /// The requested action variant is unknown to this runtime version. + #[codec(index = 0)] + UnknownAction, + /// The canonical pool swap failed (e.g. slippage guard). + #[codec(index = 1)] + SwapFailed, + /// The staking leg failed (e.g. bad netuid, staking limits). + #[codec(index = 2)] + StakeFailed, + // index 3 retired: ReleaseFailed (unwrap-to-hub, cut). + /// The buy-shares pipeline failed after the deposit was secured; tUSD + /// stays credited to the buyer's mirror account. + #[codec(index = 4)] + BuyFailed, + /// The sell-shares pipeline failed. Shares were already burned on the + /// spoke; the receipt records the failure for manual follow-up (no tUSD + /// is credited). + #[codec(index = 5)] + SellFailed, +} + +/// Terminal record of an executed inbound envelope, stored per nonce. +#[freeze_struct("a2c07a90fc2eddc8")] +#[derive( + Deserialize, + Serialize, + Clone, + Copy, + Decode, + DecodeWithMemTracking, + Encode, + Eq, + MaxEncodedLen, + PartialEq, + RuntimeDebug, + TypeInfo, +)] +pub struct InboundReceipt { + /// Block at which the envelope was executed. + pub block: u32, + /// `None` if the requested action executed; `Some(reason)` if the + /// fallback path credited tUSD instead. + pub fallback: Option, +} + +/// Errors decoding an envelope from wire bytes. These are the only inbound +/// failures that revert delivery (the bridge will retry / funds stay locked +/// at origin). +#[derive(Clone, Copy, Eq, PartialEq, RuntimeDebug)] +pub enum EnvelopeError { + /// Empty payload. + Empty, + /// Unknown version byte. + UnsupportedVersion(u8), + /// SCALE decoding of the payload body failed. + Malformed, +} + +impl GatewayEnvelope { + /// Encode to wire bytes: `[version] ++ SCALE(body)`. + pub fn to_wire(&self) -> Vec { + let mut out = Vec::with_capacity(self.encoded_size().saturating_add(1)); + out.push(ENVELOPE_VERSION_V1); + self.encode_to(&mut out); + out + } + + /// Decode from wire bytes, dispatching on the version byte. + pub fn from_wire(bytes: &[u8]) -> Result { + let (version, mut body) = match bytes.split_first() { + Some((v, rest)) => (*v, rest), + None => return Err(EnvelopeError::Empty), + }; + match version { + ENVELOPE_VERSION_V1 => { + Self::decode(&mut body).map_err(|_| EnvelopeError::Malformed) + } + other => Err(EnvelopeError::UnsupportedVersion(other)), + } + } +} + +/// A linearly-refilling rate limit window. +/// +/// This is the single rate-limit algorithm used on both sides of the bridge: +/// runtime PSM caps here, and the equivalent implementation in the +/// canonical xERC-20 contracts. `used` decays by `refill_per_block` for every +/// elapsed block; reservations fail once `used` would exceed `limit`. +#[freeze_struct("a957b157945fb6d4")] +#[derive( + Deserialize, + Serialize, + Clone, + Copy, + Decode, + DecodeWithMemTracking, + Default, + Encode, + Eq, + MaxEncodedLen, + PartialEq, + RuntimeDebug, + TypeInfo, +)] +pub struct RateWindow { + /// Maximum outstanding amount inside the window. + pub limit: u64, + /// Amount currently consumed (after decay). + pub used: u64, + /// Linear decay of `used` per block. + pub refill_per_block: u64, + /// Block at which `used` was last updated. + pub last_update_block: u32, +} + +impl RateWindow { + /// A window with a fixed limit and refill rate and nothing consumed. + pub fn new(limit: u64, refill_per_block: u64) -> Self { + Self { + limit, + used: 0, + refill_per_block, + last_update_block: 0, + } + } + + /// Decay `used` according to blocks elapsed since the last update. + pub fn refresh(&mut self, now: u32) { + let elapsed = u64::from(now.saturating_sub(self.last_update_block)); + let refill = elapsed.saturating_mul(self.refill_per_block); + self.used = self.used.saturating_sub(refill); + self.last_update_block = now; + } + + /// Headroom available at block `now` without mutating the window. + pub fn available(&self, now: u32) -> u64 { + let mut probe = *self; + probe.refresh(now); + probe.limit.saturating_sub(probe.used) + } + + /// Atomically consume `amount` of headroom. Returns `false` (and leaves + /// `used` untouched apart from decay) if the window lacks capacity. + pub fn try_reserve(&mut self, now: u32, amount: u64) -> bool { + self.refresh(now); + match self.used.checked_add(amount) { + Some(next) if next <= self.limit => { + self.used = next; + true + } + _ => false, + } + } + + /// Release previously reserved headroom (e.g. reserves leaving the PSM). + pub fn release(&mut self, now: u32, amount: u64) { + self.refresh(now); + self.used = self.used.saturating_sub(amount); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample_envelope() -> GatewayEnvelope { + GatewayEnvelope { + asset: AssetId::Usd(0), + amount: 1_000_000_000_000, + dest: AccountId32::new([7u8; 32]), + action: GatewayAction::Stake { + netuid: NetUid::from(64), + hotkey: AccountId32::new([9u8; 32]), + min_alpha: AlphaBalance::from(1), + }, + nonce: 42, + } + } + + #[test] + fn envelope_wire_roundtrip() { + let env = sample_envelope(); + let wire = env.to_wire(); + assert_eq!(wire.first(), Some(&ENVELOPE_VERSION_V1)); + let decoded = GatewayEnvelope::from_wire(&wire).expect("roundtrip"); + assert_eq!(decoded, env); + } + + /// Golden wire vectors, mirrored in + /// `ts-tests/suites/rails/fixtures/golden-envelopes.json` and replayed by + /// the rails e2e suite: both encoders must produce these exact bytes. + #[test] + fn envelope_golden_vectors() { + let alice = AccountId32::new( + hex_literal::hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"), + ); + let hot = AccountId32::new([0x90u8; 32]); + let evm_recipient: [u8; 20] = + hex_literal::hex!("f39fd6e51aad88f6f4ce6ab8827279cfffb92266"); + let zero_dest = AccountId32::new([0u8; 32]); + + let cases: [(GatewayEnvelope, &str); 4] = [ + ( + GatewayEnvelope { + asset: AssetId::Usd(0), + amount: 250_000_000_000, + dest: alice.clone(), + action: GatewayAction::CreditTUsd, + nonce: 7, + }, + "010300000000004429353a000000d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d000700000000000000", + ), + ( + GatewayEnvelope { + asset: AssetId::Usd(0), + amount: 1_000_000_000_000, + dest: alice, + action: GatewayAction::Stake { + netuid: NetUid::from(64), + hotkey: hot, + min_alpha: AlphaBalance::from(1u64), + }, + nonce: 42, + }, + "0103000000000010a5d4e8000000d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d024000909090909090909090909090909090909090909090909090909090909090909001000000000000002a00000000000000", + ), + ( + GatewayEnvelope { + asset: AssetId::Usd(0), + amount: 500_000_000_000, + dest: zero_dest.clone(), + action: GatewayAction::BuyShares { + netuid: NetUid::from(64), + recipient: evm_recipient, + min_alpha: AlphaBalance::from(1u64), + domain: 8453, + }, + nonce: 0, + }, + "0103000000000088526a740000000000000000000000000000000000000000000000000000000000000000000000044000f39fd6e51aad88f6f4ce6ab8827279cfffb922660100000000000000052100000000000000000000", + ), + ( + GatewayEnvelope { + asset: AssetId::Alpha(NetUid::from(64)), + amount: 2_000_000_000, + dest: zero_dest, + action: GatewayAction::SellShares { + netuid: NetUid::from(64), + recipient: evm_recipient, + usd_asset: 0, + min_usd: 1_000_000_000, + domain: 8453, + }, + nonce: 1, + }, + "0102400000943577000000000000000000000000000000000000000000000000000000000000000000000000054000f39fd6e51aad88f6f4ce6ab8827279cfffb922660000000000ca9a3b00000000052100000100000000000000", + ), + ]; + + for (envelope, expected_hex) in cases { + assert_eq!( + hex::encode(envelope.to_wire()), + expected_hex, + "wire mismatch for {envelope:?}" + ); + } + } + + #[test] + fn envelope_rejects_unknown_version() { + let mut wire = sample_envelope().to_wire(); + if let Some(first) = wire.first_mut() { + *first = 99; + } + assert_eq!( + GatewayEnvelope::from_wire(&wire), + Err(EnvelopeError::UnsupportedVersion(99)) + ); + } + + #[test] + fn envelope_rejects_empty_and_malformed() { + assert_eq!(GatewayEnvelope::from_wire(&[]), Err(EnvelopeError::Empty)); + assert_eq!( + GatewayEnvelope::from_wire(&[ENVELOPE_VERSION_V1, 0xFF]), + Err(EnvelopeError::Malformed) + ); + } + + #[test] + fn rate_window_reserve_and_refill() { + let mut w = RateWindow::new(100, 10); + assert!(w.try_reserve(0, 100)); + assert!(!w.try_reserve(0, 1)); + // 5 blocks refill 50 units. + assert_eq!(w.available(5), 50); + assert!(w.try_reserve(5, 50)); + assert!(!w.try_reserve(5, 1)); + // Full refill after long idle; never exceeds limit. + assert_eq!(w.available(1_000), 100); + } + + #[test] + fn rate_window_release() { + let mut w = RateWindow::new(100, 0); + assert!(w.try_reserve(0, 80)); + w.release(0, 30); + assert_eq!(w.available(0), 50); + // Releasing more than used saturates to zero used. + w.release(0, 1_000); + assert_eq!(w.available(0), 100); + } +} diff --git a/contracts/evm/export-artifacts.sh b/contracts/evm/export-artifacts.sh new file mode 100755 index 0000000000..c6aef315a1 --- /dev/null +++ b/contracts/evm/export-artifacts.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Build the rails contracts and export ABIs + creation bytecode to a single +# JSON artifact consumed by ts-tests and btcli. +set -euo pipefail + +cd "$(dirname "$0")" + +OUT="${1:-../../ts-tests/utils/rails-artifacts.json}" + +forge build --skip test --skip script >/dev/null + +CONTRACTS=(MockUSDC CanonicalShareToken Gateway RailsPortal Chutes) + +{ + echo "{" + first=1 + for c in "${CONTRACTS[@]}"; do + artifact="out/${c}.sol/${c}.json" + [ -f "$artifact" ] || { echo "missing artifact $artifact" >&2; exit 1; } + [ $first -eq 1 ] || echo "," + first=0 + printf ' "%s": ' "$c" + jq -c '{abi: .abi, bytecode: .bytecode.object}' "$artifact" + done + echo "" + echo "}" +} > "$OUT" + +echo "wrote $(cd "$(dirname "$OUT")" && pwd)/$(basename "$OUT")" diff --git a/contracts/evm/foundry.toml b/contracts/evm/foundry.toml new file mode 100644 index 0000000000..57d08bfe7d --- /dev/null +++ b/contracts/evm/foundry.toml @@ -0,0 +1,15 @@ +[profile.default] +src = "src" +out = "out" +libs = ["lib"] +test = "test" +script = "script" +solc_version = "0.8.24" +# Bittensor EVM (Frontier) does not support post-London opcodes like PUSH0. +evm_version = "london" +optimizer = true +optimizer_runs = 200 + +[fmt] +line_length = 100 +tab_width = 4 diff --git a/contracts/evm/lib/forge-std/.gitattributes b/contracts/evm/lib/forge-std/.gitattributes new file mode 100644 index 0000000000..27042d458c --- /dev/null +++ b/contracts/evm/lib/forge-std/.gitattributes @@ -0,0 +1 @@ +src/Vm.sol linguist-generated diff --git a/contracts/evm/lib/forge-std/.gitignore b/contracts/evm/lib/forge-std/.gitignore new file mode 100644 index 0000000000..756106d388 --- /dev/null +++ b/contracts/evm/lib/forge-std/.gitignore @@ -0,0 +1,4 @@ +cache/ +out/ +.vscode +.idea diff --git a/contracts/evm/lib/forge-std/CONTRIBUTING.md b/contracts/evm/lib/forge-std/CONTRIBUTING.md new file mode 100644 index 0000000000..8f4aa895b4 --- /dev/null +++ b/contracts/evm/lib/forge-std/CONTRIBUTING.md @@ -0,0 +1,193 @@ +## Contributing to Foundry + +Thanks for your interest in improving Foundry! + +There are multiple opportunities to contribute at any level. It doesn't matter if you are just getting started with Rust or are the most weathered expert, we can use your help. + +This document will help you get started. **Do not let the document intimidate you**. +It should be considered as a guide to help you navigate the process. + +The [dev Telegram][dev-tg] is available for any concerns you may have that are not covered in this guide. + +### Code of Conduct + +The Foundry project adheres to the [Rust Code of Conduct][rust-coc]. This code of conduct describes the _minimum_ behavior expected from all contributors. + +Instances of violations of the Code of Conduct can be reported by contacting the team at [me@gakonst.com](mailto:me@gakonst.com). + +### Ways to contribute + +There are fundamentally four ways an individual can contribute: + +1. **By opening an issue:** For example, if you believe that you have uncovered a bug + in Foundry, creating a new issue in the issue tracker is the way to report it. +2. **By adding context:** Providing additional context to existing issues, + such as screenshots and code snippets, which help resolve issues. +3. **By resolving issues:** Typically this is done in the form of either + demonstrating that the issue reported is not a problem after all, or more often, + by opening a pull request that fixes the underlying problem, in a concrete and + reviewable manner. + +**Anybody can participate in any stage of contribution**. We urge you to participate in the discussion +around bugs and participate in reviewing PRs. + +### Contributions Related to Spelling and Grammar + +At this time, we will not be accepting contributions that only fix spelling or grammatical errors in documentation, code or +elsewhere. + +### Asking for help + +If you have reviewed existing documentation and still have questions, or you are having problems, you can get help in the following ways: + +- **Asking in the support Telegram:** The [Foundry Support Telegram][support-tg] is a fast and easy way to ask questions. +- **Opening a discussion:** This repository comes with a discussions board where you can also ask for help. Click the "Discussions" tab at the top. + +As Foundry is still in heavy development, the documentation can be a bit scattered. +The [Foundry Book][foundry-book] is our current best-effort attempt at keeping up-to-date information. + +### Submitting a bug report + +When filing a new bug report in the issue tracker, you will be presented with a basic form to fill out. + +If you believe that you have uncovered a bug, please fill out the form to the best of your ability. Do not worry if you cannot answer every detail; just fill in what you can. Contributors will ask follow-up questions if something is unclear. + +The most important pieces of information we need in a bug report are: + +- The Foundry version you are on (and that it is up to date) +- The platform you are on (Windows, macOS, an M1 Mac or Linux) +- Code snippets if this is happening in relation to testing or building code +- Concrete steps to reproduce the bug + +In order to rule out the possibility of the bug being in your project, the code snippets should be as minimal +as possible. It is better if you can reproduce the bug with a small snippet as opposed to an entire project! + +See [this guide][mcve] on how to create a minimal, complete, and verifiable example. + +### Submitting a feature request + +When adding a feature request in the issue tracker, you will be presented with a basic form to fill out. + +Please include as detailed of an explanation as possible of the feature you would like, adding additional context if necessary. + +If you have examples of other tools that have the feature you are requesting, please include them as well. + +### Resolving an issue + +Pull requests are the way concrete changes are made to the code, documentation, and dependencies of Foundry. + +Even minor pull requests, such as those fixing wording, are greatly appreciated. Before making a large change, it is usually +a good idea to first open an issue describing the change to solicit feedback and guidance. This will increase +the likelihood of the PR getting merged. + +Please make sure that the following commands pass if you have changed the code: + +```sh +forge fmt --check +forge test -vvv +``` + +To make sure your changes are compatible with all compiler version targets, run the following commands: + +```sh +forge build --skip test --use solc:0.6.2 +forge build --skip test --use solc:0.6.12 +forge build --skip test --use solc:0.7.0 +forge build --skip test --use solc:0.7.6 +forge build --skip test --use solc:0.8.0 +``` + +The CI will also ensure that the code is formatted correctly and that the tests are passing across all compiler version targets. + +#### Adding cheatcodes + +Please follow the guide outlined in the [cheatcodes](https://github.com/foundry-rs/foundry/blob/master/docs/dev/cheatcodes.md#adding-a-new-cheatcode) documentation of Foundry. + +When making modifications to the native cheatcodes or adding new ones, please make sure to run [`./scripts/vm.py`](./scripts/vm.py) to update the cheatcodes in the [`src/Vm.sol`](./src/Vm.sol) file. + +By default the script will automatically generate the cheatcodes from the [`cheatcodes.json`](https://raw.githubusercontent.com/foundry-rs/foundry/master/crates/cheatcodes/assets/cheatcodes.json) file but alternatively you can provide a path to a JSON file containing the Vm interface, as generated by Foundry, with the `--from` flag. + +```sh +./scripts/vm.py --from path/to/cheatcodes.json +``` + +It is possible that the resulting [`src/Vm.sol`](./src/Vm.sol) file will have some changes that are not directly related to your changes, this is not a problem. + +#### Commits + +It is a recommended best practice to keep your changes as logically grouped as possible within individual commits. There is no limit to the number of commits any single pull request may have, and many contributors find it easier to review changes that are split across multiple commits. + +That said, if you have a number of commits that are "checkpoints" and don't represent a single logical change, please squash those together. + +#### Opening the pull request + +From within GitHub, opening a new pull request will present you with a template that should be filled out. Please try your best at filling out the details, but feel free to skip parts if you're not sure what to put. + +#### Discuss and update + +You will probably get feedback or requests for changes to your pull request. +This is a big part of the submission process, so don't be discouraged! Some contributors may sign off on the pull request right away, others may have more detailed comments or feedback. +This is a necessary part of the process in order to evaluate whether the changes are correct and necessary. + +**Any community member can review a PR, so you might get conflicting feedback**. +Keep an eye out for comments from code owners to provide guidance on conflicting feedback. + +#### Reviewing pull requests + +**Any Foundry community member is welcome to review any pull request**. + +All contributors who choose to review and provide feedback on pull requests have a responsibility to both the project and individual making the contribution. Reviews and feedback must be helpful, insightful, and geared towards improving the contribution as opposed to simply blocking it. If there are reasons why you feel the PR should not be merged, explain what those are. Do not expect to be able to block a PR from advancing simply because you say "no" without giving an explanation. Be open to having your mind changed. Be open to working _with_ the contributor to make the pull request better. + +Reviews that are dismissive or disrespectful of the contributor or any other reviewers are strictly counter to the Code of Conduct. + +When reviewing a pull request, the primary goals are for the codebase to improve and for the person submitting the request to succeed. **Even if a pull request is not merged, the submitter should come away from the experience feeling like their effort was appreciated**. Every PR from a new contributor is an opportunity to grow the community. + +##### Review a bit at a time + +Do not overwhelm new contributors. + +It is tempting to micro-optimize and make everything about relative performance, perfect grammar, or exact style matches. Do not succumb to that temptation. + +Focus first on the most significant aspects of the change: + +1. Does this change make sense for Foundry? +2. Does this change make Foundry better, even if only incrementally? +3. Are there clear bugs or larger scale issues that need attending? +4. Are the commit messages readable and correct? If it contains a breaking change, is it clear enough? + +Note that only **incremental** improvement is needed to land a PR. This means that the PR does not need to be perfect, only better than the status quo. Follow-up PRs may be opened to continue iterating. + +When changes are necessary, _request_ them, do not _demand_ them, and **do not assume that the submitter already knows how to add a test or run a benchmark**. + +Specific performance optimization techniques, coding styles and conventions change over time. The first impression you give to a new contributor never does. + +Nits (requests for small changes that are not essential) are fine, but try to avoid stalling the pull request. Most nits can typically be fixed by the Foundry maintainers merging the pull request, but they can also be an opportunity for the contributor to learn a bit more about the project. + +It is always good to clearly indicate nits when you comment, e.g.: `Nit: change foo() to bar(). But this is not blocking`. + +If your comments were addressed but were not folded after new commits, or if they proved to be mistaken, please, [hide them][hiding-a-comment] with the appropriate reason to keep the conversation flow concise and relevant. + +##### Be aware of the person behind the code + +Be aware that _how_ you communicate requests and reviews in your feedback can have a significant impact on the success of the pull request. Yes, we may merge a particular change that makes Foundry better, but the individual might just not want to have anything to do with Foundry ever again. The goal is not just having good code. + +##### Abandoned or stale pull requests + +If a pull request appears to be abandoned or stalled, it is polite to first check with the contributor to see if they intend to continue the work before checking if they would mind if you took it over (especially if it just has nits left). When doing so, it is courteous to give the original contributor credit for the work they started, either by preserving their name and e-mail address in the commit log, or by using the `Author: ` or `Co-authored-by: ` metadata tag in the commits. + +_Adapted from the [ethers-rs contributing guide](https://github.com/gakonst/ethers-rs/blob/master/CONTRIBUTING.md)_. + +### Releasing + +Releases are automatically done by the release workflow when a tag is pushed, however, these steps still need to be taken: + +1. Ensure that the versions in the relevant `Cargo.toml` files are up-to-date. +2. Update documentation links +3. Perform a final audit for breaking changes. + +[rust-coc]: https://github.com/rust-lang/rust/blob/master/CODE_OF_CONDUCT.md +[dev-tg]: https://t.me/foundry_rs +[foundry-book]: https://github.com/foundry-rs/foundry-book +[support-tg]: https://t.me/foundry_support +[mcve]: https://stackoverflow.com/help/mcve +[hiding-a-comment]: https://help.github.com/articles/managing-disruptive-comments/#hiding-a-comment diff --git a/contracts/evm/lib/forge-std/LICENSE-APACHE b/contracts/evm/lib/forge-std/LICENSE-APACHE new file mode 100644 index 0000000000..cf01a499fb --- /dev/null +++ b/contracts/evm/lib/forge-std/LICENSE-APACHE @@ -0,0 +1,203 @@ +Copyright Contributors to Forge Standard Library + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/contracts/evm/lib/forge-std/LICENSE-MIT b/contracts/evm/lib/forge-std/LICENSE-MIT new file mode 100644 index 0000000000..28f98304ac --- /dev/null +++ b/contracts/evm/lib/forge-std/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright Contributors to Forge Standard Library + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE O THE USE OR OTHER +DEALINGS IN THE SOFTWARE.R diff --git a/contracts/evm/lib/forge-std/README.md b/contracts/evm/lib/forge-std/README.md new file mode 100644 index 0000000000..13015e4fc6 --- /dev/null +++ b/contracts/evm/lib/forge-std/README.md @@ -0,0 +1,314 @@ +# Forge Standard Library • [![CI status](https://github.com/foundry-rs/forge-std/actions/workflows/ci.yml/badge.svg)](https://github.com/foundry-rs/forge-std/actions/workflows/ci.yml) + +Forge Standard Library is a collection of helpful contracts and libraries for use with [Forge and Foundry](https://github.com/foundry-rs/foundry). It leverages Forge's cheatcodes to make writing tests easier and faster, while improving the UX of cheatcodes. + +**Learn how to use Forge-Std with the [📖 Foundry Book (Forge-Std Guide)](https://getfoundry.sh/reference/forge-std/overview/).** + +## Install + +```bash +forge install foundry-rs/forge-std +``` + +## Contracts + +### stdError + +This is a helper contract for errors and reverts. In Forge, this contract is particularly helpful for the `expectRevert` cheatcode, as it provides all compiler built-in errors. + +See the contract itself for all error codes. + +#### Example usage + +```solidity + +import "forge-std/Test.sol"; + +contract TestContract is Test { + ErrorsTest test; + + function setUp() public { + test = new ErrorsTest(); + } + + function testExpectArithmetic() public { + vm.expectRevert(stdError.arithmeticError); + test.arithmeticError(10); + } +} + +contract ErrorsTest { + function arithmeticError(uint256 a) public { + a = a - 100; + } +} +``` + +### stdStorage + +This is a rather large contract due to all of the overloading to make the UX decent. Primarily, it is a wrapper around the `record` and `accesses` cheatcodes. It can _always_ find and write the storage slot(s) associated with a particular variable without knowing the storage layout. By default, writing to packed storage variables is not supported and will throw an error. However, you can enable packed slot support by calling `enable_packed_slots()` before using `find()` or `checked_write()`. + +This works by recording all `SLOAD`s and `SSTORE`s during a function call. If there is a single slot read or written to, it immediately returns the slot. Otherwise, behind the scenes, we iterate through and check each one (assuming the user passed in a `depth` parameter). If the variable is a struct, you can pass in a `depth` parameter which is basically the field depth. + +I.e.: + +```solidity +struct T { + // depth 0 + uint256 a; + // depth 1 + uint256 b; +} +``` + +#### Example usage + +```solidity +import "forge-std/Test.sol"; + +contract TestContract is Test { + using stdStorage for StdStorage; + + Storage test; + + function setUp() public { + test = new Storage(); + } + + function testFindExists() public { + // Let's say we want to find the slot for the public + // variable `exists`. We just pass in the function selector + // to the `find` command + uint256 slot = stdstore.target(address(test)).sig("exists()").find(); + assertEq(slot, 0); + } + + function testWriteExists() public { + // Let's say we want to write to the slot for the public + // variable `exists`. We just pass in the function selector + // to the `checked_write` command + stdstore.target(address(test)).sig("exists()").checked_write(100); + assertEq(test.exists(), 100); + } + + // It supports arbitrary storage layouts, like assembly-based storage locations + function testFindHidden() public { + // `hidden` is a random hash of bytes; iterating through slots would + // not find it. Our mechanism does + // Also, you can use the selector instead of a string + uint256 slot = stdstore.target(address(test)).sig(test.hidden.selector).find(); + assertEq(slot, uint256(keccak256("my.random.var"))); + } + + // If targeting a mapping, you have to pass in the keys necessary to perform the find + // i.e.: + function testFindMapping() public { + uint256 slot = stdstore + .target(address(test)) + .sig(test.map_addr.selector) + .with_key(address(this)) + .find(); + // in the `Storage` constructor, we wrote that this address' value was 1 in the map + // so when we load the slot, we expect it to be 1 + assertEq(uint(vm.load(address(test), bytes32(slot))), 1); + } + + // If the target is a struct, you can specify the field depth: + function testFindStruct() public { + // NOTE: see the depth parameter - 0 means 0th field, 1 means 1st field, etc. + uint256 slot_for_a_field = stdstore + .target(address(test)) + .sig(test.basicStruct.selector) + .depth(0) + .find(); + + uint256 slot_for_b_field = stdstore + .target(address(test)) + .sig(test.basicStruct.selector) + .depth(1) + .find(); + + assertEq(uint(vm.load(address(test), bytes32(slot_for_a_field))), 1); + assertEq(uint(vm.load(address(test), bytes32(slot_for_b_field))), 2); + } +} + +// A complex storage contract +contract Storage { + struct UnpackedStruct { + uint256 a; + uint256 b; + } + + constructor() { + map_addr[msg.sender] = 1; + } + + uint256 public exists = 1; + mapping(address => uint256) public map_addr; + // mapping(address => Packed) public map_packed; + mapping(address => UnpackedStruct) public map_struct; + mapping(address => mapping(address => uint256)) public deep_map; + mapping(address => mapping(address => UnpackedStruct)) public deep_map_struct; + UnpackedStruct public basicStruct = UnpackedStruct({ + a: 1, + b: 2 + }); + + function hidden() public view returns (bytes32 t) { + // an extremely hidden storage slot + bytes32 slot = keccak256("my.random.var"); + assembly { + t := sload(slot) + } + } +} +``` + +### stdCheats + +This is a wrapper around miscellaneous cheatcodes that need wrappers to be more dev-friendly. It includes functions for pranking, dealing with ETH and tokens, deploying contracts, creating test addresses, time manipulation, and fuzzing helpers. In general, users may expect ETH to be put into an address with `prank`, but this is not the case for safety reasons. Explicitly, this `hoax` function should only be used for addresses that have expected balances as it will get overwritten. If an address already has ETH, you should just use `prank`. If you want to change that balance explicitly, just use `deal`. If you want to do both, `hoax` is also right for you. + +#### Example usage: + +```solidity + +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity ^0.8.0; + +import "forge-std/Test.sol"; + +// Inherit the stdCheats +contract StdCheatsTest is Test { + Bar test; + function setUp() public { + test = new Bar(); + } + + function testHoax() public { + // we call `hoax`, which gives the target address + // eth and then calls `prank` + hoax(address(1337)); + test.bar{value: 100}(address(1337)); + + // overloaded to allow you to specify how much eth to + // initialize the address with + hoax(address(1337), 1); + test.bar{value: 1}(address(1337)); + } + + function testStartHoax() public { + // we call `startHoax`, which gives the target address + // eth and then calls `startPrank` + // + // it is also overloaded so that you can specify an eth amount + startHoax(address(1337)); + test.bar{value: 100}(address(1337)); + test.bar{value: 100}(address(1337)); + vm.stopPrank(); + test.bar(address(this)); + } +} + +contract Bar { + function bar(address expectedSender) public payable { + require(msg.sender == expectedSender, "!prank"); + } +} +``` + +### Std Assertions + +Provides comprehensive assertion functions for testing, including equality checks (assertEq, assertNotEq), comparisons (assertLt, assertGt, assertLe, assertGe), approximate equality (assertApproxEqAbs, assertApproxEqRel), and boolean assertions (assertTrue, assertFalse). All assertions support multiple data types and optional custom error messages. + +### StdConfig + +This is a contract that parses a TOML configuration file and loads its variables into storage, automatically casting them on deployment. It assumes a TOML structure where top-level keys represent chain IDs or aliases. Under each chain key, variables are organized by type in separate sub-tables like `[.]`, where type must be: `bool`, `address`, `bytes32`, `uint`, `int`, `string`, or `bytes`. + +#### Example usage + +```solidity + +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity ^0.8.13; + +import "forge-std/Script.sol"; +import "forge-std/StdConfig.sol"; + +contract MyScript is Script { + StdConfig config; + + function run() public { + // Load config (set writeToFile=true only in scripts to persist changes) + config = new StdConfig("config.toml", false); + + // Get values for the current chain + uint256 myNumber = config.get("important_number").toUint256(); + address weth = config.get("weth").toAddress(); + address[] memory admins = config.get("whitelisted_admins").toAddressArray(); + + // Get values for a specific chain + bool isLive = config.get(1, "is_live").toBool(); + + // Check if a key exists + if (config.exists("optional_param")) { + // ... + } + + // Get RPC URL for current or specific chain + string memory rpc = config.getRpcUrl(); + string memory mainnetRpc = config.getRpcUrl(1); + + // Get all configured chain IDs + uint256[] memory chainIds = config.getChainIds(); + } +} +``` + +See the contract itself for supported TOML format and all available methods. + +### `console.log` + +Usage follows the same format as [Hardhat](https://hardhat.org/hardhat-network/reference/#console-log). +It's recommended to use `console2.sol` as shown below, as this will show the decoded logs in Forge traces. + +```solidity +// import it indirectly via Test.sol +import "forge-std/Test.sol"; +// or directly import it +import "forge-std/console2.sol"; +... +console2.log(someValue); +``` + +If you need compatibility with Hardhat, you must use the standard `console.sol` instead. +Due to a bug in `console.sol`, logs that use `uint256` or `int256` types will not be properly decoded in Forge traces. + +```solidity +// import it indirectly via Test.sol +import "forge-std/Test.sol"; +// or directly import it +import "forge-std/console.sol"; +... +console.log(someValue); +``` + +## Contributing + +See our [contributing guidelines](./CONTRIBUTING.md). + +## Getting Help + +First, see if the answer to your question can be found in [book](https://getfoundry.sh/). + +If the answer is not there: + +- Join the [support Telegram](https://t.me/foundry_support) to get help, or +- Open a [discussion](https://github.com/foundry-rs/foundry/discussions/new/choose) with your question, or +- Open an issue with [the bug](https://github.com/foundry-rs/foundry/issues/new/choose) + +If you want to contribute, or follow along with contributor discussion, you can use our [main telegram](https://t.me/foundry_rs) to chat with us about the development of Foundry! + +## License + +Forge Standard Library is offered under either [MIT](LICENSE-MIT) or [Apache 2.0](LICENSE-APACHE) license. diff --git a/contracts/evm/lib/forge-std/RELEASE_CHECKLIST.md b/contracts/evm/lib/forge-std/RELEASE_CHECKLIST.md new file mode 100644 index 0000000000..82b33c2cd4 --- /dev/null +++ b/contracts/evm/lib/forge-std/RELEASE_CHECKLIST.md @@ -0,0 +1,12 @@ +# Release checklist + +This checklist is meant to be used as a guide for the `forge-std` release process. + +## Steps + +- [ ] Update the version number in `package.json` +- [ ] Open and merge a PR with the version bump +- [ ] Tag the merged commit with the version number: `git tag v` +- [ ] Push the tag to the repository: `git push --tags` +- [ ] Create a new GitHub release with the automatically generated changelog and the name set to `v` +- [ ] Add `## Featured Changes` section to the top of the release notes diff --git a/contracts/evm/lib/forge-std/foundry.toml b/contracts/evm/lib/forge-std/foundry.toml new file mode 100644 index 0000000000..6035b855c4 --- /dev/null +++ b/contracts/evm/lib/forge-std/foundry.toml @@ -0,0 +1,18 @@ +[profile.default] +fs_permissions = [{ access = "read-write", path = "./" }] +optimizer = true +optimizer_runs = 200 + +# A list of solidity error codes to ignore. +# 3860 = init-code-size +ignored_error_codes = [3860] + +[rpc_endpoints] +# The RPC URLs are modified versions of the default for testing initialization. +mainnet = "https://ethereum.reth.rs/rpc" +optimism_sepolia = "https://sepolia.optimism.io/" # Adds a trailing slash. +arbitrum_one_sepolia = "https://sepolia-rollup.arbitrum.io/rpc/" # Adds a trailing slash. +needs_undefined_env_var = "${UNDEFINED_RPC_URL_PLACEHOLDER}" + +[lint] +lint_on_build = false diff --git a/contracts/evm/lib/forge-std/package.json b/contracts/evm/lib/forge-std/package.json new file mode 100644 index 0000000000..fbcea6682a --- /dev/null +++ b/contracts/evm/lib/forge-std/package.json @@ -0,0 +1,16 @@ +{ + "name": "forge-std", + "version": "1.16.2", + "description": "Forge Standard Library is a collection of helpful contracts and libraries for use with Forge and Foundry.", + "homepage": "https://book.getfoundry.sh/forge/forge-std", + "bugs": "https://github.com/foundry-rs/forge-std/issues", + "license": "(Apache-2.0 OR MIT)", + "author": "Contributors to Forge Standard Library", + "files": [ + "src/**/*" + ], + "repository": { + "type": "git", + "url": "https://github.com/foundry-rs/forge-std.git" + } +} diff --git a/contracts/evm/lib/forge-std/scripts/vm.py b/contracts/evm/lib/forge-std/scripts/vm.py new file mode 100755 index 0000000000..187cf632ae --- /dev/null +++ b/contracts/evm/lib/forge-std/scripts/vm.py @@ -0,0 +1,655 @@ +#!/usr/bin/env python3 + +import argparse +import copy +import json +import re +import subprocess +from enum import Enum as PyEnum +from pathlib import Path +from typing import Callable, Optional, Union +from urllib import request + +VoidFn = Callable[[], None] + +CHEATCODES_JSON_URL = "https://raw.githubusercontent.com/foundry-rs/foundry/master/crates/cheatcodes/assets/cheatcodes.json" +OUT_PATH = "src/Vm.sol" +TEST_PATH = "test/Vm.t.sol" + +VM_SAFE_DOC = """\ +/// The `VmSafe` interface does not allow manipulation of the EVM state or other actions that may +/// result in Script simulations differing from on-chain execution. It is recommended to only use +/// these cheats in scripts. +""" + +VM_DOC = """\ +/// The `Vm` interface does allow manipulation of the EVM state. These are all intended to be used +/// in tests, but it is not recommended to use these cheats in scripts. +""" + + +def main(): + parser = argparse.ArgumentParser( + description="Generate Vm.sol based on the cheatcodes json created by Foundry") + parser.add_argument( + "--from", + metavar="PATH", + dest="path", + required=False, + help="path to a json file containing the Vm interface, as generated by Foundry") + args = parser.parse_args() + json_str = request.urlopen(CHEATCODES_JSON_URL).read().decode("utf-8") if args.path is None else Path(args.path).read_text() + contract = Cheatcodes.from_json(json_str) + + ccs = contract.cheatcodes + ccs = list(filter(lambda cc: cc.status not in ["experimental", "internal"], ccs)) + ccs.sort(key=lambda cc: cc.func.id) + + safe = list(filter(lambda cc: cc.safety == "safe", ccs)) + safe.sort(key=CmpCheatcode) + unsafe = list(filter(lambda cc: cc.safety == "unsafe", ccs)) + unsafe.sort(key=CmpCheatcode) + assert len(safe) + len(unsafe) == len(ccs) + + update_interface_ids(safe, unsafe) + + prefix_with_group_headers(safe) + prefix_with_group_headers(unsafe) + + out = "" + + out += "// Automatically @generated by scripts/vm.py. Do not modify manually.\n\n" + + pp = CheatcodesPrinter( + spdx_identifier="MIT OR Apache-2.0", + solidity_requirement=">=0.8.13 <0.9.0", + ) + pp.p_prelude() + pp.prelude = False + out += pp.finish() + + out += "\n\n" + out += VM_SAFE_DOC + vm_safe = Cheatcodes( + # TODO: Custom errors were introduced in 0.8.4 + errors=[], # contract.errors + events=contract.events, + enums=contract.enums, + structs=contract.structs, + cheatcodes=safe, + ) + pp.p_contract(vm_safe, "VmSafe") + out += pp.finish() + + out += "\n\n" + out += VM_DOC + vm_unsafe = Cheatcodes( + errors=[], + events=[], + enums=[], + structs=[], + cheatcodes=unsafe, + ) + pp.p_contract(vm_unsafe, "Vm", "VmSafe") + out += pp.finish() + + # Compatibility with <0.8.0 + def memory_to_calldata(m: re.Match) -> str: + return " calldata " + m.group(1) + + out = re.sub(r" memory (.*returns)", memory_to_calldata, out) + + with open(OUT_PATH, "w") as f: + f.write(out) + + forge_fmt = ["forge", "fmt", OUT_PATH] + res = subprocess.run(forge_fmt) + assert res.returncode == 0, f"command failed: {forge_fmt}" + + print(f"Wrote to {OUT_PATH}") + + +def update_interface_ids(safe: list["Cheatcode"], unsafe: list["Cheatcode"]): + test_path = Path(TEST_PATH) + out = test_path.read_text() + + for name, cheatcodes in [("Vm", unsafe), ("VmSafe", safe)]: + interface_id = 0 + for cheatcode in cheatcodes: + interface_id ^= int.from_bytes(cheatcode.func.selector_bytes, byteorder="big") + + pattern = rf"(type\({name}\)\.interfaceId, bytes4\()0x[0-9a-fA-F]{{8}}(\), \"{name}\"\))" + out, count = re.subn(pattern, rf"\g<1>0x{interface_id:08x}\g<2>", out) + assert count == 1, f"failed to update {name} interface ID in {TEST_PATH}" + + test_path.write_text(out) + + +class CmpCheatcode: + cheatcode: "Cheatcode" + + def __init__(self, cheatcode: "Cheatcode"): + self.cheatcode = cheatcode + + def __lt__(self, other: "CmpCheatcode") -> bool: + return cmp_cheatcode(self.cheatcode, other.cheatcode) < 0 + + def __eq__(self, other: "CmpCheatcode") -> bool: + return cmp_cheatcode(self.cheatcode, other.cheatcode) == 0 + + def __gt__(self, other: "CmpCheatcode") -> bool: + return cmp_cheatcode(self.cheatcode, other.cheatcode) > 0 + + +def cmp_cheatcode(a: "Cheatcode", b: "Cheatcode") -> int: + if a.group != b.group: + return -1 if a.group < b.group else 1 + if a.status != b.status: + return -1 if a.status < b.status else 1 + if a.safety != b.safety: + return -1 if a.safety < b.safety else 1 + if a.func.id != b.func.id: + return -1 if a.func.id < b.func.id else 1 + return 0 + + +# HACK: A way to add group header comments without having to modify printer code +def prefix_with_group_headers(cheats: list["Cheatcode"]): + s = set() + for i, cheat in enumerate(cheats): + if cheat.group in s: + continue + + s.add(cheat.group) + + c = copy.deepcopy(cheat) + c.func.description = "" + c.func.declaration = f"// ======== {group(c.group)} ========" + cheats.insert(i, c) + return cheats + + +def group(s: str) -> str: + if s == "evm": + return "EVM" + if s == "json": + return "JSON" + return s[0].upper() + s[1:] + + +class Visibility(PyEnum): + EXTERNAL: str = "external" + PUBLIC: str = "public" + INTERNAL: str = "internal" + PRIVATE: str = "private" + + def __str__(self): + return self.value + + +class Mutability(PyEnum): + PURE: str = "pure" + VIEW: str = "view" + NONE: str = "" + + def __str__(self): + return self.value + + +class Function: + id: str + description: str + declaration: str + visibility: Visibility + mutability: Mutability + signature: str + selector: str + selector_bytes: bytes + + def __init__( + self, + id: str, + description: str, + declaration: str, + visibility: Visibility, + mutability: Mutability, + signature: str, + selector: str, + selector_bytes: bytes, + ): + self.id = id + self.description = description + self.declaration = declaration + self.visibility = visibility + self.mutability = mutability + self.signature = signature + self.selector = selector + self.selector_bytes = selector_bytes + + @staticmethod + def from_dict(d: dict) -> "Function": + return Function( + d["id"], + d["description"], + d["declaration"], + Visibility(d["visibility"]), + Mutability(d["mutability"]), + d["signature"], + d["selector"], + bytes(d["selectorBytes"]), + ) + + +class Cheatcode: + func: Function + group: str + status: str + safety: str + + def __init__(self, func: Function, group: str, status: str, safety: str): + self.func = func + self.group = group + self.status = status + self.safety = safety + + @staticmethod + def from_dict(d: dict) -> "Cheatcode": + return Cheatcode( + Function.from_dict(d["func"]), + str(d["group"]), + str(d["status"]), + str(d["safety"]), + ) + + +class Error: + name: str + description: str + declaration: str + + def __init__(self, name: str, description: str, declaration: str): + self.name = name + self.description = description + self.declaration = declaration + + @staticmethod + def from_dict(d: dict) -> "Error": + return Error(**d) + + +class Event: + name: str + description: str + declaration: str + + def __init__(self, name: str, description: str, declaration: str): + self.name = name + self.description = description + self.declaration = declaration + + @staticmethod + def from_dict(d: dict) -> "Event": + return Event(**d) + + +class EnumVariant: + name: str + description: str + + def __init__(self, name: str, description: str): + self.name = name + self.description = description + + +class Enum: + name: str + description: str + variants: list[EnumVariant] + + def __init__(self, name: str, description: str, variants: list[EnumVariant]): + self.name = name + self.description = description + self.variants = variants + + @staticmethod + def from_dict(d: dict) -> "Enum": + return Enum( + d["name"], + d["description"], + list(map(lambda v: EnumVariant(**v), d["variants"])), + ) + + +class StructField: + name: str + ty: str + description: str + + def __init__(self, name: str, ty: str, description: str): + self.name = name + self.ty = ty + self.description = description + + +class Struct: + name: str + description: str + fields: list[StructField] + + def __init__(self, name: str, description: str, fields: list[StructField]): + self.name = name + self.description = description + self.fields = fields + + @staticmethod + def from_dict(d: dict) -> "Struct": + return Struct( + d["name"], + d["description"], + list(map(lambda f: StructField(**f), d["fields"])), + ) + + +class Cheatcodes: + errors: list[Error] + events: list[Event] + enums: list[Enum] + structs: list[Struct] + cheatcodes: list[Cheatcode] + + def __init__( + self, + errors: list[Error], + events: list[Event], + enums: list[Enum], + structs: list[Struct], + cheatcodes: list[Cheatcode], + ): + self.errors = errors + self.events = events + self.enums = enums + self.structs = structs + self.cheatcodes = cheatcodes + + @staticmethod + def from_dict(d: dict) -> "Cheatcodes": + return Cheatcodes( + errors=[Error.from_dict(e) for e in d["errors"]], + events=[Event.from_dict(e) for e in d["events"]], + enums=[Enum.from_dict(e) for e in d["enums"]], + structs=[Struct.from_dict(e) for e in d["structs"]], + cheatcodes=[Cheatcode.from_dict(e) for e in d["cheatcodes"]], + ) + + @staticmethod + def from_json(s) -> "Cheatcodes": + return Cheatcodes.from_dict(json.loads(s)) + + @staticmethod + def from_json_file(file_path: str) -> "Cheatcodes": + with open(file_path, "r") as f: + return Cheatcodes.from_dict(json.load(f)) + + +class Item(PyEnum): + ERROR: str = "error" + EVENT: str = "event" + ENUM: str = "enum" + STRUCT: str = "struct" + FUNCTION: str = "function" + + +class ItemOrder: + _list: list[Item] + + def __init__(self, list: list[Item]) -> None: + assert len(list) <= len(Item), "list must not contain more items than Item" + assert len(list) == len(set(list)), "list must not contain duplicates" + self._list = list + pass + + def get_list(self) -> list[Item]: + return self._list + + @staticmethod + def default() -> "ItemOrder": + return ItemOrder( + [ + Item.ERROR, + Item.EVENT, + Item.ENUM, + Item.STRUCT, + Item.FUNCTION, + ] + ) + + +class CheatcodesPrinter: + buffer: str + + prelude: bool + spdx_identifier: str + solidity_requirement: str + + block_doc_style: bool + + indent_level: int + _indent_str: str + + nl_str: str + + items_order: ItemOrder + + def __init__( + self, + buffer: str = "", + prelude: bool = True, + spdx_identifier: str = "UNLICENSED", + solidity_requirement: str = "", + block_doc_style: bool = False, + indent_level: int = 0, + indent_with: Union[int, str] = 4, + nl_str: str = "\n", + items_order: ItemOrder = ItemOrder.default(), + ): + self.prelude = prelude + self.spdx_identifier = spdx_identifier + self.solidity_requirement = solidity_requirement + self.block_doc_style = block_doc_style + self.buffer = buffer + self.indent_level = indent_level + self.nl_str = nl_str + + if isinstance(indent_with, int): + assert indent_with >= 0 + self._indent_str = " " * indent_with + elif isinstance(indent_with, str): + self._indent_str = indent_with + else: + assert False, "indent_with must be int or str" + + self.items_order = items_order + + def finish(self) -> str: + ret = self.buffer.rstrip() + self.buffer = "" + return ret + + def p_contract(self, contract: Cheatcodes, name: str, inherits: str = ""): + if self.prelude: + self.p_prelude(contract) + + self._p_str("interface ") + name = name.strip() + if name != "": + self._p_str(name) + self._p_str(" ") + if inherits != "": + self._p_str("is ") + self._p_str(inherits) + self._p_str(" ") + self._p_str("{") + self._p_nl() + self._with_indent(lambda: self._p_items(contract)) + self._p_str("}") + self._p_nl() + + def _p_items(self, contract: Cheatcodes): + for item in self.items_order.get_list(): + if item == Item.ERROR: + self.p_errors(contract.errors) + elif item == Item.EVENT: + self.p_events(contract.events) + elif item == Item.ENUM: + self.p_enums(contract.enums) + elif item == Item.STRUCT: + self.p_structs(contract.structs) + elif item == Item.FUNCTION: + self.p_functions(contract.cheatcodes) + else: + assert False, f"unknown item {item}" + + def p_prelude(self, contract: Optional[Cheatcodes] = None): + self._p_str(f"// SPDX-License-Identifier: {self.spdx_identifier}") + self._p_nl() + + if self.solidity_requirement != "": + req = self.solidity_requirement + else: + req = ">=0.8.13 <0.9.0" + self._p_str(f"pragma solidity {req};") + self._p_nl() + + self._p_nl() + + def p_errors(self, errors: list[Error]): + for error in errors: + self._p_line(lambda: self.p_error(error)) + + def p_error(self, error: Error): + self._p_comment(error.description, doc=True) + self._p_line(lambda: self._p_str(error.declaration)) + + def p_events(self, events: list[Event]): + for event in events: + self._p_line(lambda: self.p_event(event)) + + def p_event(self, event: Event): + self._p_comment(event.description, doc=True) + self._p_line(lambda: self._p_str(event.declaration)) + + def p_enums(self, enums: list[Enum]): + for enum in enums: + self._p_line(lambda: self.p_enum(enum)) + + def p_enum(self, enum: Enum): + self._p_comment(enum.description, doc=True) + self._p_line(lambda: self._p_str(f"enum {enum.name} {{")) + self._with_indent(lambda: self.p_enum_variants(enum.variants)) + self._p_line(lambda: self._p_str("}")) + + def p_enum_variants(self, variants: list[EnumVariant]): + for i, variant in enumerate(variants): + self._p_indent() + self._p_comment(variant.description) + + self._p_indent() + self._p_str(variant.name) + if i < len(variants) - 1: + self._p_str(",") + self._p_nl() + + def p_structs(self, structs: list[Struct]): + for struct in structs: + self._p_line(lambda: self.p_struct(struct)) + + def p_struct(self, struct: Struct): + self._p_comment(struct.description, doc=True) + self._p_line(lambda: self._p_str(f"struct {struct.name} {{")) + self._with_indent(lambda: self.p_struct_fields(struct.fields)) + self._p_line(lambda: self._p_str("}")) + + def p_struct_fields(self, fields: list[StructField]): + for field in fields: + self._p_line(lambda: self.p_struct_field(field)) + + def p_struct_field(self, field: StructField): + self._p_comment(field.description) + self._p_indented(lambda: self._p_str(f"{field.ty} {field.name};")) + + def p_functions(self, cheatcodes: list[Cheatcode]): + for cheatcode in cheatcodes: + self._p_line(lambda: self.p_function(cheatcode.func)) + + def p_function(self, func: Function): + self._p_comment(func.description, doc=True) + self._p_line(lambda: self._p_str(func.declaration)) + + def _p_comment(self, s: str, doc: bool = False): + s = s.strip() + if s == "": + return + + s = map(lambda line: line.lstrip(), s.split("\n")) + if self.block_doc_style: + self._p_str("/*") + if doc: + self._p_str("*") + self._p_nl() + for line in s: + self._p_indent() + self._p_str(" ") + if doc: + self._p_str("* ") + self._p_str(line) + self._p_nl() + self._p_indent() + self._p_str(" */") + self._p_nl() + else: + first_line = True + for line in s: + if not first_line: + self._p_indent() + first_line = False + + if doc: + self._p_str("/// ") + else: + self._p_str("// ") + self._p_str(line) + self._p_nl() + + def _with_indent(self, f: VoidFn): + self._inc_indent() + f() + self._dec_indent() + + def _p_line(self, f: VoidFn): + self._p_indent() + f() + self._p_nl() + + def _p_indented(self, f: VoidFn): + self._p_indent() + f() + + def _p_indent(self): + for _ in range(self.indent_level): + self._p_str(self._indent_str) + + def _p_nl(self): + self._p_str(self.nl_str) + + def _p_str(self, txt: str): + self.buffer += txt + + def _inc_indent(self): + self.indent_level += 1 + + def _dec_indent(self): + self.indent_level -= 1 + + +if __name__ == "__main__": + main() diff --git a/contracts/evm/lib/forge-std/src/Base.sol b/contracts/evm/lib/forge-std/src/Base.sol new file mode 100644 index 0000000000..d948010fe9 --- /dev/null +++ b/contracts/evm/lib/forge-std/src/Base.sol @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {StdStorage} from "./StdStorage.sol"; +import {Vm, VmSafe} from "./Vm.sol"; + +abstract contract CommonBase { + /// @dev Cheat code address. + /// Calculated as `address(uint160(uint256(keccak256("hevm cheat code"))))`. + address internal constant VM_ADDRESS = 0x7109709ECfa91a80626fF3989D68f67F5b1DD12D; + + /// @dev console.sol and console2.sol work by executing a staticcall to this address. + /// Calculated as `address(uint160(uint88(bytes11("console.log"))))`. + address internal constant CONSOLE = 0x000000000000000000636F6e736F6c652e6c6f67; + + /// @dev Used when deploying with create2. + /// Taken from https://github.com/Arachnid/deterministic-deployment-proxy. + address internal constant CREATE2_FACTORY = 0x4e59b44847b379578588920cA78FbF26c0B4956C; + + /// @dev The default address for tx.origin and msg.sender. + /// Calculated as `address(uint160(uint256(keccak256("foundry default caller"))))`. + address internal constant DEFAULT_SENDER = 0x1804c8AB1F12E6bbf3894d4083f33e07309d1f38; + + /// @dev The address of the first contract `CREATE`d by a running test contract. + /// When running tests, each test contract is `CREATE`d by `DEFAULT_SENDER` with nonce 1. + /// Calculated as `VM.computeCreateAddress(VM.computeCreateAddress(DEFAULT_SENDER, 1), 1)`. + address internal constant DEFAULT_TEST_CONTRACT = 0x5615dEB798BB3E4dFa0139dFa1b3D433Cc23b72f; + + /// @dev Deterministic deployment address of the Multicall3 contract. + /// Taken from https://www.multicall3.com. + address internal constant MULTICALL3_ADDRESS = 0xcA11bde05977b3631167028862bE2a173976CA11; + + /// @dev The order of the secp256k1 curve. + uint256 internal constant SECP256K1_ORDER = + 115792089237316195423570985008687907852837564279074904382605163141518161494337; + + uint256 internal constant UINT256_MAX = + 115792089237316195423570985008687907853269984665640564039457584007913129639935; + + Vm internal constant vm = Vm(VM_ADDRESS); + StdStorage internal stdstore; +} + +abstract contract TestBase is CommonBase {} + +abstract contract ScriptBase is CommonBase { + VmSafe internal constant vmSafe = VmSafe(VM_ADDRESS); +} diff --git a/contracts/evm/lib/forge-std/src/Config.sol b/contracts/evm/lib/forge-std/src/Config.sol new file mode 100644 index 0000000000..3d35bb583a --- /dev/null +++ b/contracts/evm/lib/forge-std/src/Config.sol @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity ^0.8.13; + +import {console} from "./console.sol"; +import {StdConfig} from "./StdConfig.sol"; +import {CommonBase} from "./Base.sol"; + +/// @notice Boilerplate to streamline the setup of multi-chain environments. +abstract contract Config is CommonBase { + // -- STORAGE (CONFIG + CHAINS + FORKS) ------------------------------------ + + /// @dev Contract instance holding the data from the TOML config file. + StdConfig internal config; + + /// @dev Array of chain IDs for which forks have been created. + uint256[] internal chainIds; + + /// @dev A mapping from a chain ID to its initialized fork ID. + mapping(uint256 => uint256) internal forkOf; + + // -- HELPER FUNCTIONS ----------------------------------------------------- + + /// @notice Loads configuration from a file. + /// + /// @dev This function instantiates a `Config` contract, caching all its config variables. + /// + /// @param filePath: the path to the TOML configuration file. + /// @param writeToFile: whether updates are written back to the TOML file. + function _loadConfig(string memory filePath, bool writeToFile) internal { + console.log("----------"); + console.log(string.concat("Loading config from '", filePath, "'")); + config = new StdConfig(filePath, writeToFile); + vm.makePersistent(address(config)); + console.log("Config successfully loaded"); + console.log("----------"); + } + + /// @notice Loads configuration from a file and creates forks for each specified chain. + /// + /// @dev This function instantiates a `Config` contract, caching all its config variables, + /// reads the configured chain ids, and iterates through them to create a fork for each one. + /// It also creates a map `forkOf[chainId] -> forkId` to easily switch between forks. + /// + /// @param filePath: the path to the TOML configuration file. + /// @param writeToFile: whether updates are written back to the TOML file. + function _loadConfigAndForks(string memory filePath, bool writeToFile) internal { + _loadConfig(filePath, writeToFile); + + console.log("Setting up forks for the configured chains..."); + uint256[] memory chains = config.getChainIds(); + for (uint256 i = 0; i < chains.length; i++) { + uint256 chainId = chains[i]; + uint256 forkId = vm.createFork(config.getRpcUrl(chainId)); + forkOf[chainId] = forkId; + chainIds.push(chainId); + } + console.log("Forks successfully created"); + console.log("----------"); + } +} diff --git a/contracts/evm/lib/forge-std/src/LibVariable.sol b/contracts/evm/lib/forge-std/src/LibVariable.sol new file mode 100644 index 0000000000..32fe5bfa92 --- /dev/null +++ b/contracts/evm/lib/forge-std/src/LibVariable.sol @@ -0,0 +1,477 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity ^0.8.13; + +// Enable globally. +using LibVariable for Variable global; + +struct Variable { + Type ty; + bytes data; +} + +struct Type { + TypeKind kind; + bool isArray; +} + +enum TypeKind { + None, + Bool, + Address, + Bytes32, + Uint256, + Int256, + String, + Bytes +} + +/// @notice Library for type-safe coercion of the `Variable` struct to concrete types. +/// +/// @dev Ensures that when a `Variable` is cast to a concrete Solidity type, the operation is safe and the +/// underlying type matches what is expected. +/// Provides functions to check types, convert them to strings, and coerce `Variable` instances into +/// both single values and arrays of various types. +/// +/// Usage example: +/// ```solidity +/// import {LibVariable} from "./LibVariable.sol"; +/// +/// contract MyContract { +/// using LibVariable for Variable; +/// StdConfig config; // Assume 'config' is an instance of `StdConfig` and has already been loaded. +/// +/// function readValues() public { +/// // Retrieve a 'uint256' value from the config. +/// uint256 myNumber = config.get("important_number").toUint256(); +/// +/// // Would revert with `TypeMismatch` as 'important_number' isn't a `uint256` in the config file. +/// // string memory notANumber = config.get("important_number").toString(); +/// +/// // Retrieve a address array from the config. +/// address[] memory admins = config.get("whitelisted_admins").toAddressArray(); +/// } +/// } +/// ``` +library LibVariable { + error NotInitialized(); + error TypeMismatch(string expected, string actual); + error UnsafeCast(string message); + + // -- TYPE HELPERS ---------------------------------------------------- + + /// @notice Compares two Type instances for equality. + function isEqual(Type memory self, Type memory other) internal pure returns (bool) { + return self.kind == other.kind && self.isArray == other.isArray; + } + + /// @notice Compares two Type instances for equality. Reverts if they are not equal. + function assertEq(Type memory self, Type memory other) internal pure { + if (!isEqual(self, other)) { + revert TypeMismatch(toString(other), toString(self)); + } + } + + /// @notice Converts a Type struct to its full string representation (i.e. "uint256[]"). + function toString(Type memory self) internal pure returns (string memory) { + string memory tyStr = toString(self.kind); + if (!self.isArray || self.kind == TypeKind.None) { + return tyStr; + } else { + return string.concat(tyStr, "[]"); + } + } + + /// @dev Converts a `TypeKind` enum to its base string representation. + function toString(TypeKind self) internal pure returns (string memory) { + if (self == TypeKind.Bool) return "bool"; + if (self == TypeKind.Address) return "address"; + if (self == TypeKind.Bytes32) return "bytes32"; + if (self == TypeKind.Uint256) return "uint256"; + if (self == TypeKind.Int256) return "int256"; + if (self == TypeKind.String) return "string"; + if (self == TypeKind.Bytes) return "bytes"; + return "none"; + } + + /// @dev Converts a `TypeKind` enum to its base string representation. + function toTomlKey(TypeKind self) internal pure returns (string memory) { + if (self == TypeKind.Bool) return "bool"; + if (self == TypeKind.Address) return "address"; + if (self == TypeKind.Bytes32) return "bytes32"; + if (self == TypeKind.Uint256) return "uint"; + if (self == TypeKind.Int256) return "int"; + if (self == TypeKind.String) return "string"; + if (self == TypeKind.Bytes) return "bytes"; + return "none"; + } + + // -- VARIABLE HELPERS ---------------------------------------------------- + + /// @dev Checks if a `Variable` has been initialized and matches the expected type reverting if not. + modifier check(Variable memory self, Type memory expected) { + assertExists(self); + assertEq(self.ty, expected); + _; + } + + /// @dev Checks if a `Variable` has been initialized, reverting if not. + function assertExists(Variable memory self) public pure { + if (self.ty.kind == TypeKind.None) { + revert NotInitialized(); + } + } + + // -- VARIABLE COERCION FUNCTIONS (SINGLE VALUES) -------------------------- + + /// @notice Coerces a `Variable` to a `bool` value. + function toBool(Variable memory self) internal pure check(self, Type(TypeKind.Bool, false)) returns (bool) { + return abi.decode(self.data, (bool)); + } + + /// @notice Coerces a `Variable` to an `address` value. + function toAddress(Variable memory self) + internal + pure + check(self, Type(TypeKind.Address, false)) + returns (address) + { + return abi.decode(self.data, (address)); + } + + /// @notice Coerces a `Variable` to a `bytes32` value. + function toBytes32(Variable memory self) + internal + pure + check(self, Type(TypeKind.Bytes32, false)) + returns (bytes32) + { + return abi.decode(self.data, (bytes32)); + } + + /// @notice Coerces a `Variable` to a `uint256` value. + function toUint256(Variable memory self) + internal + pure + check(self, Type(TypeKind.Uint256, false)) + returns (uint256) + { + return abi.decode(self.data, (uint256)); + } + + /// @notice Coerces a `Variable` to a `uint128` value, checking for overflow. + function toUint128(Variable memory self) internal pure returns (uint128) { + uint256 value = self.toUint256(); + if (value > type(uint128).max) { + revert UnsafeCast("value does not fit in 'uint128'"); + } + return uint128(value); + } + + /// @notice Coerces a `Variable` to a `uint64` value, checking for overflow. + function toUint64(Variable memory self) internal pure returns (uint64) { + uint256 value = self.toUint256(); + if (value > type(uint64).max) { + revert UnsafeCast("value does not fit in 'uint64'"); + } + return uint64(value); + } + + /// @notice Coerces a `Variable` to a `uint32` value, checking for overflow. + function toUint32(Variable memory self) internal pure returns (uint32) { + uint256 value = self.toUint256(); + if (value > type(uint32).max) { + revert UnsafeCast("value does not fit in 'uint32'"); + } + return uint32(value); + } + + /// @notice Coerces a `Variable` to a `uint16` value, checking for overflow. + function toUint16(Variable memory self) internal pure returns (uint16) { + uint256 value = self.toUint256(); + if (value > type(uint16).max) { + revert UnsafeCast("value does not fit in 'uint16'"); + } + return uint16(value); + } + + /// @notice Coerces a `Variable` to a `uint8` value, checking for overflow. + function toUint8(Variable memory self) internal pure returns (uint8) { + uint256 value = self.toUint256(); + if (value > type(uint8).max) { + revert UnsafeCast("value does not fit in 'uint8'"); + } + return uint8(value); + } + + /// @notice Coerces a `Variable` to an `int256` value. + function toInt256(Variable memory self) internal pure check(self, Type(TypeKind.Int256, false)) returns (int256) { + return abi.decode(self.data, (int256)); + } + + /// @notice Coerces a `Variable` to an `int128` value, checking for overflow/underflow. + function toInt128(Variable memory self) internal pure returns (int128) { + int256 value = self.toInt256(); + if (value > type(int128).max || value < type(int128).min) { + revert UnsafeCast("value does not fit in 'int128'"); + } + return int128(value); + } + + /// @notice Coerces a `Variable` to an `int64` value, checking for overflow/underflow. + function toInt64(Variable memory self) internal pure returns (int64) { + int256 value = self.toInt256(); + if (value > type(int64).max || value < type(int64).min) { + revert UnsafeCast("value does not fit in 'int64'"); + } + return int64(value); + } + + /// @notice Coerces a `Variable` to an `int32` value, checking for overflow/underflow. + function toInt32(Variable memory self) internal pure returns (int32) { + int256 value = self.toInt256(); + if (value > type(int32).max || value < type(int32).min) { + revert UnsafeCast("value does not fit in 'int32'"); + } + return int32(value); + } + + /// @notice Coerces a `Variable` to an `int16` value, checking for overflow/underflow. + function toInt16(Variable memory self) internal pure returns (int16) { + int256 value = self.toInt256(); + if (value > type(int16).max || value < type(int16).min) { + revert UnsafeCast("value does not fit in 'int16'"); + } + return int16(value); + } + + /// @notice Coerces a `Variable` to an `int8` value, checking for overflow/underflow. + function toInt8(Variable memory self) internal pure returns (int8) { + int256 value = self.toInt256(); + if (value > type(int8).max || value < type(int8).min) { + revert UnsafeCast("value does not fit in 'int8'"); + } + return int8(value); + } + + /// @notice Coerces a `Variable` to a `string` value. + function toString(Variable memory self) + internal + pure + check(self, Type(TypeKind.String, false)) + returns (string memory) + { + return abi.decode(self.data, (string)); + } + + /// @notice Coerces a `Variable` to a `bytes` value. + function toBytes(Variable memory self) + internal + pure + check(self, Type(TypeKind.Bytes, false)) + returns (bytes memory) + { + return abi.decode(self.data, (bytes)); + } + + // -- VARIABLE COERCION FUNCTIONS (ARRAYS) --------------------------------- + + /// @notice Coerces a `Variable` to a `bool` array. + function toBoolArray(Variable memory self) + internal + pure + check(self, Type(TypeKind.Bool, true)) + returns (bool[] memory) + { + return abi.decode(self.data, (bool[])); + } + + /// @notice Coerces a `Variable` to an `address` array. + function toAddressArray(Variable memory self) + internal + pure + check(self, Type(TypeKind.Address, true)) + returns (address[] memory) + { + return abi.decode(self.data, (address[])); + } + + /// @notice Coerces a `Variable` to a `bytes32` array. + function toBytes32Array(Variable memory self) + internal + pure + check(self, Type(TypeKind.Bytes32, true)) + returns (bytes32[] memory) + { + return abi.decode(self.data, (bytes32[])); + } + + /// @notice Coerces a `Variable` to a `uint256` array. + function toUint256Array(Variable memory self) + internal + pure + check(self, Type(TypeKind.Uint256, true)) + returns (uint256[] memory) + { + return abi.decode(self.data, (uint256[])); + } + + /// @notice Coerces a `Variable` to a `uint128` array, checking for overflow. + function toUint128Array(Variable memory self) internal pure returns (uint128[] memory) { + uint256[] memory values = self.toUint256Array(); + uint128[] memory result = new uint128[](values.length); + for (uint256 i = 0; i < values.length; i++) { + if (values[i] > type(uint128).max) { + revert UnsafeCast("value in array does not fit in 'uint128'"); + } + result[i] = uint128(values[i]); + } + return result; + } + + /// @notice Coerces a `Variable` to a `uint64` array, checking for overflow. + function toUint64Array(Variable memory self) internal pure returns (uint64[] memory) { + uint256[] memory values = self.toUint256Array(); + uint64[] memory result = new uint64[](values.length); + for (uint256 i = 0; i < values.length; i++) { + if (values[i] > type(uint64).max) { + revert UnsafeCast("value in array does not fit in 'uint64'"); + } + result[i] = uint64(values[i]); + } + return result; + } + + /// @notice Coerces a `Variable` to a `uint32` array, checking for overflow. + function toUint32Array(Variable memory self) internal pure returns (uint32[] memory) { + uint256[] memory values = self.toUint256Array(); + uint32[] memory result = new uint32[](values.length); + for (uint256 i = 0; i < values.length; i++) { + if (values[i] > type(uint32).max) { + revert UnsafeCast("value in array does not fit in 'uint32'"); + } + result[i] = uint32(values[i]); + } + return result; + } + + /// @notice Coerces a `Variable` to a `uint16` array, checking for overflow. + function toUint16Array(Variable memory self) internal pure returns (uint16[] memory) { + uint256[] memory values = self.toUint256Array(); + uint16[] memory result = new uint16[](values.length); + for (uint256 i = 0; i < values.length; i++) { + if (values[i] > type(uint16).max) { + revert UnsafeCast("value in array does not fit in 'uint16'"); + } + result[i] = uint16(values[i]); + } + return result; + } + + /// @notice Coerces a `Variable` to a `uint8` array, checking for overflow. + function toUint8Array(Variable memory self) internal pure returns (uint8[] memory) { + uint256[] memory values = self.toUint256Array(); + uint8[] memory result = new uint8[](values.length); + for (uint256 i = 0; i < values.length; i++) { + if (values[i] > type(uint8).max) { + revert UnsafeCast("value in array does not fit in 'uint8'"); + } + result[i] = uint8(values[i]); + } + return result; + } + + /// @notice Coerces a `Variable` to an `int256` array. + function toInt256Array(Variable memory self) + internal + pure + check(self, Type(TypeKind.Int256, true)) + returns (int256[] memory) + { + return abi.decode(self.data, (int256[])); + } + + /// @notice Coerces a `Variable` to a `int128` array, checking for overflow/underflow. + function toInt128Array(Variable memory self) internal pure returns (int128[] memory) { + int256[] memory values = self.toInt256Array(); + int128[] memory result = new int128[](values.length); + for (uint256 i = 0; i < values.length; i++) { + if (values[i] > type(int128).max || values[i] < type(int128).min) { + revert UnsafeCast("value in array does not fit in 'int128'"); + } + result[i] = int128(values[i]); + } + return result; + } + + /// @notice Coerces a `Variable` to a `int64` array, checking for overflow/underflow. + function toInt64Array(Variable memory self) internal pure returns (int64[] memory) { + int256[] memory values = self.toInt256Array(); + int64[] memory result = new int64[](values.length); + for (uint256 i = 0; i < values.length; i++) { + if (values[i] > type(int64).max || values[i] < type(int64).min) { + revert UnsafeCast("value in array does not fit in 'int64'"); + } + result[i] = int64(values[i]); + } + return result; + } + + /// @notice Coerces a `Variable` to a `int32` array, checking for overflow/underflow. + function toInt32Array(Variable memory self) internal pure returns (int32[] memory) { + int256[] memory values = self.toInt256Array(); + int32[] memory result = new int32[](values.length); + for (uint256 i = 0; i < values.length; i++) { + if (values[i] > type(int32).max || values[i] < type(int32).min) { + revert UnsafeCast("value in array does not fit in 'int32'"); + } + result[i] = int32(values[i]); + } + return result; + } + + /// @notice Coerces a `Variable` to a `int16` array, checking for overflow/underflow. + function toInt16Array(Variable memory self) internal pure returns (int16[] memory) { + int256[] memory values = self.toInt256Array(); + int16[] memory result = new int16[](values.length); + for (uint256 i = 0; i < values.length; i++) { + if (values[i] > type(int16).max || values[i] < type(int16).min) { + revert UnsafeCast("value in array does not fit in 'int16'"); + } + result[i] = int16(values[i]); + } + return result; + } + + /// @notice Coerces a `Variable` to a `int8` array, checking for overflow/underflow. + function toInt8Array(Variable memory self) internal pure returns (int8[] memory) { + int256[] memory values = self.toInt256Array(); + int8[] memory result = new int8[](values.length); + for (uint256 i = 0; i < values.length; i++) { + if (values[i] > type(int8).max || values[i] < type(int8).min) { + revert UnsafeCast("value in array does not fit in 'int8'"); + } + result[i] = int8(values[i]); + } + return result; + } + + /// @notice Coerces a `Variable` to a `string` array. + function toStringArray(Variable memory self) + internal + pure + check(self, Type(TypeKind.String, true)) + returns (string[] memory) + { + return abi.decode(self.data, (string[])); + } + + /// @notice Coerces a `Variable` to a `bytes` array. + function toBytesArray(Variable memory self) + internal + pure + check(self, Type(TypeKind.Bytes, true)) + returns (bytes[] memory) + { + return abi.decode(self.data, (bytes[])); + } +} diff --git a/contracts/evm/lib/forge-std/src/Script.sol b/contracts/evm/lib/forge-std/src/Script.sol new file mode 100644 index 0000000000..03e0beba0b --- /dev/null +++ b/contracts/evm/lib/forge-std/src/Script.sol @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +// 💬 ABOUT +// Forge Std's default Script. + +// 🧩 MODULES +import {console} from "./console.sol"; +import {console2} from "./console2.sol"; +import {safeconsole} from "./safeconsole.sol"; +import {StdChains} from "./StdChains.sol"; +import {StdCheatsSafe} from "./StdCheats.sol"; +import {StdConstants} from "./StdConstants.sol"; +import {stdJson} from "./StdJson.sol"; +import {stdMath} from "./StdMath.sol"; +import {StdStorage, stdStorageSafe} from "./StdStorage.sol"; +import {StdStyle} from "./StdStyle.sol"; +import {StdUtils} from "./StdUtils.sol"; +import {VmSafe} from "./Vm.sol"; + +// 📦 BOILERPLATE +import {ScriptBase} from "./Base.sol"; + +/// @notice Default base contract for Forge scripts. +/// @dev Includes safe cheatcodes, chain helpers, utility helpers, and console modules. +abstract contract Script is ScriptBase, StdChains, StdCheatsSafe, StdUtils { + /// @notice Marker used by Forge to identify script contracts. + /// @dev The generated `IS_SCRIPT()` getter must return true. + bool public IS_SCRIPT = true; +} diff --git a/contracts/evm/lib/forge-std/src/StdAssertions.sol b/contracts/evm/lib/forge-std/src/StdAssertions.sol new file mode 100644 index 0000000000..daad7d976d --- /dev/null +++ b/contracts/evm/lib/forge-std/src/StdAssertions.sol @@ -0,0 +1,1300 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {Vm} from "./Vm.sol"; + +/// @notice Abstract contract providing assertion utilities for Forge tests. +abstract contract StdAssertions { + Vm private constant vm = Vm(address(uint160(uint256(keccak256("hevm cheat code"))))); + + event log(string); + event logs(bytes); + + event log_address(address); + event log_bytes32(bytes32); + event log_int(int256); + event log_uint(uint256); + event log_bytes(bytes); + event log_string(string); + + event log_named_address(string key, address val); + event log_named_bytes32(string key, bytes32 val); + event log_named_decimal_int(string key, int256 val, uint256 decimals); + event log_named_decimal_uint(string key, uint256 val, uint256 decimals); + event log_named_int(string key, int256 val); + event log_named_uint(string key, uint256 val); + event log_named_bytes(string key, bytes val); + event log_named_string(string key, string val); + + event log_array(uint256[] val); + event log_array(int256[] val); + event log_array(address[] val); + event log_named_array(string key, uint256[] val); + event log_named_array(string key, int256[] val); + event log_named_array(string key, address[] val); + + bytes32 private constant _FAILED_SLOT = bytes32("failed"); + + bool private _failed; + + /// @notice Returns true if any test assertion has failed. + /// @return True if any assertion has failed, false otherwise. + function failed() public view returns (bool) { + if (_failed) { + return true; + } else { + return vm.load(address(vm), _FAILED_SLOT) != bytes32(0); + } + } + + /// @notice Marks the test as failed and records the failure in storage. + function fail() internal virtual { + vm.store(address(vm), _FAILED_SLOT, bytes32(uint256(1))); + _failed = true; + } + + /// @notice Marks the test as failed with a custom message. + /// @param message The failure message to display. + function fail(string memory message) internal virtual { + fail(); + vm.assertTrue(false, message); + } + + /// @notice Asserts that `data` is true. + /// @param data The boolean value to assert. + function assertTrue(bool data) internal pure virtual { + if (!data) { + vm.assertTrue(data); + } + } + + /// @notice Asserts that `data` is true with a custom error message. + /// @param data The boolean value to assert. + /// @param err The error message on failure. + function assertTrue(bool data, string memory err) internal pure virtual { + if (!data) { + vm.assertTrue(data, err); + } + } + + /// @notice Asserts that `data` is false. + /// @param data The boolean value to assert. + function assertFalse(bool data) internal pure virtual { + if (data) { + vm.assertFalse(data); + } + } + + /// @notice Asserts that `data` is false with a custom error message. + /// @param data The boolean value to assert. + /// @param err The error message on failure. + function assertFalse(bool data, string memory err) internal pure virtual { + if (data) { + vm.assertFalse(data, err); + } + } + + /// @notice Asserts that `left` is equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertEq(bool left, bool right) internal pure virtual { + if (left != right) { + vm.assertEq(left, right); + } + } + + /// @notice Asserts that `left` is equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertEq(bool left, bool right, string memory err) internal pure virtual { + if (left != right) { + vm.assertEq(left, right, err); + } + } + + /// @notice Asserts that `left` is equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertEq(uint256 left, uint256 right) internal pure virtual { + if (left != right) { + vm.assertEq(left, right); + } + } + + /// @notice Asserts that `left` is equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertEq(uint256 left, uint256 right, string memory err) internal pure virtual { + if (left != right) { + vm.assertEq(left, right, err); + } + } + + /// @notice Asserts that `left` is equal to `right`, formatting values with `decimals` decimal places on failure. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param decimals The number of decimals for formatting. + function assertEqDecimal(uint256 left, uint256 right, uint256 decimals) internal pure virtual { + vm.assertEqDecimal(left, right, decimals); + } + + /// @notice Asserts that `left` is equal to `right`, formatting values with `decimals` decimal places on failure, with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param decimals The number of decimals for formatting. + /// @param err The error message on failure. + function assertEqDecimal(uint256 left, uint256 right, uint256 decimals, string memory err) internal pure virtual { + vm.assertEqDecimal(left, right, decimals, err); + } + + /// @notice Asserts that `left` is equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertEq(int256 left, int256 right) internal pure virtual { + if (left != right) { + vm.assertEq(left, right); + } + } + + /// @notice Asserts that `left` is equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertEq(int256 left, int256 right, string memory err) internal pure virtual { + if (left != right) { + vm.assertEq(left, right, err); + } + } + + /// @notice Asserts that `left` is equal to `right`, formatting values with `decimals` decimal places on failure. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param decimals The number of decimals for formatting. + function assertEqDecimal(int256 left, int256 right, uint256 decimals) internal pure virtual { + vm.assertEqDecimal(left, right, decimals); + } + + /// @notice Asserts that `left` is equal to `right`, formatting values with `decimals` decimal places on failure, with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param decimals The number of decimals for formatting. + /// @param err The error message on failure. + function assertEqDecimal(int256 left, int256 right, uint256 decimals, string memory err) internal pure virtual { + vm.assertEqDecimal(left, right, decimals, err); + } + + /// @notice Asserts that `left` is equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertEq(address left, address right) internal pure virtual { + if (left != right) { + vm.assertEq(left, right); + } + } + + /// @notice Asserts that `left` is equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertEq(address left, address right, string memory err) internal pure virtual { + if (left != right) { + vm.assertEq(left, right, err); + } + } + + /// @notice Asserts that `left` is equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertEq(bytes32 left, bytes32 right) internal pure virtual { + if (left != right) { + vm.assertEq(left, right); + } + } + + /// @notice Asserts that `left` is equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertEq(bytes32 left, bytes32 right, string memory err) internal pure virtual { + if (left != right) { + vm.assertEq(left, right, err); + } + } + + /// @notice Asserts that `left` is equal to `right` (legacy bytes32 variant). + /// @dev Alias for assertEq(bytes32,bytes32) kept for backwards-compatibility. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertEq32(bytes32 left, bytes32 right) internal pure virtual { + if (left != right) { + vm.assertEq(left, right); + } + } + + /// @notice Asserts that `left` is equal to `right` with a custom error message (legacy bytes32 variant). + /// @dev Alias for assertEq(bytes32,bytes32,string) kept for backwards-compatibility. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertEq32(bytes32 left, bytes32 right, string memory err) internal pure virtual { + if (left != right) { + vm.assertEq(left, right, err); + } + } + + /// @notice Asserts that `left` is equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertEq(string memory left, string memory right) internal pure virtual { + vm.assertEq(left, right); + } + + /// @notice Asserts that `left` is equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertEq(string memory left, string memory right, string memory err) internal pure virtual { + vm.assertEq(left, right, err); + } + + /// @notice Asserts that `left` is equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertEq(bytes memory left, bytes memory right) internal pure virtual { + vm.assertEq(left, right); + } + + /// @notice Asserts that `left` is equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertEq(bytes memory left, bytes memory right, string memory err) internal pure virtual { + vm.assertEq(left, right, err); + } + + /// @notice Asserts that `left` is equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertEq(bool[] memory left, bool[] memory right) internal pure virtual { + vm.assertEq(left, right); + } + + /// @notice Asserts that `left` is equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertEq(bool[] memory left, bool[] memory right, string memory err) internal pure virtual { + vm.assertEq(left, right, err); + } + + /// @notice Asserts that `left` is equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertEq(uint256[] memory left, uint256[] memory right) internal pure virtual { + vm.assertEq(left, right); + } + + /// @notice Asserts that `left` is equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertEq(uint256[] memory left, uint256[] memory right, string memory err) internal pure virtual { + vm.assertEq(left, right, err); + } + + /// @notice Asserts that `left` is equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertEq(int256[] memory left, int256[] memory right) internal pure virtual { + vm.assertEq(left, right); + } + + /// @notice Asserts that `left` is equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertEq(int256[] memory left, int256[] memory right, string memory err) internal pure virtual { + vm.assertEq(left, right, err); + } + + /// @notice Asserts that `left` is equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertEq(address[] memory left, address[] memory right) internal pure virtual { + vm.assertEq(left, right); + } + + /// @notice Asserts that `left` is equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertEq(address[] memory left, address[] memory right, string memory err) internal pure virtual { + vm.assertEq(left, right, err); + } + + /// @notice Asserts that `left` is equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertEq(bytes32[] memory left, bytes32[] memory right) internal pure virtual { + vm.assertEq(left, right); + } + + /// @notice Asserts that `left` is equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertEq(bytes32[] memory left, bytes32[] memory right, string memory err) internal pure virtual { + vm.assertEq(left, right, err); + } + + /// @notice Asserts that `left` is equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertEq(string[] memory left, string[] memory right) internal pure virtual { + vm.assertEq(left, right); + } + + /// @notice Asserts that `left` is equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertEq(string[] memory left, string[] memory right, string memory err) internal pure virtual { + vm.assertEq(left, right, err); + } + + /// @notice Asserts that `left` is equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertEq(bytes[] memory left, bytes[] memory right) internal pure virtual { + vm.assertEq(left, right); + } + + /// @notice Asserts that `left` is equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertEq(bytes[] memory left, bytes[] memory right, string memory err) internal pure virtual { + vm.assertEq(left, right, err); + } + + // Legacy helper + /// @notice Asserts that `left` is equal to `right` (legacy uint256 variant). + /// @dev Legacy helper kept for backwards-compatibility. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertEqUint(uint256 left, uint256 right) internal pure virtual { + assertEq(left, right); + } + + /// @notice Asserts that `left` is not equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertNotEq(bool left, bool right) internal pure virtual { + if (left == right) { + vm.assertNotEq(left, right); + } + } + + /// @notice Asserts that `left` is not equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertNotEq(bool left, bool right, string memory err) internal pure virtual { + if (left == right) { + vm.assertNotEq(left, right, err); + } + } + + /// @notice Asserts that `left` is not equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertNotEq(uint256 left, uint256 right) internal pure virtual { + if (left == right) { + vm.assertNotEq(left, right); + } + } + + /// @notice Asserts that `left` is not equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertNotEq(uint256 left, uint256 right, string memory err) internal pure virtual { + if (left == right) { + vm.assertNotEq(left, right, err); + } + } + + /// @notice Asserts that `left` is not equal to `right`, formatting values with `decimals` decimal places on failure. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param decimals The number of decimals for formatting. + function assertNotEqDecimal(uint256 left, uint256 right, uint256 decimals) internal pure virtual { + vm.assertNotEqDecimal(left, right, decimals); + } + + /// @notice Asserts that `left` is not equal to `right`, formatting values with `decimals` decimal places on failure, with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param decimals The number of decimals for formatting. + /// @param err The error message on failure. + function assertNotEqDecimal(uint256 left, uint256 right, uint256 decimals, string memory err) + internal + pure + virtual + { + vm.assertNotEqDecimal(left, right, decimals, err); + } + + /// @notice Asserts that `left` is not equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertNotEq(int256 left, int256 right) internal pure virtual { + if (left == right) { + vm.assertNotEq(left, right); + } + } + + /// @notice Asserts that `left` is not equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertNotEq(int256 left, int256 right, string memory err) internal pure virtual { + if (left == right) { + vm.assertNotEq(left, right, err); + } + } + + /// @notice Asserts that `left` is not equal to `right`, formatting values with `decimals` decimal places on failure. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param decimals The number of decimals for formatting. + function assertNotEqDecimal(int256 left, int256 right, uint256 decimals) internal pure virtual { + vm.assertNotEqDecimal(left, right, decimals); + } + + /// @notice Asserts that `left` is not equal to `right`, formatting values with `decimals` decimal places on failure, with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param decimals The number of decimals for formatting. + /// @param err The error message on failure. + function assertNotEqDecimal(int256 left, int256 right, uint256 decimals, string memory err) internal pure virtual { + vm.assertNotEqDecimal(left, right, decimals, err); + } + + /// @notice Asserts that `left` is not equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertNotEq(address left, address right) internal pure virtual { + if (left == right) { + vm.assertNotEq(left, right); + } + } + + /// @notice Asserts that `left` is not equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertNotEq(address left, address right, string memory err) internal pure virtual { + if (left == right) { + vm.assertNotEq(left, right, err); + } + } + + /// @notice Asserts that `left` is not equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertNotEq(bytes32 left, bytes32 right) internal pure virtual { + if (left == right) { + vm.assertNotEq(left, right); + } + } + + /// @notice Asserts that `left` is not equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertNotEq(bytes32 left, bytes32 right, string memory err) internal pure virtual { + if (left == right) { + vm.assertNotEq(left, right, err); + } + } + + /// @notice Asserts that `left` is not equal to `right` (legacy bytes32 variant). + /// @dev Alias for assertNotEq(bytes32,bytes32) kept for backwards-compatibility. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertNotEq32(bytes32 left, bytes32 right) internal pure virtual { + if (left == right) { + vm.assertNotEq(left, right); + } + } + + /// @notice Asserts that `left` is not equal to `right` with a custom error message (legacy bytes32 variant). + /// @dev Alias for assertNotEq(bytes32,bytes32,string) kept for backwards-compatibility. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertNotEq32(bytes32 left, bytes32 right, string memory err) internal pure virtual { + if (left == right) { + vm.assertNotEq(left, right, err); + } + } + + /// @notice Asserts that `left` is not equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertNotEq(string memory left, string memory right) internal pure virtual { + vm.assertNotEq(left, right); + } + + /// @notice Asserts that `left` is not equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertNotEq(string memory left, string memory right, string memory err) internal pure virtual { + vm.assertNotEq(left, right, err); + } + + /// @notice Asserts that `left` is not equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertNotEq(bytes memory left, bytes memory right) internal pure virtual { + vm.assertNotEq(left, right); + } + + /// @notice Asserts that `left` is not equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertNotEq(bytes memory left, bytes memory right, string memory err) internal pure virtual { + vm.assertNotEq(left, right, err); + } + + /// @notice Asserts that `left` is not equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertNotEq(bool[] memory left, bool[] memory right) internal pure virtual { + vm.assertNotEq(left, right); + } + + /// @notice Asserts that `left` is not equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertNotEq(bool[] memory left, bool[] memory right, string memory err) internal pure virtual { + vm.assertNotEq(left, right, err); + } + + /// @notice Asserts that `left` is not equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertNotEq(uint256[] memory left, uint256[] memory right) internal pure virtual { + vm.assertNotEq(left, right); + } + + /// @notice Asserts that `left` is not equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertNotEq(uint256[] memory left, uint256[] memory right, string memory err) internal pure virtual { + vm.assertNotEq(left, right, err); + } + + /// @notice Asserts that `left` is not equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertNotEq(int256[] memory left, int256[] memory right) internal pure virtual { + vm.assertNotEq(left, right); + } + + /// @notice Asserts that `left` is not equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertNotEq(int256[] memory left, int256[] memory right, string memory err) internal pure virtual { + vm.assertNotEq(left, right, err); + } + + /// @notice Asserts that `left` is not equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertNotEq(address[] memory left, address[] memory right) internal pure virtual { + vm.assertNotEq(left, right); + } + + /// @notice Asserts that `left` is not equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertNotEq(address[] memory left, address[] memory right, string memory err) internal pure virtual { + vm.assertNotEq(left, right, err); + } + + /// @notice Asserts that `left` is not equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertNotEq(bytes32[] memory left, bytes32[] memory right) internal pure virtual { + vm.assertNotEq(left, right); + } + + /// @notice Asserts that `left` is not equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertNotEq(bytes32[] memory left, bytes32[] memory right, string memory err) internal pure virtual { + vm.assertNotEq(left, right, err); + } + + /// @notice Asserts that `left` is not equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertNotEq(string[] memory left, string[] memory right) internal pure virtual { + vm.assertNotEq(left, right); + } + + /// @notice Asserts that `left` is not equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertNotEq(string[] memory left, string[] memory right, string memory err) internal pure virtual { + vm.assertNotEq(left, right, err); + } + + /// @notice Asserts that `left` is not equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertNotEq(bytes[] memory left, bytes[] memory right) internal pure virtual { + vm.assertNotEq(left, right); + } + + /// @notice Asserts that `left` is not equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertNotEq(bytes[] memory left, bytes[] memory right, string memory err) internal pure virtual { + vm.assertNotEq(left, right, err); + } + + /// @notice Asserts that `left` is strictly less than `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertLt(uint256 left, uint256 right) internal pure virtual { + if (left >= right) { + vm.assertLt(left, right); + } + } + + /// @notice Asserts that `left` is strictly less than `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertLt(uint256 left, uint256 right, string memory err) internal pure virtual { + if (left >= right) { + vm.assertLt(left, right, err); + } + } + + /// @notice Asserts that `left` is strictly less than `right`, formatting values with `decimals` decimal places on failure. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param decimals The number of decimals for formatting. + function assertLtDecimal(uint256 left, uint256 right, uint256 decimals) internal pure virtual { + vm.assertLtDecimal(left, right, decimals); + } + + /// @notice Asserts that `left` is strictly less than `right`, formatting values with `decimals` decimal places on failure, with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param decimals The number of decimals for formatting. + /// @param err The error message on failure. + function assertLtDecimal(uint256 left, uint256 right, uint256 decimals, string memory err) internal pure virtual { + vm.assertLtDecimal(left, right, decimals, err); + } + + /// @notice Asserts that `left` is strictly less than `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertLt(int256 left, int256 right) internal pure virtual { + if (left >= right) { + vm.assertLt(left, right); + } + } + + /// @notice Asserts that `left` is strictly less than `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertLt(int256 left, int256 right, string memory err) internal pure virtual { + if (left >= right) { + vm.assertLt(left, right, err); + } + } + + /// @notice Asserts that `left` is strictly less than `right`, formatting values with `decimals` decimal places on failure. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param decimals The number of decimals for formatting. + function assertLtDecimal(int256 left, int256 right, uint256 decimals) internal pure virtual { + vm.assertLtDecimal(left, right, decimals); + } + + /// @notice Asserts that `left` is strictly less than `right`, formatting values with `decimals` decimal places on failure, with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param decimals The number of decimals for formatting. + /// @param err The error message on failure. + function assertLtDecimal(int256 left, int256 right, uint256 decimals, string memory err) internal pure virtual { + vm.assertLtDecimal(left, right, decimals, err); + } + + /// @notice Asserts that `left` is strictly greater than `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertGt(uint256 left, uint256 right) internal pure virtual { + if (left <= right) { + vm.assertGt(left, right); + } + } + + /// @notice Asserts that `left` is strictly greater than `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertGt(uint256 left, uint256 right, string memory err) internal pure virtual { + if (left <= right) { + vm.assertGt(left, right, err); + } + } + + /// @notice Asserts that `left` is strictly greater than `right`, formatting values with `decimals` decimal places on failure. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param decimals The number of decimals for formatting. + function assertGtDecimal(uint256 left, uint256 right, uint256 decimals) internal pure virtual { + vm.assertGtDecimal(left, right, decimals); + } + + /// @notice Asserts that `left` is strictly greater than `right`, formatting values with `decimals` decimal places on failure, with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param decimals The number of decimals for formatting. + /// @param err The error message on failure. + function assertGtDecimal(uint256 left, uint256 right, uint256 decimals, string memory err) internal pure virtual { + vm.assertGtDecimal(left, right, decimals, err); + } + + /// @notice Asserts that `left` is strictly greater than `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertGt(int256 left, int256 right) internal pure virtual { + if (left <= right) { + vm.assertGt(left, right); + } + } + + /// @notice Asserts that `left` is strictly greater than `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertGt(int256 left, int256 right, string memory err) internal pure virtual { + if (left <= right) { + vm.assertGt(left, right, err); + } + } + + /// @notice Asserts that `left` is strictly greater than `right`, formatting values with `decimals` decimal places on failure. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param decimals The number of decimals for formatting. + function assertGtDecimal(int256 left, int256 right, uint256 decimals) internal pure virtual { + vm.assertGtDecimal(left, right, decimals); + } + + /// @notice Asserts that `left` is strictly greater than `right`, formatting values with `decimals` decimal places on failure, with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param decimals The number of decimals for formatting. + /// @param err The error message on failure. + function assertGtDecimal(int256 left, int256 right, uint256 decimals, string memory err) internal pure virtual { + vm.assertGtDecimal(left, right, decimals, err); + } + + /// @notice Asserts that `left` is less than or equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertLe(uint256 left, uint256 right) internal pure virtual { + if (left > right) { + vm.assertLe(left, right); + } + } + + /// @notice Asserts that `left` is less than or equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertLe(uint256 left, uint256 right, string memory err) internal pure virtual { + if (left > right) { + vm.assertLe(left, right, err); + } + } + + /// @notice Asserts that `left` is less than or equal to `right`, formatting values with `decimals` decimal places on failure. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param decimals The number of decimals for formatting. + function assertLeDecimal(uint256 left, uint256 right, uint256 decimals) internal pure virtual { + vm.assertLeDecimal(left, right, decimals); + } + + /// @notice Asserts that `left` is less than or equal to `right`, formatting values with `decimals` decimal places on failure, with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param decimals The number of decimals for formatting. + /// @param err The error message on failure. + function assertLeDecimal(uint256 left, uint256 right, uint256 decimals, string memory err) internal pure virtual { + vm.assertLeDecimal(left, right, decimals, err); + } + + /// @notice Asserts that `left` is less than or equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertLe(int256 left, int256 right) internal pure virtual { + if (left > right) { + vm.assertLe(left, right); + } + } + + /// @notice Asserts that `left` is less than or equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertLe(int256 left, int256 right, string memory err) internal pure virtual { + if (left > right) { + vm.assertLe(left, right, err); + } + } + + /// @notice Asserts that `left` is less than or equal to `right`, formatting values with `decimals` decimal places on failure. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param decimals The number of decimals for formatting. + function assertLeDecimal(int256 left, int256 right, uint256 decimals) internal pure virtual { + vm.assertLeDecimal(left, right, decimals); + } + + /// @notice Asserts that `left` is less than or equal to `right`, formatting values with `decimals` decimal places on failure, with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param decimals The number of decimals for formatting. + /// @param err The error message on failure. + function assertLeDecimal(int256 left, int256 right, uint256 decimals, string memory err) internal pure virtual { + vm.assertLeDecimal(left, right, decimals, err); + } + + /// @notice Asserts that `left` is greater than or equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertGe(uint256 left, uint256 right) internal pure virtual { + if (left < right) { + vm.assertGe(left, right); + } + } + + /// @notice Asserts that `left` is greater than or equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertGe(uint256 left, uint256 right, string memory err) internal pure virtual { + if (left < right) { + vm.assertGe(left, right, err); + } + } + + /// @notice Asserts that `left` is greater than or equal to `right`, formatting values with `decimals` decimal places on failure. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param decimals The number of decimals for formatting. + function assertGeDecimal(uint256 left, uint256 right, uint256 decimals) internal pure virtual { + vm.assertGeDecimal(left, right, decimals); + } + + /// @notice Asserts that `left` is greater than or equal to `right`, formatting values with `decimals` decimal places on failure, with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param decimals The number of decimals for formatting. + /// @param err The error message on failure. + function assertGeDecimal(uint256 left, uint256 right, uint256 decimals, string memory err) internal pure virtual { + vm.assertGeDecimal(left, right, decimals, err); + } + + /// @notice Asserts that `left` is greater than or equal to `right`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + function assertGe(int256 left, int256 right) internal pure virtual { + if (left < right) { + vm.assertGe(left, right); + } + } + + /// @notice Asserts that `left` is greater than or equal to `right` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param err The error message on failure. + function assertGe(int256 left, int256 right, string memory err) internal pure virtual { + if (left < right) { + vm.assertGe(left, right, err); + } + } + + /// @notice Asserts that `left` is greater than or equal to `right`, formatting values with `decimals` decimal places on failure. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param decimals The number of decimals for formatting. + function assertGeDecimal(int256 left, int256 right, uint256 decimals) internal pure virtual { + vm.assertGeDecimal(left, right, decimals); + } + + /// @notice Asserts that `left` is greater than or equal to `right`, formatting values with `decimals` decimal places on failure, with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param decimals The number of decimals for formatting. + /// @param err The error message on failure. + function assertGeDecimal(int256 left, int256 right, uint256 decimals, string memory err) internal pure virtual { + vm.assertGeDecimal(left, right, decimals, err); + } + + /// @notice Asserts that the absolute difference between `left` and `right` is at most `maxDelta`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param maxDelta The maximum absolute difference allowed. + function assertApproxEqAbs(uint256 left, uint256 right, uint256 maxDelta) internal pure virtual { + vm.assertApproxEqAbs(left, right, maxDelta); + } + + /// @notice Asserts that the absolute difference between `left` and `right` is at most `maxDelta` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param maxDelta The maximum absolute difference allowed. + /// @param err The error message on failure. + function assertApproxEqAbs(uint256 left, uint256 right, uint256 maxDelta, string memory err) internal pure virtual { + vm.assertApproxEqAbs(left, right, maxDelta, err); + } + + /// @notice Asserts that the absolute difference between `left` and `right` is at most `maxDelta`, formatting values with `decimals` decimal places on failure. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param maxDelta The maximum absolute difference allowed. + /// @param decimals The number of decimals for formatting. + function assertApproxEqAbsDecimal(uint256 left, uint256 right, uint256 maxDelta, uint256 decimals) + internal + pure + virtual + { + vm.assertApproxEqAbsDecimal(left, right, maxDelta, decimals); + } + + /// @notice Asserts that the absolute difference between `left` and `right` is at most `maxDelta`, formatting values with `decimals` decimal places on failure, with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param maxDelta The maximum absolute difference allowed. + /// @param decimals The number of decimals for formatting. + /// @param err The error message on failure. + function assertApproxEqAbsDecimal( + uint256 left, + uint256 right, + uint256 maxDelta, + uint256 decimals, + string memory err + ) internal pure virtual { + vm.assertApproxEqAbsDecimal(left, right, maxDelta, decimals, err); + } + + /// @notice Asserts that the absolute difference between `left` and `right` is at most `maxDelta`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param maxDelta The maximum absolute difference allowed. + function assertApproxEqAbs(int256 left, int256 right, uint256 maxDelta) internal pure virtual { + vm.assertApproxEqAbs(left, right, maxDelta); + } + + /// @notice Asserts that the absolute difference between `left` and `right` is at most `maxDelta` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param maxDelta The maximum absolute difference allowed. + /// @param err The error message on failure. + function assertApproxEqAbs(int256 left, int256 right, uint256 maxDelta, string memory err) internal pure virtual { + vm.assertApproxEqAbs(left, right, maxDelta, err); + } + + /// @notice Asserts that the absolute difference between `left` and `right` is at most `maxDelta`, formatting values with `decimals` decimal places on failure. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param maxDelta The maximum absolute difference allowed. + /// @param decimals The number of decimals for formatting. + function assertApproxEqAbsDecimal(int256 left, int256 right, uint256 maxDelta, uint256 decimals) + internal + pure + virtual + { + vm.assertApproxEqAbsDecimal(left, right, maxDelta, decimals); + } + + /// @notice Asserts that the absolute difference between `left` and `right` is at most `maxDelta`, formatting values with `decimals` decimal places on failure, with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param maxDelta The maximum absolute difference allowed. + /// @param decimals The number of decimals for formatting. + /// @param err The error message on failure. + function assertApproxEqAbsDecimal(int256 left, int256 right, uint256 maxDelta, uint256 decimals, string memory err) + internal + pure + virtual + { + vm.assertApproxEqAbsDecimal(left, right, maxDelta, decimals, err); + } + + /// @notice Asserts that the relative difference between `left` and `right` is at most `maxPercentDelta`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param maxPercentDelta The maximum relative delta allowed, as an 18 decimal fixed point number where 1e18 == 100%. + function assertApproxEqRel( + uint256 left, + uint256 right, + uint256 maxPercentDelta // An 18 decimal fixed point number, where 1e18 == 100% + ) + internal + pure + virtual + { + vm.assertApproxEqRel(left, right, maxPercentDelta); + } + + /// @notice Asserts that the relative difference between `left` and `right` is at most `maxPercentDelta` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param maxPercentDelta The maximum relative delta allowed, as an 18 decimal fixed point number where 1e18 == 100%. + /// @param err The error message on failure. + function assertApproxEqRel( + uint256 left, + uint256 right, + uint256 maxPercentDelta, // An 18 decimal fixed point number, where 1e18 == 100% + string memory err + ) + internal + pure + virtual + { + vm.assertApproxEqRel(left, right, maxPercentDelta, err); + } + + /// @notice Asserts that the relative difference between `left` and `right` is at most `maxPercentDelta`, formatting values with `decimals` decimal places on failure. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param maxPercentDelta The maximum relative delta allowed, as an 18 decimal fixed point number where 1e18 == 100%. + /// @param decimals The number of decimals for formatting. + function assertApproxEqRelDecimal( + uint256 left, + uint256 right, + uint256 maxPercentDelta, // An 18 decimal fixed point number, where 1e18 == 100% + uint256 decimals + ) + internal + pure + virtual + { + vm.assertApproxEqRelDecimal(left, right, maxPercentDelta, decimals); + } + + /// @notice Asserts that the relative difference between `left` and `right` is at most `maxPercentDelta`, formatting values with `decimals` decimal places on failure, with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param maxPercentDelta The maximum relative delta allowed, as an 18 decimal fixed point number where 1e18 == 100%. + /// @param decimals The number of decimals for formatting. + /// @param err The error message on failure. + function assertApproxEqRelDecimal( + uint256 left, + uint256 right, + uint256 maxPercentDelta, // An 18 decimal fixed point number, where 1e18 == 100% + uint256 decimals, + string memory err + ) internal pure virtual { + vm.assertApproxEqRelDecimal(left, right, maxPercentDelta, decimals, err); + } + + /// @notice Asserts that the relative difference between `left` and `right` is at most `maxPercentDelta`. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param maxPercentDelta The maximum relative delta allowed, as an 18 decimal fixed point number where 1e18 == 100%. + function assertApproxEqRel(int256 left, int256 right, uint256 maxPercentDelta) internal pure virtual { + vm.assertApproxEqRel(left, right, maxPercentDelta); + } + + /// @notice Asserts that the relative difference between `left` and `right` is at most `maxPercentDelta` with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param maxPercentDelta The maximum relative delta allowed, as an 18 decimal fixed point number where 1e18 == 100%. + /// @param err The error message on failure. + function assertApproxEqRel( + int256 left, + int256 right, + uint256 maxPercentDelta, // An 18 decimal fixed point number, where 1e18 == 100% + string memory err + ) + internal + pure + virtual + { + vm.assertApproxEqRel(left, right, maxPercentDelta, err); + } + + /// @notice Asserts that the relative difference between `left` and `right` is at most `maxPercentDelta`, formatting values with `decimals` decimal places on failure. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param maxPercentDelta The maximum relative delta allowed, as an 18 decimal fixed point number where 1e18 == 100%. + /// @param decimals The number of decimals for formatting. + function assertApproxEqRelDecimal( + int256 left, + int256 right, + uint256 maxPercentDelta, // An 18 decimal fixed point number, where 1e18 == 100% + uint256 decimals + ) + internal + pure + virtual + { + vm.assertApproxEqRelDecimal(left, right, maxPercentDelta, decimals); + } + + /// @notice Asserts that the relative difference between `left` and `right` is at most `maxPercentDelta`, formatting values with `decimals` decimal places on failure, with a custom error message. + /// @param left The left-hand side value. + /// @param right The right-hand side value. + /// @param maxPercentDelta The maximum relative delta allowed, as an 18 decimal fixed point number where 1e18 == 100%. + /// @param decimals The number of decimals for formatting. + /// @param err The error message on failure. + function assertApproxEqRelDecimal( + int256 left, + int256 right, + uint256 maxPercentDelta, // An 18 decimal fixed point number, where 1e18 == 100% + uint256 decimals, + string memory err + ) internal pure virtual { + vm.assertApproxEqRelDecimal(left, right, maxPercentDelta, decimals, err); + } + + // Inherited from DSTest, not used but kept for backwards-compatibility + /// @notice Returns true if `left` and `right` have equal content. + /// @dev Inherited from DSTest, kept for backwards-compatibility. + /// @param left The left-hand side bytes. + /// @param right The right-hand side bytes. + /// @return True if the byte content is equal, false otherwise. + function checkEq0(bytes memory left, bytes memory right) internal pure returns (bool) { + return keccak256(left) == keccak256(right); + } + + /// @notice Asserts that `left` is equal to `right` (legacy bytes variant). + /// @dev Alias for assertEq(bytes,bytes) kept for backwards-compatibility. + /// @param left The left-hand side bytes. + /// @param right The right-hand side bytes. + function assertEq0(bytes memory left, bytes memory right) internal pure virtual { + assertEq(left, right); + } + + /// @notice Asserts that `left` is equal to `right` with a custom error message (legacy bytes variant). + /// @dev Alias for assertEq(bytes,bytes,string) kept for backwards-compatibility. + /// @param left The left-hand side bytes. + /// @param right The right-hand side bytes. + /// @param err The error message on failure. + function assertEq0(bytes memory left, bytes memory right, string memory err) internal pure virtual { + assertEq(left, right, err); + } + + /// @notice Asserts that `left` is not equal to `right` (legacy bytes variant). + /// @dev Alias for assertNotEq(bytes,bytes) kept for backwards-compatibility. + /// @param left The left-hand side bytes. + /// @param right The right-hand side bytes. + function assertNotEq0(bytes memory left, bytes memory right) internal pure virtual { + assertNotEq(left, right); + } + + /// @notice Asserts that `left` is not equal to `right` with a custom error message (legacy bytes variant). + /// @dev Alias for assertNotEq(bytes,bytes,string) kept for backwards-compatibility. + /// @param left The left-hand side bytes. + /// @param right The right-hand side bytes. + /// @param err The error message on failure. + function assertNotEq0(bytes memory left, bytes memory right, string memory err) internal pure virtual { + assertNotEq(left, right, err); + } + + /// @notice Asserts that two calls to the same target with different calldata produce equal return or revert data. + /// @param target The contract address to call. + /// @param callDataA The calldata for the first call. + /// @param callDataB The calldata for the second call. + function assertEqCall(address target, bytes memory callDataA, bytes memory callDataB) internal virtual { + assertEqCall(target, callDataA, target, callDataB, true); + } + + /// @notice Asserts that calls to two different targets produce equal return or revert data. + /// @param targetA The first contract address. + /// @param callDataA The calldata for the first call. + /// @param targetB The second contract address. + /// @param callDataB The calldata for the second call. + function assertEqCall(address targetA, bytes memory callDataA, address targetB, bytes memory callDataB) + internal + virtual + { + assertEqCall(targetA, callDataA, targetB, callDataB, true); + } + + /// @notice Asserts that two calls to the same target with different calldata produce equal return or revert data. + /// @param target The contract address to call. + /// @param callDataA The calldata for the first call. + /// @param callDataB The calldata for the second call. + /// @param strictRevertData If true, also asserts that revert data matches when both calls revert. + function assertEqCall(address target, bytes memory callDataA, bytes memory callDataB, bool strictRevertData) + internal + virtual + { + assertEqCall(target, callDataA, target, callDataB, strictRevertData); + } + + /// @notice Asserts that calls to two targets produce equal return or revert data. + /// @param targetA The first contract address. + /// @param callDataA The calldata for the first call. + /// @param targetB The second contract address. + /// @param callDataB The calldata for the second call. + /// @param strictRevertData If true, also asserts that revert data matches when both calls revert. + function assertEqCall( + address targetA, + bytes memory callDataA, + address targetB, + bytes memory callDataB, + bool strictRevertData + ) internal virtual { + (bool successA, bytes memory returnDataA) = address(targetA).call(callDataA); + (bool successB, bytes memory returnDataB) = address(targetB).call(callDataB); + + if (successA && successB) { + assertEq(returnDataA, returnDataB, "Call return data does not match"); + } + + if (!successA && !successB && strictRevertData) { + assertEq(returnDataA, returnDataB, "Call revert data does not match"); + } + + if (!successA && successB) { + emit log("Error: Calls were not equal"); + emit log_named_bytes(" Left call revert data", returnDataA); + emit log_named_bytes(" Right call return data", returnDataB); + revert("assertion failed"); + } + + if (successA && !successB) { + emit log("Error: Calls were not equal"); + emit log_named_bytes(" Left call return data", returnDataA); + emit log_named_bytes(" Right call revert data", returnDataB); + revert("assertion failed"); + } + } +} diff --git a/contracts/evm/lib/forge-std/src/StdChains.sol b/contracts/evm/lib/forge-std/src/StdChains.sol new file mode 100644 index 0000000000..4fed0b5232 --- /dev/null +++ b/contracts/evm/lib/forge-std/src/StdChains.sol @@ -0,0 +1,316 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {VmSafe} from "./Vm.sol"; + +/** + * StdChains provides information about EVM compatible chains that can be used in scripts/tests. + * For each chain, the chain's name, chain ID, and a default RPC URL are provided. Chains are + * identified by their alias, which is the same as the alias in the `[rpc_endpoints]` section of + * the `foundry.toml` file. For best UX, ensure the alias in the `foundry.toml` file matches the + * alias used in this contract, which can be found as the first argument to the + * `_setChainWithDefaultRpcUrl` call in the `_initializeStdChains` function. + * + * There are two main ways to use this contract: + * 1. Set a chain with `setChain(string memory chainAlias, ChainData memory chain)` or + * `setChain(string memory chainAlias, Chain memory chain)` + * 2. Get a chain with `getChain(string memory chainAlias)` or `getChain(uint256 chainId)`. + * + * The first time either of those are used, chains are initialized with the default set of RPC URLs. + * This is done in `_initializeStdChains`, which uses `_setChainWithDefaultRpcUrl`. Defaults are recorded in + * `_defaultRpcUrls`. + * + * The `setChain` function is straightforward, and it simply saves off the given chain data. + * + * The `getChain` methods use `_getChainWithUpdatedRpcUrl` to return a chain. For example, let's say + * we want to retrieve the RPC URL for `mainnet`: + * - If you have specified data with `setChain`, it will return that. + * - If you have configured a mainnet RPC URL in `foundry.toml`, it will return the URL, provided it + * is valid (e.g. a URL is specified, or an environment variable is given and exists). + * - If neither of the above conditions is met, the default data is returned. + * + * Summarizing the above, the prioritization hierarchy is `setChain` -> `foundry.toml` -> environment variable -> defaults. + */ +abstract contract StdChains { + VmSafe private constant vm = VmSafe(address(uint160(uint256(keccak256("hevm cheat code"))))); + + bool private _stdChainsInitialized; + + struct ChainData { + string name; + uint256 chainId; + string rpcUrl; + } + + struct Chain { + // The chain name. + string name; + // The chain's Chain ID. + uint256 chainId; + // The chain's alias. (i.e. what gets specified in `foundry.toml`). + string chainAlias; + // A default RPC endpoint for this chain. + // NOTE: This default RPC URL is included for convenience to facilitate quick tests and + // experimentation. Do not use this RPC URL for production test suites, CI, or other heavy + // usage as you will be throttled and this is a disservice to others who need this endpoint. + string rpcUrl; + } + + // Maps from the chain's alias (matching the alias in the `foundry.toml` file) to chain data. + mapping(string => Chain) private _chains; + // Maps from the chain's alias to its default RPC URL. + mapping(string => string) private _defaultRpcUrls; + // Maps from a chain ID to its alias. + mapping(uint256 => string) private _idToAlias; + + bool private _fallbackToDefaultRpcUrls = true; + + /// @notice Returns chain data for the given alias, with the RPC URL resolved from config or defaults. + /// @dev Reverts if `chainAlias` is empty or has not been registered. + function getChain(string memory chainAlias) internal virtual returns (Chain memory chain) { + require(bytes(chainAlias).length != 0, "StdChains getChain(string): Chain alias cannot be the empty string."); + + _initializeStdChains(); + chain = _chains[chainAlias]; + require( + chain.chainId != 0, + string(abi.encodePacked("StdChains getChain(string): Chain with alias \"", chainAlias, "\" not found.")) + ); + + chain = _getChainWithUpdatedRpcUrl(chainAlias, chain); + } + + /// @notice Returns chain data for the given chain ID, with the RPC URL resolved from config or defaults. + /// @dev Reverts if `chainId` is `0` or has not been registered. + function getChain(uint256 chainId) internal virtual returns (Chain memory chain) { + require(chainId != 0, "StdChains getChain(uint256): Chain ID cannot be 0."); + _initializeStdChains(); + string memory chainAlias = _idToAlias[chainId]; + + chain = _chains[chainAlias]; + + require( + chain.chainId != 0, + string(abi.encodePacked("StdChains getChain(uint256): Chain with ID ", vm.toString(chainId), " not found.")) + ); + + chain = _getChainWithUpdatedRpcUrl(chainAlias, chain); + } + + /// @notice Registers chain data under `chainAlias`, with priority given to the argument's `rpcUrl` field. + function setChain(string memory chainAlias, ChainData memory chain) internal virtual { + require( + bytes(chainAlias).length != 0, + "StdChains setChain(string,ChainData): Chain alias cannot be the empty string." + ); + + require(chain.chainId != 0, "StdChains setChain(string,ChainData): Chain ID cannot be 0."); + + _initializeStdChains(); + string memory foundAlias = _idToAlias[chain.chainId]; + + require( + bytes(foundAlias).length == 0 || keccak256(bytes(foundAlias)) == keccak256(bytes(chainAlias)), + string( + abi.encodePacked( + "StdChains setChain(string,ChainData): Chain ID ", + vm.toString(chain.chainId), + " already used by \"", + foundAlias, + "\"." + ) + ) + ); + + uint256 oldChainId = _chains[chainAlias].chainId; + delete _idToAlias[oldChainId]; + + _chains[chainAlias] = + Chain({name: chain.name, chainId: chain.chainId, chainAlias: chainAlias, rpcUrl: chain.rpcUrl}); + _idToAlias[chain.chainId] = chainAlias; + } + + /// @notice Registers chain data under `chainAlias`, with priority given to the argument's `rpcUrl` field. + function setChain(string memory chainAlias, Chain memory chain) internal virtual { + setChain(chainAlias, ChainData({name: chain.name, chainId: chain.chainId, rpcUrl: chain.rpcUrl})); + } + + function _toUpper(string memory str) private pure returns (string memory) { + bytes memory strb = bytes(str); + bytes memory copy = new bytes(strb.length); + for (uint256 i = 0; i < strb.length; i++) { + bytes1 b = strb[i]; + if (b >= 0x61 && b <= 0x7A) { + copy[i] = bytes1(uint8(b) - 32); + } else { + copy[i] = b; + } + } + return string(copy); + } + + // lookup rpcUrl, in descending order of priority: + // current -> config (foundry.toml) -> environment variable -> default + function _getChainWithUpdatedRpcUrl(string memory chainAlias, Chain memory chain) + private + view + returns (Chain memory) + { + if (bytes(chain.rpcUrl).length == 0) { + try vm.rpcUrl(chainAlias) returns (string memory configRpcUrl) { + chain.rpcUrl = configRpcUrl; + } catch (bytes memory err) { + string memory envName = string(abi.encodePacked(_toUpper(chainAlias), "_RPC_URL")); + if (_fallbackToDefaultRpcUrls) { + chain.rpcUrl = vm.envOr(envName, _defaultRpcUrls[chainAlias]); + } else { + chain.rpcUrl = vm.envString(envName); + } + // Distinguish 'not found' from 'cannot read' + // The upstream error thrown by forge for failing cheats changed so we check both the old and new versions + bytes memory oldNotFoundError = + abi.encodeWithSignature("CheatCodeError", string(abi.encodePacked("invalid rpc url ", chainAlias))); + bytes memory newNotFoundError = abi.encodeWithSignature( + "CheatcodeError(string)", string(abi.encodePacked("invalid rpc url: ", chainAlias)) + ); + bytes32 errHash = keccak256(err); + if ( + (errHash != keccak256(oldNotFoundError) && errHash != keccak256(newNotFoundError)) + || bytes(chain.rpcUrl).length == 0 + ) { + assembly ("memory-safe") { + revert(add(32, err), mload(err)) + } + } + } + } + return chain; + } + + /// @notice Sets whether to fall back to default RPC URLs when no URL is configured for a chain. + function setFallbackToDefaultRpcUrls(bool useDefault) internal { + _fallbackToDefaultRpcUrls = useDefault; + } + + function _initializeStdChains() private { + if (_stdChainsInitialized) return; + + _stdChainsInitialized = true; + + // If adding an RPC here, make sure to test the default RPC URL in `test_Rpcs` in `StdChains.t.sol` + _setChainWithDefaultRpcUrl("anvil", ChainData("Anvil", 31337, "http://127.0.0.1:8545")); + _setChainWithDefaultRpcUrl("mainnet", ChainData("Mainnet", 1, "https://eth.llamarpc.com")); + _setChainWithDefaultRpcUrl( + "sepolia", ChainData("Sepolia", 11155111, "https://sepolia.infura.io/v3/b9794ad1ddf84dfb8c34d6bb5dca2001") + ); + _setChainWithDefaultRpcUrl("holesky", ChainData("Holesky", 17000, "https://rpc.holesky.ethpandaops.io")); + _setChainWithDefaultRpcUrl("hoodi", ChainData("Hoodi", 560048, "https://rpc.hoodi.ethpandaops.io")); + _setChainWithDefaultRpcUrl("optimism", ChainData("Optimism", 10, "https://mainnet.optimism.io")); + _setChainWithDefaultRpcUrl( + "optimism_sepolia", ChainData("Optimism Sepolia", 11155420, "https://sepolia.optimism.io") + ); + _setChainWithDefaultRpcUrl("arbitrum_one", ChainData("Arbitrum One", 42161, "https://arb1.arbitrum.io/rpc")); + _setChainWithDefaultRpcUrl( + "arbitrum_one_sepolia", ChainData("Arbitrum One Sepolia", 421614, "https://sepolia-rollup.arbitrum.io/rpc") + ); + _setChainWithDefaultRpcUrl("arbitrum_nova", ChainData("Arbitrum Nova", 42170, "https://nova.arbitrum.io/rpc")); + _setChainWithDefaultRpcUrl("polygon", ChainData("Polygon", 137, "https://polygon-rpc.com")); + _setChainWithDefaultRpcUrl( + "polygon_amoy", ChainData("Polygon Amoy", 80002, "https://rpc-amoy.polygon.technology") + ); + _setChainWithDefaultRpcUrl("avalanche", ChainData("Avalanche", 43114, "https://api.avax.network/ext/bc/C/rpc")); + _setChainWithDefaultRpcUrl( + "avalanche_fuji", ChainData("Avalanche Fuji", 43113, "https://api.avax-test.network/ext/bc/C/rpc") + ); + _setChainWithDefaultRpcUrl( + "bnb_smart_chain", ChainData("BNB Smart Chain", 56, "https://bsc-dataseed1.binance.org") + ); + _setChainWithDefaultRpcUrl( + "bnb_smart_chain_testnet", + ChainData("BNB Smart Chain Testnet", 97, "https://rpc.ankr.com/bsc_testnet_chapel") + ); + _setChainWithDefaultRpcUrl("gnosis_chain", ChainData("Gnosis Chain", 100, "https://rpc.gnosischain.com")); + _setChainWithDefaultRpcUrl("moonbeam", ChainData("Moonbeam", 1284, "https://rpc.api.moonbeam.network")); + _setChainWithDefaultRpcUrl( + "moonriver", ChainData("Moonriver", 1285, "https://rpc.api.moonriver.moonbeam.network") + ); + _setChainWithDefaultRpcUrl("moonbase", ChainData("Moonbase", 1287, "https://rpc.testnet.moonbeam.network")); + _setChainWithDefaultRpcUrl("base_sepolia", ChainData("Base Sepolia", 84532, "https://sepolia.base.org")); + _setChainWithDefaultRpcUrl("base", ChainData("Base", 8453, "https://mainnet.base.org")); + _setChainWithDefaultRpcUrl("blast_sepolia", ChainData("Blast Sepolia", 168587773, "https://sepolia.blast.io")); + _setChainWithDefaultRpcUrl("blast", ChainData("Blast", 81457, "https://rpc.blast.io")); + _setChainWithDefaultRpcUrl("fantom_opera", ChainData("Fantom Opera", 250, "https://rpc.ankr.com/fantom/")); + _setChainWithDefaultRpcUrl( + "fantom_opera_testnet", ChainData("Fantom Opera Testnet", 4002, "https://rpc.ankr.com/fantom_testnet/") + ); + _setChainWithDefaultRpcUrl("fraxtal", ChainData("Fraxtal", 252, "https://rpc.frax.com")); + _setChainWithDefaultRpcUrl( + "fraxtal_testnet", ChainData("Fraxtal Testnet", 2522, "https://rpc.testnet.frax.com") + ); + _setChainWithDefaultRpcUrl( + "berachain_bartio_testnet", ChainData("Berachain bArtio Testnet", 80084, "https://bartio.rpc.berachain.com") + ); + _setChainWithDefaultRpcUrl("flare", ChainData("Flare", 14, "https://flare-api.flare.network/ext/C/rpc")); + _setChainWithDefaultRpcUrl( + "flare_coston2", ChainData("Flare Coston2", 114, "https://coston2-api.flare.network/ext/C/rpc") + ); + + _setChainWithDefaultRpcUrl("ink", ChainData("Ink", 57073, "https://rpc-gel.inkonchain.com")); + _setChainWithDefaultRpcUrl( + "ink_sepolia", ChainData("Ink Sepolia", 763373, "https://rpc-gel-sepolia.inkonchain.com") + ); + + _setChainWithDefaultRpcUrl("mode", ChainData("Mode", 34443, "https://mode.drpc.org")); + _setChainWithDefaultRpcUrl("mode_sepolia", ChainData("Mode Sepolia", 919, "https://sepolia.mode.network")); + + _setChainWithDefaultRpcUrl("zora", ChainData("Zora", 7777777, "https://zora.drpc.org")); + _setChainWithDefaultRpcUrl( + "zora_sepolia", ChainData("Zora Sepolia", 999999999, "https://sepolia.rpc.zora.energy") + ); + + _setChainWithDefaultRpcUrl("race", ChainData("Race", 6805, "https://racemainnet.io")); + _setChainWithDefaultRpcUrl("race_sepolia", ChainData("Race Sepolia", 6806, "https://racemainnet.io")); + + _setChainWithDefaultRpcUrl("radius", ChainData("Radius", 723487, "https://rpc.radiustech.xyz")); + _setChainWithDefaultRpcUrl( + "radius_testnet", ChainData("Radius Testnet", 72344, "https://rpc.testnet.radiustech.xyz") + ); + + _setChainWithDefaultRpcUrl("metal", ChainData("Metal", 1750, "https://metall2.drpc.org")); + _setChainWithDefaultRpcUrl("metal_sepolia", ChainData("Metal Sepolia", 1740, "https://testnet.rpc.metall2.com")); + + _setChainWithDefaultRpcUrl("binary", ChainData("Binary", 624, "https://rpc.zero.thebinaryholdings.com")); + _setChainWithDefaultRpcUrl( + "binary_sepolia", ChainData("Binary Sepolia", 625, "https://rpc.zero.thebinaryholdings.com") + ); + + _setChainWithDefaultRpcUrl("orderly", ChainData("Orderly", 291, "https://rpc.orderly.network")); + _setChainWithDefaultRpcUrl( + "orderly_sepolia", ChainData("Orderly Sepolia", 4460, "https://testnet-rpc.orderly.org") + ); + + _setChainWithDefaultRpcUrl("unichain", ChainData("Unichain", 130, "https://mainnet.unichain.org")); + _setChainWithDefaultRpcUrl( + "unichain_sepolia", ChainData("Unichain Sepolia", 1301, "https://sepolia.unichain.org") + ); + + _setChainWithDefaultRpcUrl("tempo", ChainData("Tempo", 4217, "https://rpc.mainnet.tempo.xyz")); + _setChainWithDefaultRpcUrl( + "tempo_moderato", ChainData("Tempo Moderato", 42431, "https://rpc.moderato.tempo.xyz") + ); + _setChainWithDefaultRpcUrl( + "tempo_andantino", ChainData("Tempo Andantino", 42429, "https://rpc.testnet.tempo.xyz") + ); + + _setChainWithDefaultRpcUrl("grav", ChainData("Gravity", 127001, "https://mainnet-rpc.gravity.xyz")); + } + + // set chain info, with priority to chainAlias' rpc url in foundry.toml + function _setChainWithDefaultRpcUrl(string memory chainAlias, ChainData memory chain) private { + string memory rpcUrl = chain.rpcUrl; + _defaultRpcUrls[chainAlias] = rpcUrl; + chain.rpcUrl = ""; + setChain(chainAlias, chain); + chain.rpcUrl = rpcUrl; // restore argument + } +} diff --git a/contracts/evm/lib/forge-std/src/StdCheats.sol b/contracts/evm/lib/forge-std/src/StdCheats.sol new file mode 100644 index 0000000000..95a5bf95e9 --- /dev/null +++ b/contracts/evm/lib/forge-std/src/StdCheats.sol @@ -0,0 +1,922 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {StdStorage, stdStorage} from "./StdStorage.sol"; +import {console2} from "./console2.sol"; +import {Vm} from "./Vm.sol"; + +abstract contract StdCheatsSafe { + Vm private constant vm = Vm(address(uint160(uint256(keccak256("hevm cheat code"))))); + + uint256 private constant _UINT256_MAX = + 115792089237316195423570985008687907853269984665640564039457584007913129639935; + + bool private _gasMeteringOff; + + // Data structures to parse Transaction objects from the broadcast artifact + // that conform to EIP1559. The Raw structs are what are parsed from the JSON + // and then converted to the one that is used by the user for better UX. + + struct RawTx1559 { + string[] arguments; + address contractAddress; + string contractName; + // json value name = function + string functionSig; + bytes32 hash; + // json value name = tx + RawTx1559Detail txDetail; + // json value name = type + string opcode; + } + + struct RawTx1559Detail { + AccessList[] accessList; + bytes data; + address from; + bytes gas; + bytes nonce; + address to; + bytes txType; + bytes value; + } + + struct Tx1559 { + string[] arguments; + address contractAddress; + string contractName; + string functionSig; + bytes32 hash; + Tx1559Detail txDetail; + string opcode; + } + + struct Tx1559Detail { + AccessList[] accessList; + bytes data; + address from; + uint256 gas; + uint256 nonce; + address to; + uint256 txType; + uint256 value; + } + + // Data structures to parse Transaction objects from the broadcast artifact + // that DO NOT conform to EIP1559. The Raw structs are what are parsed from the JSON + // and then converted to the one that is used by the user for better UX. + + struct TxLegacy { + string[] arguments; + address contractAddress; + string contractName; + string functionSig; + string hash; + string opcode; + TxDetailLegacy transaction; + } + + struct TxDetailLegacy { + AccessList[] accessList; + uint256 chainId; + bytes data; + address from; + uint256 gas; + uint256 gasPrice; + bytes32 hash; + uint256 nonce; + bytes1 opcode; + bytes32 r; + bytes32 s; + uint256 txType; + address to; + uint8 v; + uint256 value; + } + + struct AccessList { + address accessAddress; + bytes32[] storageKeys; + } + + // Data structures to parse Receipt objects from the broadcast artifact. + // The Raw structs is what is parsed from the JSON + // and then converted to the one that is used by the user for better UX. + + struct RawReceipt { + bytes32 blockHash; + bytes blockNumber; + address contractAddress; + bytes cumulativeGasUsed; + bytes effectiveGasPrice; + address from; + bytes gasUsed; + RawReceiptLog[] logs; + bytes logsBloom; + bytes status; + address to; + bytes32 transactionHash; + bytes transactionIndex; + } + + struct Receipt { + bytes32 blockHash; + uint256 blockNumber; + address contractAddress; + uint256 cumulativeGasUsed; + uint256 effectiveGasPrice; + address from; + uint256 gasUsed; + ReceiptLog[] logs; + bytes logsBloom; + uint256 status; + address to; + bytes32 transactionHash; + uint256 transactionIndex; + } + + // Data structures to parse the entire broadcast artifact, assuming the + // transactions conform to EIP1559. + + struct EIP1559ScriptArtifact { + string[] libraries; + string path; + string[] pending; + Receipt[] receipts; + uint256 timestamp; + Tx1559[] transactions; + TxReturn[] txReturns; + } + + struct RawEIP1559ScriptArtifact { + string[] libraries; + string path; + string[] pending; + RawReceipt[] receipts; + TxReturn[] txReturns; + uint256 timestamp; + RawTx1559[] transactions; + } + + struct RawReceiptLog { + // json value = address + address logAddress; + bytes32 blockHash; + bytes blockNumber; + bytes data; + bytes logIndex; + bool removed; + bytes32[] topics; + bytes32 transactionHash; + bytes transactionIndex; + bytes transactionLogIndex; + } + + struct ReceiptLog { + // json value = address + address logAddress; + bytes32 blockHash; + uint256 blockNumber; + bytes data; + uint256 logIndex; + bytes32[] topics; + uint256 transactionIndex; + uint256 transactionLogIndex; + bool removed; + } + + struct TxReturn { + string internalType; + string value; + } + + struct Account { + address addr; + uint256 key; + } + + enum AddressType { + Payable, + NonPayable, + ZeroAddress, + Precompile, + ForgeAddress + } + + /// @notice Assumes `addr` is not blacklisted by `token`, skipping the fuzz run if it is. + function assumeNotBlacklisted(address token, address addr) internal view virtual { + // Nothing to check if `token` is not a contract. + uint256 tokenCodeSize; + assembly { + tokenCodeSize := extcodesize(token) + } + require(tokenCodeSize > 0, "StdCheats assumeNotBlacklisted(address,address): Token address is not a contract."); + + bool success; + bytes memory returnData; + + // 4-byte selector for `isBlacklisted(address)`, used by USDC. + (success, returnData) = token.staticcall(abi.encodeWithSelector(0xfe575a87, addr)); + vm.assume(!success || abi.decode(returnData, (bool)) == false); + + // 4-byte selector for `isBlackListed(address)`, used by USDT. + (success, returnData) = token.staticcall(abi.encodeWithSelector(0xe47d6060, addr)); + vm.assume(!success || abi.decode(returnData, (bool)) == false); + } + + /// @notice Assumes `addr` is not blacklisted by `token`, skipping the fuzz run if it is. + /// @dev Deprecated alias for `assumeNotBlacklisted`. Will be removed in a future breaking release. + function assumeNoBlacklisted(address token, address addr) internal view virtual { + assumeNotBlacklisted(token, addr); + } + + /// @notice Assumes `addr` does not match `addressType`, skipping the fuzz run if it does. + function assumeAddressIsNot(address addr, AddressType addressType) internal virtual { + if (addressType == AddressType.Payable) { + assumeNotPayable(addr); + } else if (addressType == AddressType.NonPayable) { + assumePayable(addr); + } else if (addressType == AddressType.ZeroAddress) { + assumeNotZeroAddress(addr); + } else if (addressType == AddressType.Precompile) { + assumeNotPrecompile(addr); + } else if (addressType == AddressType.ForgeAddress) { + assumeNotForgeAddress(addr); + } + } + + /// @notice Assumes `addr` does not match `addressType1` or `addressType2`, skipping the fuzz run if it does. + function assumeAddressIsNot(address addr, AddressType addressType1, AddressType addressType2) internal virtual { + assumeAddressIsNot(addr, addressType1); + assumeAddressIsNot(addr, addressType2); + } + + /// @notice Assumes `addr` does not match any of the three given address types, skipping the fuzz run if it does. + function assumeAddressIsNot( + address addr, + AddressType addressType1, + AddressType addressType2, + AddressType addressType3 + ) internal virtual { + assumeAddressIsNot(addr, addressType1); + assumeAddressIsNot(addr, addressType2); + assumeAddressIsNot(addr, addressType3); + } + + /// @notice Assumes `addr` does not match any of the four given address types, skipping the fuzz run if it does. + function assumeAddressIsNot( + address addr, + AddressType addressType1, + AddressType addressType2, + AddressType addressType3, + AddressType addressType4 + ) internal virtual { + assumeAddressIsNot(addr, addressType1); + assumeAddressIsNot(addr, addressType2); + assumeAddressIsNot(addr, addressType3); + assumeAddressIsNot(addr, addressType4); + } + + // This function checks whether an address, `addr`, is payable. It works by sending 1 wei to + // `addr` and checking the `success` return value. + // NOTE: This function may result in state changes depending on the fallback/receive logic + // implemented by `addr`, which should be taken into account when this function is used. + function _isPayable(address addr) private returns (bool) { + require( + addr.balance < _UINT256_MAX, + "StdCheats _isPayable(address): Balance equals max uint256, so it cannot receive any more funds" + ); + uint256 origBalanceTest = address(this).balance; + uint256 origBalanceAddr = address(addr).balance; + + vm.deal(address(this), 1); + (bool success,) = payable(addr).call{value: 1}(""); + + // reset balances + vm.deal(address(this), origBalanceTest); + vm.deal(addr, origBalanceAddr); + + return success; + } + + /// @notice Assumes `addr` is a payable address, skipping the fuzz run if it is not. + /// @dev May cause state changes depending on `addr`'s fallback or receive logic. + function assumePayable(address addr) internal virtual { + vm.assume(_isPayable(addr)); + } + + /// @notice Assumes `addr` is not a payable address, skipping the fuzz run if it is. + /// @dev May cause state changes depending on `addr`'s fallback or receive logic. + function assumeNotPayable(address addr) internal virtual { + vm.assume(!_isPayable(addr)); + } + + /// @notice Assumes `addr` is not the zero address, skipping the fuzz run if it is. + function assumeNotZeroAddress(address addr) internal pure virtual { + vm.assume(addr != address(0)); + } + + /// @notice Assumes `addr` is not a precompile on the current chain, skipping the fuzz run if it is. + function assumeNotPrecompile(address addr) internal pure virtual { + assumeNotPrecompile(addr, _pureChainId()); + } + + /// @notice Assumes `addr` is not a precompile on `chainId`, skipping the fuzz run if it is. + function assumeNotPrecompile(address addr, uint256 chainId) internal pure virtual { + // Note: For some chains like Optimism these are technically predeploys (i.e. bytecode placed at a specific + // address), but the same rationale for excluding them applies so we include those too. + + // These are reserved by Ethereum and may be on all EVM-compatible chains. + vm.assume(addr < address(0x1) || addr > address(0xff)); + + // forgefmt: disable-start + if (chainId == 10 || chainId == 420 || chainId == 11155420) { + // https://github.com/ethereum-optimism/optimism/blob/eaa371a0184b56b7ca6d9eb9cb0a2b78b2ccd864/op-bindings/predeploys/addresses.go#L6-L21 + vm.assume(addr < address(0x4200000000000000000000000000000000000000) || addr > address(0x4200000000000000000000000000000000000800)); + } else if (chainId == 42161 || chainId == 421613) { + // https://developer.arbitrum.io/useful-addresses#arbitrum-precompiles-l2-same-on-all-arb-chains + vm.assume(addr < address(0x0000000000000000000000000000000000000064) || addr > address(0x0000000000000000000000000000000000000068)); + } else if (chainId == 43114 || chainId == 43113) { + // https://github.com/ava-labs/subnet-evm/blob/47c03fd007ecaa6de2c52ea081596e0a88401f58/precompile/params.go#L18-L59 + vm.assume(addr < address(0x0100000000000000000000000000000000000000) || addr > address(0x01000000000000000000000000000000000000ff)); + vm.assume(addr < address(0x0200000000000000000000000000000000000000) || addr > address(0x02000000000000000000000000000000000000FF)); + vm.assume(addr < address(0x0300000000000000000000000000000000000000) || addr > address(0x03000000000000000000000000000000000000Ff)); + } + // forgefmt: disable-end + } + + /// @notice Assumes `addr` is not a Forge-reserved address (vm, console, Create2Deployer), skipping the fuzz run if it is. + function assumeNotForgeAddress(address addr) internal pure virtual { + // vm, console, and Create2Deployer addresses + vm.assume( + addr != address(vm) && addr != 0x000000000000000000636F6e736F6c652e6c6f67 + && addr != 0x4e59b44847b379578588920cA78FbF26c0B4956C + ); + } + + /// @notice Assumes `addr` has no code and is not a precompile, zero, or Forge-reserved address. + function assumeUnusedAddress(address addr) internal view virtual { + uint256 size; + assembly { + size := extcodesize(addr) + } + vm.assume(size == 0); + + assumeNotPrecompile(addr); + assumeNotZeroAddress(addr); + assumeNotForgeAddress(addr); + } + + /// @notice Reads and parses an EIP-1559 broadcast artifact from `path`. + function readEIP1559ScriptArtifact(string memory path) + internal + view + virtual + returns (EIP1559ScriptArtifact memory) + { + string memory data = vm.readFile(path); + bytes memory parsedData = vm.parseJson(data); + RawEIP1559ScriptArtifact memory rawArtifact = abi.decode(parsedData, (RawEIP1559ScriptArtifact)); + EIP1559ScriptArtifact memory artifact; + artifact.libraries = rawArtifact.libraries; + artifact.path = rawArtifact.path; + artifact.timestamp = rawArtifact.timestamp; + artifact.pending = rawArtifact.pending; + artifact.txReturns = rawArtifact.txReturns; + artifact.receipts = rawToConvertedReceipts(rawArtifact.receipts); + artifact.transactions = rawToConvertedEIPTx1559s(rawArtifact.transactions); + return artifact; + } + + /// @notice Converts an array of raw EIP-1559 transactions to the user-friendly `Tx1559` format. + function rawToConvertedEIPTx1559s(RawTx1559[] memory rawTxs) internal pure virtual returns (Tx1559[] memory) { + Tx1559[] memory txs = new Tx1559[](rawTxs.length); + for (uint256 i; i < rawTxs.length; i++) { + txs[i] = rawToConvertedEIPTx1559(rawTxs[i]); + } + return txs; + } + + /// @notice Converts a single raw EIP-1559 transaction to the user-friendly `Tx1559` format. + function rawToConvertedEIPTx1559(RawTx1559 memory rawTx) internal pure virtual returns (Tx1559 memory) { + Tx1559 memory transaction; + transaction.arguments = rawTx.arguments; + transaction.contractAddress = rawTx.contractAddress; + transaction.contractName = rawTx.contractName; + transaction.functionSig = rawTx.functionSig; + transaction.hash = rawTx.hash; + transaction.txDetail = rawToConvertedEIP1559Detail(rawTx.txDetail); + transaction.opcode = rawTx.opcode; + return transaction; + } + + /// @notice Converts raw EIP-1559 transaction detail fields to the user-friendly `Tx1559Detail` format. + function rawToConvertedEIP1559Detail(RawTx1559Detail memory rawDetail) + internal + pure + virtual + returns (Tx1559Detail memory) + { + Tx1559Detail memory txDetail; + txDetail.data = rawDetail.data; + txDetail.from = rawDetail.from; + txDetail.to = rawDetail.to; + txDetail.nonce = _bytesToUint(rawDetail.nonce); + txDetail.txType = _bytesToUint(rawDetail.txType); + txDetail.value = _bytesToUint(rawDetail.value); + txDetail.gas = _bytesToUint(rawDetail.gas); + txDetail.accessList = rawDetail.accessList; + return txDetail; + } + + /// @notice Reads all EIP-1559 transactions from the broadcast artifact at `path`. + function readTx1559s(string memory path) internal view virtual returns (Tx1559[] memory) { + string memory deployData = vm.readFile(path); + bytes memory parsedDeployData = vm.parseJson(deployData, ".transactions"); + RawTx1559[] memory rawTxs = abi.decode(parsedDeployData, (RawTx1559[])); + return rawToConvertedEIPTx1559s(rawTxs); + } + + /// @notice Reads the EIP-1559 transaction at `index` from the broadcast artifact at `path`. + function readTx1559(string memory path, uint256 index) internal view virtual returns (Tx1559 memory) { + string memory deployData = vm.readFile(path); + string memory key = string(abi.encodePacked(".transactions[", vm.toString(index), "]")); + bytes memory parsedDeployData = vm.parseJson(deployData, key); + RawTx1559 memory rawTx = abi.decode(parsedDeployData, (RawTx1559)); + return rawToConvertedEIPTx1559(rawTx); + } + + /// @notice Reads all transaction receipts from the broadcast artifact at `path`. + function readReceipts(string memory path) internal view virtual returns (Receipt[] memory) { + string memory deployData = vm.readFile(path); + bytes memory parsedDeployData = vm.parseJson(deployData, ".receipts"); + RawReceipt[] memory rawReceipts = abi.decode(parsedDeployData, (RawReceipt[])); + return rawToConvertedReceipts(rawReceipts); + } + + /// @notice Reads the transaction receipt at `index` from the broadcast artifact at `path`. + function readReceipt(string memory path, uint256 index) internal view virtual returns (Receipt memory) { + string memory deployData = vm.readFile(path); + string memory key = string(abi.encodePacked(".receipts[", vm.toString(index), "]")); + bytes memory parsedDeployData = vm.parseJson(deployData, key); + RawReceipt memory rawReceipt = abi.decode(parsedDeployData, (RawReceipt)); + return rawToConvertedReceipt(rawReceipt); + } + + /// @notice Converts an array of raw receipts to the user-friendly `Receipt` format. + function rawToConvertedReceipts(RawReceipt[] memory rawReceipts) internal pure virtual returns (Receipt[] memory) { + Receipt[] memory receipts = new Receipt[](rawReceipts.length); + for (uint256 i; i < rawReceipts.length; i++) { + receipts[i] = rawToConvertedReceipt(rawReceipts[i]); + } + return receipts; + } + + /// @notice Converts a single raw receipt to the user-friendly `Receipt` format. + function rawToConvertedReceipt(RawReceipt memory rawReceipt) internal pure virtual returns (Receipt memory) { + Receipt memory receipt; + receipt.blockHash = rawReceipt.blockHash; + receipt.to = rawReceipt.to; + receipt.from = rawReceipt.from; + receipt.contractAddress = rawReceipt.contractAddress; + receipt.effectiveGasPrice = _bytesToUint(rawReceipt.effectiveGasPrice); + receipt.cumulativeGasUsed = _bytesToUint(rawReceipt.cumulativeGasUsed); + receipt.gasUsed = _bytesToUint(rawReceipt.gasUsed); + receipt.status = _bytesToUint(rawReceipt.status); + receipt.transactionIndex = _bytesToUint(rawReceipt.transactionIndex); + receipt.blockNumber = _bytesToUint(rawReceipt.blockNumber); + receipt.logs = rawToConvertedReceiptLogs(rawReceipt.logs); + receipt.logsBloom = rawReceipt.logsBloom; + receipt.transactionHash = rawReceipt.transactionHash; + return receipt; + } + + /// @notice Converts an array of raw receipt logs to the user-friendly `ReceiptLog` format. + function rawToConvertedReceiptLogs(RawReceiptLog[] memory rawLogs) + internal + pure + virtual + returns (ReceiptLog[] memory) + { + ReceiptLog[] memory logs = new ReceiptLog[](rawLogs.length); + for (uint256 i; i < rawLogs.length; i++) { + logs[i].logAddress = rawLogs[i].logAddress; + logs[i].blockHash = rawLogs[i].blockHash; + logs[i].blockNumber = _bytesToUint(rawLogs[i].blockNumber); + logs[i].data = rawLogs[i].data; + logs[i].logIndex = _bytesToUint(rawLogs[i].logIndex); + logs[i].topics = rawLogs[i].topics; + logs[i].transactionIndex = _bytesToUint(rawLogs[i].transactionIndex); + logs[i].transactionLogIndex = _bytesToUint(rawLogs[i].transactionLogIndex); + logs[i].removed = rawLogs[i].removed; + } + return logs; + } + + /// @notice Deploys a contract from the artifacts directory with ABI-encoded constructor arguments. + function deployCode(string memory what, bytes memory args) internal virtual returns (address addr) { + bytes memory bytecode = abi.encodePacked(vm.getCode(what), args); + assembly ("memory-safe") { + addr := create(0, add(bytecode, 0x20), mload(bytecode)) + } + + require(addr != address(0), "StdCheats deployCode(string,bytes): Deployment failed."); + } + + /// @notice Deploys a contract from the artifacts directory. + function deployCode(string memory what) internal virtual returns (address addr) { + bytes memory bytecode = vm.getCode(what); + assembly ("memory-safe") { + addr := create(0, add(bytecode, 0x20), mload(bytecode)) + } + + require(addr != address(0), "StdCheats deployCode(string): Deployment failed."); + } + + /// @notice Deploys a contract from the artifacts directory with ABI-encoded constructor arguments, sending `val` wei on construction. + function deployCode(string memory what, bytes memory args, uint256 val) internal virtual returns (address addr) { + bytes memory bytecode = abi.encodePacked(vm.getCode(what), args); + assembly ("memory-safe") { + addr := create(val, add(bytecode, 0x20), mload(bytecode)) + } + + require(addr != address(0), "StdCheats deployCode(string,bytes,uint256): Deployment failed."); + } + + /// @notice Deploys a contract from the artifacts directory, sending `val` wei on construction. + function deployCode(string memory what, uint256 val) internal virtual returns (address addr) { + bytes memory bytecode = vm.getCode(what); + assembly ("memory-safe") { + addr := create(val, add(bytecode, 0x20), mload(bytecode)) + } + + require(addr != address(0), "StdCheats deployCode(string,uint256): Deployment failed."); + } + + /// @notice Creates a labeled address and the corresponding private key derived from `name`. + function makeAddrAndKey(string memory name) internal virtual returns (address addr, uint256 privateKey) { + privateKey = uint256(keccak256(abi.encodePacked(name))); + addr = vm.addr(privateKey); + vm.label(addr, name); + } + + /// @notice Creates a labeled address derived from `name`. + function makeAddr(string memory name) internal virtual returns (address addr) { + (addr,) = makeAddrAndKey(name); + } + + /// @notice Immediately destroys `who`, zeroing its balance, code, and nonce, and sending its balance to `beneficiary`. + /// @dev Unlike `selfdestruct`, this takes effect immediately within the same transaction. + function destroyAccount(address who, address beneficiary) internal virtual { + uint256 currBalance = who.balance; + vm.etch(who, abi.encode()); + vm.deal(who, 0); + vm.resetNonce(who); + + uint256 beneficiaryBalance = beneficiary.balance; + vm.deal(beneficiary, currBalance + beneficiaryBalance); + } + + /// @notice Creates an `Account` struct with a labeled address and private key derived from `name`. + function makeAccount(string memory name) internal virtual returns (Account memory account) { + (account.addr, account.key) = makeAddrAndKey(name); + } + + /// @notice Derives a private key from `mnemonic` at `index`, stores it in the local wallet, and returns the address and key. + function deriveRememberKey(string memory mnemonic, uint32 index) + internal + virtual + returns (address who, uint256 privateKey) + { + privateKey = vm.deriveKey(mnemonic, index); + who = vm.rememberKey(privateKey); + } + + function _bytesToUint(bytes memory b) private pure returns (uint256) { + require(b.length <= 32, "StdCheats _bytesToUint(bytes): Bytes length exceeds 32."); + return abi.decode(abi.encodePacked(new bytes(32 - b.length), b), (uint256)); + } + + /// @notice Returns whether the current test environment is running against a forked network. + function isFork() internal view virtual returns (bool status) { + try vm.activeFork() { + status = true; + } catch (bytes memory) {} + } + + /// @notice Skips the test body when running against a forked network. + modifier skipWhenForking() { + if (!isFork()) { + _; + } + } + + /// @notice Skips the test body when not running against a forked network. + modifier skipWhenNotForking() { + if (isFork()) { + _; + } + } + + /// @notice Disables gas metering for the duration of the function, re-enabling it on exit. + /// @dev When nested, gas metering is only resumed at the end of the outermost function that uses this modifier. + modifier noGasMetering() { + vm.pauseGasMetering(); + // To prevent turning gas monitoring back on with nested functions that use this modifier, + // we check if gasMetering started in the off position. If it did, we don't want to turn + // it back on until we exit the top level function that used the modifier + // + // i.e. funcA() noGasMetering { funcB() }, where funcB has noGasMetering as well. + // funcA will have `gasStartedOff` as false, funcB will have it as true, + // so we only turn metering back on at the end of the funcA + bool gasStartedOff = _gasMeteringOff; + _gasMeteringOff = true; + + _; + + // if gas metering was on when this modifier was called, turn it back on at the end + if (!gasStartedOff) { + _gasMeteringOff = false; + vm.resumeGasMetering(); + } + } + + // We use this complex approach of `_viewChainId` and `_pureChainId` to ensure there are no + // compiler warnings when accessing chain ID in any solidity version supported by forge-std. We + // can't simply access the chain ID in a normal view or pure function because the solc View Pure + // Checker changed `chainid` from pure to view in 0.8.0. + function _viewChainId() private view returns (uint256 chainId) { + // Assembly required since `block.chainid` was introduced in 0.8.0. + assembly { + chainId := chainid() + } + + address(this); // Silence warnings in older Solc versions. + } + + function _pureChainId() private pure returns (uint256 chainId) { + function() internal view returns (uint256) fnIn = _viewChainId; + function() internal pure returns (uint256) pureChainId; + assembly { + pureChainId := fnIn + } + chainId = pureChainId(); + } +} + +// Wrappers around cheatcodes to avoid footguns +abstract contract StdCheats is StdCheatsSafe { + using stdStorage for StdStorage; + + StdStorage private _stdstore; + Vm private constant vm = Vm(address(uint160(uint256(keccak256("hevm cheat code"))))); + address private constant _CONSOLE2_ADDRESS = 0x000000000000000000636F6e736F6c652e6c6f67; + + /// @notice Advances the block timestamp forward by `time` seconds. + function skip(uint256 time) internal virtual { + vm.warp(vm.getBlockTimestamp() + time); + } + + /// @notice Rewinds the block timestamp backward by `time` seconds. + function rewind(uint256 time) internal virtual { + vm.warp(vm.getBlockTimestamp() - time); + } + + /// @notice Sets up a single-call prank from `msgSender`, giving it `2**128` wei. + function hoax(address msgSender) internal virtual { + vm.deal(msgSender, 1 << 128); + vm.prank(msgSender); + } + + /// @notice Sets up a single-call prank from `msgSender`, giving it `give` wei. + function hoax(address msgSender, uint256 give) internal virtual { + vm.deal(msgSender, give); + vm.prank(msgSender); + } + + /// @notice Sets up a single-call prank from `msgSender` with `origin` as `tx.origin`, giving `msgSender` `2**128` wei. + function hoax(address msgSender, address origin) internal virtual { + vm.deal(msgSender, 1 << 128); + vm.prank(msgSender, origin); + } + + /// @notice Sets up a single-call prank from `msgSender` with `origin` as `tx.origin`, giving `msgSender` `give` wei. + function hoax(address msgSender, address origin, uint256 give) internal virtual { + vm.deal(msgSender, give); + vm.prank(msgSender, origin); + } + + /// @notice Starts a persistent prank from `msgSender`, giving it `2**128` wei. + function startHoax(address msgSender) internal virtual { + vm.deal(msgSender, 1 << 128); + vm.startPrank(msgSender); + } + + /// @notice Starts a persistent prank from `msgSender`, giving it `give` wei. + function startHoax(address msgSender, uint256 give) internal virtual { + vm.deal(msgSender, give); + vm.startPrank(msgSender); + } + + /// @notice Starts a persistent prank from `msgSender` with `origin` as `tx.origin`, giving `msgSender` `2**128` wei. + function startHoax(address msgSender, address origin) internal virtual { + vm.deal(msgSender, 1 << 128); + vm.startPrank(msgSender, origin); + } + + /// @notice Starts a persistent prank from `msgSender` with `origin` as `tx.origin`, giving `msgSender` `give` wei. + function startHoax(address msgSender, address origin, uint256 give) internal virtual { + vm.deal(msgSender, give); + vm.startPrank(msgSender, origin); + } + + /// @notice Changes the active prank to `msgSender`. + /// @dev Deprecated. Use `vm.startPrank` instead. + function changePrank(address msgSender) internal virtual { + _console2_log_StdCheats("changePrank is deprecated. Please use vm.startPrank instead."); + vm.stopPrank(); + vm.startPrank(msgSender); + } + + /// @notice Changes the active prank to `msgSender` with `txOrigin` as `tx.origin`. + /// @dev Deprecated. Use `vm.startPrank` instead. + function changePrank(address msgSender, address txOrigin) internal virtual { + _console2_log_StdCheats("changePrank is deprecated. Please use vm.startPrank instead."); + vm.stopPrank(); + vm.startPrank(msgSender, txOrigin); + } + + /// @notice Expects a call to `callee` with `data` and mocks it to return `returnData`. + function expectAndMockCall(address callee, bytes memory data, bytes memory returnData) internal virtual { + vm.expectCall(callee, data); + vm.mockCall(callee, data, returnData); + } + + /// @notice Expects exactly `count` calls to `callee` with `data` and mocks them to return `returnData`. + function expectAndMockCall(address callee, bytes memory data, uint64 count, bytes memory returnData) + internal + virtual + { + vm.expectCall(callee, data, count); + vm.mockCall(callee, data, returnData); + } + + /// @notice Expects a call to `callee` with `msgValue` and `data` and mocks it to return `returnData`. + function expectAndMockCall(address callee, uint256 msgValue, bytes memory data, bytes memory returnData) + internal + virtual + { + vm.expectCall(callee, msgValue, data); + vm.mockCall(callee, msgValue, data, returnData); + } + + /// @notice Expects exactly `count` calls to `callee` with `msgValue` and `data` and mocks them to return `returnData`. + function expectAndMockCall( + address callee, + uint256 msgValue, + bytes memory data, + uint64 count, + bytes memory returnData + ) internal virtual { + vm.expectCall(callee, msgValue, data, count); + vm.mockCall(callee, msgValue, data, returnData); + } + + /// @notice Expects a call to `callee` with `msgValue` and `data` forwarding `gas`, and mocks it to return `returnData`. + /// @dev `gas` only applies to the call expectation; the mock call ignores `gas`. + function expectAndMockCall(address callee, uint256 msgValue, uint64 gas, bytes memory data, bytes memory returnData) + internal + virtual + { + vm.expectCall(callee, msgValue, gas, data); + vm.mockCall(callee, msgValue, data, returnData); + } + + /// @notice Expects exactly `count` calls to `callee` with `msgValue` and `data` forwarding `gas`, and mocks them to return `returnData`. + /// @dev `gas` only applies to the call expectation; the mock call ignores `gas`. + function expectAndMockCall( + address callee, + uint256 msgValue, + uint64 gas, + bytes memory data, + uint64 count, + bytes memory returnData + ) internal virtual { + vm.expectCall(callee, msgValue, gas, data, count); + vm.mockCall(callee, msgValue, data, returnData); + } + + /// @notice Sets the ETH balance of `to` to `give`. + function deal(address to, uint256 give) internal virtual { + vm.deal(to, give); + } + + /// @notice Sets the ERC20 `token` balance of `to` to `give`. + function deal(address token, address to, uint256 give) internal virtual { + deal(token, to, give, false); + } + + /// @notice Sets the ERC1155 `token` balance of `to` for token `id` to `give`. + function dealERC1155(address token, address to, uint256 id, uint256 give) internal virtual { + dealERC1155(token, to, id, give, false); + } + + /// @notice Sets the ERC20 `token` balance of `to` to `give`, optionally adjusting the total supply. + function deal(address token, address to, uint256 give, bool adjust) internal virtual { + // get current balance + (, bytes memory balData) = token.staticcall(abi.encodeWithSelector(0x70a08231, to)); + uint256 prevBal = abi.decode(balData, (uint256)); + + // update balance + _stdstore.target(token).sig(0x70a08231).with_key(to).checked_write(give); + + // update total supply + if (adjust) { + (, bytes memory totSupData) = token.staticcall(abi.encodeWithSelector(0x18160ddd)); + uint256 totSup = abi.decode(totSupData, (uint256)); + if (give < prevBal) { + totSup -= (prevBal - give); + } else { + totSup += (give - prevBal); + } + _stdstore.target(token).sig(0x18160ddd).checked_write(totSup); + } + } + + /// @notice Sets the ERC1155 `token` balance of `to` for token `id` to `give`, optionally adjusting the total supply. + function dealERC1155(address token, address to, uint256 id, uint256 give, bool adjust) internal virtual { + // get current balance + (, bytes memory balData) = token.staticcall(abi.encodeWithSelector(0x00fdd58e, to, id)); + uint256 prevBal = abi.decode(balData, (uint256)); + + // update balance + _stdstore.target(token).sig(0x00fdd58e).with_key(to).with_key(id).checked_write(give); + + // update total supply + if (adjust) { + (, bytes memory totSupData) = token.staticcall(abi.encodeWithSelector(0xbd85b039, id)); + require( + totSupData.length != 0, + "StdCheats dealERC1155(address,address,uint256,uint256,bool): target contract is not ERC1155Supply." + ); + uint256 totSup = abi.decode(totSupData, (uint256)); + if (give < prevBal) { + totSup -= (prevBal - give); + } else { + totSup += (give - prevBal); + } + _stdstore.target(token).sig(0xbd85b039).with_key(id).checked_write(totSup); + } + } + + /// @notice Transfers ownership of ERC721 `token` with `id` to `to`, updating balances accordingly. + function dealERC721(address token, address to, uint256 id) internal virtual { + // check if token id is already minted and the actual owner. + (bool successMinted, bytes memory ownerData) = token.staticcall(abi.encodeWithSelector(0x6352211e, id)); + require(successMinted, "StdCheats dealERC721(address,address,uint256): id not minted."); + + // get owner current balance + (, bytes memory fromBalData) = + token.staticcall(abi.encodeWithSelector(0x70a08231, abi.decode(ownerData, (address)))); + uint256 fromPrevBal = abi.decode(fromBalData, (uint256)); + + // get new user current balance + (, bytes memory toBalData) = token.staticcall(abi.encodeWithSelector(0x70a08231, to)); + uint256 toPrevBal = abi.decode(toBalData, (uint256)); + + // update balances + _stdstore.target(token).sig(0x70a08231).with_key(abi.decode(ownerData, (address))).checked_write(--fromPrevBal); + _stdstore.target(token).sig(0x70a08231).with_key(to).checked_write(++toPrevBal); + + // update owner + _stdstore.target(token).sig(0x6352211e).with_key(id).checked_write(to); + } + + /// @notice Etches the runtime bytecode of `what` (from the artifacts directory) at `where`. + /// @dev Runs the contract's creation code via `vm.etch` + a self-call, then etches the resulting runtime code at `where`. Constructor side-effects on other contracts are not preserved. + function deployCodeTo(string memory what, address where) internal virtual { + deployCodeTo(what, "", 0, where); + } + + /// @notice Etches the runtime bytecode of `what` (from the artifacts directory) at `where`, using `args` as ABI-encoded constructor arguments. + /// @dev Runs the contract's creation code via `vm.etch` + a self-call, then etches the resulting runtime code at `where`. Constructor side-effects on other contracts are not preserved. + function deployCodeTo(string memory what, bytes memory args, address where) internal virtual { + deployCodeTo(what, args, 0, where); + } + + /// @notice Etches the runtime bytecode of `what` (from the artifacts directory) at `where`, using `args` as ABI-encoded constructor arguments and sending `value` wei to the constructor. + /// @dev Runs the contract's creation code via `vm.etch` + a self-call, then etches the resulting runtime code at `where`. Constructor side-effects on other contracts are not preserved. + function deployCodeTo(string memory what, bytes memory args, uint256 value, address where) internal virtual { + bytes memory creationCode = vm.getCode(what); + vm.etch(where, abi.encodePacked(creationCode, args)); + (bool success, bytes memory runtimeBytecode) = where.call{value: value}(""); + require(success, "StdCheats deployCodeTo(string,bytes,uint256,address): Failed to create runtime bytecode."); + vm.etch(where, runtimeBytecode); + } + + // Used to prevent the compilation of console, which shortens the compilation time when console is not used elsewhere. + function _console2_log_StdCheats(string memory p0) private view { + (bool status,) = address(_CONSOLE2_ADDRESS).staticcall(abi.encodeWithSignature("log(string)", p0)); + status; + } +} diff --git a/contracts/evm/lib/forge-std/src/StdConfig.sol b/contracts/evm/lib/forge-std/src/StdConfig.sol new file mode 100644 index 0000000000..167523082b --- /dev/null +++ b/contracts/evm/lib/forge-std/src/StdConfig.sol @@ -0,0 +1,632 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity ^0.8.13; + +import {VmSafe} from "./Vm.sol"; +import {Variable, Type, TypeKind, LibVariable} from "./LibVariable.sol"; + +/// @notice A contract that parses a toml configuration file and loads its +/// variables into storage, automatically casting them, on deployment. +/// +/// @dev This contract assumes a toml structure where top-level keys +/// represent chain ids or aliases. Under each chain key, variables are +/// organized by type in separate sub-tables like `[.]`, where +/// type must be: `bool`, `address`, `bytes32`, `uint`, `int`, `string`, or `bytes`. +/// +/// Supported format: +/// ``` +/// [mainnet] +/// endpoint_url = "${MAINNET_RPC}" +/// +/// [mainnet.bool] +/// is_live = true +/// +/// [mainnet.address] +/// weth = "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" +/// whitelisted_admins = [ +/// "${MAINNET_ADMIN}", +/// "0x00000000000000000000000000000000deadbeef", +/// "0x000000000000000000000000000000c0ffeebabe" +/// ] +/// +/// [mainnet.uint] +/// important_number = 123 +/// ``` +contract StdConfig { + using LibVariable for Type; + using LibVariable for TypeKind; + + VmSafe private constant vm = VmSafe(address(uint160(uint256(keccak256("hevm cheat code"))))); + + /// @dev Types: `bool`, `address`, `bytes32`, `uint`, `int`, `string`, `bytes`. + uint8 private constant _NUM_TYPES = 7; + + // -- ERRORS --------------------------------------------------------------- + + error AlreadyInitialized(string key); + error InvalidChainKey(string aliasOrId); + error ChainNotInitialized(uint256 chainId); + error UnableToParseVariable(string key); + error WriteToFileInForbiddenCtxt(); + + // -- STORAGE (CACHE FROM CONFIG FILE) ------------------------------------ + + /// @dev Path to the loaded TOML configuration file. + string private _filePath; + + /// @dev List of top-level keys found in the TOML file, assumed to be chain names/aliases. + string[] private _chainKeys; + + /// @dev Storage for the configured RPC URL for each chain. + mapping(uint256 => string) private _rpcOf; + + /// @dev Storage for values, organized by chain ID and variable key. + mapping(uint256 => mapping(string => bytes)) private _dataOf; + + /// @dev Type cache for runtime checking when casting. + mapping(uint256 => mapping(string => Type)) private _typeOf; + + /// @dev When enabled, `set` will always write updates back to the configuration file. + /// Can only be enabled in a scripting context to prevent file corruption from + /// concurrent I/O access, as tests run in parallel. + bool private _writeToFile; + + // -- CONSTRUCTOR ---------------------------------------------------------- + + /// @notice Reads the TOML file and iterates through each top-level key, which is + /// assumed to be a chain name or ID. For each chain, it caches its RPC + /// endpoint and all variables defined in typed sub-tables like `[.]`, + /// where type must be: `bool`, `address`, `bytes32`, `uint`, `int`, `string`, or `bytes`. + /// + /// The constructor attempts to parse each variable first as a single value, + /// and if that fails, as an array of that type. If a variable cannot be + /// parsed as either, the constructor will revert with an error. + /// + /// @param configFilePath: The local path to the TOML configuration file. + /// @param writeToFile: Whether to write updates back to the TOML file. Only for scripts. + constructor(string memory configFilePath, bool writeToFile) { + if (writeToFile && !vm.isContext(VmSafe.ForgeContext.ScriptGroup)) { + revert WriteToFileInForbiddenCtxt(); + } + + _filePath = configFilePath; + _writeToFile = writeToFile; + string memory content = vm.resolveEnv(vm.readFile(configFilePath)); + string[] memory chain_keys = vm.parseTomlKeys(content, "$"); + + // Cache the entire configuration to storage + for (uint256 i = 0; i < chain_keys.length; i++) { + string memory chain_key = chain_keys[i]; + // Ignore top-level keys that are not tables + if (vm.parseTomlKeys(content, string.concat("$.", chain_key)).length == 0) { + continue; + } + uint256 chainId = resolveChainId(chain_key); + _chainKeys.push(chain_key); + + // Cache the configured RPC endpoint for that chain. + // Falls back to `[rpc_endpoints]`. Panics if no rpc endpoint is configured. + try vm.parseTomlString(content, string.concat("$.", chain_key, ".endpoint_url")) returns ( + string memory url + ) { + _rpcOf[chainId] = vm.resolveEnv(url); + } catch { + _rpcOf[chainId] = vm.resolveEnv(vm.rpcUrl(chain_key)); + } + + // Iterate through all the available `TypeKind`s (except `None`) to create the sub-section paths + for (uint8 t = 1; t <= _NUM_TYPES; t++) { + TypeKind ty = TypeKind(t); + string memory typePath = string.concat("$.", chain_key, ".", ty.toTomlKey()); + + try vm.parseTomlKeys(content, typePath) returns (string[] memory keys) { + for (uint256 j = 0; j < keys.length; j++) { + string memory key = keys[j]; + if (_typeOf[chainId][key].kind == TypeKind.None) { + _loadAndCacheValue(content, string.concat(typePath, ".", key), chainId, key, ty); + } else { + revert AlreadyInitialized(key); + } + } + } catch {} + } + } + } + + function _loadAndCacheValue( + string memory content, + string memory path, + uint256 chainId, + string memory key, + TypeKind ty + ) private { + bool success = false; + if (ty == TypeKind.Bool) { + try vm.parseTomlBool(content, path) returns (bool val) { + _dataOf[chainId][key] = abi.encode(val); + _typeOf[chainId][key] = Type(TypeKind.Bool, false); + success = true; + } catch { + try vm.parseTomlBoolArray(content, path) returns (bool[] memory val) { + _dataOf[chainId][key] = abi.encode(val); + _typeOf[chainId][key] = Type(TypeKind.Bool, true); + success = true; + } catch {} + } + } else if (ty == TypeKind.Address) { + try vm.parseTomlAddress(content, path) returns (address val) { + _dataOf[chainId][key] = abi.encode(val); + _typeOf[chainId][key] = Type(TypeKind.Address, false); + success = true; + } catch { + try vm.parseTomlAddressArray(content, path) returns (address[] memory val) { + _dataOf[chainId][key] = abi.encode(val); + _typeOf[chainId][key] = Type(TypeKind.Address, true); + success = true; + } catch {} + } + } else if (ty == TypeKind.Bytes32) { + try vm.parseTomlBytes32(content, path) returns (bytes32 val) { + _dataOf[chainId][key] = abi.encode(val); + _typeOf[chainId][key] = Type(TypeKind.Bytes32, false); + success = true; + } catch { + try vm.parseTomlBytes32Array(content, path) returns (bytes32[] memory val) { + _dataOf[chainId][key] = abi.encode(val); + _typeOf[chainId][key] = Type(TypeKind.Bytes32, true); + success = true; + } catch {} + } + } else if (ty == TypeKind.Uint256) { + try vm.parseTomlUint(content, path) returns (uint256 val) { + _dataOf[chainId][key] = abi.encode(val); + _typeOf[chainId][key] = Type(TypeKind.Uint256, false); + success = true; + } catch { + try vm.parseTomlUintArray(content, path) returns (uint256[] memory val) { + _dataOf[chainId][key] = abi.encode(val); + _typeOf[chainId][key] = Type(TypeKind.Uint256, true); + success = true; + } catch {} + } + } else if (ty == TypeKind.Int256) { + try vm.parseTomlInt(content, path) returns (int256 val) { + _dataOf[chainId][key] = abi.encode(val); + _typeOf[chainId][key] = Type(TypeKind.Int256, false); + success = true; + } catch { + try vm.parseTomlIntArray(content, path) returns (int256[] memory val) { + _dataOf[chainId][key] = abi.encode(val); + _typeOf[chainId][key] = Type(TypeKind.Int256, true); + success = true; + } catch {} + } + } else if (ty == TypeKind.Bytes) { + try vm.parseTomlBytes(content, path) returns (bytes memory val) { + _dataOf[chainId][key] = abi.encode(val); + _typeOf[chainId][key] = Type(TypeKind.Bytes, false); + success = true; + } catch { + try vm.parseTomlBytesArray(content, path) returns (bytes[] memory val) { + _dataOf[chainId][key] = abi.encode(val); + _typeOf[chainId][key] = Type(TypeKind.Bytes, true); + success = true; + } catch {} + } + } else if (ty == TypeKind.String) { + try vm.parseTomlString(content, path) returns (string memory val) { + _dataOf[chainId][key] = abi.encode(val); + _typeOf[chainId][key] = Type(TypeKind.String, false); + success = true; + } catch { + try vm.parseTomlStringArray(content, path) returns (string[] memory val) { + _dataOf[chainId][key] = abi.encode(val); + _typeOf[chainId][key] = Type(TypeKind.String, true); + success = true; + } catch {} + } + } + + if (!success) { + revert UnableToParseVariable(key); + } + } + + // -- HELPER FUNCTIONS ----------------------------------------------------- + + /// @notice Enable or disable automatic writing to the TOML file on `set`. + /// Can only be enabled when scripting. + function writeUpdatesBackToFile(bool enabled) public { + if (enabled && !vm.isContext(VmSafe.ForgeContext.ScriptGroup)) { + revert WriteToFileInForbiddenCtxt(); + } + + _writeToFile = enabled; + } + + /// @notice Resolves a chain alias or a chain id string to its numerical chain id. + /// @param aliasOrId The string representing the chain alias (i.e. "mainnet") or a numerical ID (i.e. "1"). + /// @return The numerical chain ID. + /// @dev It first attempts to parse the input as a number. If that fails, it uses `vm.getChain` to resolve a named alias. + /// Reverts if the alias is not valid or not a number. + function resolveChainId(string memory aliasOrId) public view returns (uint256) { + try vm.parseUint(aliasOrId) returns (uint256 chainId) { + return chainId; + } catch { + try vm.getChain(aliasOrId) returns (VmSafe.Chain memory chainInfo) { + return chainInfo.chainId; + } catch { + revert InvalidChainKey(aliasOrId); + } + } + } + + /// @dev Retrieves the chain key/alias from the configuration based on the chain ID. + function _getChainKeyFromId(uint256 chainId) private view returns (string memory) { + for (uint256 i = 0; i < _chainKeys.length; i++) { + if (resolveChainId(_chainKeys[i]) == chainId) { + return _chainKeys[i]; + } + } + revert ChainNotInitialized(chainId); + } + + /// @dev Ensures type consistency when setting a value - prevents changing types unless uninitialized. + /// Updates type only when the previous type was `None`. + function _ensureTypeConsistency(uint256 chainId, string memory key, Type memory ty) private { + Type memory current = _typeOf[chainId][key]; + + if (current.kind == TypeKind.None) { + _typeOf[chainId][key] = ty; + } else { + current.assertEq(ty); + } + } + + /// @dev Wraps a string in double quotes for JSON compatibility. + function _quote(string memory s) private pure returns (string memory) { + return string.concat('"', s, '"'); + } + + /// @dev Writes a JSON-formatted value to a specific key in the TOML file. + /// @param chainId The chain id to write under. + /// @param ty The type category ('bool', 'address', 'uint', 'bytes32', 'string', or 'bytes'). + /// @param key The variable key name. + /// @param jsonValue The JSON-formatted value to write. + function _writeToToml(uint256 chainId, string memory ty, string memory key, string memory jsonValue) private { + string memory chainKey = _getChainKeyFromId(chainId); + string memory valueKey = string.concat("$.", chainKey, ".", ty, ".", key); + vm.writeToml(jsonValue, _filePath, valueKey); + } + + // -- GETTER FUNCTIONS ----------------------------------------------------- + + /// @dev Reads a variable for a given chain id and key, and returns it in a generic container. + /// The caller should use `LibVariable` to safely coerce the type. + /// Example: `uint256 myVar = config.get("my_key").toUint256();` + /// + /// @param chain_id The chain ID to read from. + /// @param key The key of the variable to retrieve. + /// @return `Variable` struct containing the type and the ABI-encoded value. + function get(uint256 chain_id, string memory key) public view returns (Variable memory) { + return Variable(_typeOf[chain_id][key], _dataOf[chain_id][key]); + } + + /// @dev Reads a variable for the current chain and a given key, and returns it in a generic container. + /// The caller should use `LibVariable` to safely coerce the type. + /// Example: `uint256 myVar = config.get("my_key").toUint256();` + /// + /// @param key The key of the variable to retrieve. + /// @return `Variable` struct containing the type and the ABI-encoded value. + function get(string memory key) public view returns (Variable memory) { + return get(vm.getChainId(), key); + } + + /// @dev Checks the existence of a variable for a given chain ID and key, and returns a boolean. + /// Example: `bool hasKey = config.exists(1, "my_key");` + /// + /// @param chain_id The chain ID to check. + /// @param key The variable key name. + /// @return `bool` indicating whether a variable with the given key exists. + function exists(uint256 chain_id, string memory key) public view returns (bool) { + return _dataOf[chain_id][key].length > 0; + } + + /// @dev Checks the existence of a variable for the current chain id and a given key, and returns a boolean. + /// Example: `bool hasKey = config.exists("my_key");` + /// + /// @param key The variable key name. + /// @return `bool` indicating whether a variable with the given key exists. + function exists(string memory key) public view returns (bool) { + return exists(vm.getChainId(), key); + } + + /// @notice Returns the numerical chain ids for all configured chains. + function getChainIds() public view returns (uint256[] memory) { + string[] memory keys = _chainKeys; + + uint256[] memory ids = new uint256[](keys.length); + for (uint256 i = 0; i < keys.length; i++) { + ids[i] = resolveChainId(keys[i]); + } + + return ids; + } + + /// @notice Reads the RPC URL for a specific chain id. + function getRpcUrl(uint256 chainId) public view returns (string memory) { + return _rpcOf[chainId]; + } + + /// @notice Reads the RPC URL for the current chain. + function getRpcUrl() public view returns (string memory) { + return _rpcOf[vm.getChainId()]; + } + + // -- SETTER FUNCTIONS (SINGLE VALUES) ------------------------------------- + + /// @notice Sets a boolean value for a given key and chain ID. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(uint256 chainId, string memory key, bool value) public { + Type memory ty = Type(TypeKind.Bool, false); + _ensureTypeConsistency(chainId, key, ty); + _dataOf[chainId][key] = abi.encode(value); + if (_writeToFile) _writeToToml(chainId, ty.kind.toTomlKey(), key, vm.toString(value)); + } + + /// @notice Sets a boolean value for a given key on the current chain. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(string memory key, bool value) public { + set(vm.getChainId(), key, value); + } + + /// @notice Sets an address value for a given key and chain ID. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(uint256 chainId, string memory key, address value) public { + Type memory ty = Type(TypeKind.Address, false); + _ensureTypeConsistency(chainId, key, ty); + _dataOf[chainId][key] = abi.encode(value); + if (_writeToFile) _writeToToml(chainId, ty.kind.toTomlKey(), key, _quote(vm.toString(value))); + } + + /// @notice Sets an address value for a given key on the current chain. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(string memory key, address value) public { + set(vm.getChainId(), key, value); + } + + /// @notice Sets a bytes32 value for a given key and chain ID. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(uint256 chainId, string memory key, bytes32 value) public { + Type memory ty = Type(TypeKind.Bytes32, false); + _ensureTypeConsistency(chainId, key, ty); + _dataOf[chainId][key] = abi.encode(value); + if (_writeToFile) _writeToToml(chainId, ty.kind.toTomlKey(), key, _quote(vm.toString(value))); + } + + /// @notice Sets a bytes32 value for a given key on the current chain. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(string memory key, bytes32 value) public { + set(vm.getChainId(), key, value); + } + + /// @notice Sets a uint256 value for a given key and chain ID. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(uint256 chainId, string memory key, uint256 value) public { + Type memory ty = Type(TypeKind.Uint256, false); + _ensureTypeConsistency(chainId, key, ty); + _dataOf[chainId][key] = abi.encode(value); + if (_writeToFile) _writeToToml(chainId, ty.kind.toTomlKey(), key, vm.toString(value)); + } + + /// @notice Sets a uint256 value for a given key on the current chain. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(string memory key, uint256 value) public { + set(vm.getChainId(), key, value); + } + + /// @notice Sets an int256 value for a given key and chain ID. + function set(uint256 chainId, string memory key, int256 value) public { + Type memory ty = Type(TypeKind.Int256, false); + _ensureTypeConsistency(chainId, key, ty); + _dataOf[chainId][key] = abi.encode(value); + if (_writeToFile) _writeToToml(chainId, ty.kind.toTomlKey(), key, vm.toString(value)); + } + + /// @notice Sets an int256 value for a given key on the current chain. + function set(string memory key, int256 value) public { + set(vm.getChainId(), key, value); + } + + /// @notice Sets a string value for a given key and chain ID. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(uint256 chainId, string memory key, string memory value) public { + Type memory ty = Type(TypeKind.String, false); + _ensureTypeConsistency(chainId, key, ty); + _dataOf[chainId][key] = abi.encode(value); + if (_writeToFile) _writeToToml(chainId, ty.kind.toTomlKey(), key, _quote(value)); + } + + /// @notice Sets a string value for a given key on the current chain. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(string memory key, string memory value) public { + set(vm.getChainId(), key, value); + } + + /// @notice Sets a bytes value for a given key and chain ID. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(uint256 chainId, string memory key, bytes memory value) public { + Type memory ty = Type(TypeKind.Bytes, false); + _ensureTypeConsistency(chainId, key, ty); + _dataOf[chainId][key] = abi.encode(value); + if (_writeToFile) _writeToToml(chainId, ty.kind.toTomlKey(), key, _quote(vm.toString(value))); + } + + /// @notice Sets a bytes value for a given key on the current chain. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(string memory key, bytes memory value) public { + set(vm.getChainId(), key, value); + } + + // -- SETTER FUNCTIONS (ARRAYS) -------------------------------------------- + + /// @notice Sets a boolean array for a given key and chain ID. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(uint256 chainId, string memory key, bool[] memory value) public { + Type memory ty = Type(TypeKind.Bool, true); + _ensureTypeConsistency(chainId, key, ty); + _dataOf[chainId][key] = abi.encode(value); + if (_writeToFile) { + string memory json = "["; + for (uint256 i = 0; i < value.length; i++) { + json = string.concat(json, vm.toString(value[i])); + if (i < value.length - 1) json = string.concat(json, ","); + } + json = string.concat(json, "]"); + _writeToToml(chainId, ty.kind.toTomlKey(), key, json); + } + } + + /// @notice Sets a boolean array for a given key on the current chain. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(string memory key, bool[] memory value) public { + set(vm.getChainId(), key, value); + } + + /// @notice Sets an address array for a given key and chain ID. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(uint256 chainId, string memory key, address[] memory value) public { + Type memory ty = Type(TypeKind.Address, true); + _ensureTypeConsistency(chainId, key, ty); + _dataOf[chainId][key] = abi.encode(value); + if (_writeToFile) { + string memory json = "["; + for (uint256 i = 0; i < value.length; i++) { + json = string.concat(json, _quote(vm.toString(value[i]))); + if (i < value.length - 1) json = string.concat(json, ","); + } + json = string.concat(json, "]"); + _writeToToml(chainId, ty.kind.toTomlKey(), key, json); + } + } + + /// @notice Sets an address array for a given key on the current chain. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(string memory key, address[] memory value) public { + set(vm.getChainId(), key, value); + } + + /// @notice Sets a bytes32 array for a given key and chain ID. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(uint256 chainId, string memory key, bytes32[] memory value) public { + Type memory ty = Type(TypeKind.Bytes32, true); + _ensureTypeConsistency(chainId, key, ty); + _dataOf[chainId][key] = abi.encode(value); + if (_writeToFile) { + string memory json = "["; + for (uint256 i = 0; i < value.length; i++) { + json = string.concat(json, _quote(vm.toString(value[i]))); + if (i < value.length - 1) json = string.concat(json, ","); + } + json = string.concat(json, "]"); + _writeToToml(chainId, ty.kind.toTomlKey(), key, json); + } + } + + /// @notice Sets a bytes32 array for a given key on the current chain. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(string memory key, bytes32[] memory value) public { + set(vm.getChainId(), key, value); + } + + /// @notice Sets a uint256 array for a given key and chain ID. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(uint256 chainId, string memory key, uint256[] memory value) public { + Type memory ty = Type(TypeKind.Uint256, true); + _ensureTypeConsistency(chainId, key, ty); + _dataOf[chainId][key] = abi.encode(value); + if (_writeToFile) { + string memory json = "["; + for (uint256 i = 0; i < value.length; i++) { + json = string.concat(json, vm.toString(value[i])); + if (i < value.length - 1) json = string.concat(json, ","); + } + json = string.concat(json, "]"); + _writeToToml(chainId, ty.kind.toTomlKey(), key, json); + } + } + + /// @notice Sets a uint256 array for a given key on the current chain. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(string memory key, uint256[] memory value) public { + set(vm.getChainId(), key, value); + } + + /// @notice Sets a int256 array for a given key and chain ID. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(uint256 chainId, string memory key, int256[] memory value) public { + Type memory ty = Type(TypeKind.Int256, true); + _ensureTypeConsistency(chainId, key, ty); + _dataOf[chainId][key] = abi.encode(value); + if (_writeToFile) { + string memory json = "["; + for (uint256 i = 0; i < value.length; i++) { + json = string.concat(json, vm.toString(value[i])); + if (i < value.length - 1) json = string.concat(json, ","); + } + json = string.concat(json, "]"); + _writeToToml(chainId, ty.kind.toTomlKey(), key, json); + } + } + + /// @notice Sets a int256 array for a given key on the current chain. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(string memory key, int256[] memory value) public { + set(vm.getChainId(), key, value); + } + + /// @notice Sets a string array for a given key and chain ID. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(uint256 chainId, string memory key, string[] memory value) public { + Type memory ty = Type(TypeKind.String, true); + _ensureTypeConsistency(chainId, key, ty); + _dataOf[chainId][key] = abi.encode(value); + if (_writeToFile) { + string memory json = "["; + for (uint256 i = 0; i < value.length; i++) { + json = string.concat(json, _quote(value[i])); + if (i < value.length - 1) json = string.concat(json, ","); + } + json = string.concat(json, "]"); + _writeToToml(chainId, ty.kind.toTomlKey(), key, json); + } + } + + /// @notice Sets a string array for a given key on the current chain. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(string memory key, string[] memory value) public { + set(vm.getChainId(), key, value); + } + + /// @notice Sets a bytes array for a given key and chain ID. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(uint256 chainId, string memory key, bytes[] memory value) public { + Type memory ty = Type(TypeKind.Bytes, true); + _ensureTypeConsistency(chainId, key, ty); + _dataOf[chainId][key] = abi.encode(value); + if (_writeToFile) { + string memory json = "["; + for (uint256 i = 0; i < value.length; i++) { + json = string.concat(json, _quote(vm.toString(value[i]))); + if (i < value.length - 1) json = string.concat(json, ","); + } + json = string.concat(json, "]"); + _writeToToml(chainId, ty.kind.toTomlKey(), key, json); + } + } + + /// @notice Sets a bytes array for a given key on the current chain. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(string memory key, bytes[] memory value) public { + set(vm.getChainId(), key, value); + } +} diff --git a/contracts/evm/lib/forge-std/src/StdConstants.sol b/contracts/evm/lib/forge-std/src/StdConstants.sol new file mode 100644 index 0000000000..9f069ef8cb --- /dev/null +++ b/contracts/evm/lib/forge-std/src/StdConstants.sol @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {IMulticall3} from "./interfaces/IMulticall3.sol"; +import {Vm} from "./Vm.sol"; + +library StdConstants { + /// @dev Cheat code address. + /// Calculated as `address(uint160(uint256(keccak256("hevm cheat code"))))`. + Vm internal constant VM = Vm(0x7109709ECfa91a80626fF3989D68f67F5b1DD12D); + /// @dev console.sol and console2.sol work by executing a staticcall to this address. + /// Calculated as `address(uint160(uint88(bytes11("console.log"))))`. + address internal constant CONSOLE = 0x000000000000000000636F6e736F6c652e6c6f67; + /// @dev Used when deploying with create2. + /// Taken from https://github.com/Arachnid/deterministic-deployment-proxy. + address internal constant CREATE2_FACTORY = 0x4e59b44847b379578588920cA78FbF26c0B4956C; + /// @dev The default address for tx.origin and msg.sender. + /// Calculated as `address(uint160(uint256(keccak256("foundry default caller"))))`. + address internal constant DEFAULT_SENDER = 0x1804c8AB1F12E6bbf3894d4083f33e07309d1f38; + /// @dev The address of the first contract `CREATE`d by a running test contract. + /// When running tests, each test contract is `CREATE`d by `DEFAULT_SENDER` with nonce 1. + /// Calculated as `VM.computeCreateAddress(VM.computeCreateAddress(DEFAULT_SENDER, 1), 1)`. + address internal constant DEFAULT_TEST_CONTRACT = 0x5615dEB798BB3E4dFa0139dFa1b3D433Cc23b72f; + /// @dev Deterministic deployment address of the Multicall3 contract. + /// Taken from https://www.multicall3.com. + IMulticall3 internal constant MULTICALL3_ADDRESS = IMulticall3(0xcA11bde05977b3631167028862bE2a173976CA11); + /// @dev The order of the secp256k1 curve. + uint256 internal constant SECP256K1_ORDER = + 115792089237316195423570985008687907852837564279074904382605163141518161494337; +} diff --git a/contracts/evm/lib/forge-std/src/StdError.sol b/contracts/evm/lib/forge-std/src/StdError.sol new file mode 100644 index 0000000000..94df159451 --- /dev/null +++ b/contracts/evm/lib/forge-std/src/StdError.sol @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// Panics work for versions >=0.8.0, but we lowered the pragma to make this compatible with Test +pragma solidity >=0.8.13 <0.9.0; + +/// @notice Pre-encoded Solidity panic error selectors for use in test assertions. +library stdError { + /// @notice Panic caused by `assert(false)` or an assertion failure (0x01). + bytes public constant assertionError = abi.encodeWithSignature("Panic(uint256)", 0x01); + + /// @notice Panic caused by arithmetic overflow or underflow (0x11). + bytes public constant arithmeticError = abi.encodeWithSignature("Panic(uint256)", 0x11); + + /// @notice Panic caused by division or modulo by zero (0x12). + bytes public constant divisionError = abi.encodeWithSignature("Panic(uint256)", 0x12); + + /// @notice Panic caused by converting a value that is too large or negative into an enum type (0x21). + bytes public constant enumConversionError = abi.encodeWithSignature("Panic(uint256)", 0x21); + + /// @notice Panic caused by accessing incorrectly encoded storage data (0x22). + bytes public constant encodeStorageError = abi.encodeWithSignature("Panic(uint256)", 0x22); + + /// @notice Panic caused by calling `.pop()` on an empty array (0x31). + bytes public constant popError = abi.encodeWithSignature("Panic(uint256)", 0x31); + + /// @notice Panic caused by accessing an array, bytesN, or slice at an out-of-bounds index (0x32). + bytes public constant indexOOBError = abi.encodeWithSignature("Panic(uint256)", 0x32); + + /// @notice Panic caused by allocating too much memory or creating an array that is too large (0x41). + bytes public constant memOverflowError = abi.encodeWithSignature("Panic(uint256)", 0x41); + + /// @notice Panic caused by calling a zero-initialized variable of internal function type (0x51). + bytes public constant zeroVarError = abi.encodeWithSignature("Panic(uint256)", 0x51); +} diff --git a/contracts/evm/lib/forge-std/src/StdInvariant.sol b/contracts/evm/lib/forge-std/src/StdInvariant.sol new file mode 100644 index 0000000000..2c79b6e259 --- /dev/null +++ b/contracts/evm/lib/forge-std/src/StdInvariant.sol @@ -0,0 +1,161 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +/// @notice Abstract contract providing configuration utilities for Forge invariant tests. +abstract contract StdInvariant { + struct FuzzSelector { + address addr; + bytes4[] selectors; + } + + struct FuzzArtifactSelector { + string artifact; + bytes4[] selectors; + } + + struct FuzzInterface { + address addr; + string[] artifacts; + } + + address[] private _excludedContracts; + address[] private _excludedSenders; + address[] private _targetedContracts; + address[] private _targetedSenders; + + string[] private _excludedArtifacts; + string[] private _targetedArtifacts; + + FuzzArtifactSelector[] private _targetedArtifactSelectors; + + FuzzSelector[] private _excludedSelectors; + FuzzSelector[] private _targetedSelectors; + + FuzzInterface[] private _targetedInterfaces; + + // Functions for users: + // These are intended to be called in tests. + + /// @notice Excludes a contract address from invariant target selection. + /// @param newExcludedContract_ The contract address to exclude. + function excludeContract(address newExcludedContract_) internal { + _excludedContracts.push(newExcludedContract_); + } + + /// @notice Excludes specific selectors on a contract from invariant fuzzing. + /// @param newExcludedSelector_ The selector configuration to exclude. + function excludeSelector(FuzzSelector memory newExcludedSelector_) internal { + _excludedSelectors.push(newExcludedSelector_); + } + + /// @notice Excludes a sender from invariant fuzzing; exclusion takes precedence over targeted senders. + /// @param newExcludedSender_ The sender address to exclude. + function excludeSender(address newExcludedSender_) internal { + _excludedSenders.push(newExcludedSender_); + } + + /// @notice Excludes an artifact identifier from invariant target selection. + /// @param newExcludedArtifact_ The artifact identifier to exclude. + function excludeArtifact(string memory newExcludedArtifact_) internal { + _excludedArtifacts.push(newExcludedArtifact_); + } + + /// @notice Targets an artifact identifier for invariant fuzzing. + /// @param newTargetedArtifact_ The artifact identifier to target. + function targetArtifact(string memory newTargetedArtifact_) internal { + _targetedArtifacts.push(newTargetedArtifact_); + } + + /// @notice Targets specific selectors for an artifact identifier during invariant fuzzing. + /// @param newTargetedArtifactSelector_ The artifact-selector configuration to target. + function targetArtifactSelector(FuzzArtifactSelector memory newTargetedArtifactSelector_) internal { + _targetedArtifactSelectors.push(newTargetedArtifactSelector_); + } + + /// @notice Targets a contract address for invariant fuzzing. + /// @param newTargetedContract_ The contract address to target. + function targetContract(address newTargetedContract_) internal { + _targetedContracts.push(newTargetedContract_); + } + + /// @notice Targets specific selectors on a contract for invariant fuzzing. + /// @param newTargetedSelector_ The selector configuration to target. + function targetSelector(FuzzSelector memory newTargetedSelector_) internal { + _targetedSelectors.push(newTargetedSelector_); + } + + /// @notice Adds a sender to the invariant sender allowlist; when non-empty, fuzzing uses only targeted non-excluded senders. + /// @param newTargetedSender_ The sender address to target. + function targetSender(address newTargetedSender_) internal { + _targetedSenders.push(newTargetedSender_); + } + + /// @notice Targets an address plus artifact interfaces for invariant fuzzing. + /// @param newTargetedInterface_ The address-interface configuration to target. + function targetInterface(FuzzInterface memory newTargetedInterface_) internal { + _targetedInterfaces.push(newTargetedInterface_); + } + + // Functions for forge: + // These are called by forge to run invariant tests and don't need to be called in tests. + + /// @notice Returns artifact identifiers configured via `excludeArtifact`. + /// @return excludedArtifacts_ The list of excluded artifact identifiers. + function excludeArtifacts() public view returns (string[] memory excludedArtifacts_) { + excludedArtifacts_ = _excludedArtifacts; + } + + /// @notice Returns contract addresses configured via `excludeContract`. + /// @return excludedContracts_ The list of excluded contract addresses. + function excludeContracts() public view returns (address[] memory excludedContracts_) { + excludedContracts_ = _excludedContracts; + } + + /// @notice Returns selector exclusions configured via `excludeSelector`. + /// @return excludedSelectors_ The list of excluded selector configurations. + function excludeSelectors() public view returns (FuzzSelector[] memory excludedSelectors_) { + excludedSelectors_ = _excludedSelectors; + } + + /// @notice Returns senders configured via `excludeSender`. + /// @return excludedSenders_ The list of excluded sender addresses. + function excludeSenders() public view returns (address[] memory excludedSenders_) { + excludedSenders_ = _excludedSenders; + } + + /// @notice Returns artifact identifiers configured via `targetArtifact`. + /// @return targetedArtifacts_ The list of targeted artifact identifiers. + function targetArtifacts() public view returns (string[] memory targetedArtifacts_) { + targetedArtifacts_ = _targetedArtifacts; + } + + /// @notice Returns artifact-selector targets configured via `targetArtifactSelector`. + /// @return targetedArtifactSelectors_ The list of targeted artifact-selector configurations. + function targetArtifactSelectors() public view returns (FuzzArtifactSelector[] memory targetedArtifactSelectors_) { + targetedArtifactSelectors_ = _targetedArtifactSelectors; + } + + /// @notice Returns contract addresses configured via `targetContract`. + /// @return targetedContracts_ The list of targeted contract addresses. + function targetContracts() public view returns (address[] memory targetedContracts_) { + targetedContracts_ = _targetedContracts; + } + + /// @notice Returns selector targets configured via `targetSelector`. + /// @return targetedSelectors_ The list of targeted selector configurations. + function targetSelectors() public view returns (FuzzSelector[] memory targetedSelectors_) { + targetedSelectors_ = _targetedSelectors; + } + + /// @notice Returns sender allowlist configured via `targetSender` (empty means no sender allowlist). + /// @return targetedSenders_ The list of targeted sender addresses. + function targetSenders() public view returns (address[] memory targetedSenders_) { + targetedSenders_ = _targetedSenders; + } + + /// @notice Returns address-interface targets configured via `targetInterface`. + /// @return targetedInterfaces_ The list of targeted address-interface configurations. + function targetInterfaces() public view returns (FuzzInterface[] memory targetedInterfaces_) { + targetedInterfaces_ = _targetedInterfaces; + } +} diff --git a/contracts/evm/lib/forge-std/src/StdJson.sol b/contracts/evm/lib/forge-std/src/StdJson.sol new file mode 100644 index 0000000000..2c8944222a --- /dev/null +++ b/contracts/evm/lib/forge-std/src/StdJson.sol @@ -0,0 +1,327 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {VmSafe} from "./Vm.sol"; + +// Helpers for parsing and writing JSON files. +// `key` parameters use the same selector syntax as the `vm.parseJson*` cheatcodes, +// for example `.a` for a nested field or `$` for the root object. +// To parse: +// ``` +// using stdJson for string; +// string memory json = vm.readFile(""); +// uint256 value = json.readUint(".a"); +// bytes memory encoded = json.parseRaw("$"); +// ``` +// To write: +// ``` +// using stdJson for string; +// string memory json = "json"; +// json.serialize("a", uint256(123)); +// string memory semiFinal = json.serialize("b", string("test")); +// string memory finalJson = json.serialize("c", semiFinal); +// finalJson.write(""); +// ``` + +library stdJson { + VmSafe private constant vm = VmSafe(address(uint160(uint256(keccak256("hevm cheat code"))))); + + /// @notice Returns whether `key` exists in `json`. + /// @dev `key` uses the same selector syntax as `vm.parseJson*`, such as `.a` or `$`. + function keyExists(string memory json, string memory key) internal view returns (bool) { + return vm.keyExistsJson(json, key); + } + + /// @notice ABI-encodes the JSON value selected by `key`. + /// @dev `key` uses the same selector syntax as `vm.parseJson*`, such as `.a` or `$`. + function parseRaw(string memory json, string memory key) internal pure returns (bytes memory) { + return vm.parseJson(json, key); + } + + /// @notice Reads a uint256 value at `key` from `json`. + function readUint(string memory json, string memory key) internal pure returns (uint256) { + return vm.parseJsonUint(json, key); + } + + /// @notice Reads a uint256 array at `key` from `json`. + function readUintArray(string memory json, string memory key) internal pure returns (uint256[] memory) { + return vm.parseJsonUintArray(json, key); + } + + /// @notice Reads an int256 value at `key` from `json`. + function readInt(string memory json, string memory key) internal pure returns (int256) { + return vm.parseJsonInt(json, key); + } + + /// @notice Reads an int256 array at `key` from `json`. + function readIntArray(string memory json, string memory key) internal pure returns (int256[] memory) { + return vm.parseJsonIntArray(json, key); + } + + /// @notice Reads a bytes32 value at `key` from `json`. + function readBytes32(string memory json, string memory key) internal pure returns (bytes32) { + return vm.parseJsonBytes32(json, key); + } + + /// @notice Reads a bytes32 array at `key` from `json`. + function readBytes32Array(string memory json, string memory key) internal pure returns (bytes32[] memory) { + return vm.parseJsonBytes32Array(json, key); + } + + /// @notice Reads a string value at `key` from `json`. + function readString(string memory json, string memory key) internal pure returns (string memory) { + return vm.parseJsonString(json, key); + } + + /// @notice Reads a string array at `key` from `json`. + function readStringArray(string memory json, string memory key) internal pure returns (string[] memory) { + return vm.parseJsonStringArray(json, key); + } + + /// @notice Reads an address value at `key` from `json`. + function readAddress(string memory json, string memory key) internal pure returns (address) { + return vm.parseJsonAddress(json, key); + } + + /// @notice Reads an address array at `key` from `json`. + function readAddressArray(string memory json, string memory key) internal pure returns (address[] memory) { + return vm.parseJsonAddressArray(json, key); + } + + /// @notice Reads a bool value at `key` from `json`. + function readBool(string memory json, string memory key) internal pure returns (bool) { + return vm.parseJsonBool(json, key); + } + + /// @notice Reads a bool array at `key` from `json`. + function readBoolArray(string memory json, string memory key) internal pure returns (bool[] memory) { + return vm.parseJsonBoolArray(json, key); + } + + /// @notice Reads a bytes value at `key` from `json`. + function readBytes(string memory json, string memory key) internal pure returns (bytes memory) { + return vm.parseJsonBytes(json, key); + } + + /// @notice Reads a bytes array at `key` from `json`. + function readBytesArray(string memory json, string memory key) internal pure returns (bytes[] memory) { + return vm.parseJsonBytesArray(json, key); + } + + /// @notice Reads a uint256 value at `key` from `json`, returning `defaultValue` if the key does not exist. + function readUintOr(string memory json, string memory key, uint256 defaultValue) internal view returns (uint256) { + return keyExists(json, key) ? readUint(json, key) : defaultValue; + } + + /// @notice Reads a uint256 array at `key` from `json`, returning `defaultValue` if the key does not exist. + function readUintArrayOr(string memory json, string memory key, uint256[] memory defaultValue) + internal + view + returns (uint256[] memory) + { + return keyExists(json, key) ? readUintArray(json, key) : defaultValue; + } + + /// @notice Reads an int256 value at `key` from `json`, returning `defaultValue` if the key does not exist. + function readIntOr(string memory json, string memory key, int256 defaultValue) internal view returns (int256) { + return keyExists(json, key) ? readInt(json, key) : defaultValue; + } + + /// @notice Reads an int256 array at `key` from `json`, returning `defaultValue` if the key does not exist. + function readIntArrayOr(string memory json, string memory key, int256[] memory defaultValue) + internal + view + returns (int256[] memory) + { + return keyExists(json, key) ? readIntArray(json, key) : defaultValue; + } + + /// @notice Reads a bytes32 value at `key` from `json`, returning `defaultValue` if the key does not exist. + function readBytes32Or(string memory json, string memory key, bytes32 defaultValue) + internal + view + returns (bytes32) + { + return keyExists(json, key) ? readBytes32(json, key) : defaultValue; + } + + /// @notice Reads a bytes32 array at `key` from `json`, returning `defaultValue` if the key does not exist. + function readBytes32ArrayOr(string memory json, string memory key, bytes32[] memory defaultValue) + internal + view + returns (bytes32[] memory) + { + return keyExists(json, key) ? readBytes32Array(json, key) : defaultValue; + } + + /// @notice Reads a string value at `key` from `json`, returning `defaultValue` if the key does not exist. + function readStringOr(string memory json, string memory key, string memory defaultValue) + internal + view + returns (string memory) + { + return keyExists(json, key) ? readString(json, key) : defaultValue; + } + + /// @notice Reads a string array at `key` from `json`, returning `defaultValue` if the key does not exist. + function readStringArrayOr(string memory json, string memory key, string[] memory defaultValue) + internal + view + returns (string[] memory) + { + return keyExists(json, key) ? readStringArray(json, key) : defaultValue; + } + + /// @notice Reads an address value at `key` from `json`, returning `defaultValue` if the key does not exist. + function readAddressOr(string memory json, string memory key, address defaultValue) + internal + view + returns (address) + { + return keyExists(json, key) ? readAddress(json, key) : defaultValue; + } + + /// @notice Reads an address array at `key` from `json`, returning `defaultValue` if the key does not exist. + function readAddressArrayOr(string memory json, string memory key, address[] memory defaultValue) + internal + view + returns (address[] memory) + { + return keyExists(json, key) ? readAddressArray(json, key) : defaultValue; + } + + /// @notice Reads a bool value at `key` from `json`, returning `defaultValue` if the key does not exist. + function readBoolOr(string memory json, string memory key, bool defaultValue) internal view returns (bool) { + return keyExists(json, key) ? readBool(json, key) : defaultValue; + } + + /// @notice Reads a bool array at `key` from `json`, returning `defaultValue` if the key does not exist. + function readBoolArrayOr(string memory json, string memory key, bool[] memory defaultValue) + internal + view + returns (bool[] memory) + { + return keyExists(json, key) ? readBoolArray(json, key) : defaultValue; + } + + /// @notice Reads a bytes value at `key` from `json`, returning `defaultValue` if the key does not exist. + function readBytesOr(string memory json, string memory key, bytes memory defaultValue) + internal + view + returns (bytes memory) + { + return keyExists(json, key) ? readBytes(json, key) : defaultValue; + } + + /// @notice Reads a bytes array at `key` from `json`, returning `defaultValue` if the key does not exist. + function readBytesArrayOr(string memory json, string memory key, bytes[] memory defaultValue) + internal + view + returns (bytes[] memory) + { + return keyExists(json, key) ? readBytesArray(json, key) : defaultValue; + } + + /// @notice Serializes a JSON object `rootObject` under `jsonKey` and returns the serialized JSON string. + function serialize(string memory jsonKey, string memory rootObject) internal returns (string memory) { + return vm.serializeJson(jsonKey, rootObject); + } + + /// @notice Serializes a bool `value` under `key` within `jsonKey` and returns the serialized JSON string. + function serialize(string memory jsonKey, string memory key, bool value) internal returns (string memory) { + return vm.serializeBool(jsonKey, key, value); + } + + /// @notice Serializes a bool array `value` under `key` within `jsonKey` and returns the serialized JSON string. + function serialize(string memory jsonKey, string memory key, bool[] memory value) internal returns (string memory) { + return vm.serializeBool(jsonKey, key, value); + } + + /// @notice Serializes a uint256 `value` under `key` within `jsonKey` and returns the serialized JSON string. + function serialize(string memory jsonKey, string memory key, uint256 value) internal returns (string memory) { + return vm.serializeUint(jsonKey, key, value); + } + + /// @notice Serializes a uint256 array `value` under `key` within `jsonKey` and returns the serialized JSON string. + function serialize(string memory jsonKey, string memory key, uint256[] memory value) + internal + returns (string memory) + { + return vm.serializeUint(jsonKey, key, value); + } + + /// @notice Serializes an int256 `value` under `key` within `jsonKey` and returns the serialized JSON string. + function serialize(string memory jsonKey, string memory key, int256 value) internal returns (string memory) { + return vm.serializeInt(jsonKey, key, value); + } + + /// @notice Serializes an int256 array `value` under `key` within `jsonKey` and returns the serialized JSON string. + function serialize(string memory jsonKey, string memory key, int256[] memory value) + internal + returns (string memory) + { + return vm.serializeInt(jsonKey, key, value); + } + + /// @notice Serializes an address `value` under `key` within `jsonKey` and returns the serialized JSON string. + function serialize(string memory jsonKey, string memory key, address value) internal returns (string memory) { + return vm.serializeAddress(jsonKey, key, value); + } + + /// @notice Serializes an address array `value` under `key` within `jsonKey` and returns the serialized JSON string. + function serialize(string memory jsonKey, string memory key, address[] memory value) + internal + returns (string memory) + { + return vm.serializeAddress(jsonKey, key, value); + } + + /// @notice Serializes a bytes32 `value` under `key` within `jsonKey` and returns the serialized JSON string. + function serialize(string memory jsonKey, string memory key, bytes32 value) internal returns (string memory) { + return vm.serializeBytes32(jsonKey, key, value); + } + + /// @notice Serializes a bytes32 array `value` under `key` within `jsonKey` and returns the serialized JSON string. + function serialize(string memory jsonKey, string memory key, bytes32[] memory value) + internal + returns (string memory) + { + return vm.serializeBytes32(jsonKey, key, value); + } + + /// @notice Serializes a bytes `value` under `key` within `jsonKey` and returns the serialized JSON string. + function serialize(string memory jsonKey, string memory key, bytes memory value) internal returns (string memory) { + return vm.serializeBytes(jsonKey, key, value); + } + + /// @notice Serializes a bytes array `value` under `key` within `jsonKey` and returns the serialized JSON string. + function serialize(string memory jsonKey, string memory key, bytes[] memory value) + internal + returns (string memory) + { + return vm.serializeBytes(jsonKey, key, value); + } + + /// @notice Serializes a string `value` under `key` within `jsonKey` and returns the serialized JSON string. + function serialize(string memory jsonKey, string memory key, string memory value) internal returns (string memory) { + return vm.serializeString(jsonKey, key, value); + } + + /// @notice Serializes a string array `value` under `key` within `jsonKey` and returns the serialized JSON string. + function serialize(string memory jsonKey, string memory key, string[] memory value) + internal + returns (string memory) + { + return vm.serializeString(jsonKey, key, value); + } + + /// @notice Writes the serialized JSON object `jsonKey` to `path`. + function write(string memory jsonKey, string memory path) internal { + vm.writeJson(jsonKey, path); + } + + /// @notice Writes the value at `valueKey` from the serialized JSON object `jsonKey` to `path`. + function write(string memory jsonKey, string memory path, string memory valueKey) internal { + vm.writeJson(jsonKey, path, valueKey); + } +} diff --git a/contracts/evm/lib/forge-std/src/StdMath.sol b/contracts/evm/lib/forge-std/src/StdMath.sol new file mode 100644 index 0000000000..19942f78db --- /dev/null +++ b/contracts/evm/lib/forge-std/src/StdMath.sol @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +/// @notice Mathematical utility functions for unsigned and signed integers. +library stdMath { + int256 private constant _INT256_MIN = + -57896044618658097711785492504343953926634992332820282019728792003956564819968; + + /// @notice Computes the absolute value of a signed integer. + /// @param a The signed integer to compute the absolute value of. + /// @return The absolute value as an unsigned integer. + function abs(int256 a) internal pure returns (uint256) { + // Required or it will fail when `a = type(int256).min` + if (a == _INT256_MIN) { + return 57896044618658097711785492504343953926634992332820282019728792003956564819968; + } + + return uint256(a > 0 ? a : -a); + } + + /// @notice Computes the absolute difference between two unsigned integers. + /// @param a The first unsigned integer. + /// @param b The second unsigned integer. + /// @return The absolute difference between `a` and `b`. + function delta(uint256 a, uint256 b) internal pure returns (uint256) { + return a > b ? a - b : b - a; + } + + /// @notice Computes the absolute difference between two signed integers. + /// @param a The first signed integer. + /// @param b The second signed integer. + /// @return The absolute difference between `a` and `b`. + function delta(int256 a, int256 b) internal pure returns (uint256) { + // a and b are of the same sign + // this works thanks to two's complement, the left-most bit is the sign bit + if ((a ^ b) > -1) { + return delta(abs(a), abs(b)); + } + + // a and b are of opposite signs + return abs(a) + abs(b); + } + + /// @notice Computes the percentage difference between two unsigned integers, scaled by 1e18. + /// @param a The value to compare. + /// @param b The reference value (divisor). Must not be zero. + /// @return The percentage difference scaled by 1e18 (1e18 represents 100%). + function percentDelta(uint256 a, uint256 b) internal pure returns (uint256) { + // Prevent division by zero + require(b != 0, "stdMath percentDelta(uint256,uint256): Divisor is zero"); + uint256 absDelta = delta(a, b); + + return absDelta * 1e18 / b; + } + + /// @notice Computes the percentage difference between two signed integers, scaled by 1e18. + /// @param a The value to compare. + /// @param b The reference value (divisor). Its absolute value must not be zero. + /// @return The percentage difference scaled by 1e18 (1e18 represents 100%). + function percentDelta(int256 a, int256 b) internal pure returns (uint256) { + uint256 absDelta = delta(a, b); + uint256 absB = abs(b); + // Prevent division by zero + require(absB != 0, "stdMath percentDelta(int256,int256): Divisor is zero"); + + return absDelta * 1e18 / absB; + } +} diff --git a/contracts/evm/lib/forge-std/src/StdStorage.sol b/contracts/evm/lib/forge-std/src/StdStorage.sol new file mode 100644 index 0000000000..3b56eb8e3d --- /dev/null +++ b/contracts/evm/lib/forge-std/src/StdStorage.sol @@ -0,0 +1,582 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {Vm} from "./Vm.sol"; + +struct FindData { + uint256 slot; + uint256 offsetLeft; + uint256 offsetRight; + bool found; +} + +struct StdStorage { + mapping(address => mapping(bytes4 => mapping(bytes32 => FindData))) finds; + bytes32[] _keys; + bytes4 _sig; + uint256 _depth; + address _target; + bytes32 _set; + bool _enable_packed_slots; + bytes _calldata; +} + +library stdStorageSafe { + struct FindCallData { + bytes32 result; + bytes32 shortBytesStorageValue; + bytes32[] reads; + } + + event SlotFound(address who, bytes4 fsig, bytes32 keysHash, uint256 slot); + event WARNING_UninitedSlot(address who, uint256 slot); + + Vm private constant vm = Vm(address(uint160(uint256(keccak256("hevm cheat code"))))); + uint256 constant UINT256_MAX = 115792089237316195423570985008687907853269984665640564039457584007913129639935; + + /// @notice Returns the 4-byte function selector for `sigStr`. + function sigs(string memory sigStr) internal pure returns (bytes4) { + return bytes4(keccak256(bytes(sigStr))); + } + + /// @notice Returns the encoded call parameters (keys or raw calldata) for the configured target function. + function getCallParams(StdStorage storage self) internal view returns (bytes memory) { + if (self._calldata.length == 0) { + return _flatten(self._keys); + } else { + return self._calldata; + } + } + + /// @notice Calls the target contract with the configured parameters and returns its raw return data. + function callTargetRaw(StdStorage storage self) private view returns (bool, bytes memory) { + bytes memory cd = abi.encodePacked(self._sig, getCallParams(self)); + (bool success, bytes memory rdat) = self._target.staticcall(cd); + + return (success, rdat); + } + + /// @notice Calls the target contract with the configured parameters and returns the success flag and return value. + function callTarget(StdStorage storage self) internal view returns (bool, bytes32) { + (bool success, bytes memory rdat) = callTargetRaw(self); + bytes32 result = _bytesToBytes32(rdat, 32 * self._depth); + + return (success, result); + } + + /// @notice Returns the storage encoding when `rdat` is one non-empty short `bytes` or `string` value. + function _parseShortBytesReturn(bytes memory rdat) private pure returns (bytes32) { + if (rdat.length != 96 || uint256(_bytesToBytes32(rdat, 0)) != 32) { + return bytes32(0); + } + + uint256 length = uint256(_bytesToBytes32(rdat, 32)); + if (length == 0 || length > 31) { + return bytes32(0); + } + + bytes32 value = _bytesToBytes32(rdat, 64); + if (uint256(value) << (length * 8) != 0) { + return bytes32(0); + } + + return value | bytes32(length * 2); + } + + /// @notice Returns whether the payload and length marker match a short `bytes` or `string` storage value. + function _matchesShortBytes(bytes32 slotValue, bytes32 expected) private pure returns (bool) { + uint256 length = uint8(uint256(expected)) / 2; + uint256 mask = (type(uint256).max << ((32 - length) * 8)) | 0xFF; + return uint256(slotValue) & mask == uint256(expected); + } + + /// @notice Returns whether clearing `slot` makes the configured target return an empty dynamic byte array. + function _checkShortBytesSlot(StdStorage storage self, bytes32 slot) private returns (bool) { + bytes32 prevSlotValue = vm.load(self._target, slot); + vm.store(self._target, slot, bytes32(0)); + (bool success, bytes memory rdat) = callTargetRaw(self); + vm.store(self._target, slot, prevSlotValue); + + return success && rdat.length == 64 && uint256(_bytesToBytes32(rdat, 0)) == 32 + && uint256(_bytesToBytes32(rdat, 32)) == 0; + } + + /// @notice Returns whether mutating `slot` changes the return value of the configured target call. + /// @dev Temporarily writes either `type(uint256).max` or `0` to the slot to detect sensitivity. + function checkSlotMutatesCall(StdStorage storage self, bytes32 slot) internal returns (bool) { + bytes32 prevSlotValue = vm.load(self._target, slot); + (bool success, bytes32 prevReturnValue) = callTarget(self); + + bytes32 testVal = prevReturnValue == bytes32(0) ? bytes32(UINT256_MAX) : bytes32(0); + vm.store(self._target, slot, testVal); + + (, bytes32 newReturnValue) = callTarget(self); + + vm.store(self._target, slot, prevSlotValue); + + return (success && (prevReturnValue != newReturnValue)); + } + + /// @notice Searches for the bit offset of the packed variable within `slot` from the left or right side. + function findOffset(StdStorage storage self, bytes32 slot, bool left) internal returns (bool, uint256) { + for (uint256 offset = 0; offset < 256; offset++) { + uint256 valueToPut = left ? (1 << (255 - offset)) : (1 << offset); + vm.store(self._target, slot, bytes32(valueToPut)); + + (bool success, bytes32 data) = callTarget(self); + + if (success && (uint256(data) > 0)) { + return (true, offset); + } + } + return (false, 0); + } + + /// @notice Returns whether both offsets were found, along with the left and right bit offsets of the packed variable within `slot`. + function findOffsets(StdStorage storage self, bytes32 slot) internal returns (bool, uint256, uint256) { + bytes32 prevSlotValue = vm.load(self._target, slot); + + (bool foundLeft, uint256 offsetLeft) = findOffset(self, slot, true); + (bool foundRight, uint256 offsetRight) = findOffset(self, slot, false); + + // `findOffset` may mutate slot value, so we are setting it to initial value + vm.store(self._target, slot, prevSlotValue); + return (foundLeft && foundRight, offsetLeft, offsetRight); + } + + /// @notice Finds the storage slot for the configured target and returns its data, clearing the configuration. + function find(StdStorage storage self) internal returns (FindData storage) { + return find(self, true); + } + + /// @notice find an arbitrary storage slot given a function sig, input data, address of the contract and a value to check against + // slot complexity: + // if flat, will be bytes32(uint256(uint)); + // if map, will be keccak256(abi.encode(key, uint(slot))); + // if deep map, will be keccak256(abi.encode(key1, keccak256(abi.encode(key0, uint(slot))))); + // if map struct, will be bytes32(uint256(keccak256(abi.encode(key1, keccak256(abi.encode(key0, uint(slot)))))) + structFieldDepth); + function find(StdStorage storage self, bool _clear) internal returns (FindData storage) { + address who = self._target; + bytes4 fsig = self._sig; + uint256 field_depth = self._depth; + bytes memory params = getCallParams(self); + + // calldata to test against + if (self.finds[who][fsig][keccak256(abi.encodePacked(params, field_depth))].found) { + if (_clear) { + clear(self); + } + return self.finds[who][fsig][keccak256(abi.encodePacked(params, field_depth))]; + } + FindCallData memory callData; + { + vm.record(); + (bool callSuccess, bytes memory rdat) = callTargetRaw(self); + callData.result = _bytesToBytes32(rdat, 32 * field_depth); + if (callSuccess && field_depth == 0) { + callData.shortBytesStorageValue = _parseShortBytesReturn(rdat); + } + (callData.reads,) = vm.accesses(address(who)); + } + + if (callData.reads.length == 0) { + revert("stdStorage find(StdStorage): No storage use detected for target."); + } else { + for (uint256 i = callData.reads.length; i > 0;) { + --i; + bytes32 slot = callData.reads[i]; + bytes32 prev = vm.load(who, slot); + if (prev == bytes32(0)) { + emit WARNING_UninitedSlot(who, uint256(slot)); + } + + bool shortBytesFound = callData.shortBytesStorageValue != bytes32(0) + && _matchesShortBytes(prev, callData.shortBytesStorageValue) && _checkShortBytesSlot(self, slot); + + if (!shortBytesFound && !checkSlotMutatesCall(self, slot)) { + continue; + } + + (uint256 offsetLeft, uint256 offsetRight) = (0, 0); + + if (!shortBytesFound && self._enable_packed_slots) { + bool found; + (found, offsetLeft, offsetRight) = findOffsets(self, slot); + if (!found) { + continue; + } + } + + // Check that value between found offsets is equal to the current call result + uint256 curVal = (uint256(prev) & getMaskByOffsets(offsetLeft, offsetRight)) >> offsetRight; + + if (!shortBytesFound && uint256(callData.result) != curVal) { + continue; + } + + emit SlotFound(who, fsig, keccak256(abi.encodePacked(params, field_depth)), uint256(slot)); + self.finds[who][fsig][keccak256(abi.encodePacked(params, field_depth))] = + FindData(uint256(slot), offsetLeft, offsetRight, true); + break; + } + } + + require( + self.finds[who][fsig][keccak256(abi.encodePacked(params, field_depth))].found, + "stdStorage find(StdStorage): Slot(s) not found." + ); + + if (_clear) { + clear(self); + } + return self.finds[who][fsig][keccak256(abi.encodePacked(params, field_depth))]; + } + + /// @notice Sets the target contract address for the storage lookup. + function target(StdStorage storage self, address _target) internal returns (StdStorage storage) { + self._target = _target; + return self; + } + + /// @notice Sets the target function selector for the storage lookup. + function sig(StdStorage storage self, bytes4 _sig) internal returns (StdStorage storage) { + self._sig = _sig; + return self; + } + + /// @notice Sets the target function selector from a signature string for the storage lookup. + function sig(StdStorage storage self, string memory _sig) internal returns (StdStorage storage) { + self._sig = sigs(_sig); + return self; + } + + /// @notice Sets raw calldata to use instead of ABI-encoded keys for the target call. + function with_calldata(StdStorage storage self, bytes memory _calldata) internal returns (StdStorage storage) { + self._calldata = _calldata; + return self; + } + + /// @notice Adds an address mapping key to the storage lookup path. + function with_key(StdStorage storage self, address who) internal returns (StdStorage storage) { + self._keys.push(bytes32(uint256(uint160(who)))); + return self; + } + + /// @notice Adds a uint256 mapping key to the storage lookup path. + function with_key(StdStorage storage self, uint256 amt) internal returns (StdStorage storage) { + self._keys.push(bytes32(amt)); + return self; + } + + /// @notice Adds a bytes32 mapping key to the storage lookup path. + function with_key(StdStorage storage self, bytes32 key) internal returns (StdStorage storage) { + self._keys.push(key); + return self; + } + + /// @notice Enables detection and handling of values packed into shared storage slots. + function enable_packed_slots(StdStorage storage self) internal returns (StdStorage storage) { + self._enable_packed_slots = true; + return self; + } + + /// @notice Sets the struct field depth for storage lookups into nested structs. + function depth(StdStorage storage self, uint256 _depth) internal returns (StdStorage storage) { + self._depth = _depth; + return self; + } + + function _read(StdStorage storage self) private returns (bytes memory) { + FindData storage data = find(self, false); + uint256 mask = getMaskByOffsets(data.offsetLeft, data.offsetRight); + uint256 value = (uint256(vm.load(self._target, bytes32(data.slot))) & mask) >> data.offsetRight; + clear(self); + return abi.encode(value); + } + + /// @notice Reads the found storage slot value as bytes32. + function read_bytes32(StdStorage storage self) internal returns (bytes32) { + return abi.decode(_read(self), (bytes32)); + } + + /// @notice Reads the found storage slot value as bool. + /// @dev Reverts if the stored value is neither `0` nor `1`. + function read_bool(StdStorage storage self) internal returns (bool) { + int256 v = read_int(self); + if (v == 0) return false; + if (v == 1) return true; + revert("stdStorage read_bool(StdStorage): Cannot decode. Make sure you are reading a bool."); + } + + /// @notice Reads the found storage slot value as address. + function read_address(StdStorage storage self) internal returns (address) { + return abi.decode(_read(self), (address)); + } + + /// @notice Reads the found storage slot value as uint256. + function read_uint(StdStorage storage self) internal returns (uint256) { + return abi.decode(_read(self), (uint256)); + } + + /// @notice Reads the found storage slot value as int256. + function read_int(StdStorage storage self) internal returns (int256) { + return abi.decode(_read(self), (int256)); + } + + /// @notice Returns the parent mapping slot index and the key used to reach the found slot. + function parent(StdStorage storage self) internal returns (uint256, bytes32) { + address who = self._target; + uint256 field_depth = self._depth; + vm.startMappingRecording(); + uint256 child = find(self, true).slot - field_depth; + (bool found, bytes32 key, bytes32 parent_slot) = vm.getMappingKeyAndParentOf(who, bytes32(child)); + if (!found) { + revert( + "stdStorage parent(StdStorage): Cannot find parent. Make sure you give a slot and startMappingRecording() has been called." + ); + } + return (uint256(parent_slot), key); + } + + /// @notice Returns the root mapping slot index by traversing the mapping parent chain. + function root(StdStorage storage self) internal returns (uint256) { + address who = self._target; + uint256 field_depth = self._depth; + vm.startMappingRecording(); + uint256 child = find(self, true).slot - field_depth; + bool found; + bytes32 root_slot; + bytes32 parent_slot; + (found,, parent_slot) = vm.getMappingKeyAndParentOf(who, bytes32(child)); + if (!found) { + revert( + "stdStorage root(StdStorage): Cannot find parent. Make sure you give a slot and startMappingRecording() has been called." + ); + } + while (found) { + root_slot = parent_slot; + (found,, parent_slot) = vm.getMappingKeyAndParentOf(who, bytes32(root_slot)); + } + return uint256(root_slot); + } + + function _bytesToBytes32(bytes memory b, uint256 offset) private pure returns (bytes32) { + bytes32 out; + + // Cap read length by remaining bytes from `offset`, and at most 32 bytes to avoid out-of-bounds + uint256 max = b.length > offset ? b.length - offset : 0; + if (max > 32) { + max = 32; + } + for (uint256 i = 0; i < max; i++) { + out |= bytes32(b[offset + i] & 0xFF) >> (i * 8); + } + return out; + } + + function _flatten(bytes32[] memory b) private pure returns (bytes memory) { + bytes memory result = new bytes(b.length * 32); + for (uint256 i = 0; i < b.length; i++) { + bytes32 k = b[i]; + assembly ("memory-safe") { + mstore(add(result, add(32, mul(32, i))), k) + } + } + + return result; + } + + /// @notice Resets all configured parameters on `self`. + function clear(StdStorage storage self) internal { + delete self._target; + delete self._sig; + delete self._keys; + delete self._depth; + delete self._enable_packed_slots; + delete self._calldata; + } + + /// @notice Returns a bitmask with ones in the bit range `[offsetRight, 255 - offsetLeft]`. + /// @dev `(slotValue & mask) >> offsetRight` extracts the packed variable's value. + function getMaskByOffsets(uint256 offsetLeft, uint256 offsetRight) internal pure returns (uint256 mask) { + // mask = ((1 << (256 - (offsetRight + offsetLeft))) - 1) << offsetRight; + // using assembly because (1 << 256) causes overflow + assembly { + mask := shl(offsetRight, sub(shl(sub(256, add(offsetRight, offsetLeft)), 1), 1)) + } + } + + /// @notice Returns `curValue` with the packed variable at `[offsetRight, 255 - offsetLeft]` replaced by `varValue`. + function getUpdatedSlotValue(bytes32 curValue, uint256 varValue, uint256 offsetLeft, uint256 offsetRight) + internal + pure + returns (bytes32 newValue) + { + return bytes32((uint256(curValue) & ~getMaskByOffsets(offsetLeft, offsetRight)) | (varValue << offsetRight)); + } +} + +library stdStorage { + Vm private constant vm = Vm(address(uint160(uint256(keccak256("hevm cheat code"))))); + + /// @notice Returns the 4-byte function selector for `sigStr`. + function sigs(string memory sigStr) internal pure returns (bytes4) { + return stdStorageSafe.sigs(sigStr); + } + + /// @notice Finds the storage slot index for the configured target, clearing the configuration. + function find(StdStorage storage self) internal returns (uint256) { + return find(self, true); + } + + /// @notice Finds the storage slot index for the configured target, optionally clearing the configuration. + function find(StdStorage storage self, bool _clear) internal returns (uint256) { + return stdStorageSafe.find(self, _clear).slot; + } + + /// @notice Sets the target contract address for the storage lookup. + function target(StdStorage storage self, address _target) internal returns (StdStorage storage) { + return stdStorageSafe.target(self, _target); + } + + /// @notice Sets the target function selector for the storage lookup. + function sig(StdStorage storage self, bytes4 _sig) internal returns (StdStorage storage) { + return stdStorageSafe.sig(self, _sig); + } + + /// @notice Sets the target function selector from a signature string for the storage lookup. + function sig(StdStorage storage self, string memory _sig) internal returns (StdStorage storage) { + return stdStorageSafe.sig(self, _sig); + } + + /// @notice Adds an address mapping key to the storage lookup path. + function with_key(StdStorage storage self, address who) internal returns (StdStorage storage) { + return stdStorageSafe.with_key(self, who); + } + + /// @notice Adds a uint256 mapping key to the storage lookup path. + function with_key(StdStorage storage self, uint256 amt) internal returns (StdStorage storage) { + return stdStorageSafe.with_key(self, amt); + } + + /// @notice Adds a bytes32 mapping key to the storage lookup path. + function with_key(StdStorage storage self, bytes32 key) internal returns (StdStorage storage) { + return stdStorageSafe.with_key(self, key); + } + + /// @notice Sets raw calldata to use instead of ABI-encoded keys for the target call. + function with_calldata(StdStorage storage self, bytes memory _calldata) internal returns (StdStorage storage) { + return stdStorageSafe.with_calldata(self, _calldata); + } + + /// @notice Enables detection and handling of values packed into shared storage slots. + function enable_packed_slots(StdStorage storage self) internal returns (StdStorage storage) { + return stdStorageSafe.enable_packed_slots(self); + } + + /// @notice Sets the struct field depth for storage lookups into nested structs. + function depth(StdStorage storage self, uint256 _depth) internal returns (StdStorage storage) { + return stdStorageSafe.depth(self, _depth); + } + + /// @notice Resets all configured parameters on `self`. + function clear(StdStorage storage self) internal { + stdStorageSafe.clear(self); + } + + /// @notice Writes `who` to the found storage slot and verifies the value was applied correctly. + function checked_write(StdStorage storage self, address who) internal { + checked_write(self, bytes32(uint256(uint160(who)))); + } + + /// @notice Writes `amt` to the found storage slot and verifies the value was applied correctly. + function checked_write(StdStorage storage self, uint256 amt) internal { + checked_write(self, bytes32(amt)); + } + + /// @notice Writes `val` to the found storage slot and verifies the value was applied correctly. + function checked_write_int(StdStorage storage self, int256 val) internal { + checked_write(self, bytes32(uint256(val))); + } + + /// @notice Writes `write` to the found storage slot and verifies the value was applied correctly. + function checked_write(StdStorage storage self, bool write) internal { + bytes32 t; + assembly ("memory-safe") { + t := write + } + checked_write(self, t); + } + + /// @notice Writes `set` to the found storage slot and verifies the value was applied correctly. + function checked_write(StdStorage storage self, bytes32 set) internal { + address who = self._target; + bytes4 fsig = self._sig; + uint256 field_depth = self._depth; + bytes memory params = stdStorageSafe.getCallParams(self); + + if (!self.finds[who][fsig][keccak256(abi.encodePacked(params, field_depth))].found) { + find(self, false); + } + FindData storage data = self.finds[who][fsig][keccak256(abi.encodePacked(params, field_depth))]; + if ((data.offsetLeft + data.offsetRight) > 0) { + uint256 maxVal = 2 ** (256 - (data.offsetLeft + data.offsetRight)); + require( + uint256(set) < maxVal, + string( + abi.encodePacked( + "stdStorage checked_write(StdStorage): Packed slot. We can't fit value greater than ", + vm.toString(maxVal) + ) + ) + ); + } + bytes32 curVal = vm.load(who, bytes32(data.slot)); + bytes32 valToSet = stdStorageSafe.getUpdatedSlotValue(curVal, uint256(set), data.offsetLeft, data.offsetRight); + + vm.store(who, bytes32(data.slot), valToSet); + + (bool success, bytes32 callResult) = stdStorageSafe.callTarget(self); + + if (!success || callResult != set) { + vm.store(who, bytes32(data.slot), curVal); + revert("stdStorage checked_write(StdStorage): Failed to write value."); + } + clear(self); + } + + /// @notice Reads the found storage slot value as bytes32. + function read_bytes32(StdStorage storage self) internal returns (bytes32) { + return stdStorageSafe.read_bytes32(self); + } + + /// @notice Reads the found storage slot value as bool. + function read_bool(StdStorage storage self) internal returns (bool) { + return stdStorageSafe.read_bool(self); + } + + /// @notice Reads the found storage slot value as address. + function read_address(StdStorage storage self) internal returns (address) { + return stdStorageSafe.read_address(self); + } + + /// @notice Reads the found storage slot value as uint256. + function read_uint(StdStorage storage self) internal returns (uint256) { + return stdStorageSafe.read_uint(self); + } + + /// @notice Reads the found storage slot value as int256. + function read_int(StdStorage storage self) internal returns (int256) { + return stdStorageSafe.read_int(self); + } + + /// @notice Returns the parent mapping slot index and the key used to reach the found slot. + function parent(StdStorage storage self) internal returns (uint256, bytes32) { + return stdStorageSafe.parent(self); + } + + /// @notice Returns the root mapping slot index by traversing the mapping parent chain. + function root(StdStorage storage self) internal returns (uint256) { + return stdStorageSafe.root(self); + } +} diff --git a/contracts/evm/lib/forge-std/src/StdStyle.sol b/contracts/evm/lib/forge-std/src/StdStyle.sol new file mode 100644 index 0000000000..33b815fcbd --- /dev/null +++ b/contracts/evm/lib/forge-std/src/StdStyle.sol @@ -0,0 +1,410 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {VmSafe} from "./Vm.sol"; + +library StdStyle { + VmSafe private constant vm = VmSafe(address(uint160(uint256(keccak256("hevm cheat code"))))); + + string constant RED = "\u001b[91m"; + string constant GREEN = "\u001b[92m"; + string constant YELLOW = "\u001b[93m"; + string constant BLUE = "\u001b[94m"; + string constant MAGENTA = "\u001b[95m"; + string constant CYAN = "\u001b[96m"; + string constant BOLD = "\u001b[1m"; + string constant DIM = "\u001b[2m"; + string constant ITALIC = "\u001b[3m"; + string constant UNDERLINE = "\u001b[4m"; + string constant INVERSE = "\u001b[7m"; + string constant RESET = "\u001b[0m"; + + function _styleConcat(string memory style, string memory self) private pure returns (string memory) { + return string(abi.encodePacked(style, self, RESET)); + } + + /// @notice Returns `self` wrapped in red ANSI color codes. + function red(string memory self) internal pure returns (string memory) { + return _styleConcat(RED, self); + } + + /// @notice Returns the string representation of `self` wrapped in red ANSI color codes. + function red(uint256 self) internal pure returns (string memory) { + return red(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in red ANSI color codes. + function red(int256 self) internal pure returns (string memory) { + return red(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in red ANSI color codes. + function red(address self) internal pure returns (string memory) { + return red(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in red ANSI color codes. + function red(bool self) internal pure returns (string memory) { + return red(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in red ANSI color codes. + function redBytes(bytes memory self) internal pure returns (string memory) { + return red(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in red ANSI color codes. + function redBytes32(bytes32 self) internal pure returns (string memory) { + return red(vm.toString(self)); + } + + /// @notice Returns `self` wrapped in green ANSI color codes. + function green(string memory self) internal pure returns (string memory) { + return _styleConcat(GREEN, self); + } + + /// @notice Returns the string representation of `self` wrapped in green ANSI color codes. + function green(uint256 self) internal pure returns (string memory) { + return green(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in green ANSI color codes. + function green(int256 self) internal pure returns (string memory) { + return green(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in green ANSI color codes. + function green(address self) internal pure returns (string memory) { + return green(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in green ANSI color codes. + function green(bool self) internal pure returns (string memory) { + return green(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in green ANSI color codes. + function greenBytes(bytes memory self) internal pure returns (string memory) { + return green(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in green ANSI color codes. + function greenBytes32(bytes32 self) internal pure returns (string memory) { + return green(vm.toString(self)); + } + + /// @notice Returns `self` wrapped in yellow ANSI color codes. + function yellow(string memory self) internal pure returns (string memory) { + return _styleConcat(YELLOW, self); + } + + /// @notice Returns the string representation of `self` wrapped in yellow ANSI color codes. + function yellow(uint256 self) internal pure returns (string memory) { + return yellow(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in yellow ANSI color codes. + function yellow(int256 self) internal pure returns (string memory) { + return yellow(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in yellow ANSI color codes. + function yellow(address self) internal pure returns (string memory) { + return yellow(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in yellow ANSI color codes. + function yellow(bool self) internal pure returns (string memory) { + return yellow(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in yellow ANSI color codes. + function yellowBytes(bytes memory self) internal pure returns (string memory) { + return yellow(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in yellow ANSI color codes. + function yellowBytes32(bytes32 self) internal pure returns (string memory) { + return yellow(vm.toString(self)); + } + + /// @notice Returns `self` wrapped in blue ANSI color codes. + function blue(string memory self) internal pure returns (string memory) { + return _styleConcat(BLUE, self); + } + + /// @notice Returns the string representation of `self` wrapped in blue ANSI color codes. + function blue(uint256 self) internal pure returns (string memory) { + return blue(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in blue ANSI color codes. + function blue(int256 self) internal pure returns (string memory) { + return blue(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in blue ANSI color codes. + function blue(address self) internal pure returns (string memory) { + return blue(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in blue ANSI color codes. + function blue(bool self) internal pure returns (string memory) { + return blue(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in blue ANSI color codes. + function blueBytes(bytes memory self) internal pure returns (string memory) { + return blue(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in blue ANSI color codes. + function blueBytes32(bytes32 self) internal pure returns (string memory) { + return blue(vm.toString(self)); + } + + /// @notice Returns `self` wrapped in magenta ANSI color codes. + function magenta(string memory self) internal pure returns (string memory) { + return _styleConcat(MAGENTA, self); + } + + /// @notice Returns the string representation of `self` wrapped in magenta ANSI color codes. + function magenta(uint256 self) internal pure returns (string memory) { + return magenta(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in magenta ANSI color codes. + function magenta(int256 self) internal pure returns (string memory) { + return magenta(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in magenta ANSI color codes. + function magenta(address self) internal pure returns (string memory) { + return magenta(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in magenta ANSI color codes. + function magenta(bool self) internal pure returns (string memory) { + return magenta(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in magenta ANSI color codes. + function magentaBytes(bytes memory self) internal pure returns (string memory) { + return magenta(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in magenta ANSI color codes. + function magentaBytes32(bytes32 self) internal pure returns (string memory) { + return magenta(vm.toString(self)); + } + + /// @notice Returns `self` wrapped in cyan ANSI color codes. + function cyan(string memory self) internal pure returns (string memory) { + return _styleConcat(CYAN, self); + } + + /// @notice Returns the string representation of `self` wrapped in cyan ANSI color codes. + function cyan(uint256 self) internal pure returns (string memory) { + return cyan(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in cyan ANSI color codes. + function cyan(int256 self) internal pure returns (string memory) { + return cyan(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in cyan ANSI color codes. + function cyan(address self) internal pure returns (string memory) { + return cyan(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in cyan ANSI color codes. + function cyan(bool self) internal pure returns (string memory) { + return cyan(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in cyan ANSI color codes. + function cyanBytes(bytes memory self) internal pure returns (string memory) { + return cyan(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in cyan ANSI color codes. + function cyanBytes32(bytes32 self) internal pure returns (string memory) { + return cyan(vm.toString(self)); + } + + /// @notice Returns `self` wrapped in bold ANSI style codes. + function bold(string memory self) internal pure returns (string memory) { + return _styleConcat(BOLD, self); + } + + /// @notice Returns the string representation of `self` wrapped in bold ANSI style codes. + function bold(uint256 self) internal pure returns (string memory) { + return bold(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in bold ANSI style codes. + function bold(int256 self) internal pure returns (string memory) { + return bold(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in bold ANSI style codes. + function bold(address self) internal pure returns (string memory) { + return bold(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in bold ANSI style codes. + function bold(bool self) internal pure returns (string memory) { + return bold(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in bold ANSI style codes. + function boldBytes(bytes memory self) internal pure returns (string memory) { + return bold(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in bold ANSI style codes. + function boldBytes32(bytes32 self) internal pure returns (string memory) { + return bold(vm.toString(self)); + } + + /// @notice Returns `self` wrapped in dim ANSI style codes. + function dim(string memory self) internal pure returns (string memory) { + return _styleConcat(DIM, self); + } + + /// @notice Returns the string representation of `self` wrapped in dim ANSI style codes. + function dim(uint256 self) internal pure returns (string memory) { + return dim(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in dim ANSI style codes. + function dim(int256 self) internal pure returns (string memory) { + return dim(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in dim ANSI style codes. + function dim(address self) internal pure returns (string memory) { + return dim(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in dim ANSI style codes. + function dim(bool self) internal pure returns (string memory) { + return dim(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in dim ANSI style codes. + function dimBytes(bytes memory self) internal pure returns (string memory) { + return dim(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in dim ANSI style codes. + function dimBytes32(bytes32 self) internal pure returns (string memory) { + return dim(vm.toString(self)); + } + + /// @notice Returns `self` wrapped in italic ANSI style codes. + function italic(string memory self) internal pure returns (string memory) { + return _styleConcat(ITALIC, self); + } + + /// @notice Returns the string representation of `self` wrapped in italic ANSI style codes. + function italic(uint256 self) internal pure returns (string memory) { + return italic(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in italic ANSI style codes. + function italic(int256 self) internal pure returns (string memory) { + return italic(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in italic ANSI style codes. + function italic(address self) internal pure returns (string memory) { + return italic(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in italic ANSI style codes. + function italic(bool self) internal pure returns (string memory) { + return italic(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in italic ANSI style codes. + function italicBytes(bytes memory self) internal pure returns (string memory) { + return italic(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in italic ANSI style codes. + function italicBytes32(bytes32 self) internal pure returns (string memory) { + return italic(vm.toString(self)); + } + + /// @notice Returns `self` wrapped in underline ANSI style codes. + function underline(string memory self) internal pure returns (string memory) { + return _styleConcat(UNDERLINE, self); + } + + /// @notice Returns the string representation of `self` wrapped in underline ANSI style codes. + function underline(uint256 self) internal pure returns (string memory) { + return underline(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in underline ANSI style codes. + function underline(int256 self) internal pure returns (string memory) { + return underline(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in underline ANSI style codes. + function underline(address self) internal pure returns (string memory) { + return underline(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in underline ANSI style codes. + function underline(bool self) internal pure returns (string memory) { + return underline(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in underline ANSI style codes. + function underlineBytes(bytes memory self) internal pure returns (string memory) { + return underline(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in underline ANSI style codes. + function underlineBytes32(bytes32 self) internal pure returns (string memory) { + return underline(vm.toString(self)); + } + + /// @notice Returns `self` wrapped in inverse ANSI style codes. + function inverse(string memory self) internal pure returns (string memory) { + return _styleConcat(INVERSE, self); + } + + /// @notice Returns the string representation of `self` wrapped in inverse ANSI style codes. + function inverse(uint256 self) internal pure returns (string memory) { + return inverse(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in inverse ANSI style codes. + function inverse(int256 self) internal pure returns (string memory) { + return inverse(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in inverse ANSI style codes. + function inverse(address self) internal pure returns (string memory) { + return inverse(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in inverse ANSI style codes. + function inverse(bool self) internal pure returns (string memory) { + return inverse(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in inverse ANSI style codes. + function inverseBytes(bytes memory self) internal pure returns (string memory) { + return inverse(vm.toString(self)); + } + + /// @notice Returns the string representation of `self` wrapped in inverse ANSI style codes. + function inverseBytes32(bytes32 self) internal pure returns (string memory) { + return inverse(vm.toString(self)); + } +} diff --git a/contracts/evm/lib/forge-std/src/StdToml.sol b/contracts/evm/lib/forge-std/src/StdToml.sol new file mode 100644 index 0000000000..a5198d82e9 --- /dev/null +++ b/contracts/evm/lib/forge-std/src/StdToml.sol @@ -0,0 +1,323 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {VmSafe} from "./Vm.sol"; + +// Helpers for parsing and writing TOML files +// To parse: +// ``` +// using stdToml for string; +// string memory toml = vm.readFile(""); +// toml.readUint(""); +// ``` +// To write: +// ``` +// using stdToml for string; +// string memory toml = "toml"; +// toml.serialize("a", uint256(123)); +// string memory semiFinal = toml.serialize("b", string("test")); +// string memory finalToml = toml.serialize("c", semiFinal); +// finalToml.write(""); +// ``` + +library stdToml { + VmSafe private constant vm = VmSafe(address(uint160(uint256(keccak256("hevm cheat code"))))); + + /// @notice Returns whether `key` exists in `toml`. + function keyExists(string memory toml, string memory key) internal view returns (bool) { + return vm.keyExistsToml(toml, key); + } + + /// @notice ABI-encodes the TOML value selected by `key`. + function parseRaw(string memory toml, string memory key) internal pure returns (bytes memory) { + return vm.parseToml(toml, key); + } + + /// @notice Reads a uint256 value at `key` from `toml`. + function readUint(string memory toml, string memory key) internal pure returns (uint256) { + return vm.parseTomlUint(toml, key); + } + + /// @notice Reads a uint256 array at `key` from `toml`. + function readUintArray(string memory toml, string memory key) internal pure returns (uint256[] memory) { + return vm.parseTomlUintArray(toml, key); + } + + /// @notice Reads an int256 value at `key` from `toml`. + function readInt(string memory toml, string memory key) internal pure returns (int256) { + return vm.parseTomlInt(toml, key); + } + + /// @notice Reads an int256 array at `key` from `toml`. + function readIntArray(string memory toml, string memory key) internal pure returns (int256[] memory) { + return vm.parseTomlIntArray(toml, key); + } + + /// @notice Reads a bytes32 value at `key` from `toml`. + function readBytes32(string memory toml, string memory key) internal pure returns (bytes32) { + return vm.parseTomlBytes32(toml, key); + } + + /// @notice Reads a bytes32 array at `key` from `toml`. + function readBytes32Array(string memory toml, string memory key) internal pure returns (bytes32[] memory) { + return vm.parseTomlBytes32Array(toml, key); + } + + /// @notice Reads a string value at `key` from `toml`. + function readString(string memory toml, string memory key) internal pure returns (string memory) { + return vm.parseTomlString(toml, key); + } + + /// @notice Reads a string array at `key` from `toml`. + function readStringArray(string memory toml, string memory key) internal pure returns (string[] memory) { + return vm.parseTomlStringArray(toml, key); + } + + /// @notice Reads an address value at `key` from `toml`. + function readAddress(string memory toml, string memory key) internal pure returns (address) { + return vm.parseTomlAddress(toml, key); + } + + /// @notice Reads an address array at `key` from `toml`. + function readAddressArray(string memory toml, string memory key) internal pure returns (address[] memory) { + return vm.parseTomlAddressArray(toml, key); + } + + /// @notice Reads a bool value at `key` from `toml`. + function readBool(string memory toml, string memory key) internal pure returns (bool) { + return vm.parseTomlBool(toml, key); + } + + /// @notice Reads a bool array at `key` from `toml`. + function readBoolArray(string memory toml, string memory key) internal pure returns (bool[] memory) { + return vm.parseTomlBoolArray(toml, key); + } + + /// @notice Reads a bytes value at `key` from `toml`. + function readBytes(string memory toml, string memory key) internal pure returns (bytes memory) { + return vm.parseTomlBytes(toml, key); + } + + /// @notice Reads a bytes array at `key` from `toml`. + function readBytesArray(string memory toml, string memory key) internal pure returns (bytes[] memory) { + return vm.parseTomlBytesArray(toml, key); + } + + /// @notice Reads a uint256 value at `key` from `toml`, returning `defaultValue` if the key does not exist. + function readUintOr(string memory toml, string memory key, uint256 defaultValue) internal view returns (uint256) { + return keyExists(toml, key) ? readUint(toml, key) : defaultValue; + } + + /// @notice Reads a uint256 array at `key` from `toml`, returning `defaultValue` if the key does not exist. + function readUintArrayOr(string memory toml, string memory key, uint256[] memory defaultValue) + internal + view + returns (uint256[] memory) + { + return keyExists(toml, key) ? readUintArray(toml, key) : defaultValue; + } + + /// @notice Reads an int256 value at `key` from `toml`, returning `defaultValue` if the key does not exist. + function readIntOr(string memory toml, string memory key, int256 defaultValue) internal view returns (int256) { + return keyExists(toml, key) ? readInt(toml, key) : defaultValue; + } + + /// @notice Reads an int256 array at `key` from `toml`, returning `defaultValue` if the key does not exist. + function readIntArrayOr(string memory toml, string memory key, int256[] memory defaultValue) + internal + view + returns (int256[] memory) + { + return keyExists(toml, key) ? readIntArray(toml, key) : defaultValue; + } + + /// @notice Reads a bytes32 value at `key` from `toml`, returning `defaultValue` if the key does not exist. + function readBytes32Or(string memory toml, string memory key, bytes32 defaultValue) + internal + view + returns (bytes32) + { + return keyExists(toml, key) ? readBytes32(toml, key) : defaultValue; + } + + /// @notice Reads a bytes32 array at `key` from `toml`, returning `defaultValue` if the key does not exist. + function readBytes32ArrayOr(string memory toml, string memory key, bytes32[] memory defaultValue) + internal + view + returns (bytes32[] memory) + { + return keyExists(toml, key) ? readBytes32Array(toml, key) : defaultValue; + } + + /// @notice Reads a string value at `key` from `toml`, returning `defaultValue` if the key does not exist. + function readStringOr(string memory toml, string memory key, string memory defaultValue) + internal + view + returns (string memory) + { + return keyExists(toml, key) ? readString(toml, key) : defaultValue; + } + + /// @notice Reads a string array at `key` from `toml`, returning `defaultValue` if the key does not exist. + function readStringArrayOr(string memory toml, string memory key, string[] memory defaultValue) + internal + view + returns (string[] memory) + { + return keyExists(toml, key) ? readStringArray(toml, key) : defaultValue; + } + + /// @notice Reads an address value at `key` from `toml`, returning `defaultValue` if the key does not exist. + function readAddressOr(string memory toml, string memory key, address defaultValue) + internal + view + returns (address) + { + return keyExists(toml, key) ? readAddress(toml, key) : defaultValue; + } + + /// @notice Reads an address array at `key` from `toml`, returning `defaultValue` if the key does not exist. + function readAddressArrayOr(string memory toml, string memory key, address[] memory defaultValue) + internal + view + returns (address[] memory) + { + return keyExists(toml, key) ? readAddressArray(toml, key) : defaultValue; + } + + /// @notice Reads a bool value at `key` from `toml`, returning `defaultValue` if the key does not exist. + function readBoolOr(string memory toml, string memory key, bool defaultValue) internal view returns (bool) { + return keyExists(toml, key) ? readBool(toml, key) : defaultValue; + } + + /// @notice Reads a bool array at `key` from `toml`, returning `defaultValue` if the key does not exist. + function readBoolArrayOr(string memory toml, string memory key, bool[] memory defaultValue) + internal + view + returns (bool[] memory) + { + return keyExists(toml, key) ? readBoolArray(toml, key) : defaultValue; + } + + /// @notice Reads a bytes value at `key` from `toml`, returning `defaultValue` if the key does not exist. + function readBytesOr(string memory toml, string memory key, bytes memory defaultValue) + internal + view + returns (bytes memory) + { + return keyExists(toml, key) ? readBytes(toml, key) : defaultValue; + } + + /// @notice Reads a bytes array at `key` from `toml`, returning `defaultValue` if the key does not exist. + function readBytesArrayOr(string memory toml, string memory key, bytes[] memory defaultValue) + internal + view + returns (bytes[] memory) + { + return keyExists(toml, key) ? readBytesArray(toml, key) : defaultValue; + } + + /// @notice Serializes a JSON object `rootObject` under `jsonKey` and returns the serialized string. + /// @dev Values are accumulated as JSON in memory; conversion to TOML happens on `write`. + function serialize(string memory jsonKey, string memory rootObject) internal returns (string memory) { + return vm.serializeJson(jsonKey, rootObject); + } + + /// @notice Serializes a bool `value` under `key` within `jsonKey` and returns the serialized string. + function serialize(string memory jsonKey, string memory key, bool value) internal returns (string memory) { + return vm.serializeBool(jsonKey, key, value); + } + + /// @notice Serializes a bool array `value` under `key` within `jsonKey` and returns the serialized string. + function serialize(string memory jsonKey, string memory key, bool[] memory value) internal returns (string memory) { + return vm.serializeBool(jsonKey, key, value); + } + + /// @notice Serializes a uint256 `value` under `key` within `jsonKey` and returns the serialized string. + function serialize(string memory jsonKey, string memory key, uint256 value) internal returns (string memory) { + return vm.serializeUint(jsonKey, key, value); + } + + /// @notice Serializes a uint256 array `value` under `key` within `jsonKey` and returns the serialized string. + function serialize(string memory jsonKey, string memory key, uint256[] memory value) + internal + returns (string memory) + { + return vm.serializeUint(jsonKey, key, value); + } + + /// @notice Serializes an int256 `value` under `key` within `jsonKey` and returns the serialized string. + function serialize(string memory jsonKey, string memory key, int256 value) internal returns (string memory) { + return vm.serializeInt(jsonKey, key, value); + } + + /// @notice Serializes an int256 array `value` under `key` within `jsonKey` and returns the serialized string. + function serialize(string memory jsonKey, string memory key, int256[] memory value) + internal + returns (string memory) + { + return vm.serializeInt(jsonKey, key, value); + } + + /// @notice Serializes an address `value` under `key` within `jsonKey` and returns the serialized string. + function serialize(string memory jsonKey, string memory key, address value) internal returns (string memory) { + return vm.serializeAddress(jsonKey, key, value); + } + + /// @notice Serializes an address array `value` under `key` within `jsonKey` and returns the serialized string. + function serialize(string memory jsonKey, string memory key, address[] memory value) + internal + returns (string memory) + { + return vm.serializeAddress(jsonKey, key, value); + } + + /// @notice Serializes a bytes32 `value` under `key` within `jsonKey` and returns the serialized string. + function serialize(string memory jsonKey, string memory key, bytes32 value) internal returns (string memory) { + return vm.serializeBytes32(jsonKey, key, value); + } + + /// @notice Serializes a bytes32 array `value` under `key` within `jsonKey` and returns the serialized string. + function serialize(string memory jsonKey, string memory key, bytes32[] memory value) + internal + returns (string memory) + { + return vm.serializeBytes32(jsonKey, key, value); + } + + /// @notice Serializes a bytes `value` under `key` within `jsonKey` and returns the serialized string. + function serialize(string memory jsonKey, string memory key, bytes memory value) internal returns (string memory) { + return vm.serializeBytes(jsonKey, key, value); + } + + /// @notice Serializes a bytes array `value` under `key` within `jsonKey` and returns the serialized string. + function serialize(string memory jsonKey, string memory key, bytes[] memory value) + internal + returns (string memory) + { + return vm.serializeBytes(jsonKey, key, value); + } + + /// @notice Serializes a string `value` under `key` within `jsonKey` and returns the serialized string. + function serialize(string memory jsonKey, string memory key, string memory value) internal returns (string memory) { + return vm.serializeString(jsonKey, key, value); + } + + /// @notice Serializes a string array `value` under `key` within `jsonKey` and returns the serialized string. + function serialize(string memory jsonKey, string memory key, string[] memory value) + internal + returns (string memory) + { + return vm.serializeString(jsonKey, key, value); + } + + /// @notice Writes the serialized object `jsonKey` to `path` as a TOML file. + function write(string memory jsonKey, string memory path) internal { + vm.writeToml(jsonKey, path); + } + + /// @notice Writes the value at `valueKey` from the serialized object `jsonKey` to `path` as a TOML file. + function write(string memory jsonKey, string memory path, string memory valueKey) internal { + vm.writeToml(jsonKey, path, valueKey); + } +} diff --git a/contracts/evm/lib/forge-std/src/StdUtils.sol b/contracts/evm/lib/forge-std/src/StdUtils.sol new file mode 100644 index 0000000000..8dd7b4732c --- /dev/null +++ b/contracts/evm/lib/forge-std/src/StdUtils.sol @@ -0,0 +1,247 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {IMulticall3} from "./interfaces/IMulticall3.sol"; +import {StdConstants} from "./StdConstants.sol"; +import {VmSafe} from "./Vm.sol"; + +abstract contract StdUtils { + /*////////////////////////////////////////////////////////////////////////// + CONSTANTS + //////////////////////////////////////////////////////////////////////////*/ + + VmSafe private constant vm = VmSafe(address(uint160(uint256(keccak256("hevm cheat code"))))); + address private constant _CONSOLE2_ADDRESS = 0x000000000000000000636F6e736F6c652e6c6f67; + uint256 private constant _INT256_MIN_ABS = + 57896044618658097711785492504343953926634992332820282019728792003956564819968; + uint256 private constant _SECP256K1_ORDER = + 115792089237316195423570985008687907852837564279074904382605163141518161494337; + uint256 private constant _UINT256_MAX = + 115792089237316195423570985008687907853269984665640564039457584007913129639935; + + /*////////////////////////////////////////////////////////////////////////// + INTERNAL FUNCTIONS + //////////////////////////////////////////////////////////////////////////*/ + + /// @notice Maps an unsigned integer into the inclusive range `[min, max]`. + /// @dev Values outside the range are wrapped into it. + /// @param x The unsigned value to bound. + /// @param min The inclusive lower bound. + /// @param max The inclusive upper bound. + /// @return result The bounded value. + function _bound(uint256 x, uint256 min, uint256 max) internal pure virtual returns (uint256 result) { + require(min <= max, "StdUtils bound(uint256,uint256,uint256): Max is less than min."); + // If x is between min and max, return x directly. This is to ensure that dictionary values + // do not get shifted if the min is nonzero. More info: https://github.com/foundry-rs/forge-std/issues/188 + if (x >= min && x <= max) return x; + + uint256 size = max - min + 1; + + // If the value is 0, 1, 2, 3, wrap that to min, min+1, min+2, min+3. Similarly for the _UINT256_MAX side. + // This helps ensure coverage of the min/max values. + if (x <= 3 && size > x) return min + x; + if (x >= _UINT256_MAX - 3 && size > _UINT256_MAX - x) return max - (_UINT256_MAX - x); + + // Otherwise, wrap x into the range [min, max], i.e. the range is inclusive. + if (x > max) { + uint256 diff = x - max; + uint256 rem = diff % size; + if (rem == 0) return max; + result = min + rem - 1; + } else if (x < min) { + uint256 diff = min - x; + uint256 rem = diff % size; + if (rem == 0) return min; + result = max - rem + 1; + } + } + + /// @notice Wrapper for `_bound(uint256,uint256,uint256)`. + /// @param x The unsigned value to bound. + /// @param min The inclusive lower bound. + /// @param max The inclusive upper bound. + /// @return result The bounded value. + function bound(uint256 x, uint256 min, uint256 max) internal pure virtual returns (uint256 result) { + result = _bound(x, min, max); + } + + /// @notice Maps a signed integer into the inclusive range `[min, max]`. + /// @dev Values outside the range are wrapped into it. + /// @param x The signed value to bound. + /// @param min The inclusive lower bound. + /// @param max The inclusive upper bound. + /// @return result The bounded value. + function _bound(int256 x, int256 min, int256 max) internal pure virtual returns (int256 result) { + require(min <= max, "StdUtils bound(int256,int256,int256): Max is less than min."); + + // Shifting all int256 values to uint256 to use _bound function. The range of two types are: + // int256 : -(2**255) ~ (2**255 - 1) + // uint256: 0 ~ (2**256 - 1) + // So, add 2**255, _INT256_MIN_ABS to the integer values. + // + // If the given integer value is -2**255, we cannot use `-uint256(-x)` because of the overflow. + // So, use `~uint256(x) + 1` instead. + uint256 _x = x < 0 ? (_INT256_MIN_ABS - ~uint256(x) - 1) : (uint256(x) + _INT256_MIN_ABS); + uint256 _min = min < 0 ? (_INT256_MIN_ABS - ~uint256(min) - 1) : (uint256(min) + _INT256_MIN_ABS); + uint256 _max = max < 0 ? (_INT256_MIN_ABS - ~uint256(max) - 1) : (uint256(max) + _INT256_MIN_ABS); + + uint256 y = _bound(_x, _min, _max); + + // To move it back to int256 value, subtract _INT256_MIN_ABS at here. + result = y < _INT256_MIN_ABS ? int256(~(_INT256_MIN_ABS - y) + 1) : int256(y - _INT256_MIN_ABS); + } + + /// @notice Wrapper for `_bound(int256,int256,int256)`. + /// @param x The signed value to bound. + /// @param min The inclusive lower bound. + /// @param max The inclusive upper bound. + /// @return result The bounded value. + function bound(int256 x, int256 min, int256 max) internal pure virtual returns (int256 result) { + result = _bound(x, min, max); + } + + /// @notice Maps a value into the valid secp256k1 private key range `[1, n - 1]`. + /// @param privateKey The raw private key candidate. + /// @return result The bounded private key. + function boundPrivateKey(uint256 privateKey) internal pure virtual returns (uint256 result) { + result = _bound(privateKey, 1, _SECP256K1_ORDER - 1); + } + + /// @notice Converts a byte array (up to 32 bytes) into a `uint256`. + /// @param b The byte array to decode. + /// @return The decoded unsigned integer. + function bytesToUint(bytes memory b) internal pure virtual returns (uint256) { + require(b.length <= 32, "StdUtils bytesToUint(bytes): Bytes length exceeds 32."); + return abi.decode(abi.encodePacked(new bytes(32 - b.length), b), (uint256)); + } + + /// @notice Computes the CREATE deployment address for `deployer` and `nonce`. + /// @dev Deprecated in favor of `vm.computeCreateAddress`. + /// @param deployer The deployer address. + /// @param nonce The deployer nonce used for CREATE. + /// @return The computed CREATE address. + function computeCreateAddress(address deployer, uint256 nonce) internal pure virtual returns (address) { + _console2_log_StdUtils("computeCreateAddress is deprecated. Please use vm.computeCreateAddress instead."); + return vm.computeCreateAddress(deployer, nonce); + } + + /// @notice Computes the CREATE2 address from a salt, init code hash, and deployer. + /// @dev Deprecated in favor of `vm.computeCreate2Address`. + /// @param salt The CREATE2 salt. + /// @param initcodeHash The hash of the full init code. + /// @param deployer The deployer address. + /// @return The computed CREATE2 address. + function computeCreate2Address(bytes32 salt, bytes32 initcodeHash, address deployer) + internal + pure + virtual + returns (address) + { + _console2_log_StdUtils("computeCreate2Address is deprecated. Please use vm.computeCreate2Address instead."); + return vm.computeCreate2Address(salt, initcodeHash, deployer); + } + + /// @notice Computes a CREATE2 address using the default CREATE2 deployer. + /// @dev Deprecated in favor of `vm.computeCreate2Address`. + /// @param salt The CREATE2 salt. + /// @param initCodeHash The hash of the full init code. + /// @return The computed CREATE2 address. + function computeCreate2Address(bytes32 salt, bytes32 initCodeHash) internal pure returns (address) { + _console2_log_StdUtils("computeCreate2Address is deprecated. Please use vm.computeCreate2Address instead."); + return vm.computeCreate2Address(salt, initCodeHash); + } + + /// @notice Returns the init code hash for CREATE2 without constructor arguments. + /// @param creationCode The creation code of contract `C`, as returned by `type(C).creationCode`. + /// @return The keccak256 hash of the init code. + function hashInitCode(bytes memory creationCode) internal pure returns (bytes32) { + return hashInitCode(creationCode, ""); + } + + /// @notice Returns the init code hash for CREATE2 with ABI-encoded constructor arguments. + /// @param creationCode The creation code of contract `C`, as returned by `type(C).creationCode`. + /// @param args The ABI-encoded constructor arguments for `C`. + /// @return The keccak256 hash of `creationCode || args`. + function hashInitCode(bytes memory creationCode, bytes memory args) internal pure returns (bytes32) { + return keccak256(abi.encodePacked(creationCode, args)); + } + + /// @notice Queries ERC-20 balances for multiple addresses in one Multicall3 request. + /// @param token The ERC-20 token contract to query. + /// @param addresses The addresses to query balances for. + /// @return balances The token balances in the same order as `addresses`. + function getTokenBalances(address token, address[] memory addresses) + internal + virtual + returns (uint256[] memory balances) + { + uint256 tokenCodeSize; + assembly { + tokenCodeSize := extcodesize(token) + } + require(tokenCodeSize > 0, "StdUtils getTokenBalances(address,address[]): Token address is not a contract."); + + // ABI encode the aggregate call to Multicall3. + uint256 length = addresses.length; + IMulticall3.Call[] memory calls = new IMulticall3.Call[](length); + for (uint256 i = 0; i < length; ++i) { + // 0x70a08231 = bytes4(keccak256("balanceOf(address)")) + calls[i] = IMulticall3.Call({target: token, callData: abi.encodeWithSelector(0x70a08231, (addresses[i]))}); + } + + // Make the aggregate call. + (, bytes[] memory returnData) = StdConstants.MULTICALL3_ADDRESS.aggregate(calls); + + // ABI decode the return data and return the balances. + balances = new uint256[](length); + for (uint256 i = 0; i < length; ++i) { + balances[i] = abi.decode(returnData[i], (uint256)); + } + } + + /*////////////////////////////////////////////////////////////////////////// + PRIVATE FUNCTIONS + //////////////////////////////////////////////////////////////////////////*/ + + function _addressFromLast20Bytes(bytes32 bytesValue) private pure returns (address) { + return address(uint160(uint256(bytesValue))); + } + + // This section is used to prevent the compilation of console, which shortens the compilation time when console is + // not used elsewhere. We also trick the compiler into letting us make the console log methods as `pure` to avoid + // any breaking changes to function signatures. + function _castLogPayloadViewToPure(function(bytes memory) internal view fnIn) + internal + pure + returns (function(bytes memory) internal pure fnOut) + { + assembly { + fnOut := fnIn + } + } + + function _sendLogPayload(bytes memory payload) internal pure { + _castLogPayloadViewToPure(_sendLogPayloadView)(payload); + } + + function _sendLogPayloadView(bytes memory payload) private view { + uint256 payloadLength = payload.length; + address consoleAddress = _CONSOLE2_ADDRESS; + assembly ("memory-safe") { + let payloadStart := add(payload, 32) + let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) + } + } + + function _console2_log_StdUtils(string memory p0) private pure { + _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); + } + + function _console2_log_StdUtils(string memory p0, uint256 p1) private pure { + _sendLogPayload(abi.encodeWithSignature("log(string,uint256)", p0, p1)); + } + + function _console2_log_StdUtils(string memory p0, string memory p1) private pure { + _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); + } +} diff --git a/contracts/evm/lib/forge-std/src/Test.sol b/contracts/evm/lib/forge-std/src/Test.sol new file mode 100644 index 0000000000..204d58374f --- /dev/null +++ b/contracts/evm/lib/forge-std/src/Test.sol @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +// 💬 ABOUT +// Forge Std's default Test. + +// 🧩 MODULES +import {console} from "./console.sol"; +import {console2} from "./console2.sol"; +import {safeconsole} from "./safeconsole.sol"; +import {StdAssertions} from "./StdAssertions.sol"; +import {StdChains} from "./StdChains.sol"; +import {StdCheats} from "./StdCheats.sol"; +import {StdConstants} from "./StdConstants.sol"; +import {stdError} from "./StdError.sol"; +import {StdInvariant} from "./StdInvariant.sol"; +import {stdJson} from "./StdJson.sol"; +import {stdMath} from "./StdMath.sol"; +import {StdStorage, stdStorage} from "./StdStorage.sol"; +import {StdStyle} from "./StdStyle.sol"; +import {stdToml} from "./StdToml.sol"; +import {StdUtils} from "./StdUtils.sol"; +import {Vm} from "./Vm.sol"; + +// 📦 BOILERPLATE +import {TestBase} from "./Base.sol"; + +/// @notice Default base contract for Forge tests. +/// @dev Includes assertions, cheatcodes, invariant helpers, chain helpers, utility helpers, and console modules. +abstract contract Test is TestBase, StdAssertions, StdChains, StdCheats, StdInvariant, StdUtils { + /// @notice Marker used by Forge to identify test contracts. + /// @dev The generated `IS_TEST()` getter must return true. + bool public IS_TEST = true; +} diff --git a/contracts/evm/lib/forge-std/src/Vm.sol b/contracts/evm/lib/forge-std/src/Vm.sol new file mode 100644 index 0000000000..3ff0018b6e --- /dev/null +++ b/contracts/evm/lib/forge-std/src/Vm.sol @@ -0,0 +1,2700 @@ +// Automatically @generated by scripts/vm.py. Do not modify manually. + +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +/// The `VmSafe` interface does not allow manipulation of the EVM state or other actions that may +/// result in Script simulations differing from on-chain execution. It is recommended to only use +/// these cheats in scripts. +interface VmSafe { + /// A modification applied to either `msg.sender` or `tx.origin`. Returned by `readCallers`. + enum CallerMode { + // No caller modification is currently active. + None, + // A one time broadcast triggered by a `vm.broadcast()` call is currently active. + Broadcast, + // A recurrent broadcast triggered by a `vm.startBroadcast()` call is currently active. + RecurrentBroadcast, + // A one time prank triggered by a `vm.prank()` call is currently active. + Prank, + // A recurrent prank triggered by a `vm.startPrank()` call is currently active. + RecurrentPrank + } + + /// The kind of account access that occurred. + enum AccountAccessKind { + // The account was called. + Call, + // The account was called via delegatecall. + DelegateCall, + // The account was called via callcode. + CallCode, + // The account was called via staticcall. + StaticCall, + // The account was created. + Create, + // The account was selfdestructed. + SelfDestruct, + // Synthetic access indicating the current context has resumed after a previous sub-context (AccountAccess). + Resume, + // The account's balance was read. + Balance, + // The account's codesize was read. + Extcodesize, + // The account's codehash was read. + Extcodehash, + // The account's code was copied. + Extcodecopy + } + + /// Forge execution contexts. + enum ForgeContext { + // Test group execution context (test, coverage or snapshot). + TestGroup, + // `forge test` execution context. + Test, + // `forge coverage` execution context. + Coverage, + // `forge snapshot` execution context. + Snapshot, + // Script group execution context (dry run, broadcast or resume). + ScriptGroup, + // `forge script` execution context. + ScriptDryRun, + // `forge script --broadcast` execution context. + ScriptBroadcast, + // `forge script --resume` execution context. + ScriptResume, + // Unknown `forge` execution context. + Unknown + } + + /// The transaction type (`txType`) of the broadcast. + enum BroadcastTxType { + // Represents a CALL broadcast tx. + Call, + // Represents a CREATE broadcast tx. + Create, + // Represents a CREATE2 broadcast tx. + Create2 + } + + /// An Ethereum log. Returned by `getRecordedLogs`. + struct Log { + // The topics of the log, including the signature, if any. + bytes32[] topics; + // The raw data of the log. + bytes data; + // The address of the log's emitter. + address emitter; + } + + /// An RPC URL and its alias. Returned by `rpcUrlStructs`. + struct Rpc { + // The alias of the RPC URL. + string key; + // The RPC URL. + string url; + } + + /// An RPC log object. Returned by `eth_getLogs`. + struct EthGetLogs { + // The address of the log's emitter. + address emitter; + // The topics of the log, including the signature, if any. + bytes32[] topics; + // The raw data of the log. + bytes data; + // The block hash. + bytes32 blockHash; + // The block number. + uint64 blockNumber; + // The transaction hash. + bytes32 transactionHash; + // The transaction index in the block. + uint64 transactionIndex; + // The log index. + uint256 logIndex; + // Whether the log was removed. + bool removed; + } + + /// A single entry in a directory listing. Returned by `readDir`. + struct DirEntry { + // The error message, if any. + string errorMessage; + // The path of the entry. + string path; + // The depth of the entry. + uint64 depth; + // Whether the entry is a directory. + bool isDir; + // Whether the entry is a symlink. + bool isSymlink; + } + + /// Metadata information about a file. + /// This structure is returned from the `fsMetadata` function and represents known + /// metadata about a file such as its permissions, size, modification + /// times, etc. + struct FsMetadata { + // True if this metadata is for a directory. + bool isDir; + // True if this metadata is for a symlink. + bool isSymlink; + // The size of the file, in bytes, this metadata is for. + uint256 length; + // True if this metadata is for a readonly (unwritable) file. + bool readOnly; + // The last modification time listed in this metadata. + uint256 modified; + // The last access time of this metadata. + uint256 accessed; + // The creation time listed in this metadata. + uint256 created; + } + + /// A wallet with a public and private key. + struct Wallet { + // The wallet's address. + address addr; + // The wallet's public key `X`. + uint256 publicKeyX; + // The wallet's public key `Y`. + uint256 publicKeyY; + // The wallet's private key. + uint256 privateKey; + } + + /// The result of a `tryFfi` call. + struct FfiResult { + // The exit code of the call. + int32 exitCode; + // The optionally hex-decoded `stdout` data. + bytes stdout; + // The `stderr` data. + bytes stderr; + } + + /// Information on the chain and fork. + struct ChainInfo { + // The fork identifier. Set to zero if no fork is active. + uint256 forkId; + // The chain ID of the current fork. + uint256 chainId; + } + + /// Information about a blockchain. + struct Chain { + // The chain name. + string name; + // The chain's Chain ID. + uint256 chainId; + // The chain's alias. (i.e. what gets specified in `foundry.toml`). + string chainAlias; + // A default RPC endpoint for this chain. + string rpcUrl; + } + + /// The result of a `stopAndReturnStateDiff` call. + struct AccountAccess { + // The chain and fork the access occurred. + ChainInfo chainInfo; + // The kind of account access that determines what the account is. + // If kind is Call, DelegateCall, StaticCall or CallCode, then the account is the callee. + // If kind is Create, then the account is the newly created account. + // If kind is SelfDestruct, then the account is the selfdestruct recipient. + // If kind is a Resume, then account represents a account context that has resumed. + AccountAccessKind kind; + // The account that was accessed. + // It's either the account created, callee or a selfdestruct recipient for CREATE, CALL or SELFDESTRUCT. + address account; + // What accessed the account. + address accessor; + // If the account was initialized or empty prior to the access. + // An account is considered initialized if it has code, a + // non-zero nonce, or a non-zero balance. + bool initialized; + // The previous balance of the accessed account. + uint256 oldBalance; + // The potential new balance of the accessed account. + // That is, all balance changes are recorded here, even if reverts occurred. + uint256 newBalance; + // Code of the account deployed by CREATE. + bytes deployedCode; + // Value passed along with the account access + uint256 value; + // Input data provided to the CREATE or CALL + bytes data; + // If this access reverted in either the current or parent context. + bool reverted; + // An ordered list of storage accesses made during an account access operation. + StorageAccess[] storageAccesses; + // Call depth traversed during the recording of state differences + uint64 depth; + // The previous nonce of the accessed account. + uint64 oldNonce; + // The new nonce of the accessed account. + uint64 newNonce; + } + + /// The storage accessed during an `AccountAccess`. + struct StorageAccess { + // The account whose storage was accessed. + address account; + // The slot that was accessed. + bytes32 slot; + // If the access was a write. + bool isWrite; + // The previous value of the slot. + bytes32 previousValue; + // The new value of the slot. + bytes32 newValue; + // If the access was reverted. + bool reverted; + } + + /// Gas used. Returned by `lastCallGas` and `lastFrameGas`. + struct Gas { + // The gas limit of the call. + uint64 gasLimit; + // The total gas used. + uint64 gasTotalUsed; + // DEPRECATED: The amount of gas used for memory expansion. Ref: + uint64 gasMemoryUsed; + // The amount of gas refunded. + int64 gasRefunded; + // The amount of gas remaining. + uint64 gasRemaining; + } + + /// The result of the `stopDebugTraceRecording` call + struct DebugStep { + // The stack before executing the step of the run. + // stack\[0\] represents the top of the stack. + // and only stack data relevant to the opcode execution is contained. + uint256[] stack; + // The memory input data before executing the step of the run. + // only input data relevant to the opcode execution is contained. + // e.g. for MLOAD, it will have memory\[offset:offset+32\] copied here. + // the offset value can be get by the stack data. + bytes memoryInput; + // The opcode that was accessed. + uint8 opcode; + // The call depth of the step. + uint64 depth; + // Whether the call end up with out of gas error. + bool isOutOfGas; + // The contract address where the opcode is running + address contractAddr; + } + + /// Represents a transaction's broadcast details. + struct BroadcastTxSummary { + // The hash of the transaction that was broadcasted + bytes32 txHash; + // Represent the type of transaction among CALL, CREATE, CREATE2 + BroadcastTxType txType; + // The address of the contract that was called or created. + // This is address of the contract that is created if the txType is CREATE or CREATE2. + address contractAddress; + // The block number the transaction landed in. + uint64 blockNumber; + // Status of the transaction, retrieved from the transaction receipt. + bool success; + } + + /// Holds a signed EIP-7702 authorization for an authority account to delegate to an implementation. + struct SignedDelegation { + // The y-parity of the recovered secp256k1 signature (0 or 1). + uint8 v; + // First 32 bytes of the signature. + bytes32 r; + // Second 32 bytes of the signature. + bytes32 s; + // The current nonce of the authority account at signing time. + // Used to ensure signature can't be replayed after account nonce changes. + uint64 nonce; + // Address of the contract implementation that will be delegated to. + // Gets encoded into delegation code: 0xef0100 || implementation. + address implementation; + } + + /// Represents a "potential" revert reason from a single subsequent call when using `vm.assumeNoReverts`. + /// Reverts that match will result in a FOUNDRY::ASSUME rejection, whereas unmatched reverts will be surfaced + /// as normal. + struct PotentialRevert { + // The allowed origin of the revert opcode; address(0) allows reverts from any address + address reverter; + // When true, only matches on the beginning of the revert data, otherwise, matches on entire revert data + bool partialMatch; + // The data to use to match encountered reverts + bytes revertData; + } + + /// An EIP-2930 access list item. + struct AccessListItem { + // The address to be added in access list. + address target; + // The storage keys to be added in access list. + bytes32[] storageKeys; + } + + // ======== Crypto ======== + + /// Generates an Ed25519 key pair from a deterministic salt. + /// Returns (publicKey, privateKey) as 32-byte values. + function createEd25519Key(bytes32 salt) external pure returns (bytes32 publicKey, bytes32 privateKey); + + /// Derives a private key from the name, labels the account with that name, and returns the wallet. + function createWallet(string calldata walletLabel) external returns (Wallet memory wallet); + + /// Generates a wallet from the private key and returns the wallet. + function createWallet(uint256 privateKey) external returns (Wallet memory wallet); + + /// Generates a wallet from the private key, labels the account with that name, and returns the wallet. + function createWallet(uint256 privateKey, string calldata walletLabel) external returns (Wallet memory wallet); + + /// Derive a private key from a provided mnemonic string (or mnemonic file path) + /// at the derivation path `m/44'/60'/0'/0/{index}`. + function deriveKey(string calldata mnemonic, uint32 index) external pure returns (uint256 privateKey); + + /// Derive a private key from a provided mnemonic string (or mnemonic file path) + /// at `{derivationPath}{index}`. + function deriveKey(string calldata mnemonic, string calldata derivationPath, uint32 index) + external + pure + returns (uint256 privateKey); + + /// Derive a private key from a provided mnemonic string (or mnemonic file path) in the specified language + /// at the derivation path `m/44'/60'/0'/0/{index}`. + function deriveKey(string calldata mnemonic, uint32 index, string calldata language) + external + pure + returns (uint256 privateKey); + + /// Derive a private key from a provided mnemonic string (or mnemonic file path) in the specified language + /// at `{derivationPath}{index}`. + function deriveKey(string calldata mnemonic, string calldata derivationPath, uint32 index, string calldata language) + external + pure + returns (uint256 privateKey); + + /// Adds the secp256k1 affine points `point1 = (pointX1, pointY1)` and + /// `point2 = (pointX2, pointY2)`. + /// The point at infinity is represented as `(0, 0)`. + function ecAddAffine(uint256 pointX1, uint256 pointY1, uint256 pointX2, uint256 pointY2) + external + pure + returns (uint256 resultX, uint256 resultY); + + /// Adds the secp256k1 projective points `point1 = (pointX1, pointY1, pointZ1)` and + /// `point2 = (pointX2, pointY2, pointZ2)`. + /// The point at infinity is accepted as `(0, y, 0)` for any non-zero `y` and returned as + /// `(0, 1, 0)`. Any other result is normalized to `(x, y, 1)`. + function ecAddProjective( + uint256 pointX1, + uint256 pointY1, + uint256 pointZ1, + uint256 pointX2, + uint256 pointY2, + uint256 pointZ2 + ) external pure returns (uint256 resultX, uint256 resultY, uint256 resultZ); + + /// Multiplies the secp256k1 affine point `(pointX, pointY)` by `scalar`. + /// The scalar is reduced modulo the secp256k1 group order. + /// The point at infinity is represented as `(0, 0)`. + function ecMulAffine(uint256 pointX, uint256 pointY, uint256 scalar) + external + pure + returns (uint256 resultX, uint256 resultY); + + /// Multiplies the secp256k1 projective point `(pointX, pointY, pointZ)` by `scalar`. + /// The scalar is reduced modulo the secp256k1 group order. + /// The point at infinity is accepted as `(0, y, 0)` for any non-zero `y` and returned as + /// `(0, 1, 0)`. Any other result is normalized to `(x, y, 1)`. + function ecMulProjective(uint256 pointX, uint256 pointY, uint256 pointZ, uint256 scalar) + external + pure + returns (uint256 resultX, uint256 resultY, uint256 resultZ); + + /// Derives the Ed25519 public key from a private key. + function publicKeyEd25519(bytes32 privateKey) external pure returns (bytes32 publicKey); + + /// Derives secp256r1 public key from the provided `privateKey`. + function publicKeyP256(uint256 privateKey) external pure returns (uint256 publicKeyX, uint256 publicKeyY); + + /// Adds a private key to the local forge wallet and returns the address. + function rememberKey(uint256 privateKey) external returns (address keyAddr); + + /// Derive a set number of wallets from a mnemonic at the derivation path `m/44'/60'/0'/0/{0..count}`. + /// The respective private keys are saved to the local forge wallet for later use and their addresses are returned. + function rememberKeys(string calldata mnemonic, string calldata derivationPath, uint32 count) + external + returns (address[] memory keyAddrs); + + /// Derive a set number of wallets from a mnemonic in the specified language at the derivation path `m/44'/60'/0'/0/{0..count}`. + /// The respective private keys are saved to the local forge wallet for later use and their addresses are returned. + function rememberKeys( + string calldata mnemonic, + string calldata derivationPath, + string calldata language, + uint32 count + ) external returns (address[] memory keyAddrs); + + /// Signs data with a `Wallet`. + /// Returns a compact signature (`r`, `vs`) as per EIP-2098, where `vs` encodes both the + /// signature's `s` value, and the recovery id `v` in a single bytes32. + /// This format reduces the signature size from 65 to 64 bytes. + function signCompact(Wallet calldata wallet, bytes32 digest) external pure returns (bytes32 r, bytes32 vs); + + /// Signs `digest` with `privateKey` using the secp256k1 curve. + /// Returns a compact signature (`r`, `vs`) as per EIP-2098, where `vs` encodes both the + /// signature's `s` value, and the recovery id `v` in a single bytes32. + /// This format reduces the signature size from 65 to 64 bytes. + function signCompact(uint256 privateKey, bytes32 digest) external pure returns (bytes32 r, bytes32 vs); + + /// Signs `digest` with signer provided to script using the secp256k1 curve. + /// Returns a compact signature (`r`, `vs`) as per EIP-2098, where `vs` encodes both the + /// signature's `s` value, and the recovery id `v` in a single bytes32. + /// This format reduces the signature size from 65 to 64 bytes. + /// If `--sender` is provided, the signer with provided address is used, otherwise, + /// if exactly one signer is provided to the script, that signer is used. + /// Raises error if signer passed through `--sender` does not match any unlocked signers or + /// if `--sender` is not provided and not exactly one signer is passed to the script. + function signCompact(bytes32 digest) external pure returns (bytes32 r, bytes32 vs); + + /// Signs `digest` with signer provided to script using the secp256k1 curve. + /// Returns a compact signature (`r`, `vs`) as per EIP-2098, where `vs` encodes both the + /// signature's `s` value, and the recovery id `v` in a single bytes32. + /// This format reduces the signature size from 65 to 64 bytes. + /// Raises error if none of the signers passed into the script have provided address. + function signCompact(address signer, bytes32 digest) external pure returns (bytes32 r, bytes32 vs); + + /// Signs a message with namespace using Ed25519. + /// The signature covers namespace || message for domain separation. + /// Returns a 64-byte Ed25519 signature. + function signEd25519(bytes calldata namespace, bytes calldata message, bytes32 privateKey) + external + pure + returns (bytes memory signature); + + /// Signs `digest` as a Tempo V2 keychain signature for `account` using a secp256k1 access key. + /// Returns the encoded signature bytes accepted by `SignatureVerifier.verifyKeychain`. + function signKeychain(uint256 privateKey, address account, bytes32 digest) + external + pure + returns (bytes memory signature); + + /// Signs `digest` as a Tempo V2 keychain signature for `account` using a root or admin secp256k1 key. + /// Returns the encoded signature bytes accepted by `SignatureVerifier.verifyKeychainAdmin`. + /// The supplied `digest` should already be domain-separated with chain ID, contract address, + /// and account address. + function signKeychainAdmin(uint256 privateKey, address account, bytes32 digest) + external + pure + returns (bytes memory signature); + + /// Signs `digest` with `privateKey` using the secp256r1 curve. + function signP256(uint256 privateKey, bytes32 digest) external pure returns (bytes32 r, bytes32 s); + + /// Signs `digest` with `privateKey` on the secp256k1 curve, using the given `nonce` + /// as the raw ephemeral k value in ECDSA (instead of deriving it deterministically). + function signWithNonceUnsafe(uint256 privateKey, bytes32 digest, uint256 nonce) + external + pure + returns (uint8 v, bytes32 r, bytes32 s); + + /// Signs data with a `Wallet`. + function sign(Wallet calldata wallet, bytes32 digest) external pure returns (uint8 v, bytes32 r, bytes32 s); + + /// Signs `digest` with `privateKey` using the secp256k1 curve. + function sign(uint256 privateKey, bytes32 digest) external pure returns (uint8 v, bytes32 r, bytes32 s); + + /// Signs `digest` with signer provided to script using the secp256k1 curve. + /// If `--sender` is provided, the signer with provided address is used, otherwise, + /// if exactly one signer is provided to the script, that signer is used. + /// Raises error if signer passed through `--sender` does not match any unlocked signers or + /// if `--sender` is not provided and not exactly one signer is passed to the script. + function sign(bytes32 digest) external pure returns (uint8 v, bytes32 r, bytes32 s); + + /// Signs `digest` with signer provided to script using the secp256k1 curve. + /// Raises error if none of the signers passed into the script have provided address. + function sign(address signer, bytes32 digest) external pure returns (uint8 v, bytes32 r, bytes32 s); + + /// Verifies an Ed25519 signature over namespace || message. + /// Returns true if signature is valid, false otherwise. + function verifyEd25519( + bytes calldata signature, + bytes calldata namespace, + bytes calldata message, + bytes32 publicKey + ) external pure returns (bool valid); + + // ======== Environment ======== + + /// Gets the environment variable `name` and parses it as `address`. + /// Reverts if the variable was not found or could not be parsed. + function envAddress(string calldata name) external view returns (address value); + + /// Gets the environment variable `name` and parses it as an array of `address`, delimited by `delim`. + /// Reverts if the variable was not found or could not be parsed. + function envAddress(string calldata name, string calldata delim) external view returns (address[] memory value); + + /// Gets the environment variable `name` and parses it as `bool`. + /// Reverts if the variable was not found or could not be parsed. + function envBool(string calldata name) external view returns (bool value); + + /// Gets the environment variable `name` and parses it as an array of `bool`, delimited by `delim`. + /// Reverts if the variable was not found or could not be parsed. + function envBool(string calldata name, string calldata delim) external view returns (bool[] memory value); + + /// Gets the environment variable `name` and parses it as `bytes32`. + /// Reverts if the variable was not found or could not be parsed. + function envBytes32(string calldata name) external view returns (bytes32 value); + + /// Gets the environment variable `name` and parses it as an array of `bytes32`, delimited by `delim`. + /// Reverts if the variable was not found or could not be parsed. + function envBytes32(string calldata name, string calldata delim) external view returns (bytes32[] memory value); + + /// Gets the environment variable `name` and parses it as `bytes`. + /// Reverts if the variable was not found or could not be parsed. + function envBytes(string calldata name) external view returns (bytes memory value); + + /// Gets the environment variable `name` and parses it as an array of `bytes`, delimited by `delim`. + /// Reverts if the variable was not found or could not be parsed. + function envBytes(string calldata name, string calldata delim) external view returns (bytes[] memory value); + + /// Gets the environment variable `name` and returns true if it exists, else returns false. + function envExists(string calldata name) external view returns (bool result); + + /// Gets the environment variable `name` and parses it as `int256`. + /// Reverts if the variable was not found or could not be parsed. + function envInt(string calldata name) external view returns (int256 value); + + /// Gets the environment variable `name` and parses it as an array of `int256`, delimited by `delim`. + /// Reverts if the variable was not found or could not be parsed. + function envInt(string calldata name, string calldata delim) external view returns (int256[] memory value); + + /// Gets the environment variable `name` and parses it as `bool`. + /// Reverts if the variable could not be parsed. + /// Returns `defaultValue` if the variable was not found. + function envOr(string calldata name, bool defaultValue) external view returns (bool value); + + /// Gets the environment variable `name` and parses it as `uint256`. + /// Reverts if the variable could not be parsed. + /// Returns `defaultValue` if the variable was not found. + function envOr(string calldata name, uint256 defaultValue) external view returns (uint256 value); + + /// Gets the environment variable `name` and parses it as an array of `address`, delimited by `delim`. + /// Reverts if the variable could not be parsed. + /// Returns `defaultValue` if the variable was not found. + function envOr(string calldata name, string calldata delim, address[] calldata defaultValue) + external + view + returns (address[] memory value); + + /// Gets the environment variable `name` and parses it as an array of `bytes32`, delimited by `delim`. + /// Reverts if the variable could not be parsed. + /// Returns `defaultValue` if the variable was not found. + function envOr(string calldata name, string calldata delim, bytes32[] calldata defaultValue) + external + view + returns (bytes32[] memory value); + + /// Gets the environment variable `name` and parses it as an array of `string`, delimited by `delim`. + /// Reverts if the variable could not be parsed. + /// Returns `defaultValue` if the variable was not found. + function envOr(string calldata name, string calldata delim, string[] calldata defaultValue) + external + view + returns (string[] memory value); + + /// Gets the environment variable `name` and parses it as an array of `bytes`, delimited by `delim`. + /// Reverts if the variable could not be parsed. + /// Returns `defaultValue` if the variable was not found. + function envOr(string calldata name, string calldata delim, bytes[] calldata defaultValue) + external + view + returns (bytes[] memory value); + + /// Gets the environment variable `name` and parses it as `int256`. + /// Reverts if the variable could not be parsed. + /// Returns `defaultValue` if the variable was not found. + function envOr(string calldata name, int256 defaultValue) external view returns (int256 value); + + /// Gets the environment variable `name` and parses it as `address`. + /// Reverts if the variable could not be parsed. + /// Returns `defaultValue` if the variable was not found. + function envOr(string calldata name, address defaultValue) external view returns (address value); + + /// Gets the environment variable `name` and parses it as `bytes32`. + /// Reverts if the variable could not be parsed. + /// Returns `defaultValue` if the variable was not found. + function envOr(string calldata name, bytes32 defaultValue) external view returns (bytes32 value); + + /// Gets the environment variable `name` and parses it as `string`. + /// Reverts if the variable could not be parsed. + /// Returns `defaultValue` if the variable was not found. + function envOr(string calldata name, string calldata defaultValue) external view returns (string memory value); + + /// Gets the environment variable `name` and parses it as `bytes`. + /// Reverts if the variable could not be parsed. + /// Returns `defaultValue` if the variable was not found. + function envOr(string calldata name, bytes calldata defaultValue) external view returns (bytes memory value); + + /// Gets the environment variable `name` and parses it as an array of `bool`, delimited by `delim`. + /// Reverts if the variable could not be parsed. + /// Returns `defaultValue` if the variable was not found. + function envOr(string calldata name, string calldata delim, bool[] calldata defaultValue) + external + view + returns (bool[] memory value); + + /// Gets the environment variable `name` and parses it as an array of `uint256`, delimited by `delim`. + /// Reverts if the variable could not be parsed. + /// Returns `defaultValue` if the variable was not found. + function envOr(string calldata name, string calldata delim, uint256[] calldata defaultValue) + external + view + returns (uint256[] memory value); + + /// Gets the environment variable `name` and parses it as an array of `int256`, delimited by `delim`. + /// Reverts if the variable could not be parsed. + /// Returns `defaultValue` if the variable was not found. + function envOr(string calldata name, string calldata delim, int256[] calldata defaultValue) + external + view + returns (int256[] memory value); + + /// Gets the environment variable `name` and parses it as `string`. + /// Reverts if the variable was not found or could not be parsed. + function envString(string calldata name) external view returns (string memory value); + + /// Gets the environment variable `name` and parses it as an array of `string`, delimited by `delim`. + /// Reverts if the variable was not found or could not be parsed. + function envString(string calldata name, string calldata delim) external view returns (string[] memory value); + + /// Gets the environment variable `name` and parses it as `uint256`. + /// Reverts if the variable was not found or could not be parsed. + function envUint(string calldata name) external view returns (uint256 value); + + /// Gets the environment variable `name` and parses it as an array of `uint256`, delimited by `delim`. + /// Reverts if the variable was not found or could not be parsed. + function envUint(string calldata name, string calldata delim) external view returns (uint256[] memory value); + + /// Returns true if `forge` command was executed in given context. + function isContext(ForgeContext context) external view returns (bool result); + + /// Resolves the env variable placeholders of a given input string. + function resolveEnv(string calldata input) external returns (string memory); + + /// Sets environment variables. + function setEnv(string calldata name, string calldata value) external; + + // ======== EVM ======== + + /// Gets all accessed reads and write slot from a `vm.record` session, for a given address. + function accesses(address target) external view returns (bytes32[] memory readSlots, bytes32[] memory writeSlots); + + /// Gets the address for a given private key. + function addr(uint256 privateKey) external pure returns (address keyAddr); + + /// Gets all the logs according to specified filter. + function eth_getLogs(uint256 fromBlock, uint256 toBlock, address target, bytes32[] calldata topics) + external + view + returns (EthGetLogs[] memory logs); + + /// Gets the current `block.blobbasefee`. + /// You should use this instead of `block.blobbasefee` if you use `vm.blobBaseFee`, as `block.blobbasefee` is assumed to be constant across a transaction, + /// and as a result will get optimized out by the compiler. + /// See https://github.com/foundry-rs/foundry/issues/6180 + function getBlobBaseFee() external view returns (uint256 blobBaseFee); + + /// Gets the current `block.number`. + /// You should use this instead of `block.number` if you use `vm.roll`, as `block.number` is assumed to be constant across a transaction, + /// and as a result will get optimized out by the compiler. + /// See https://github.com/foundry-rs/foundry/issues/6180 + function getBlockNumber() external view returns (uint256 height); + + /// Gets the current `block.timestamp`. + /// You should use this instead of `block.timestamp` if you use `vm.warp`, as `block.timestamp` is assumed to be constant across a transaction, + /// and as a result will get optimized out by the compiler. + /// See https://github.com/foundry-rs/foundry/issues/6180 + function getBlockTimestamp() external view returns (uint256 timestamp); + + /// Gets the current `block.chainid` of the currently selected environment. + /// You should use this instead of `block.chainid` if you use `vm.selectFork` or `vm.createSelectFork`, as `block.chainid` could be assumed + /// to be constant across a transaction, and as a result will get optimized out by the compiler. + /// See https://github.com/foundry-rs/foundry/issues/6180 + function getChainId() external view returns (uint256 blockChainId); + + /// Returns the test or script execution evm version. + /// **Note:** The execution evm version is not the same as the compilation one. + function getEvmVersion() external pure returns (string memory evm); + + /// Gets the map key and parent of a mapping at a given slot, for a given address. + function getMappingKeyAndParentOf(address target, bytes32 elementSlot) + external + view + returns (bool found, bytes32 key, bytes32 parent); + + /// Gets the number of elements in the mapping at the given slot, for a given address. + function getMappingLength(address target, bytes32 mappingSlot) external view returns (uint256 length); + + /// Gets the elements at index idx of the mapping at the given slot, for a given address. The + /// index must be less than the length of the mapping (i.e. the number of keys in the mapping). + function getMappingSlotAt(address target, bytes32 mappingSlot, uint256 idx) external view returns (bytes32 value); + + /// Gets the nonce of an account. + function getNonce(address account) external view returns (uint64 nonce); + + /// Get the nonce of a `Wallet`. + function getNonce(Wallet calldata wallet) external view returns (uint64 nonce); + + /// Gets the RLP encoded block header for a given block number. + /// Returns the block header in the same format as `cast block --raw`. + function getRawBlockHeader(uint256 blockNumber) external view returns (bytes memory rlpHeader); + + /// Gets all the recorded logs. + function getRecordedLogs() external view returns (Log[] memory logs); + + /// Gets all the recorded logs, in JSON format. + function getRecordedLogsJson() external view returns (string memory logsJson); + + /// Returns state diffs from current `vm.startStateDiffRecording` session. + function getStateDiff() external view returns (string memory diff); + + /// Returns state diffs from current `vm.startStateDiffRecording` session, in json format. + function getStateDiffJson() external view returns (string memory diff); + + /// Returns an array of `StorageAccess` from current `vm.stateStateDiffRecording` session + function getStorageAccesses() external view returns (StorageAccess[] memory storageAccesses); + + /// Returns an array of storage slots occupied by the specified variable. + function getStorageSlots(address target, string calldata variableName) + external + view + returns (uint256[] memory slots); + + /// Returns `true` if `spender` is on the active Tempo hardfork's implicit-approval list, + /// meaning it can pull TIP-20 tokens from `msg.sender` without a prior `approve()`. + /// Returns `false` on non-Tempo networks. + function isImplicitlyApproved(address spender) external view returns (bool implicitlyApproved); + + /// Returns true if isolated test execution is enabled. + function isIsolateMode() external view returns (bool result); + + /// Gets the gas used in the last call or create from the callee perspective. + function lastFrameGas() external view returns (Gas memory gas); + + /// Loads a storage slot from an address. + function load(address target, bytes32 slot) external view returns (bytes32 data); + + /// Pauses gas metering (i.e. gas usage is not counted). Noop if already paused. + function pauseGasMetering() external; + + /// Records all storage reads and writes. Use `accesses` to get the recorded data. + /// Subsequent calls to `record` will clear the previous data. + function record() external; + + /// Record all the transaction logs. + function recordLogs() external; + + /// Reset gas metering (i.e. gas usage is set to gas limit). + function resetGasMetering() external; + + /// Resumes gas metering (i.e. gas usage is counted again). Noop if already on. + function resumeGasMetering() external; + + /// Performs an Ethereum JSON-RPC request to the current fork URL and returns the JSON result. + function rpcJson(string calldata method, string calldata params) external returns (string memory data); + + /// Performs an Ethereum JSON-RPC request to the given endpoint and returns the JSON result. + function rpcJson(string calldata urlOrAlias, string calldata method, string calldata params) + external + returns (string memory data); + + /// Performs an Ethereum JSON-RPC request to the current fork URL. + function rpc(string calldata method, string calldata params) external returns (bytes memory data); + + /// Performs an Ethereum JSON-RPC request to the given endpoint. + function rpc(string calldata urlOrAlias, string calldata method, string calldata params) + external + returns (bytes memory data); + + /// Set the exact test or script execution evm version, e.g. `berlin`, `cancun`. + /// **Note:** The execution evm version is not the same as the compilation one. + function setEvmVersion(string calldata evm) external; + + /// Records the debug trace during the run. + function startDebugTraceRecording() external; + + /// Starts recording mapping SSTOREs for later retrieval. + function startMappingRecording() external; + + /// Record all account accesses as part of CREATE, CALL or SELFDESTRUCT opcodes in order, + /// along with the context of the calls + function startStateDiffRecording() external; + + /// Stop debug trace recording and returns the recorded debug trace. + function stopAndReturnDebugTraceRecording() external returns (DebugStep[] memory step); + + /// Returns an ordered array of all account accesses from a `vm.startStateDiffRecording` session. + function stopAndReturnStateDiff() external returns (AccountAccess[] memory accountAccesses); + + /// Stops recording mapping SSTOREs and clears the recorded data. + function stopMappingRecording() external; + + /// Stops recording storage reads and writes. + function stopRecord() external; + + /// DEPRECATED: use `lastFrameGas` instead. + /// Gets the gas used in the last call from the callee perspective. + function lastCallGas() external view returns (Gas memory gas); + + // ======== Filesystem ======== + + /// Closes file for reading, resetting the offset and allowing to read it from beginning with readLine. + /// `path` is relative to the project root. + function closeFile(string calldata path) external; + + /// Copies the contents of one file to another. This function will **overwrite** the contents of `to`. + /// On success, the total number of bytes copied is returned and it is equal to the length of the `to` file as reported by `metadata`. + /// Both `from` and `to` are relative to the project root. + function copyFile(string calldata from, string calldata to) external returns (uint64 copied); + + /// Creates a new, empty directory at the provided path. + /// This cheatcode will revert in the following situations, but is not limited to just these cases: + /// - User lacks permissions to modify `path`. + /// - A parent of the given path doesn't exist and `recursive` is false. + /// - `path` already exists and `recursive` is false. + /// `path` is relative to the project root. + function createDir(string calldata path, bool recursive) external; + + /// Get the source file path of the currently running test or script contract, + /// relative to the project root. + function currentFilePath() external view returns (string memory path); + + /// Deploys a contract from an artifact file. Takes in the relative path to the json file or the path to the + /// artifact in the form of :: or :: where and + /// / parts are optional. + /// Reverts if the target artifact contains unlinked library placeholders. + function deployCode(string calldata artifactPath) external returns (address deployedAddress); + + /// Deploys a contract from an artifact file. Takes in the relative path to the json file or the path to the + /// artifact in the form of :: or :: where and + /// / parts are optional. + /// Reverts if the target artifact contains unlinked library placeholders. + /// Additionally accepts abi-encoded constructor arguments. + function deployCode(string calldata artifactPath, bytes calldata constructorArgs) + external + returns (address deployedAddress); + + /// Deploys a contract from an artifact file. Takes in the relative path to the json file or the path to the + /// artifact in the form of :: or :: where and + /// / parts are optional. + /// Reverts if the target artifact contains unlinked library placeholders. + /// Additionally accepts `msg.value`. + function deployCode(string calldata artifactPath, uint256 value) external returns (address deployedAddress); + + /// Deploys a contract from an artifact file. Takes in the relative path to the json file or the path to the + /// artifact in the form of :: or :: where and + /// / parts are optional. + /// Reverts if the target artifact contains unlinked library placeholders. + /// Additionally accepts abi-encoded constructor arguments and `msg.value`. + function deployCode(string calldata artifactPath, bytes calldata constructorArgs, uint256 value) + external + returns (address deployedAddress); + + /// Deploys a contract from an artifact file, using the CREATE2 salt. Takes in the relative path to the json file or the path to the + /// artifact in the form of :: or :: where and + /// / parts are optional. + /// Reverts if the target artifact contains unlinked library placeholders. + function deployCode(string calldata artifactPath, bytes32 salt) external returns (address deployedAddress); + + /// Deploys a contract from an artifact file, using the CREATE2 salt. Takes in the relative path to the json file or the path to the + /// artifact in the form of :: or :: where and + /// / parts are optional. + /// Reverts if the target artifact contains unlinked library placeholders. + /// Additionally accepts abi-encoded constructor arguments. + function deployCode(string calldata artifactPath, bytes calldata constructorArgs, bytes32 salt) + external + returns (address deployedAddress); + + /// Deploys a contract from an artifact file, using the CREATE2 salt. Takes in the relative path to the json file or the path to the + /// artifact in the form of :: or :: where and + /// / parts are optional. + /// Reverts if the target artifact contains unlinked library placeholders. + /// Additionally accepts `msg.value`. + function deployCode(string calldata artifactPath, uint256 value, bytes32 salt) + external + returns (address deployedAddress); + + /// Deploys a contract from an artifact file, using the CREATE2 salt. Takes in the relative path to the json file or the path to the + /// artifact in the form of :: or :: where and + /// / parts are optional. + /// Reverts if the target artifact contains unlinked library placeholders. + /// Additionally accepts abi-encoded constructor arguments and `msg.value`. + function deployCode(string calldata artifactPath, bytes calldata constructorArgs, uint256 value, bytes32 salt) + external + returns (address deployedAddress); + + /// Returns true if the given path points to an existing entity, else returns false. + function exists(string calldata path) external view returns (bool result); + + /// Performs a foreign function call via the terminal. + function ffi(string[] calldata commandInput) external returns (bytes memory result); + + /// Given a path, query the file system to get information about a file, directory, etc. + function fsMetadata(string calldata path) external view returns (FsMetadata memory metadata); + + /// Gets the artifact path from code (aka. creation code). + function getArtifactPathByCode(bytes calldata code) external view returns (string memory path); + + /// Gets the artifact path from deployed code (aka. runtime code). + function getArtifactPathByDeployedCode(bytes calldata deployedCode) external view returns (string memory path); + + /// Returns the most recent broadcast for the given contract on `chainId` matching `txType`. + /// For example: + /// The most recent deployment can be fetched by passing `txType` as `CREATE` or `CREATE2`. + /// The most recent call can be fetched by passing `txType` as `CALL`. + function getBroadcast(string calldata contractName, uint64 chainId, BroadcastTxType txType) + external + view + returns (BroadcastTxSummary memory); + + /// Returns all broadcasts for the given contract on `chainId` with the specified `txType`. + /// Sorted such that the most recent broadcast is the first element, and the oldest is the last. i.e descending order of BroadcastTxSummary.blockNumber. + function getBroadcasts(string calldata contractName, uint64 chainId, BroadcastTxType txType) + external + view + returns (BroadcastTxSummary[] memory); + + /// Returns all broadcasts for the given contract on `chainId`. + /// Sorted such that the most recent broadcast is the first element, and the oldest is the last. i.e descending order of BroadcastTxSummary.blockNumber. + function getBroadcasts(string calldata contractName, uint64 chainId) + external + view + returns (BroadcastTxSummary[] memory); + + /// Gets the creation bytecode from an artifact file. Takes in the relative path to the json file or the path to the + /// artifact in the form of :: or :: where and + /// / parts are optional. Use to select artifacts compiled with a specific profile + /// from foundry.toml. + function getCode(string calldata artifactPath) external view returns (bytes memory creationBytecode); + + /// Gets the deployed bytecode from an artifact file. Takes in the relative path to the json file or the path to the + /// artifact in the form of :: or :: where and + /// / parts are optional. + function getDeployedCode(string calldata artifactPath) external view returns (bytes memory runtimeBytecode); + + /// Returns the most recent deployment for the current `chainId`. + function getDeployment(string calldata contractName) external view returns (address deployedAddress); + + /// Returns the most recent deployment for the given contract on `chainId` + function getDeployment(string calldata contractName, uint64 chainId) external view returns (address deployedAddress); + + /// Returns all deployments for the given contract on `chainId` + /// Sorted in descending order of deployment time i.e descending order of BroadcastTxSummary.blockNumber. + /// The most recent deployment is the first element, and the oldest is the last. + function getDeployments(string calldata contractName, uint64 chainId) + external + view + returns (address[] memory deployedAddresses); + + /// Gets all function selectors from a contract artifact. Takes in the relative path to the json file or the path to the + /// artifact in the form of :: where and parts are optional. + function getSelectors(string calldata artifactPath) external view returns (bytes4[] memory selectors); + + /// Returns true if the path exists on disk and is pointing at a directory, else returns false. + function isDir(string calldata path) external view returns (bool result); + + /// Returns true if the path exists on disk and is pointing at a regular file, else returns false. + function isFile(string calldata path) external view returns (bool result); + + /// Get the path of the current project root. + function projectRoot() external view returns (string memory path); + + /// Prompts the user for a string value in the terminal. + function prompt(string calldata promptText) external returns (string memory input); + + /// Prompts the user for an address in the terminal. + function promptAddress(string calldata promptText) external returns (address); + + /// Prompts the user for a hidden string value in the terminal. + function promptSecret(string calldata promptText) external returns (string memory input); + + /// Prompts the user for hidden uint256 in the terminal (usually pk). + function promptSecretUint(string calldata promptText) external returns (uint256); + + /// Prompts the user for uint256 in the terminal. + function promptUint(string calldata promptText) external returns (uint256); + + /// Reads the directory at the given path recursively, up to `maxDepth`. + /// `maxDepth` defaults to 1, meaning only the direct children of the given directory will be returned. + /// Follows symbolic links if `followLinks` is true. + function readDir(string calldata path) external view returns (DirEntry[] memory entries); + + /// See `readDir(string)`. + function readDir(string calldata path, uint64 maxDepth) external view returns (DirEntry[] memory entries); + + /// See `readDir(string)`. + function readDir(string calldata path, uint64 maxDepth, bool followLinks) + external + view + returns (DirEntry[] memory entries); + + /// Reads the entire content of file to string. `path` is relative to the project root. + function readFile(string calldata path) external view returns (string memory data); + + /// Reads the entire content of file as binary. `path` is relative to the project root. + function readFileBinary(string calldata path) external view returns (bytes memory data); + + /// Reads next line of file to string. + function readLine(string calldata path) external view returns (string memory line); + + /// Reads a symbolic link, returning the path that the link points to. + /// This cheatcode will revert in the following situations, but is not limited to just these cases: + /// - `path` is not a symbolic link. + /// - `path` does not exist. + function readLink(string calldata linkPath) external view returns (string memory targetPath); + + /// Removes a directory at the provided path. + /// This cheatcode will revert in the following situations, but is not limited to just these cases: + /// - `path` doesn't exist. + /// - `path` isn't a directory. + /// - User lacks permissions to modify `path`. + /// - The directory is not empty and `recursive` is false. + /// `path` is relative to the project root. + function removeDir(string calldata path, bool recursive) external; + + /// Removes a file from the filesystem. + /// This cheatcode will revert in the following situations, but is not limited to just these cases: + /// - `path` points to a directory. + /// - The file doesn't exist. + /// - The user lacks permissions to remove the file. + /// `path` is relative to the project root. + function removeFile(string calldata path) external; + + /// Performs a foreign function call via terminal and returns the exit code, stdout, and stderr. + function tryFfi(string[] calldata commandInput) external returns (FfiResult memory result); + + /// Returns the time since unix epoch in milliseconds. + function unixTime() external view returns (uint256 milliseconds); + + /// Writes data to file, creating a file if it does not exist, and entirely replacing its contents if it does. + /// `path` is relative to the project root. + function writeFile(string calldata path, string calldata data) external; + + /// Writes binary data to a file, creating a file if it does not exist, and entirely replacing its contents if it does. + /// `path` is relative to the project root. + function writeFileBinary(string calldata path, bytes calldata data) external; + + /// Writes line to file, creating a file if it does not exist. + /// `path` is relative to the project root. + function writeLine(string calldata path, string calldata data) external; + + // ======== JSON ======== + + /// Checks if `key` exists in a JSON object. + function keyExistsJson(string calldata json, string calldata key) external view returns (bool); + + /// Parses a string of JSON data at `key` and coerces it to `address`. + function parseJsonAddress(string calldata json, string calldata key) external pure returns (address); + + /// Parses a string of JSON data at `key` and coerces it to `address[]`. + function parseJsonAddressArray(string calldata json, string calldata key) external pure returns (address[] memory); + + /// Returns the length of the JSON array at `key`. + function parseJsonArrayLength(string calldata json, string calldata key) external pure returns (uint256 length); + + /// Parses a string of JSON data at `key` and coerces it to `bool`. + function parseJsonBool(string calldata json, string calldata key) external pure returns (bool); + + /// Parses a string of JSON data at `key` and coerces it to `bool[]`. + function parseJsonBoolArray(string calldata json, string calldata key) external pure returns (bool[] memory); + + /// Parses a string of JSON data at `key` and coerces it to `bytes`. + function parseJsonBytes(string calldata json, string calldata key) external pure returns (bytes memory); + + /// Parses a string of JSON data at `key` and coerces it to `bytes32`. + function parseJsonBytes32(string calldata json, string calldata key) external pure returns (bytes32); + + /// Parses a string of JSON data at `key` and coerces it to `bytes32[]`. + function parseJsonBytes32Array(string calldata json, string calldata key) external pure returns (bytes32[] memory); + + /// Parses a string of JSON data at `key` and coerces it to `bytes[]`. + function parseJsonBytesArray(string calldata json, string calldata key) external pure returns (bytes[] memory); + + /// Parses a string of JSON data at `key` and coerces it to `int256`. + function parseJsonInt(string calldata json, string calldata key) external pure returns (int256); + + /// Parses a string of JSON data at `key` and coerces it to `int256[]`. + function parseJsonIntArray(string calldata json, string calldata key) external pure returns (int256[] memory); + + /// Returns an array of all the keys in a JSON object. + function parseJsonKeys(string calldata json, string calldata key) external pure returns (string[] memory keys); + + /// Parses a string of JSON data at `key` and coerces it to `string`. + function parseJsonString(string calldata json, string calldata key) external pure returns (string memory); + + /// Parses a string of JSON data at `key` and coerces it to `string[]`. + function parseJsonStringArray(string calldata json, string calldata key) external pure returns (string[] memory); + + /// Parses a string of JSON data at `key` and coerces it to type array corresponding to `typeDescription`. + function parseJsonTypeArray(string calldata json, string calldata key, string calldata typeDescription) + external + pure + returns (bytes memory); + + /// Parses a string of JSON data and coerces it to type corresponding to `typeDescription`. + function parseJsonType(string calldata json, string calldata typeDescription) external pure returns (bytes memory); + + /// Parses a string of JSON data at `key` and coerces it to type corresponding to `typeDescription`. + function parseJsonType(string calldata json, string calldata key, string calldata typeDescription) + external + pure + returns (bytes memory); + + /// Parses a string of JSON data at `key` and coerces it to `uint256`. + function parseJsonUint(string calldata json, string calldata key) external pure returns (uint256); + + /// Parses a string of JSON data at `key` and coerces it to `uint256[]`. + function parseJsonUintArray(string calldata json, string calldata key) external pure returns (uint256[] memory); + + /// ABI-encodes a JSON object. + function parseJson(string calldata json) external pure returns (bytes memory abiEncodedData); + + /// ABI-encodes a JSON object at `key`. + function parseJson(string calldata json, string calldata key) external pure returns (bytes memory abiEncodedData); + + /// See `serializeJson`. + function serializeAddress(string calldata objectKey, string calldata valueKey, address value) + external + returns (string memory json); + + /// See `serializeJson`. + function serializeAddress(string calldata objectKey, string calldata valueKey, address[] calldata values) + external + returns (string memory json); + + /// See `serializeJson`. + function serializeBool(string calldata objectKey, string calldata valueKey, bool value) + external + returns (string memory json); + + /// See `serializeJson`. + function serializeBool(string calldata objectKey, string calldata valueKey, bool[] calldata values) + external + returns (string memory json); + + /// See `serializeJson`. + function serializeBytes32(string calldata objectKey, string calldata valueKey, bytes32 value) + external + returns (string memory json); + + /// See `serializeJson`. + function serializeBytes32(string calldata objectKey, string calldata valueKey, bytes32[] calldata values) + external + returns (string memory json); + + /// See `serializeJson`. + function serializeBytes(string calldata objectKey, string calldata valueKey, bytes calldata value) + external + returns (string memory json); + + /// See `serializeJson`. + function serializeBytes(string calldata objectKey, string calldata valueKey, bytes[] calldata values) + external + returns (string memory json); + + /// See `serializeJson`. + function serializeInt(string calldata objectKey, string calldata valueKey, int256 value) + external + returns (string memory json); + + /// See `serializeJson`. + function serializeInt(string calldata objectKey, string calldata valueKey, int256[] calldata values) + external + returns (string memory json); + + /// Serializes a key and value to a JSON object stored in-memory that can be later written to a file. + /// Returns the stringified version of the specific JSON file up to that moment. + function serializeJson(string calldata objectKey, string calldata value) external returns (string memory json); + + /// See `serializeJson`. + function serializeJsonType(string calldata typeDescription, bytes calldata value) + external + pure + returns (string memory json); + + /// See `serializeJson`. + function serializeJsonType( + string calldata objectKey, + string calldata valueKey, + string calldata typeDescription, + bytes calldata value + ) external returns (string memory json); + + /// See `serializeJson`. + function serializeString(string calldata objectKey, string calldata valueKey, string calldata value) + external + returns (string memory json); + + /// See `serializeJson`. + function serializeString(string calldata objectKey, string calldata valueKey, string[] calldata values) + external + returns (string memory json); + + /// See `serializeJson`. + function serializeUintToHex(string calldata objectKey, string calldata valueKey, uint256 value) + external + returns (string memory json); + + /// See `serializeJson`. + function serializeUint(string calldata objectKey, string calldata valueKey, uint256 value) + external + returns (string memory json); + + /// See `serializeJson`. + function serializeUint(string calldata objectKey, string calldata valueKey, uint256[] calldata values) + external + returns (string memory json); + + /// Write a serialized JSON object to a file. If the file exists, it will be overwritten. + function writeJson(string calldata json, string calldata path) external; + + /// Write a serialized JSON object to an **existing** JSON file, replacing a value with key = + /// This is useful to replace a specific value of a JSON file, without having to parse the entire thing. + /// This cheatcode will create new keys if they didn't previously exist. + function writeJson(string calldata json, string calldata path, string calldata valueKey) external; + + /// Checks if `key` exists in a JSON object + /// `keyExists` is being deprecated in favor of `keyExistsJson`. It will be removed in future versions. + function keyExists(string calldata json, string calldata key) external view returns (bool); + + // ======== Scripting ======== + + /// Attach an EIP-4844 blob to the next call + function attachBlob(bytes calldata blob) external; + + /// Designate the next call as an EIP-7702 transaction + function attachDelegation(SignedDelegation calldata signedDelegation) external; + + /// Designate the next call as an EIP-7702 transaction, with optional cross-chain validity. + function attachDelegation(SignedDelegation calldata signedDelegation, bool crossChain) external; + + /// Takes a signed transaction and broadcasts it to the network. + function broadcastRawTransaction(bytes calldata data) external; + + /// Has the next call (at this call depth only) create transactions that can later be signed and sent onchain. + /// Broadcasting address is determined by checking the following in order: + /// 1. If `--sender` argument was provided, that address is used. + /// 2. If exactly one signer (e.g. private key, hw wallet, keystore) is set when `forge broadcast` is invoked, that signer is used. + /// 3. Otherwise, default foundry sender (1804c8AB1F12E6bbf3894d4083f33e07309d1f38) is used. + function broadcast() external; + + /// Has the next call (at this call depth only) create a transaction with the address provided + /// as the sender that can later be signed and sent onchain. + function broadcast(address signer) external; + + /// Has the next call (at this call depth only) create a transaction with the private key + /// provided as the sender that can later be signed and sent onchain. + function broadcast(uint256 privateKey) external; + + /// Returns addresses of available unlocked wallets in the script environment. + function getWallets() external view returns (address[] memory wallets); + + /// Sign an EIP-7702 authorization and designate the next call as an EIP-7702 transaction + function signAndAttachDelegation(address implementation, uint256 privateKey) + external + returns (SignedDelegation memory signedDelegation); + + /// Sign an EIP-7702 authorization and designate the next call as an EIP-7702 transaction for specific nonce + function signAndAttachDelegation(address implementation, uint256 privateKey, uint64 nonce) + external + returns (SignedDelegation memory signedDelegation); + + /// Sign an EIP-7702 authorization and designate the next call as an EIP-7702 transaction, with optional cross-chain validity. + function signAndAttachDelegation(address implementation, uint256 privateKey, bool crossChain) + external + returns (SignedDelegation memory signedDelegation); + + /// Sign an EIP-7702 authorization for delegation + function signDelegation(address implementation, uint256 privateKey) + external + returns (SignedDelegation memory signedDelegation); + + /// Sign an EIP-7702 authorization for delegation for specific nonce + function signDelegation(address implementation, uint256 privateKey, uint64 nonce) + external + returns (SignedDelegation memory signedDelegation); + + /// Sign an EIP-7702 authorization for delegation, with optional cross-chain validity. + function signDelegation(address implementation, uint256 privateKey, bool crossChain) + external + returns (SignedDelegation memory signedDelegation); + + /// Has all subsequent calls (at this call depth only) create transactions that can later be signed and sent onchain. + /// Broadcasting address is determined by checking the following in order: + /// 1. If `--sender` argument was provided, that address is used. + /// 2. If exactly one signer (e.g. private key, hw wallet, keystore) is set when `forge broadcast` is invoked, that signer is used. + /// 3. Otherwise, default foundry sender (1804c8AB1F12E6bbf3894d4083f33e07309d1f38) is used. + function startBroadcast() external; + + /// Has all subsequent calls (at this call depth only) create transactions with the address + /// provided that can later be signed and sent onchain. + function startBroadcast(address signer) external; + + /// Has all subsequent calls (at this call depth only) create transactions with the private key + /// provided that can later be signed and sent onchain. + function startBroadcast(uint256 privateKey) external; + + /// Stops collecting onchain transactions. + function stopBroadcast() external; + + // ======== String ======== + + /// Returns true if `search` is found in `subject`, false otherwise. + function contains(string calldata subject, string calldata search) external pure returns (bool result); + + /// Returns the index of the first occurrence of a `key` in an `input` string. + /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `key` is not found. + /// Returns 0 in case of an empty `key`. + function indexOf(string calldata input, string calldata key) external pure returns (uint256); + + /// Parses the given `string` into an `address`. + function parseAddress(string calldata stringifiedValue) external pure returns (address parsedValue); + + /// Parses the given `string` into a `bool`. + function parseBool(string calldata stringifiedValue) external pure returns (bool parsedValue); + + /// Parses the given `string` into `bytes`. + function parseBytes(string calldata stringifiedValue) external pure returns (bytes memory parsedValue); + + /// Parses the given `string` into a `bytes32`. + function parseBytes32(string calldata stringifiedValue) external pure returns (bytes32 parsedValue); + + /// Parses the given `string` into a `int256`. + function parseInt(string calldata stringifiedValue) external pure returns (int256 parsedValue); + + /// Parses the given `string` into a `uint256`. + function parseUint(string calldata stringifiedValue) external pure returns (uint256 parsedValue); + + /// Replaces occurrences of `from` in the given `string` with `to`. + function replace(string calldata input, string calldata from, string calldata to) + external + pure + returns (string memory output); + + /// Splits the given `string` into an array of strings divided by the `delimiter`. + function split(string calldata input, string calldata delimiter) external pure returns (string[] memory outputs); + + /// Converts the given `string` value to Lowercase. + function toLowercase(string calldata input) external pure returns (string memory output); + + /// Converts the given value to a `string`. + function toString(address value) external pure returns (string memory stringifiedValue); + + /// Converts the given value to a `string`. + function toString(bytes calldata value) external pure returns (string memory stringifiedValue); + + /// Converts the given value to a `string`. + function toString(bytes32 value) external pure returns (string memory stringifiedValue); + + /// Converts the given value to a `string`. + function toString(bool value) external pure returns (string memory stringifiedValue); + + /// Converts the given value to a `string`. + function toString(uint256 value) external pure returns (string memory stringifiedValue); + + /// Converts the given value to a `string`. + function toString(int256 value) external pure returns (string memory stringifiedValue); + + /// Converts the given `string` value to Uppercase. + function toUppercase(string calldata input) external pure returns (string memory output); + + /// Trims leading and trailing whitespace from the given `string` value. + function trim(string calldata input) external pure returns (string memory output); + + // ======== Testing ======== + + /// Compares two `uint256` values. Expects difference to be less than or equal to `maxDelta`. + /// Formats values with decimals in failure message. + function assertApproxEqAbsDecimal(uint256 left, uint256 right, uint256 maxDelta, uint256 decimals) external pure; + + /// Compares two `uint256` values. Expects difference to be less than or equal to `maxDelta`. + /// Formats values with decimals in failure message. Includes error message into revert string on failure. + function assertApproxEqAbsDecimal( + uint256 left, + uint256 right, + uint256 maxDelta, + uint256 decimals, + string calldata err + ) external pure; + + /// Compares two `int256` values. Expects difference to be less than or equal to `maxDelta`. + /// Formats values with decimals in failure message. + function assertApproxEqAbsDecimal(int256 left, int256 right, uint256 maxDelta, uint256 decimals) external pure; + + /// Compares two `int256` values. Expects difference to be less than or equal to `maxDelta`. + /// Formats values with decimals in failure message. Includes error message into revert string on failure. + function assertApproxEqAbsDecimal( + int256 left, + int256 right, + uint256 maxDelta, + uint256 decimals, + string calldata err + ) external pure; + + /// Compares two `uint256` values. Expects difference to be less than or equal to `maxDelta`. + function assertApproxEqAbs(uint256 left, uint256 right, uint256 maxDelta) external pure; + + /// Compares two `uint256` values. Expects difference to be less than or equal to `maxDelta`. + /// Includes error message into revert string on failure. + function assertApproxEqAbs(uint256 left, uint256 right, uint256 maxDelta, string calldata err) external pure; + + /// Compares two `int256` values. Expects difference to be less than or equal to `maxDelta`. + function assertApproxEqAbs(int256 left, int256 right, uint256 maxDelta) external pure; + + /// Compares two `int256` values. Expects difference to be less than or equal to `maxDelta`. + /// Includes error message into revert string on failure. + function assertApproxEqAbs(int256 left, int256 right, uint256 maxDelta, string calldata err) external pure; + + /// Compares two `uint256` values. Expects relative difference in percents to be less than or equal to `maxPercentDelta`. + /// `maxPercentDelta` is an 18 decimal fixed point number, where 1e18 == 100% + /// Formats values with decimals in failure message. + function assertApproxEqRelDecimal(uint256 left, uint256 right, uint256 maxPercentDelta, uint256 decimals) + external + pure; + + /// Compares two `uint256` values. Expects relative difference in percents to be less than or equal to `maxPercentDelta`. + /// `maxPercentDelta` is an 18 decimal fixed point number, where 1e18 == 100% + /// Formats values with decimals in failure message. Includes error message into revert string on failure. + function assertApproxEqRelDecimal( + uint256 left, + uint256 right, + uint256 maxPercentDelta, + uint256 decimals, + string calldata err + ) external pure; + + /// Compares two `int256` values. Expects relative difference in percents to be less than or equal to `maxPercentDelta`. + /// `maxPercentDelta` is an 18 decimal fixed point number, where 1e18 == 100% + /// Formats values with decimals in failure message. + function assertApproxEqRelDecimal(int256 left, int256 right, uint256 maxPercentDelta, uint256 decimals) + external + pure; + + /// Compares two `int256` values. Expects relative difference in percents to be less than or equal to `maxPercentDelta`. + /// `maxPercentDelta` is an 18 decimal fixed point number, where 1e18 == 100% + /// Formats values with decimals in failure message. Includes error message into revert string on failure. + function assertApproxEqRelDecimal( + int256 left, + int256 right, + uint256 maxPercentDelta, + uint256 decimals, + string calldata err + ) external pure; + + /// Compares two `uint256` values. Expects relative difference in percents to be less than or equal to `maxPercentDelta`. + /// `maxPercentDelta` is an 18 decimal fixed point number, where 1e18 == 100% + function assertApproxEqRel(uint256 left, uint256 right, uint256 maxPercentDelta) external pure; + + /// Compares two `uint256` values. Expects relative difference in percents to be less than or equal to `maxPercentDelta`. + /// `maxPercentDelta` is an 18 decimal fixed point number, where 1e18 == 100% + /// Includes error message into revert string on failure. + function assertApproxEqRel(uint256 left, uint256 right, uint256 maxPercentDelta, string calldata err) external pure; + + /// Compares two `int256` values. Expects relative difference in percents to be less than or equal to `maxPercentDelta`. + /// `maxPercentDelta` is an 18 decimal fixed point number, where 1e18 == 100% + function assertApproxEqRel(int256 left, int256 right, uint256 maxPercentDelta) external pure; + + /// Compares two `int256` values. Expects relative difference in percents to be less than or equal to `maxPercentDelta`. + /// `maxPercentDelta` is an 18 decimal fixed point number, where 1e18 == 100% + /// Includes error message into revert string on failure. + function assertApproxEqRel(int256 left, int256 right, uint256 maxPercentDelta, string calldata err) external pure; + + /// Asserts that two `uint256` values are equal, formatting them with decimals in failure message. + function assertEqDecimal(uint256 left, uint256 right, uint256 decimals) external pure; + + /// Asserts that two `uint256` values are equal, formatting them with decimals in failure message. + /// Includes error message into revert string on failure. + function assertEqDecimal(uint256 left, uint256 right, uint256 decimals, string calldata err) external pure; + + /// Asserts that two `int256` values are equal, formatting them with decimals in failure message. + function assertEqDecimal(int256 left, int256 right, uint256 decimals) external pure; + + /// Asserts that two `int256` values are equal, formatting them with decimals in failure message. + /// Includes error message into revert string on failure. + function assertEqDecimal(int256 left, int256 right, uint256 decimals, string calldata err) external pure; + + /// Asserts that two `bool` values are equal. + function assertEq(bool left, bool right) external pure; + + /// Asserts that two `bool` values are equal and includes error message into revert string on failure. + function assertEq(bool left, bool right, string calldata err) external pure; + + /// Asserts that two `string` values are equal. + function assertEq(string calldata left, string calldata right) external pure; + + /// Asserts that two `string` values are equal and includes error message into revert string on failure. + function assertEq(string calldata left, string calldata right, string calldata err) external pure; + + /// Asserts that two `bytes` values are equal. + function assertEq(bytes calldata left, bytes calldata right) external pure; + + /// Asserts that two `bytes` values are equal and includes error message into revert string on failure. + function assertEq(bytes calldata left, bytes calldata right, string calldata err) external pure; + + /// Asserts that two arrays of `bool` values are equal. + function assertEq(bool[] calldata left, bool[] calldata right) external pure; + + /// Asserts that two arrays of `bool` values are equal and includes error message into revert string on failure. + function assertEq(bool[] calldata left, bool[] calldata right, string calldata err) external pure; + + /// Asserts that two arrays of `uint256 values are equal. + function assertEq(uint256[] calldata left, uint256[] calldata right) external pure; + + /// Asserts that two arrays of `uint256` values are equal and includes error message into revert string on failure. + function assertEq(uint256[] calldata left, uint256[] calldata right, string calldata err) external pure; + + /// Asserts that two arrays of `int256` values are equal. + function assertEq(int256[] calldata left, int256[] calldata right) external pure; + + /// Asserts that two arrays of `int256` values are equal and includes error message into revert string on failure. + function assertEq(int256[] calldata left, int256[] calldata right, string calldata err) external pure; + + /// Asserts that two `uint256` values are equal. + function assertEq(uint256 left, uint256 right) external pure; + + /// Asserts that two arrays of `address` values are equal. + function assertEq(address[] calldata left, address[] calldata right) external pure; + + /// Asserts that two arrays of `address` values are equal and includes error message into revert string on failure. + function assertEq(address[] calldata left, address[] calldata right, string calldata err) external pure; + + /// Asserts that two arrays of `bytes32` values are equal. + function assertEq(bytes32[] calldata left, bytes32[] calldata right) external pure; + + /// Asserts that two arrays of `bytes32` values are equal and includes error message into revert string on failure. + function assertEq(bytes32[] calldata left, bytes32[] calldata right, string calldata err) external pure; + + /// Asserts that two arrays of `string` values are equal. + function assertEq(string[] calldata left, string[] calldata right) external pure; + + /// Asserts that two arrays of `string` values are equal and includes error message into revert string on failure. + function assertEq(string[] calldata left, string[] calldata right, string calldata err) external pure; + + /// Asserts that two arrays of `bytes` values are equal. + function assertEq(bytes[] calldata left, bytes[] calldata right) external pure; + + /// Asserts that two arrays of `bytes` values are equal and includes error message into revert string on failure. + function assertEq(bytes[] calldata left, bytes[] calldata right, string calldata err) external pure; + + /// Asserts that two `uint256` values are equal and includes error message into revert string on failure. + function assertEq(uint256 left, uint256 right, string calldata err) external pure; + + /// Asserts that two `int256` values are equal. + function assertEq(int256 left, int256 right) external pure; + + /// Asserts that two `int256` values are equal and includes error message into revert string on failure. + function assertEq(int256 left, int256 right, string calldata err) external pure; + + /// Asserts that two `address` values are equal. + function assertEq(address left, address right) external pure; + + /// Asserts that two `address` values are equal and includes error message into revert string on failure. + function assertEq(address left, address right, string calldata err) external pure; + + /// Asserts that two `bytes32` values are equal. + function assertEq(bytes32 left, bytes32 right) external pure; + + /// Asserts that two `bytes32` values are equal and includes error message into revert string on failure. + function assertEq(bytes32 left, bytes32 right, string calldata err) external pure; + + /// Asserts that the given condition is false. + function assertFalse(bool condition) external pure; + + /// Asserts that the given condition is false and includes error message into revert string on failure. + function assertFalse(bool condition, string calldata err) external pure; + + /// Compares two `uint256` values. Expects first value to be greater than or equal to second. + /// Formats values with decimals in failure message. + function assertGeDecimal(uint256 left, uint256 right, uint256 decimals) external pure; + + /// Compares two `uint256` values. Expects first value to be greater than or equal to second. + /// Formats values with decimals in failure message. Includes error message into revert string on failure. + function assertGeDecimal(uint256 left, uint256 right, uint256 decimals, string calldata err) external pure; + + /// Compares two `int256` values. Expects first value to be greater than or equal to second. + /// Formats values with decimals in failure message. + function assertGeDecimal(int256 left, int256 right, uint256 decimals) external pure; + + /// Compares two `int256` values. Expects first value to be greater than or equal to second. + /// Formats values with decimals in failure message. Includes error message into revert string on failure. + function assertGeDecimal(int256 left, int256 right, uint256 decimals, string calldata err) external pure; + + /// Compares two `uint256` values. Expects first value to be greater than or equal to second. + function assertGe(uint256 left, uint256 right) external pure; + + /// Compares two `uint256` values. Expects first value to be greater than or equal to second. + /// Includes error message into revert string on failure. + function assertGe(uint256 left, uint256 right, string calldata err) external pure; + + /// Compares two `int256` values. Expects first value to be greater than or equal to second. + function assertGe(int256 left, int256 right) external pure; + + /// Compares two `int256` values. Expects first value to be greater than or equal to second. + /// Includes error message into revert string on failure. + function assertGe(int256 left, int256 right, string calldata err) external pure; + + /// Compares two `uint256` values. Expects first value to be greater than second. + /// Formats values with decimals in failure message. + function assertGtDecimal(uint256 left, uint256 right, uint256 decimals) external pure; + + /// Compares two `uint256` values. Expects first value to be greater than second. + /// Formats values with decimals in failure message. Includes error message into revert string on failure. + function assertGtDecimal(uint256 left, uint256 right, uint256 decimals, string calldata err) external pure; + + /// Compares two `int256` values. Expects first value to be greater than second. + /// Formats values with decimals in failure message. + function assertGtDecimal(int256 left, int256 right, uint256 decimals) external pure; + + /// Compares two `int256` values. Expects first value to be greater than second. + /// Formats values with decimals in failure message. Includes error message into revert string on failure. + function assertGtDecimal(int256 left, int256 right, uint256 decimals, string calldata err) external pure; + + /// Compares two `uint256` values. Expects first value to be greater than second. + function assertGt(uint256 left, uint256 right) external pure; + + /// Compares two `uint256` values. Expects first value to be greater than second. + /// Includes error message into revert string on failure. + function assertGt(uint256 left, uint256 right, string calldata err) external pure; + + /// Compares two `int256` values. Expects first value to be greater than second. + function assertGt(int256 left, int256 right) external pure; + + /// Compares two `int256` values. Expects first value to be greater than second. + /// Includes error message into revert string on failure. + function assertGt(int256 left, int256 right, string calldata err) external pure; + + /// Compares two `uint256` values. Expects first value to be less than or equal to second. + /// Formats values with decimals in failure message. + function assertLeDecimal(uint256 left, uint256 right, uint256 decimals) external pure; + + /// Compares two `uint256` values. Expects first value to be less than or equal to second. + /// Formats values with decimals in failure message. Includes error message into revert string on failure. + function assertLeDecimal(uint256 left, uint256 right, uint256 decimals, string calldata err) external pure; + + /// Compares two `int256` values. Expects first value to be less than or equal to second. + /// Formats values with decimals in failure message. + function assertLeDecimal(int256 left, int256 right, uint256 decimals) external pure; + + /// Compares two `int256` values. Expects first value to be less than or equal to second. + /// Formats values with decimals in failure message. Includes error message into revert string on failure. + function assertLeDecimal(int256 left, int256 right, uint256 decimals, string calldata err) external pure; + + /// Compares two `uint256` values. Expects first value to be less than or equal to second. + function assertLe(uint256 left, uint256 right) external pure; + + /// Compares two `uint256` values. Expects first value to be less than or equal to second. + /// Includes error message into revert string on failure. + function assertLe(uint256 left, uint256 right, string calldata err) external pure; + + /// Compares two `int256` values. Expects first value to be less than or equal to second. + function assertLe(int256 left, int256 right) external pure; + + /// Compares two `int256` values. Expects first value to be less than or equal to second. + /// Includes error message into revert string on failure. + function assertLe(int256 left, int256 right, string calldata err) external pure; + + /// Compares two `uint256` values. Expects first value to be less than second. + /// Formats values with decimals in failure message. + function assertLtDecimal(uint256 left, uint256 right, uint256 decimals) external pure; + + /// Compares two `uint256` values. Expects first value to be less than second. + /// Formats values with decimals in failure message. Includes error message into revert string on failure. + function assertLtDecimal(uint256 left, uint256 right, uint256 decimals, string calldata err) external pure; + + /// Compares two `int256` values. Expects first value to be less than second. + /// Formats values with decimals in failure message. + function assertLtDecimal(int256 left, int256 right, uint256 decimals) external pure; + + /// Compares two `int256` values. Expects first value to be less than second. + /// Formats values with decimals in failure message. Includes error message into revert string on failure. + function assertLtDecimal(int256 left, int256 right, uint256 decimals, string calldata err) external pure; + + /// Compares two `uint256` values. Expects first value to be less than second. + function assertLt(uint256 left, uint256 right) external pure; + + /// Compares two `uint256` values. Expects first value to be less than second. + /// Includes error message into revert string on failure. + function assertLt(uint256 left, uint256 right, string calldata err) external pure; + + /// Compares two `int256` values. Expects first value to be less than second. + function assertLt(int256 left, int256 right) external pure; + + /// Compares two `int256` values. Expects first value to be less than second. + /// Includes error message into revert string on failure. + function assertLt(int256 left, int256 right, string calldata err) external pure; + + /// Asserts that two `uint256` values are not equal, formatting them with decimals in failure message. + function assertNotEqDecimal(uint256 left, uint256 right, uint256 decimals) external pure; + + /// Asserts that two `uint256` values are not equal, formatting them with decimals in failure message. + /// Includes error message into revert string on failure. + function assertNotEqDecimal(uint256 left, uint256 right, uint256 decimals, string calldata err) external pure; + + /// Asserts that two `int256` values are not equal, formatting them with decimals in failure message. + function assertNotEqDecimal(int256 left, int256 right, uint256 decimals) external pure; + + /// Asserts that two `int256` values are not equal, formatting them with decimals in failure message. + /// Includes error message into revert string on failure. + function assertNotEqDecimal(int256 left, int256 right, uint256 decimals, string calldata err) external pure; + + /// Asserts that two `bool` values are not equal. + function assertNotEq(bool left, bool right) external pure; + + /// Asserts that two `bool` values are not equal and includes error message into revert string on failure. + function assertNotEq(bool left, bool right, string calldata err) external pure; + + /// Asserts that two `string` values are not equal. + function assertNotEq(string calldata left, string calldata right) external pure; + + /// Asserts that two `string` values are not equal and includes error message into revert string on failure. + function assertNotEq(string calldata left, string calldata right, string calldata err) external pure; + + /// Asserts that two `bytes` values are not equal. + function assertNotEq(bytes calldata left, bytes calldata right) external pure; + + /// Asserts that two `bytes` values are not equal and includes error message into revert string on failure. + function assertNotEq(bytes calldata left, bytes calldata right, string calldata err) external pure; + + /// Asserts that two arrays of `bool` values are not equal. + function assertNotEq(bool[] calldata left, bool[] calldata right) external pure; + + /// Asserts that two arrays of `bool` values are not equal and includes error message into revert string on failure. + function assertNotEq(bool[] calldata left, bool[] calldata right, string calldata err) external pure; + + /// Asserts that two arrays of `uint256` values are not equal. + function assertNotEq(uint256[] calldata left, uint256[] calldata right) external pure; + + /// Asserts that two arrays of `uint256` values are not equal and includes error message into revert string on failure. + function assertNotEq(uint256[] calldata left, uint256[] calldata right, string calldata err) external pure; + + /// Asserts that two arrays of `int256` values are not equal. + function assertNotEq(int256[] calldata left, int256[] calldata right) external pure; + + /// Asserts that two arrays of `int256` values are not equal and includes error message into revert string on failure. + function assertNotEq(int256[] calldata left, int256[] calldata right, string calldata err) external pure; + + /// Asserts that two `uint256` values are not equal. + function assertNotEq(uint256 left, uint256 right) external pure; + + /// Asserts that two arrays of `address` values are not equal. + function assertNotEq(address[] calldata left, address[] calldata right) external pure; + + /// Asserts that two arrays of `address` values are not equal and includes error message into revert string on failure. + function assertNotEq(address[] calldata left, address[] calldata right, string calldata err) external pure; + + /// Asserts that two arrays of `bytes32` values are not equal. + function assertNotEq(bytes32[] calldata left, bytes32[] calldata right) external pure; + + /// Asserts that two arrays of `bytes32` values are not equal and includes error message into revert string on failure. + function assertNotEq(bytes32[] calldata left, bytes32[] calldata right, string calldata err) external pure; + + /// Asserts that two arrays of `string` values are not equal. + function assertNotEq(string[] calldata left, string[] calldata right) external pure; + + /// Asserts that two arrays of `string` values are not equal and includes error message into revert string on failure. + function assertNotEq(string[] calldata left, string[] calldata right, string calldata err) external pure; + + /// Asserts that two arrays of `bytes` values are not equal. + function assertNotEq(bytes[] calldata left, bytes[] calldata right) external pure; + + /// Asserts that two arrays of `bytes` values are not equal and includes error message into revert string on failure. + function assertNotEq(bytes[] calldata left, bytes[] calldata right, string calldata err) external pure; + + /// Asserts that two `uint256` values are not equal and includes error message into revert string on failure. + function assertNotEq(uint256 left, uint256 right, string calldata err) external pure; + + /// Asserts that two `int256` values are not equal. + function assertNotEq(int256 left, int256 right) external pure; + + /// Asserts that two `int256` values are not equal and includes error message into revert string on failure. + function assertNotEq(int256 left, int256 right, string calldata err) external pure; + + /// Asserts that two `address` values are not equal. + function assertNotEq(address left, address right) external pure; + + /// Asserts that two `address` values are not equal and includes error message into revert string on failure. + function assertNotEq(address left, address right, string calldata err) external pure; + + /// Asserts that two `bytes32` values are not equal. + function assertNotEq(bytes32 left, bytes32 right) external pure; + + /// Asserts that two `bytes32` values are not equal and includes error message into revert string on failure. + function assertNotEq(bytes32 left, bytes32 right, string calldata err) external pure; + + /// Asserts that the given condition is true. + function assertTrue(bool condition) external pure; + + /// Asserts that the given condition is true and includes error message into revert string on failure. + function assertTrue(bool condition, string calldata err) external pure; + + /// If the condition is false, discard this run's fuzz inputs and generate new ones. + function assume(bool condition) external pure; + + /// Skips a fuzz/invariant input unless `spender` is implicitly approved. + function assumeImplicitApproval(address spender) external view; + + /// Discard this run's fuzz inputs and generate new ones if next call reverted. + function assumeNoRevert() external pure; + + /// Discard this run's fuzz inputs and generate new ones if next call reverts with the potential revert parameters. + function assumeNoRevert(PotentialRevert calldata potentialRevert) external pure; + + /// Discard this run's fuzz inputs and generate new ones if next call reverts with the any of the potential revert parameters. + function assumeNoRevert(PotentialRevert[] calldata potentialReverts) external pure; + + /// Writes a breakpoint to jump to in the debugger. + function breakpoint(string calldata char) external pure; + + /// Writes a conditional breakpoint to jump to in the debugger. + function breakpoint(string calldata char, bool value) external pure; + + /// Returns true if the current Foundry version is greater than or equal to the given version. + /// The given version string must be in the format `major.minor.patch`. + /// This is equivalent to `foundryVersionCmp(version) >= 0`. + function foundryVersionAtLeast(string calldata version) external view returns (bool); + + /// Compares the current Foundry version with the given version string. + /// The given version string must be in the format `major.minor.patch`. + /// Returns: + /// -1 if current Foundry version is less than the given version + /// 0 if current Foundry version equals the given version + /// 1 if current Foundry version is greater than the given version + /// This result can then be used with a comparison operator against `0`. + /// For example, to check if the current Foundry version is greater than or equal to `1.0.0`: + /// `if (foundryVersionCmp("1.0.0") >= 0) { ... }` + function foundryVersionCmp(string calldata version) external view returns (int256); + + /// Returns a Chain struct for specific alias + function getChain(string calldata chainAlias) external view returns (Chain memory chain); + + /// Returns a Chain struct for specific chainId + function getChain(uint256 chainId) external view returns (Chain memory chain); + + /// Returns the Foundry version. + /// Format: -+.. + /// Sample output: 0.3.0-nightly+3cb96bde9b.1737036656.debug + /// Note: Build timestamps may vary slightly across platforms due to separate CI jobs. + /// For reliable version comparisons, use UNIX format (e.g., >= 1700000000) + /// to compare timestamps while ignoring minor time differences. + function getFoundryVersion() external view returns (string memory version); + + /// Returns the RPC url for the given alias. + function rpcUrl(string calldata rpcAlias) external view returns (string memory json); + + /// Returns all rpc urls and their aliases as structs. + function rpcUrlStructs() external view returns (Rpc[] memory urls); + + /// Returns all rpc urls and their aliases `[alias, url][]`. + function rpcUrls() external view returns (string[2][] memory urls); + + /// Suspends execution of the main thread for `duration` milliseconds. + function sleep(uint256 duration) external; + + // ======== Toml ======== + + /// Checks if `key` exists in a TOML table. + function keyExistsToml(string calldata toml, string calldata key) external view returns (bool); + + /// Parses a string of TOML data at `key` and coerces it to `address`. + function parseTomlAddress(string calldata toml, string calldata key) external pure returns (address); + + /// Parses a string of TOML data at `key` and coerces it to `address[]`. + function parseTomlAddressArray(string calldata toml, string calldata key) external pure returns (address[] memory); + + /// Parses a string of TOML data at `key` and coerces it to `bool`. + function parseTomlBool(string calldata toml, string calldata key) external pure returns (bool); + + /// Parses a string of TOML data at `key` and coerces it to `bool[]`. + function parseTomlBoolArray(string calldata toml, string calldata key) external pure returns (bool[] memory); + + /// Parses a string of TOML data at `key` and coerces it to `bytes`. + function parseTomlBytes(string calldata toml, string calldata key) external pure returns (bytes memory); + + /// Parses a string of TOML data at `key` and coerces it to `bytes32`. + function parseTomlBytes32(string calldata toml, string calldata key) external pure returns (bytes32); + + /// Parses a string of TOML data at `key` and coerces it to `bytes32[]`. + function parseTomlBytes32Array(string calldata toml, string calldata key) external pure returns (bytes32[] memory); + + /// Parses a string of TOML data at `key` and coerces it to `bytes[]`. + function parseTomlBytesArray(string calldata toml, string calldata key) external pure returns (bytes[] memory); + + /// Parses a string of TOML data at `key` and coerces it to `int256`. + function parseTomlInt(string calldata toml, string calldata key) external pure returns (int256); + + /// Parses a string of TOML data at `key` and coerces it to `int256[]`. + function parseTomlIntArray(string calldata toml, string calldata key) external pure returns (int256[] memory); + + /// Returns an array of all the keys in a TOML table. + function parseTomlKeys(string calldata toml, string calldata key) external pure returns (string[] memory keys); + + /// Parses a string of TOML data at `key` and coerces it to `string`. + function parseTomlString(string calldata toml, string calldata key) external pure returns (string memory); + + /// Parses a string of TOML data at `key` and coerces it to `string[]`. + function parseTomlStringArray(string calldata toml, string calldata key) external pure returns (string[] memory); + + /// Parses a string of TOML data at `key` and coerces it to type array corresponding to `typeDescription`. + function parseTomlTypeArray(string calldata toml, string calldata key, string calldata typeDescription) + external + pure + returns (bytes memory); + + /// Parses a string of TOML data and coerces it to type corresponding to `typeDescription`. + function parseTomlType(string calldata toml, string calldata typeDescription) external pure returns (bytes memory); + + /// Parses a string of TOML data at `key` and coerces it to type corresponding to `typeDescription`. + function parseTomlType(string calldata toml, string calldata key, string calldata typeDescription) + external + pure + returns (bytes memory); + + /// Parses a string of TOML data at `key` and coerces it to `uint256`. + function parseTomlUint(string calldata toml, string calldata key) external pure returns (uint256); + + /// Parses a string of TOML data at `key` and coerces it to `uint256[]`. + function parseTomlUintArray(string calldata toml, string calldata key) external pure returns (uint256[] memory); + + /// ABI-encodes a TOML table. + function parseToml(string calldata toml) external pure returns (bytes memory abiEncodedData); + + /// ABI-encodes a TOML table at `key`. + function parseToml(string calldata toml, string calldata key) external pure returns (bytes memory abiEncodedData); + + /// Takes serialized JSON, converts to TOML and write a serialized TOML to a file. + function writeToml(string calldata json, string calldata path) external; + + /// Takes serialized JSON, converts to TOML and write a serialized TOML table to an **existing** TOML file, replacing a value with key = + /// This is useful to replace a specific value of a TOML file, without having to parse the entire thing. + /// This cheatcode will create new keys if they didn't previously exist. + function writeToml(string calldata json, string calldata path, string calldata valueKey) external; + + // ======== Utilities ======== + + /// Returns an uint256 value bounded in given range and different from the current one. + function bound(uint256 current, uint256 min, uint256 max) external view returns (uint256); + + /// Returns an int256 value bounded in given range and different from the current one. + function bound(int256 current, int256 min, int256 max) external view returns (int256); + + /// Compute the address of a contract created with CREATE2 using the given CREATE2 deployer. + function computeCreate2Address(bytes32 salt, bytes32 initCodeHash, address deployer) external pure returns (address); + + /// Compute the address of a contract created with CREATE2 using the default CREATE2 deployer. + function computeCreate2Address(bytes32 salt, bytes32 initCodeHash) external pure returns (address); + + /// Compute the address a contract will be deployed at for a given deployer address and nonce. + function computeCreateAddress(address deployer, uint256 nonce) external pure returns (address); + + /// Generates the struct hash of the canonical EIP-712 type representation and its abi-encoded data. + /// Supports 2 different inputs: + /// 1. Name of the type (i.e. "PermitSingle"): + /// * requires previous binding generation with `forge bind-json`. + /// * bindings will be retrieved from the path configured in `foundry.toml`. + /// 2. String representation of the type (i.e. "Foo(Bar bar) Bar(uint256 baz)"). + /// * Note: the cheatcode will use the canonical type even if the input is malformed + /// with the wrong order of elements or with extra whitespaces. + function eip712HashStruct(string calldata typeNameOrDefinition, bytes calldata abiEncodedData) + external + pure + returns (bytes32 typeHash); + + /// Generates the struct hash of the canonical EIP-712 type representation and its abi-encoded data. + /// Requires previous binding generation with `forge bind-json`. + /// Params: + /// * `bindingsPath`: path where the output of `forge bind-json` is stored. + /// * `typeName`: Name of the type (i.e. "PermitSingle"). + /// * `abiEncodedData`: ABI-encoded data for the struct that is being hashed. + function eip712HashStruct(string calldata bindingsPath, string calldata typeName, bytes calldata abiEncodedData) + external + pure + returns (bytes32 typeHash); + + /// Generates the hash of the canonical EIP-712 type representation. + /// Supports 2 different inputs: + /// 1. Name of the type (i.e. "Transaction"): + /// * requires previous binding generation with `forge bind-json`. + /// * bindings will be retrieved from the path configured in `foundry.toml`. + /// 2. String representation of the type (i.e. "Foo(Bar bar) Bar(uint256 baz)"). + /// * Note: the cheatcode will output the canonical type even if the input is malformed + /// with the wrong order of elements or with extra whitespaces. + function eip712HashType(string calldata typeNameOrDefinition) external pure returns (bytes32 typeHash); + + /// Generates the hash of the canonical EIP-712 type representation. + /// Requires previous binding generation with `forge bind-json`. + /// Params: + /// * `bindingsPath`: path where the output of `forge bind-json` is stored. + /// * `typeName`: Name of the type (i.e. "Transaction"). + function eip712HashType(string calldata bindingsPath, string calldata typeName) + external + pure + returns (bytes32 typeHash); + + /// Generates a ready-to-sign digest of human-readable typed data following the EIP-712 standard. + function eip712HashTypedData(string calldata jsonData) external pure returns (bytes32 digest); + + /// Returns ENS namehash for provided string. + function ensNamehash(string calldata name) external pure returns (bytes32); + + /// RLP decodes an RLP payload into a list of bytes. + function fromRlp(bytes calldata rlp) external pure returns (bytes[] memory data); + + /// Gets the label for the specified address. + function getLabel(address account) external view returns (string memory currentLabel); + + /// Labels an address in call traces. + function label(address account, string calldata newLabel) external; + + /// Pauses collection of call traces. Useful in cases when you want to skip tracing of + /// complex calls which are not useful for debugging. + function pauseTracing() external view; + + /// Returns a random `address`. + function randomAddress() external view returns (address); + + /// Returns a random `bool`. + function randomBool() external view returns (bool); + + /// Returns a random byte array value of the given length. + function randomBytes(uint256 len) external view returns (bytes memory); + + /// Returns a random fixed-size byte array of length 4. + function randomBytes4() external view returns (bytes4); + + /// Returns a random fixed-size byte array of length 8. + function randomBytes8() external view returns (bytes8); + + /// Returns a random `int256` value. + function randomInt() external view returns (int256); + + /// Returns a random `int256` value of given bits. + function randomInt(uint256 bits) external view returns (int256); + + /// Returns a random uint256 value. + function randomUint() external view returns (uint256); + + /// Returns random uint256 value between the provided range (=min..=max). + function randomUint(uint256 min, uint256 max) external view returns (uint256); + + /// Returns a random `uint256` value of given bits. + function randomUint(uint256 bits) external view returns (uint256); + + /// Unpauses collection of call traces. + function resumeTracing() external view; + + /// Set RNG seed. + function setSeed(uint256 seed) external; + + /// Randomly shuffles an array. + function shuffle(uint256[] calldata array) external returns (uint256[] memory); + + /// Sorts an array in ascending order. + function sort(uint256[] calldata array) external returns (uint256[] memory); + + /// Encodes a `bytes` value to a base64url string. + function toBase64URL(bytes calldata data) external pure returns (string memory); + + /// Encodes a `string` value to a base64url string. + function toBase64URL(string calldata data) external pure returns (string memory); + + /// Encodes a `bytes` value to a base64 string. + function toBase64(bytes calldata data) external pure returns (string memory); + + /// Encodes a `string` value to a base64 string. + function toBase64(string calldata data) external pure returns (string memory); + + /// RLP encodes a list of bytes into an RLP payload. + function toRlp(bytes[] calldata data) external pure returns (bytes memory); +} + +/// The `Vm` interface does allow manipulation of the EVM state. These are all intended to be used +/// in tests, but it is not recommended to use these cheats in scripts. +interface Vm is VmSafe { + // ======== EVM ======== + + /// Utility cheatcode to set an EIP-2930 access list for all subsequent transactions. + function accessList(AccessListItem[] calldata access) external; + + /// Returns the identifier of the currently active fork. Reverts if no fork is currently active. + function activeFork() external view returns (uint256 forkId); + + /// In forking mode, explicitly grant the given address cheatcode access. + function allowCheatcodes(address account) external; + + /// Sets `block.blobbasefee` + function blobBaseFee(uint256 newBlobBaseFee) external; + + /// Sets the blobhashes in the transaction. + /// Not available on EVM versions before Cancun. + /// If used on unsupported EVM versions it will revert. + function blobhashes(bytes32[] calldata hashes) external; + + /// Sets `block.chainid`. + function chainId(uint256 newChainId) external; + + /// Clears all mocked calls. + function clearMockedCalls() external; + + /// Clones a source account code, state, balance and nonce to a target account and updates in-memory EVM state. + function cloneAccount(address source, address target) external; + + /// Sets `block.coinbase`. + function coinbase(address newCoinbase) external; + + /// Marks the slots of an account and the account address as cold. + function cool(address target) external; + + /// Utility cheatcode to mark specific storage slot as cold, simulating no prior read. + function coolSlot(address target, bytes32 slot) external; + + /// Creates a new fork with the given endpoint and the _latest_ block and returns the identifier of the fork. + function createFork(string calldata urlOrAlias) external returns (uint256 forkId); + + /// Creates a new fork with the given endpoint and block and returns the identifier of the fork. + function createFork(string calldata urlOrAlias, uint256 blockNumber) external returns (uint256 forkId); + + /// Creates a new fork with the given endpoint and at the block the given transaction was mined in, + /// replays all transaction mined in the block before the transaction, and returns the identifier of the fork. + function createFork(string calldata urlOrAlias, bytes32 txHash) external returns (uint256 forkId); + + /// Creates and also selects a new fork with the given endpoint and the latest block and returns the identifier of the fork. + function createSelectFork(string calldata urlOrAlias) external returns (uint256 forkId); + + /// Creates and also selects a new fork with the given endpoint and block and returns the identifier of the fork. + function createSelectFork(string calldata urlOrAlias, uint256 blockNumber) external returns (uint256 forkId); + + /// Creates and also selects new fork with the given endpoint and at the block the given transaction was mined in, + /// replays all transaction mined in the block before the transaction, returns the identifier of the fork. + function createSelectFork(string calldata urlOrAlias, bytes32 txHash) external returns (uint256 forkId); + + /// Sets an address' balance. + function deal(address account, uint256 newBalance) external; + + /// Removes the snapshot with the given ID created by `snapshot`. + /// Takes the snapshot ID to delete. + /// Returns `true` if the snapshot was successfully deleted. + /// Returns `false` if the snapshot does not exist. + function deleteStateSnapshot(uint256 snapshotId) external returns (bool success); + + /// Removes _all_ snapshots previously created by `snapshot`. + function deleteStateSnapshots() external; + + /// Sets `block.difficulty`. + /// Not available on EVM versions from Paris onwards. Use `prevrandao` instead. + /// Reverts if used on unsupported EVM versions. + function difficulty(uint256 newDifficulty) external; + + /// Dumps a genesis JSON file's `allocs` to disk. Accounts created in the current transaction + /// are ordered by deployment, followed by the remaining accounts in ascending address order. + function dumpState(string calldata pathToStateJson) external; + + /// Sets an address' code. + function etch(address target, bytes calldata newRuntimeBytecode) external; + + /// Executes an RLP-encoded signed transaction with full EVM semantics (like `--isolate` mode). + /// The transaction is decoded from EIP-2718 format (type byte prefix + RLP payload) or legacy RLP. + /// Returns the execution output bytes. + /// This cheatcode is not allowed in `forge script` contexts. + function executeTransaction(bytes calldata rawTx) external returns (bytes memory); + + /// Sets `block.basefee`. + function fee(uint256 newBasefee) external; + + /// Gets the blockhashes from the current transaction. + /// Not available on EVM versions before Cancun. + /// If used on unsupported EVM versions it will revert. + function getBlobhashes() external view returns (bytes32[] memory hashes); + + /// Returns true if the account is marked as persistent. + function isPersistent(address account) external view returns (bool persistent); + + /// Load a genesis JSON file's `allocs` into the in-memory EVM state. + function loadAllocs(string calldata pathToAllocsJson) external; + + /// Marks that the account(s) should use persistent storage across fork swaps in a multifork setup + /// Meaning, changes made to the state of this account will be kept when switching forks. + function makePersistent(address account) external; + + /// See `makePersistent(address)`. + function makePersistent(address account0, address account1) external; + + /// See `makePersistent(address)`. + function makePersistent(address account0, address account1, address account2) external; + + /// See `makePersistent(address)`. + function makePersistent(address[] calldata accounts) external; + + /// Reverts a call to an address with specified revert data. + function mockCallRevert(address callee, bytes calldata data, bytes calldata revertData) external; + + /// Reverts a call to an address with a specific `msg.value`, with specified revert data. + function mockCallRevert(address callee, uint256 msgValue, bytes calldata data, bytes calldata revertData) external; + + /// Reverts a call to an address with specified revert data. + /// Overload to pass the function selector directly `token.approve.selector` instead of `abi.encodeWithSelector(token.approve.selector)`. + function mockCallRevert(address callee, bytes4 data, bytes calldata revertData) external; + + /// Reverts a call to an address with a specific `msg.value`, with specified revert data. + /// Overload to pass the function selector directly `token.approve.selector` instead of `abi.encodeWithSelector(token.approve.selector)`. + function mockCallRevert(address callee, uint256 msgValue, bytes4 data, bytes calldata revertData) external; + + /// Mocks a call to an address, returning specified data. + /// Calldata can either be strict or a partial match, e.g. if you only + /// pass a Solidity selector to the expected calldata, then the entire Solidity + /// function will be mocked. + function mockCall(address callee, bytes calldata data, bytes calldata returnData) external; + + /// Mocks a call to an address with a specific `msg.value`, returning specified data. + /// Calldata match takes precedence over `msg.value` in case of ambiguity. + function mockCall(address callee, uint256 msgValue, bytes calldata data, bytes calldata returnData) external; + + /// Mocks a call to an address, returning specified data. + /// Calldata can either be strict or a partial match, e.g. if you only + /// pass a Solidity selector to the expected calldata, then the entire Solidity + /// function will be mocked. + /// Overload to pass the function selector directly `token.approve.selector` instead of `abi.encodeWithSelector(token.approve.selector)`. + function mockCall(address callee, bytes4 data, bytes calldata returnData) external; + + /// Mocks a call to an address with a specific `msg.value`, returning specified data. + /// Calldata match takes precedence over `msg.value` in case of ambiguity. + /// Overload to pass the function selector directly `token.approve.selector` instead of `abi.encodeWithSelector(token.approve.selector)`. + function mockCall(address callee, uint256 msgValue, bytes4 data, bytes calldata returnData) external; + + /// Mocks a call to an address, returning specified data. + /// Calldata can either be strict or a partial match, e.g. if you only + /// pass a Solidity selector to the expected calldata, then the entire Solidity + /// function will be mocked. + /// Overload to control whether code is injected into `callee`. The other overloads etch a + /// single byte into an empty account to circumvent Solidity's `extcodesize` check, with the + /// side effect that unmocked calls to it no longer revert; `injectCode = false` leaves the + /// account codeless, so unmocked calls to it revert in the caller. Mocked calls that return + /// data still succeed, as Solidity checks `returndatasize()` instead of `extcodesize()` when + /// return data is expected, but mocked calls to functions without return values may still + /// revert in the caller due to the `extcodesize` check. + function mockCall(address callee, bytes calldata data, bytes calldata returnData, bool injectCode) external; + + /// Mocks multiple calls to an address, returning specified data for each call. + function mockCalls(address callee, bytes calldata data, bytes[] calldata returnData) external; + + /// Mocks multiple calls to an address with a specific `msg.value`, returning specified data for each call. + function mockCalls(address callee, uint256 msgValue, bytes calldata data, bytes[] calldata returnData) external; + + /// Whenever a call is made to `callee` with calldata `data`, this cheatcode instead calls + /// `target` with the same calldata. This functionality is similar to a delegate call made to + /// `target` contract from `callee`. + /// Can be used to substitute a call to a function with another implementation that captures + /// the primary logic of the original function but is easier to reason about. + /// If calldata is not a strict match then partial match by selector is attempted. + function mockFunction(address callee, address target, bytes calldata data) external; + + /// Utility cheatcode to remove any EIP-2930 access list set by `accessList` cheatcode. + function noAccessList() external; + + /// Sets the *next* call's `msg.sender` to be the input address. + function prank(address msgSender) external; + + /// Sets the *next* call's `msg.sender` to be the input address, and the `tx.origin` to be the second input. + function prank(address msgSender, address txOrigin) external; + + /// Sets the *next* delegate call's `msg.sender` to be the input address. + function prank(address msgSender, bool delegateCall) external; + + /// Sets the *next* delegate call's `msg.sender` to be the input address, and the `tx.origin` to be the second input. + function prank(address msgSender, address txOrigin, bool delegateCall) external; + + /// Sets `block.prevrandao`. + /// Not available on EVM versions before Paris. Use `difficulty` instead. + /// If used on unsupported EVM versions it will revert. + function prevrandao(bytes32 newPrevrandao) external; + + /// Sets `block.prevrandao`. + /// Not available on EVM versions before Paris. Use `difficulty` instead. + /// If used on unsupported EVM versions it will revert. + function prevrandao(uint256 newPrevrandao) external; + + /// Reads the current `msg.sender` and `tx.origin` from state and reports if there is any active caller modification. + function readCallers() external view returns (CallerMode callerMode, address msgSender, address txOrigin); + + /// Resets the nonce of an account to 0 for EOAs and 1 for contract accounts. + function resetNonce(address account) external; + + /// Revert the state of the EVM to a previous snapshot + /// Takes the snapshot ID to revert to. + /// Returns `true` if the snapshot was successfully reverted. + /// Returns `false` if the snapshot does not exist. + /// **Note:** This does not automatically delete the snapshot. To delete the snapshot use `deleteStateSnapshot`. + function revertToState(uint256 snapshotId) external returns (bool success); + + /// Revert the state of the EVM to a previous snapshot and automatically deletes the snapshots + /// Takes the snapshot ID to revert to. + /// Returns `true` if the snapshot was successfully reverted and deleted. + /// Returns `false` if the snapshot does not exist. + function revertToStateAndDelete(uint256 snapshotId) external returns (bool success); + + /// Revokes persistent status from the address, previously added via `makePersistent`. + function revokePersistent(address account) external; + + /// See `revokePersistent(address)`. + function revokePersistent(address[] calldata accounts) external; + + /// Sets `block.height`. + function roll(uint256 newHeight) external; + + /// Updates the currently active fork to given block number + /// This is similar to `roll` but for the currently active fork. + function rollFork(uint256 blockNumber) external; + + /// Updates the currently active fork to given transaction. This will `rollFork` with the number + /// of the block the transaction was mined in and replays all transaction mined before it in the block. + function rollFork(bytes32 txHash) external; + + /// Updates the given fork to given block number. + function rollFork(uint256 forkId, uint256 blockNumber) external; + + /// Updates the given fork to block number of the given transaction and replays all transaction mined before it in the block. + function rollFork(uint256 forkId, bytes32 txHash) external; + + /// Takes a fork identifier created by `createFork` and sets the corresponding forked state as active. + function selectFork(uint256 forkId) external; + + /// Set blockhash for the current block. + /// It only sets the blockhash for blocks where `block.number - 256 <= number < block.number`. + function setBlockhash(uint256 blockNumber, bytes32 blockHash) external; + + /// Sets a TIP-20 token's logo URI directly in storage. + /// This bypasses the token admin check, but still validates the URI against T5 constraints. + function setLogoURI(address token, string calldata newLogoURI) external; + + /// Sets the nonce of an account. Must be higher than the current nonce of the account. + function setNonce(address account, uint64 newNonce) external; + + /// Sets the nonce of an account to an arbitrary value. + function setNonceUnsafe(address account, uint64 newNonce) external; + + /// Sets a TIP-20 token's logo URI directly in storage. + /// This bypasses the token admin check, but still validates the URI against T5 constraints. + function setTip20LogoURI(address token, string calldata newLogoURI) external; + + /// Snapshot capture the gas usage of the last call or create by name from the callee perspective. + function snapshotGasLastFrame(string calldata name) external returns (uint256 gasUsed); + + /// Snapshot capture the gas usage of the last call or create by name in a group from the callee perspective. + function snapshotGasLastFrame(string calldata group, string calldata name) external returns (uint256 gasUsed); + + /// Snapshot the current state of the evm. + /// Returns the ID of the snapshot that was created. + /// To revert a snapshot use `revertToState`. + function snapshotState() external returns (uint256 snapshotId); + + /// Snapshot capture an arbitrary numerical value by name. + /// The group name is derived from the contract name. + function snapshotValue(string calldata name, uint256 value) external; + + /// Snapshot capture an arbitrary numerical value by name in a group. + function snapshotValue(string calldata group, string calldata name, uint256 value) external; + + /// Sets all subsequent calls' `msg.sender` to be the input address until `stopPrank` is called. + function startPrank(address msgSender) external; + + /// Sets all subsequent calls' `msg.sender` to be the input address until `stopPrank` is called, and the `tx.origin` to be the second input. + function startPrank(address msgSender, address txOrigin) external; + + /// Sets all subsequent delegate calls' `msg.sender` to be the input address until `stopPrank` is called. + function startPrank(address msgSender, bool delegateCall) external; + + /// Sets all subsequent delegate calls' `msg.sender` to be the input address until `stopPrank` is called, and the `tx.origin` to be the second input. + function startPrank(address msgSender, address txOrigin, bool delegateCall) external; + + /// Start a snapshot capture of the current gas usage by name. + /// The group name is derived from the contract name. + function startSnapshotGas(string calldata name) external; + + /// Start a snapshot capture of the current gas usage by name in a group. + function startSnapshotGas(string calldata group, string calldata name) external; + + /// Resets subsequent calls' `msg.sender` to be `address(this)`. + function stopPrank() external; + + /// Stop the snapshot capture of the current gas by latest snapshot name, capturing the gas used since the start. + function stopSnapshotGas() external returns (uint256 gasUsed); + + /// Stop the snapshot capture of the current gas usage by name, capturing the gas used since the start. + /// The group name is derived from the contract name. + function stopSnapshotGas(string calldata name) external returns (uint256 gasUsed); + + /// Stop the snapshot capture of the current gas usage by name in a group, capturing the gas used since the start. + function stopSnapshotGas(string calldata group, string calldata name) external returns (uint256 gasUsed); + + /// Stores a value to an address' storage slot. + function store(address target, bytes32 slot, bytes32 value) external; + + /// Fetches the given transaction from the active fork and executes it on the current state. + function transact(bytes32 txHash) external; + + /// Fetches the given transaction from the given fork and executes it on the current state. + function transact(uint256 forkId, bytes32 txHash) external; + + /// Sets `tx.gasprice`. + function txGasPrice(uint256 newGasPrice) external; + + /// Utility cheatcode to mark specific storage slot as warm, simulating a prior read. + function warmSlot(address target, bytes32 slot) external; + + /// Sets `block.timestamp`. + function warp(uint256 newTimestamp) external; + + /// `deleteSnapshot` is being deprecated in favor of `deleteStateSnapshot`. It will be removed in future versions. + function deleteSnapshot(uint256 snapshotId) external returns (bool success); + + /// `deleteSnapshots` is being deprecated in favor of `deleteStateSnapshots`. It will be removed in future versions. + function deleteSnapshots() external; + + /// `revertToAndDelete` is being deprecated in favor of `revertToStateAndDelete`. It will be removed in future versions. + function revertToAndDelete(uint256 snapshotId) external returns (bool success); + + /// `revertTo` is being deprecated in favor of `revertToState`. It will be removed in future versions. + function revertTo(uint256 snapshotId) external returns (bool success); + + /// DEPRECATED: use `snapshotGasLastFrame` instead. + /// Snapshot capture the gas usage of the last call by name from the callee perspective. + function snapshotGasLastCall(string calldata name) external returns (uint256 gasUsed); + + /// DEPRECATED: use `snapshotGasLastFrame` instead. + /// Snapshot capture the gas usage of the last call by name in a group from the callee perspective. + function snapshotGasLastCall(string calldata group, string calldata name) external returns (uint256 gasUsed); + + /// `snapshot` is being deprecated in favor of `snapshotState`. It will be removed in future versions. + function snapshot() external returns (uint256 snapshotId); + + // ======== Testing ======== + + /// Expect a call to an address with the specified `msg.value` and calldata, and a *minimum* amount of gas. + function expectCallMinGas(address callee, uint256 msgValue, uint64 minGas, bytes calldata data) external; + + /// Expect given number of calls to an address with the specified `msg.value` and calldata, and a *minimum* amount of gas. + function expectCallMinGas(address callee, uint256 msgValue, uint64 minGas, bytes calldata data, uint64 count) + external; + + /// Expects a call to an address with the specified calldata. + /// Calldata can either be a strict or a partial match. + function expectCall(address callee, bytes calldata data) external; + + /// Expects given number of calls to an address with the specified calldata. + function expectCall(address callee, bytes calldata data, uint64 count) external; + + /// Expects a call to an address with the specified `msg.value` and calldata. + function expectCall(address callee, uint256 msgValue, bytes calldata data) external; + + /// Expects given number of calls to an address with the specified `msg.value` and calldata. + function expectCall(address callee, uint256 msgValue, bytes calldata data, uint64 count) external; + + /// Expect a call to an address with the specified `msg.value`, gas, and calldata. + function expectCall(address callee, uint256 msgValue, uint64 gas, bytes calldata data) external; + + /// Expects given number of calls to an address with the specified `msg.value`, gas, and calldata. + function expectCall(address callee, uint256 msgValue, uint64 gas, bytes calldata data, uint64 count) external; + + /// Expects the deployment of the specified bytecode by the specified address using the CREATE opcode + function expectCreate(bytes calldata bytecode, address deployer) external; + + /// Expects the deployment of the specified bytecode by the specified address using the CREATE2 opcode + function expectCreate2(bytes calldata bytecode, address deployer) external; + + /// Expects a delegate call to an address with the specified calldata. + /// Calldata can either be a strict or a partial match. + function expectDelegateCall(address callee, bytes calldata data) external; + + /// Prepare an expected anonymous log with (bool checkTopic1, bool checkTopic2, bool checkTopic3, bool checkData.). + /// Call this function, then emit an anonymous event, then call a function. Internally after the call, we check if + /// logs were emitted in the expected order with the expected topics and data (as specified by the booleans). + function expectEmitAnonymous(bool checkTopic0, bool checkTopic1, bool checkTopic2, bool checkTopic3, bool checkData) + external; + + /// Same as the previous method, but also checks supplied address against emitting contract. + function expectEmitAnonymous( + bool checkTopic0, + bool checkTopic1, + bool checkTopic2, + bool checkTopic3, + bool checkData, + address emitter + ) external; + + /// Prepare an expected anonymous log with all topic and data checks enabled. + /// Call this function, then emit an anonymous event, then call a function. Internally after the call, we check if + /// logs were emitted in the expected order with the expected topics and data. + function expectEmitAnonymous() external; + + /// Same as the previous method, but also checks supplied address against emitting contract. + function expectEmitAnonymous(address emitter) external; + + /// Prepare an expected log with (bool checkTopic1, bool checkTopic2, bool checkTopic3, bool checkData.). + /// Call this function, then emit an event, then call a function. Internally after the call, we check if + /// logs were emitted in the expected order with the expected topics and data (as specified by the booleans). + /// Must be placed immediately before the call you want to assert on. If the next call reverts and the + /// revert is caught by the caller (low-level call or try/catch), the expectation remains active and may + /// be satisfied by a log emitted from a later call. + function expectEmit(bool checkTopic1, bool checkTopic2, bool checkTopic3, bool checkData) external; + + /// Same as the previous method, but also checks supplied address against emitting contract. + function expectEmit(bool checkTopic1, bool checkTopic2, bool checkTopic3, bool checkData, address emitter) external; + + /// Prepare an expected log with all topic and data checks enabled. + /// Call this function, then emit an event, then call a function. Internally after the call, we check if + /// logs were emitted in the expected order with the expected topics and data. + /// Must be placed immediately before the call you want to assert on. If the next call reverts and the + /// revert is caught by the caller (low-level call or try/catch), the expectation remains active and may + /// be satisfied by a log emitted from a later call. + function expectEmit() external; + + /// Same as the previous method, but also checks supplied address against emitting contract. + function expectEmit(address emitter) external; + + /// Expect a given number of logs with the provided topics. + function expectEmit(bool checkTopic1, bool checkTopic2, bool checkTopic3, bool checkData, uint64 count) external; + + /// Expect a given number of logs from a specific emitter with the provided topics. + function expectEmit( + bool checkTopic1, + bool checkTopic2, + bool checkTopic3, + bool checkData, + address emitter, + uint64 count + ) external; + + /// Expect a given number of logs with all topic and data checks enabled. + function expectEmit(uint64 count) external; + + /// Expect a given number of logs from a specific emitter with all topic and data checks enabled. + function expectEmit(address emitter, uint64 count) external; + + /// Expects a call to `SignatureVerifier.verifyKeychainAdmin(account, digest, signature)`. + /// The supplied `digest` should already be domain-separated with chain ID, contract address, + /// and account address. + function expectKeychainAdminVerified(address account, bytes32 digest, bytes calldata signature) external; + + /// Expects a call to `SignatureVerifier.verifyKeychain(account, digest, signature)`. + function expectKeychainVerified(address account, bytes32 digest, bytes calldata signature) external; + + /// Expects a TIP-20 `LogoURIUpdated(address indexed updater, string newLogoURI)` event. + function expectLogoURIUpdated(address token, address updater, string calldata newLogoURI) external; + + /// Expects an error on next call that starts with the revert data. + function expectPartialRevert(bytes4 revertData) external; + + /// Expects an error on next call to reverter address, that starts with the revert data. + /// See `expectRevert(address)` for `reverter` matching semantics. + function expectPartialRevert(bytes4 revertData, address reverter) external; + + /// Expects an error on next call with any revert data. + function expectRevert() external; + + /// Expects an error on next call that exactly matches the revert data. + function expectRevert(bytes4 revertData) external; + + /// Expects a `count` number of reverts from the upcoming calls from the reverter address that match the revert data. + /// See `expectRevert(address)` for `reverter` matching semantics. + function expectRevert(bytes4 revertData, address reverter, uint64 count) external; + + /// Expects a `count` number of reverts from the upcoming calls from the reverter address that exactly match the revert data. + /// See `expectRevert(address)` for `reverter` matching semantics. + function expectRevert(bytes calldata revertData, address reverter, uint64 count) external; + + /// Expects an error on next call that exactly matches the revert data. + function expectRevert(bytes calldata revertData) external; + + /// Expects an error with any revert data on next call to reverter address. + /// The `reverter` argument is matched against the address associated with + /// the frame that produced the revert: + /// - For a CALL: the address that was called. + /// - For a CREATE / CREATE2: the would-be deployed address of the failed + /// deployment (computed from the deployer + nonce, or salt + initcode). + /// For a single expected revert, the innermost reverting frame wins in + /// nested CALL, CREATE, or mixed chains. With `count > 1`, nested + /// CREATE / CREATE2 chains apply the same rule independently to each + /// iteration; nested CALL chains keep their existing + /// outermost-call-per-iteration behavior. + function expectRevert(address reverter) external; + + /// Expects an error from reverter address on next call, with any revert data. + /// See `expectRevert(address)` for `reverter` matching semantics. + function expectRevert(bytes4 revertData, address reverter) external; + + /// Expects an error from reverter address on next call, that exactly matches the revert data. + /// See `expectRevert(address)` for `reverter` matching semantics. + function expectRevert(bytes calldata revertData, address reverter) external; + + /// Expects a `count` number of reverts from the upcoming calls with any revert data or reverter. + function expectRevert(uint64 count) external; + + /// Expects a `count` number of reverts from the upcoming calls that match the revert data. + function expectRevert(bytes4 revertData, uint64 count) external; + + /// Expects a `count` number of reverts from the upcoming calls that exactly match the revert data. + function expectRevert(bytes calldata revertData, uint64 count) external; + + /// Expects a `count` number of reverts from the upcoming calls from the reverter address. + /// See `expectRevert(address)` for `reverter` matching semantics. + function expectRevert(address reverter, uint64 count) external; + + /// Only allows memory writes to offsets [0x00, 0x60) ∪ [min, max) in the current subcontext. If any other + /// memory is written to, the test will fail. Can be called multiple times to add more ranges to the set. + function expectSafeMemory(uint64 min, uint64 max) external; + + /// Only allows memory writes to offsets [0x00, 0x60) ∪ [min, max) in the next created subcontext. + /// If any other memory is written to, the test will fail. Can be called multiple times to add more ranges + /// to the set. + function expectSafeMemoryCall(uint64 min, uint64 max) external; + + /// Expects a TIP-20 `LogoURIUpdated(address indexed updater, string newLogoURI)` event. + function expectTip20LogoURIUpdated(address token, address updater, string calldata newLogoURI) external; + + /// Marks a test as skipped. Must be called at the top level of a test. + function skip(bool skipTest) external; + + /// Marks a test as skipped with a reason. Must be called at the top level of a test. + function skip(bool skipTest, string calldata reason) external; + + /// Stops all safe memory expectation in the current subcontext. + function stopExpectSafeMemory() external; + + // ======== Utilities ======== + + /// Utility cheatcode to copy storage of `from` contract to another `to` contract. + function copyStorage(address from, address to) external; + + /// Causes the next contract creation (via new) to fail and return its initcode in the returndata buffer. + /// This allows type-safe access to the initcode payload that would be used for contract creation. + /// Example usage: + /// vm.interceptInitcode(); + /// bytes memory initcode; + /// try new MyContract(param1, param2) { assert(false); } + /// catch (bytes memory interceptedInitcode) { initcode = interceptedInitcode; } + function interceptInitcode() external; + + /// Utility cheatcode to set arbitrary storage for given target address. + function setArbitraryStorage(address target) external; + + /// Utility cheatcode to set arbitrary storage for given target address and overwrite + /// any storage slots that have been previously set. + function setArbitraryStorage(address target, bool overwrite) external; +} diff --git a/contracts/evm/lib/forge-std/src/console.sol b/contracts/evm/lib/forge-std/src/console.sol new file mode 100644 index 0000000000..0ac1b691ad --- /dev/null +++ b/contracts/evm/lib/forge-std/src/console.sol @@ -0,0 +1,1599 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +library console { + address constant CONSOLE_ADDRESS = 0x000000000000000000636F6e736F6c652e6c6f67; + + function _sendLogPayloadImplementation(bytes memory payload) internal view { + address consoleAddress = CONSOLE_ADDRESS; + assembly ("memory-safe") { + pop(staticcall(gas(), consoleAddress, add(payload, 32), mload(payload), 0, 0)) + } + } + + function _castToPure(function(bytes memory) internal view fnIn) + internal + pure + returns (function(bytes memory) pure fnOut) + { + assembly { + fnOut := fnIn + } + } + + function _sendLogPayload(bytes memory payload) internal pure { + _castToPure(_sendLogPayloadImplementation)(payload); + } + + function log() internal pure { + _sendLogPayload(abi.encodeWithSignature("log()")); + } + + function logInt(int256 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(int256)", p0)); + } + + function logUint(uint256 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256)", p0)); + } + + function logString(string memory p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); + } + + function logBool(bool p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); + } + + function logAddress(address p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); + } + + function logBytes(bytes memory p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); + } + + function logBytes1(bytes1 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); + } + + function logBytes2(bytes2 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); + } + + function logBytes3(bytes3 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); + } + + function logBytes4(bytes4 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); + } + + function logBytes5(bytes5 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); + } + + function logBytes6(bytes6 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); + } + + function logBytes7(bytes7 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); + } + + function logBytes8(bytes8 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); + } + + function logBytes9(bytes9 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); + } + + function logBytes10(bytes10 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); + } + + function logBytes11(bytes11 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); + } + + function logBytes12(bytes12 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); + } + + function logBytes13(bytes13 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); + } + + function logBytes14(bytes14 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); + } + + function logBytes15(bytes15 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); + } + + function logBytes16(bytes16 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); + } + + function logBytes17(bytes17 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); + } + + function logBytes18(bytes18 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); + } + + function logBytes19(bytes19 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); + } + + function logBytes20(bytes20 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); + } + + function logBytes21(bytes21 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); + } + + function logBytes22(bytes22 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); + } + + function logBytes23(bytes23 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); + } + + function logBytes24(bytes24 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); + } + + function logBytes25(bytes25 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); + } + + function logBytes26(bytes26 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); + } + + function logBytes27(bytes27 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); + } + + function logBytes28(bytes28 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); + } + + function logBytes29(bytes29 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); + } + + function logBytes30(bytes30 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); + } + + function logBytes31(bytes31 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); + } + + function logBytes32(bytes32 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); + } + + function log(uint256 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256)", p0)); + } + + function log(int256 p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(int256)", p0)); + } + + function log(string memory p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); + } + + function log(bool p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); + } + + function log(address p0) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); + } + + function log(uint256 p0, uint256 p1) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256)", p0, p1)); + } + + function log(uint256 p0, string memory p1) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,string)", p0, p1)); + } + + function log(uint256 p0, bool p1) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,bool)", p0, p1)); + } + + function log(uint256 p0, address p1) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,address)", p0, p1)); + } + + function log(string memory p0, uint256 p1) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,uint256)", p0, p1)); + } + + function log(string memory p0, int256 p1) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,int256)", p0, p1)); + } + + function log(string memory p0, string memory p1) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); + } + + function log(string memory p0, bool p1) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); + } + + function log(string memory p0, address p1) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); + } + + function log(bool p0, uint256 p1) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,uint256)", p0, p1)); + } + + function log(bool p0, string memory p1) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); + } + + function log(bool p0, bool p1) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); + } + + function log(bool p0, address p1) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); + } + + function log(address p0, uint256 p1) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,uint256)", p0, p1)); + } + + function log(address p0, string memory p1) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); + } + + function log(address p0, bool p1) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); + } + + function log(address p0, address p1) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); + } + + function log(uint256 p0, uint256 p1, uint256 p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256)", p0, p1, p2)); + } + + function log(uint256 p0, uint256 p1, string memory p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string)", p0, p1, p2)); + } + + function log(uint256 p0, uint256 p1, bool p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool)", p0, p1, p2)); + } + + function log(uint256 p0, uint256 p1, address p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address)", p0, p1, p2)); + } + + function log(uint256 p0, string memory p1, uint256 p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256)", p0, p1, p2)); + } + + function log(uint256 p0, string memory p1, string memory p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string)", p0, p1, p2)); + } + + function log(uint256 p0, string memory p1, bool p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool)", p0, p1, p2)); + } + + function log(uint256 p0, string memory p1, address p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address)", p0, p1, p2)); + } + + function log(uint256 p0, bool p1, uint256 p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256)", p0, p1, p2)); + } + + function log(uint256 p0, bool p1, string memory p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string)", p0, p1, p2)); + } + + function log(uint256 p0, bool p1, bool p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool)", p0, p1, p2)); + } + + function log(uint256 p0, bool p1, address p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address)", p0, p1, p2)); + } + + function log(uint256 p0, address p1, uint256 p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256)", p0, p1, p2)); + } + + function log(uint256 p0, address p1, string memory p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string)", p0, p1, p2)); + } + + function log(uint256 p0, address p1, bool p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool)", p0, p1, p2)); + } + + function log(uint256 p0, address p1, address p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address)", p0, p1, p2)); + } + + function log(string memory p0, uint256 p1, uint256 p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256)", p0, p1, p2)); + } + + function log(string memory p0, uint256 p1, string memory p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string)", p0, p1, p2)); + } + + function log(string memory p0, uint256 p1, bool p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool)", p0, p1, p2)); + } + + function log(string memory p0, uint256 p1, address p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address)", p0, p1, p2)); + } + + function log(string memory p0, string memory p1, uint256 p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256)", p0, p1, p2)); + } + + function log(string memory p0, string memory p1, string memory p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); + } + + function log(string memory p0, string memory p1, bool p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); + } + + function log(string memory p0, string memory p1, address p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); + } + + function log(string memory p0, bool p1, uint256 p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256)", p0, p1, p2)); + } + + function log(string memory p0, bool p1, string memory p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); + } + + function log(string memory p0, bool p1, bool p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); + } + + function log(string memory p0, bool p1, address p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); + } + + function log(string memory p0, address p1, uint256 p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256)", p0, p1, p2)); + } + + function log(string memory p0, address p1, string memory p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); + } + + function log(string memory p0, address p1, bool p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); + } + + function log(string memory p0, address p1, address p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); + } + + function log(bool p0, uint256 p1, uint256 p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256)", p0, p1, p2)); + } + + function log(bool p0, uint256 p1, string memory p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string)", p0, p1, p2)); + } + + function log(bool p0, uint256 p1, bool p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool)", p0, p1, p2)); + } + + function log(bool p0, uint256 p1, address p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address)", p0, p1, p2)); + } + + function log(bool p0, string memory p1, uint256 p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256)", p0, p1, p2)); + } + + function log(bool p0, string memory p1, string memory p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); + } + + function log(bool p0, string memory p1, bool p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); + } + + function log(bool p0, string memory p1, address p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); + } + + function log(bool p0, bool p1, uint256 p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256)", p0, p1, p2)); + } + + function log(bool p0, bool p1, string memory p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); + } + + function log(bool p0, bool p1, bool p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); + } + + function log(bool p0, bool p1, address p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); + } + + function log(bool p0, address p1, uint256 p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256)", p0, p1, p2)); + } + + function log(bool p0, address p1, string memory p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); + } + + function log(bool p0, address p1, bool p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); + } + + function log(bool p0, address p1, address p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); + } + + function log(address p0, uint256 p1, uint256 p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256)", p0, p1, p2)); + } + + function log(address p0, uint256 p1, string memory p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string)", p0, p1, p2)); + } + + function log(address p0, uint256 p1, bool p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool)", p0, p1, p2)); + } + + function log(address p0, uint256 p1, address p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address)", p0, p1, p2)); + } + + function log(address p0, string memory p1, uint256 p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256)", p0, p1, p2)); + } + + function log(address p0, string memory p1, string memory p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); + } + + function log(address p0, string memory p1, bool p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); + } + + function log(address p0, string memory p1, address p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); + } + + function log(address p0, bool p1, uint256 p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256)", p0, p1, p2)); + } + + function log(address p0, bool p1, string memory p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); + } + + function log(address p0, bool p1, bool p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); + } + + function log(address p0, bool p1, address p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); + } + + function log(address p0, address p1, uint256 p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256)", p0, p1, p2)); + } + + function log(address p0, address p1, string memory p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); + } + + function log(address p0, address p1, bool p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); + } + + function log(address p0, address p1, address p2) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); + } + + function log(uint256 p0, uint256 p1, uint256 p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,uint256)", p0, p1, p2, p3)); + } + + function log(uint256 p0, uint256 p1, uint256 p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,string)", p0, p1, p2, p3)); + } + + function log(uint256 p0, uint256 p1, uint256 p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,bool)", p0, p1, p2, p3)); + } + + function log(uint256 p0, uint256 p1, uint256 p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,address)", p0, p1, p2, p3)); + } + + function log(uint256 p0, uint256 p1, string memory p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,uint256)", p0, p1, p2, p3)); + } + + function log(uint256 p0, uint256 p1, string memory p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,string)", p0, p1, p2, p3)); + } + + function log(uint256 p0, uint256 p1, string memory p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,bool)", p0, p1, p2, p3)); + } + + function log(uint256 p0, uint256 p1, string memory p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,address)", p0, p1, p2, p3)); + } + + function log(uint256 p0, uint256 p1, bool p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,uint256)", p0, p1, p2, p3)); + } + + function log(uint256 p0, uint256 p1, bool p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,string)", p0, p1, p2, p3)); + } + + function log(uint256 p0, uint256 p1, bool p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,bool)", p0, p1, p2, p3)); + } + + function log(uint256 p0, uint256 p1, bool p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,address)", p0, p1, p2, p3)); + } + + function log(uint256 p0, uint256 p1, address p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,uint256)", p0, p1, p2, p3)); + } + + function log(uint256 p0, uint256 p1, address p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,string)", p0, p1, p2, p3)); + } + + function log(uint256 p0, uint256 p1, address p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,bool)", p0, p1, p2, p3)); + } + + function log(uint256 p0, uint256 p1, address p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,address)", p0, p1, p2, p3)); + } + + function log(uint256 p0, string memory p1, uint256 p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,uint256)", p0, p1, p2, p3)); + } + + function log(uint256 p0, string memory p1, uint256 p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,string)", p0, p1, p2, p3)); + } + + function log(uint256 p0, string memory p1, uint256 p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,bool)", p0, p1, p2, p3)); + } + + function log(uint256 p0, string memory p1, uint256 p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,address)", p0, p1, p2, p3)); + } + + function log(uint256 p0, string memory p1, string memory p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,uint256)", p0, p1, p2, p3)); + } + + function log(uint256 p0, string memory p1, string memory p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,string)", p0, p1, p2, p3)); + } + + function log(uint256 p0, string memory p1, string memory p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,bool)", p0, p1, p2, p3)); + } + + function log(uint256 p0, string memory p1, string memory p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,address)", p0, p1, p2, p3)); + } + + function log(uint256 p0, string memory p1, bool p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,uint256)", p0, p1, p2, p3)); + } + + function log(uint256 p0, string memory p1, bool p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,string)", p0, p1, p2, p3)); + } + + function log(uint256 p0, string memory p1, bool p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,bool)", p0, p1, p2, p3)); + } + + function log(uint256 p0, string memory p1, bool p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,address)", p0, p1, p2, p3)); + } + + function log(uint256 p0, string memory p1, address p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,uint256)", p0, p1, p2, p3)); + } + + function log(uint256 p0, string memory p1, address p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,string)", p0, p1, p2, p3)); + } + + function log(uint256 p0, string memory p1, address p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,bool)", p0, p1, p2, p3)); + } + + function log(uint256 p0, string memory p1, address p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,address)", p0, p1, p2, p3)); + } + + function log(uint256 p0, bool p1, uint256 p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,uint256)", p0, p1, p2, p3)); + } + + function log(uint256 p0, bool p1, uint256 p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,string)", p0, p1, p2, p3)); + } + + function log(uint256 p0, bool p1, uint256 p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,bool)", p0, p1, p2, p3)); + } + + function log(uint256 p0, bool p1, uint256 p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,address)", p0, p1, p2, p3)); + } + + function log(uint256 p0, bool p1, string memory p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,uint256)", p0, p1, p2, p3)); + } + + function log(uint256 p0, bool p1, string memory p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,string)", p0, p1, p2, p3)); + } + + function log(uint256 p0, bool p1, string memory p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,bool)", p0, p1, p2, p3)); + } + + function log(uint256 p0, bool p1, string memory p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,address)", p0, p1, p2, p3)); + } + + function log(uint256 p0, bool p1, bool p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,uint256)", p0, p1, p2, p3)); + } + + function log(uint256 p0, bool p1, bool p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,string)", p0, p1, p2, p3)); + } + + function log(uint256 p0, bool p1, bool p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,bool)", p0, p1, p2, p3)); + } + + function log(uint256 p0, bool p1, bool p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,address)", p0, p1, p2, p3)); + } + + function log(uint256 p0, bool p1, address p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,uint256)", p0, p1, p2, p3)); + } + + function log(uint256 p0, bool p1, address p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,string)", p0, p1, p2, p3)); + } + + function log(uint256 p0, bool p1, address p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,bool)", p0, p1, p2, p3)); + } + + function log(uint256 p0, bool p1, address p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,address)", p0, p1, p2, p3)); + } + + function log(uint256 p0, address p1, uint256 p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,uint256)", p0, p1, p2, p3)); + } + + function log(uint256 p0, address p1, uint256 p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,string)", p0, p1, p2, p3)); + } + + function log(uint256 p0, address p1, uint256 p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,bool)", p0, p1, p2, p3)); + } + + function log(uint256 p0, address p1, uint256 p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,address)", p0, p1, p2, p3)); + } + + function log(uint256 p0, address p1, string memory p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,uint256)", p0, p1, p2, p3)); + } + + function log(uint256 p0, address p1, string memory p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,string)", p0, p1, p2, p3)); + } + + function log(uint256 p0, address p1, string memory p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,bool)", p0, p1, p2, p3)); + } + + function log(uint256 p0, address p1, string memory p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,address)", p0, p1, p2, p3)); + } + + function log(uint256 p0, address p1, bool p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,uint256)", p0, p1, p2, p3)); + } + + function log(uint256 p0, address p1, bool p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,string)", p0, p1, p2, p3)); + } + + function log(uint256 p0, address p1, bool p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,bool)", p0, p1, p2, p3)); + } + + function log(uint256 p0, address p1, bool p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,address)", p0, p1, p2, p3)); + } + + function log(uint256 p0, address p1, address p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,uint256)", p0, p1, p2, p3)); + } + + function log(uint256 p0, address p1, address p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,string)", p0, p1, p2, p3)); + } + + function log(uint256 p0, address p1, address p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,bool)", p0, p1, p2, p3)); + } + + function log(uint256 p0, address p1, address p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,address)", p0, p1, p2, p3)); + } + + function log(string memory p0, uint256 p1, uint256 p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,uint256)", p0, p1, p2, p3)); + } + + function log(string memory p0, uint256 p1, uint256 p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,string)", p0, p1, p2, p3)); + } + + function log(string memory p0, uint256 p1, uint256 p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,bool)", p0, p1, p2, p3)); + } + + function log(string memory p0, uint256 p1, uint256 p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,address)", p0, p1, p2, p3)); + } + + function log(string memory p0, uint256 p1, string memory p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,uint256)", p0, p1, p2, p3)); + } + + function log(string memory p0, uint256 p1, string memory p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,string)", p0, p1, p2, p3)); + } + + function log(string memory p0, uint256 p1, string memory p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,bool)", p0, p1, p2, p3)); + } + + function log(string memory p0, uint256 p1, string memory p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,address)", p0, p1, p2, p3)); + } + + function log(string memory p0, uint256 p1, bool p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,uint256)", p0, p1, p2, p3)); + } + + function log(string memory p0, uint256 p1, bool p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,string)", p0, p1, p2, p3)); + } + + function log(string memory p0, uint256 p1, bool p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,bool)", p0, p1, p2, p3)); + } + + function log(string memory p0, uint256 p1, bool p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,address)", p0, p1, p2, p3)); + } + + function log(string memory p0, uint256 p1, address p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,uint256)", p0, p1, p2, p3)); + } + + function log(string memory p0, uint256 p1, address p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,string)", p0, p1, p2, p3)); + } + + function log(string memory p0, uint256 p1, address p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,bool)", p0, p1, p2, p3)); + } + + function log(string memory p0, uint256 p1, address p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,address)", p0, p1, p2, p3)); + } + + function log(string memory p0, string memory p1, uint256 p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,uint256)", p0, p1, p2, p3)); + } + + function log(string memory p0, string memory p1, uint256 p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,string)", p0, p1, p2, p3)); + } + + function log(string memory p0, string memory p1, uint256 p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,bool)", p0, p1, p2, p3)); + } + + function log(string memory p0, string memory p1, uint256 p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,address)", p0, p1, p2, p3)); + } + + function log(string memory p0, string memory p1, string memory p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint256)", p0, p1, p2, p3)); + } + + function log(string memory p0, string memory p1, string memory p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); + } + + function log(string memory p0, string memory p1, string memory p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); + } + + function log(string memory p0, string memory p1, string memory p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); + } + + function log(string memory p0, string memory p1, bool p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint256)", p0, p1, p2, p3)); + } + + function log(string memory p0, string memory p1, bool p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); + } + + function log(string memory p0, string memory p1, bool p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); + } + + function log(string memory p0, string memory p1, bool p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); + } + + function log(string memory p0, string memory p1, address p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint256)", p0, p1, p2, p3)); + } + + function log(string memory p0, string memory p1, address p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); + } + + function log(string memory p0, string memory p1, address p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); + } + + function log(string memory p0, string memory p1, address p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); + } + + function log(string memory p0, bool p1, uint256 p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,uint256)", p0, p1, p2, p3)); + } + + function log(string memory p0, bool p1, uint256 p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,string)", p0, p1, p2, p3)); + } + + function log(string memory p0, bool p1, uint256 p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,bool)", p0, p1, p2, p3)); + } + + function log(string memory p0, bool p1, uint256 p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,address)", p0, p1, p2, p3)); + } + + function log(string memory p0, bool p1, string memory p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint256)", p0, p1, p2, p3)); + } + + function log(string memory p0, bool p1, string memory p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); + } + + function log(string memory p0, bool p1, string memory p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); + } + + function log(string memory p0, bool p1, string memory p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); + } + + function log(string memory p0, bool p1, bool p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint256)", p0, p1, p2, p3)); + } + + function log(string memory p0, bool p1, bool p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); + } + + function log(string memory p0, bool p1, bool p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); + } + + function log(string memory p0, bool p1, bool p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); + } + + function log(string memory p0, bool p1, address p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint256)", p0, p1, p2, p3)); + } + + function log(string memory p0, bool p1, address p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); + } + + function log(string memory p0, bool p1, address p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); + } + + function log(string memory p0, bool p1, address p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); + } + + function log(string memory p0, address p1, uint256 p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,uint256)", p0, p1, p2, p3)); + } + + function log(string memory p0, address p1, uint256 p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,string)", p0, p1, p2, p3)); + } + + function log(string memory p0, address p1, uint256 p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,bool)", p0, p1, p2, p3)); + } + + function log(string memory p0, address p1, uint256 p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,address)", p0, p1, p2, p3)); + } + + function log(string memory p0, address p1, string memory p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint256)", p0, p1, p2, p3)); + } + + function log(string memory p0, address p1, string memory p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); + } + + function log(string memory p0, address p1, string memory p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); + } + + function log(string memory p0, address p1, string memory p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); + } + + function log(string memory p0, address p1, bool p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint256)", p0, p1, p2, p3)); + } + + function log(string memory p0, address p1, bool p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); + } + + function log(string memory p0, address p1, bool p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); + } + + function log(string memory p0, address p1, bool p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); + } + + function log(string memory p0, address p1, address p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint256)", p0, p1, p2, p3)); + } + + function log(string memory p0, address p1, address p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); + } + + function log(string memory p0, address p1, address p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); + } + + function log(string memory p0, address p1, address p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); + } + + function log(bool p0, uint256 p1, uint256 p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,uint256)", p0, p1, p2, p3)); + } + + function log(bool p0, uint256 p1, uint256 p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,string)", p0, p1, p2, p3)); + } + + function log(bool p0, uint256 p1, uint256 p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,bool)", p0, p1, p2, p3)); + } + + function log(bool p0, uint256 p1, uint256 p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,address)", p0, p1, p2, p3)); + } + + function log(bool p0, uint256 p1, string memory p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,uint256)", p0, p1, p2, p3)); + } + + function log(bool p0, uint256 p1, string memory p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,string)", p0, p1, p2, p3)); + } + + function log(bool p0, uint256 p1, string memory p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,bool)", p0, p1, p2, p3)); + } + + function log(bool p0, uint256 p1, string memory p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,address)", p0, p1, p2, p3)); + } + + function log(bool p0, uint256 p1, bool p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,uint256)", p0, p1, p2, p3)); + } + + function log(bool p0, uint256 p1, bool p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,string)", p0, p1, p2, p3)); + } + + function log(bool p0, uint256 p1, bool p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,bool)", p0, p1, p2, p3)); + } + + function log(bool p0, uint256 p1, bool p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,address)", p0, p1, p2, p3)); + } + + function log(bool p0, uint256 p1, address p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,uint256)", p0, p1, p2, p3)); + } + + function log(bool p0, uint256 p1, address p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,string)", p0, p1, p2, p3)); + } + + function log(bool p0, uint256 p1, address p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,bool)", p0, p1, p2, p3)); + } + + function log(bool p0, uint256 p1, address p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,address)", p0, p1, p2, p3)); + } + + function log(bool p0, string memory p1, uint256 p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,uint256)", p0, p1, p2, p3)); + } + + function log(bool p0, string memory p1, uint256 p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,string)", p0, p1, p2, p3)); + } + + function log(bool p0, string memory p1, uint256 p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,bool)", p0, p1, p2, p3)); + } + + function log(bool p0, string memory p1, uint256 p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,address)", p0, p1, p2, p3)); + } + + function log(bool p0, string memory p1, string memory p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint256)", p0, p1, p2, p3)); + } + + function log(bool p0, string memory p1, string memory p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); + } + + function log(bool p0, string memory p1, string memory p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); + } + + function log(bool p0, string memory p1, string memory p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); + } + + function log(bool p0, string memory p1, bool p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint256)", p0, p1, p2, p3)); + } + + function log(bool p0, string memory p1, bool p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); + } + + function log(bool p0, string memory p1, bool p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); + } + + function log(bool p0, string memory p1, bool p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); + } + + function log(bool p0, string memory p1, address p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint256)", p0, p1, p2, p3)); + } + + function log(bool p0, string memory p1, address p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); + } + + function log(bool p0, string memory p1, address p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); + } + + function log(bool p0, string memory p1, address p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); + } + + function log(bool p0, bool p1, uint256 p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,uint256)", p0, p1, p2, p3)); + } + + function log(bool p0, bool p1, uint256 p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,string)", p0, p1, p2, p3)); + } + + function log(bool p0, bool p1, uint256 p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,bool)", p0, p1, p2, p3)); + } + + function log(bool p0, bool p1, uint256 p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,address)", p0, p1, p2, p3)); + } + + function log(bool p0, bool p1, string memory p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint256)", p0, p1, p2, p3)); + } + + function log(bool p0, bool p1, string memory p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); + } + + function log(bool p0, bool p1, string memory p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); + } + + function log(bool p0, bool p1, string memory p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); + } + + function log(bool p0, bool p1, bool p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint256)", p0, p1, p2, p3)); + } + + function log(bool p0, bool p1, bool p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); + } + + function log(bool p0, bool p1, bool p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); + } + + function log(bool p0, bool p1, bool p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); + } + + function log(bool p0, bool p1, address p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint256)", p0, p1, p2, p3)); + } + + function log(bool p0, bool p1, address p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); + } + + function log(bool p0, bool p1, address p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); + } + + function log(bool p0, bool p1, address p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); + } + + function log(bool p0, address p1, uint256 p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,uint256)", p0, p1, p2, p3)); + } + + function log(bool p0, address p1, uint256 p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,string)", p0, p1, p2, p3)); + } + + function log(bool p0, address p1, uint256 p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,bool)", p0, p1, p2, p3)); + } + + function log(bool p0, address p1, uint256 p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,address)", p0, p1, p2, p3)); + } + + function log(bool p0, address p1, string memory p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint256)", p0, p1, p2, p3)); + } + + function log(bool p0, address p1, string memory p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); + } + + function log(bool p0, address p1, string memory p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); + } + + function log(bool p0, address p1, string memory p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); + } + + function log(bool p0, address p1, bool p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint256)", p0, p1, p2, p3)); + } + + function log(bool p0, address p1, bool p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); + } + + function log(bool p0, address p1, bool p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); + } + + function log(bool p0, address p1, bool p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); + } + + function log(bool p0, address p1, address p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint256)", p0, p1, p2, p3)); + } + + function log(bool p0, address p1, address p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); + } + + function log(bool p0, address p1, address p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); + } + + function log(bool p0, address p1, address p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); + } + + function log(address p0, uint256 p1, uint256 p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,uint256)", p0, p1, p2, p3)); + } + + function log(address p0, uint256 p1, uint256 p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,string)", p0, p1, p2, p3)); + } + + function log(address p0, uint256 p1, uint256 p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,bool)", p0, p1, p2, p3)); + } + + function log(address p0, uint256 p1, uint256 p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,address)", p0, p1, p2, p3)); + } + + function log(address p0, uint256 p1, string memory p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,uint256)", p0, p1, p2, p3)); + } + + function log(address p0, uint256 p1, string memory p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,string)", p0, p1, p2, p3)); + } + + function log(address p0, uint256 p1, string memory p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,bool)", p0, p1, p2, p3)); + } + + function log(address p0, uint256 p1, string memory p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,address)", p0, p1, p2, p3)); + } + + function log(address p0, uint256 p1, bool p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,uint256)", p0, p1, p2, p3)); + } + + function log(address p0, uint256 p1, bool p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,string)", p0, p1, p2, p3)); + } + + function log(address p0, uint256 p1, bool p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,bool)", p0, p1, p2, p3)); + } + + function log(address p0, uint256 p1, bool p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,address)", p0, p1, p2, p3)); + } + + function log(address p0, uint256 p1, address p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,uint256)", p0, p1, p2, p3)); + } + + function log(address p0, uint256 p1, address p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,string)", p0, p1, p2, p3)); + } + + function log(address p0, uint256 p1, address p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,bool)", p0, p1, p2, p3)); + } + + function log(address p0, uint256 p1, address p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,address)", p0, p1, p2, p3)); + } + + function log(address p0, string memory p1, uint256 p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,uint256)", p0, p1, p2, p3)); + } + + function log(address p0, string memory p1, uint256 p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,string)", p0, p1, p2, p3)); + } + + function log(address p0, string memory p1, uint256 p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,bool)", p0, p1, p2, p3)); + } + + function log(address p0, string memory p1, uint256 p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,address)", p0, p1, p2, p3)); + } + + function log(address p0, string memory p1, string memory p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint256)", p0, p1, p2, p3)); + } + + function log(address p0, string memory p1, string memory p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); + } + + function log(address p0, string memory p1, string memory p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); + } + + function log(address p0, string memory p1, string memory p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); + } + + function log(address p0, string memory p1, bool p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint256)", p0, p1, p2, p3)); + } + + function log(address p0, string memory p1, bool p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); + } + + function log(address p0, string memory p1, bool p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); + } + + function log(address p0, string memory p1, bool p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); + } + + function log(address p0, string memory p1, address p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint256)", p0, p1, p2, p3)); + } + + function log(address p0, string memory p1, address p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); + } + + function log(address p0, string memory p1, address p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); + } + + function log(address p0, string memory p1, address p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); + } + + function log(address p0, bool p1, uint256 p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,uint256)", p0, p1, p2, p3)); + } + + function log(address p0, bool p1, uint256 p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,string)", p0, p1, p2, p3)); + } + + function log(address p0, bool p1, uint256 p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,bool)", p0, p1, p2, p3)); + } + + function log(address p0, bool p1, uint256 p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,address)", p0, p1, p2, p3)); + } + + function log(address p0, bool p1, string memory p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint256)", p0, p1, p2, p3)); + } + + function log(address p0, bool p1, string memory p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); + } + + function log(address p0, bool p1, string memory p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); + } + + function log(address p0, bool p1, string memory p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); + } + + function log(address p0, bool p1, bool p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint256)", p0, p1, p2, p3)); + } + + function log(address p0, bool p1, bool p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); + } + + function log(address p0, bool p1, bool p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); + } + + function log(address p0, bool p1, bool p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); + } + + function log(address p0, bool p1, address p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint256)", p0, p1, p2, p3)); + } + + function log(address p0, bool p1, address p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); + } + + function log(address p0, bool p1, address p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); + } + + function log(address p0, bool p1, address p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); + } + + function log(address p0, address p1, uint256 p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,uint256)", p0, p1, p2, p3)); + } + + function log(address p0, address p1, uint256 p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,string)", p0, p1, p2, p3)); + } + + function log(address p0, address p1, uint256 p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,bool)", p0, p1, p2, p3)); + } + + function log(address p0, address p1, uint256 p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,address)", p0, p1, p2, p3)); + } + + function log(address p0, address p1, string memory p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint256)", p0, p1, p2, p3)); + } + + function log(address p0, address p1, string memory p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); + } + + function log(address p0, address p1, string memory p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); + } + + function log(address p0, address p1, string memory p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); + } + + function log(address p0, address p1, bool p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint256)", p0, p1, p2, p3)); + } + + function log(address p0, address p1, bool p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); + } + + function log(address p0, address p1, bool p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); + } + + function log(address p0, address p1, bool p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); + } + + function log(address p0, address p1, address p2, uint256 p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint256)", p0, p1, p2, p3)); + } + + function log(address p0, address p1, address p2, string memory p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); + } + + function log(address p0, address p1, address p2, bool p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); + } + + function log(address p0, address p1, address p2, address p3) internal pure { + _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); + } + + function table(uint256[] memory values) internal pure { + _sendLogPayload(abi.encodeWithSignature("table(uint256[])", values)); + } + + function table(int256[] memory values) internal pure { + _sendLogPayload(abi.encodeWithSignature("table(int256[])", values)); + } + + function table(address[] memory values) internal pure { + _sendLogPayload(abi.encodeWithSignature("table(address[])", values)); + } + + function table(bytes32[] memory values) internal pure { + _sendLogPayload(abi.encodeWithSignature("table(bytes32[])", values)); + } + + function table(string[] memory values) internal pure { + _sendLogPayload(abi.encodeWithSignature("table(string[])", values)); + } + + function table(bool[] memory values) internal pure { + _sendLogPayload(abi.encodeWithSignature("table(bool[])", values)); + } + + function table(string[] memory keys, uint256[] memory values) internal pure { + _sendLogPayload(abi.encodeWithSignature("table(string[],uint256[])", keys, values)); + } + + function table(string[] memory keys, int256[] memory values) internal pure { + _sendLogPayload(abi.encodeWithSignature("table(string[],int256[])", keys, values)); + } + + function table(string[] memory keys, address[] memory values) internal pure { + _sendLogPayload(abi.encodeWithSignature("table(string[],address[])", keys, values)); + } + + function table(string[] memory keys, bytes32[] memory values) internal pure { + _sendLogPayload(abi.encodeWithSignature("table(string[],bytes32[])", keys, values)); + } + + function table(string[] memory keys, string[] memory values) internal pure { + _sendLogPayload(abi.encodeWithSignature("table(string[],string[])", keys, values)); + } + + function table(string[] memory keys, bool[] memory values) internal pure { + _sendLogPayload(abi.encodeWithSignature("table(string[],bool[])", keys, values)); + } +} diff --git a/contracts/evm/lib/forge-std/src/console2.sol b/contracts/evm/lib/forge-std/src/console2.sol new file mode 100644 index 0000000000..1ecdbbf723 --- /dev/null +++ b/contracts/evm/lib/forge-std/src/console2.sol @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {console as console2} from "./console.sol"; diff --git a/contracts/evm/lib/forge-std/src/interfaces/IERC1155.sol b/contracts/evm/lib/forge-std/src/interfaces/IERC1155.sol new file mode 100644 index 0000000000..9bf979dc5a --- /dev/null +++ b/contracts/evm/lib/forge-std/src/interfaces/IERC1155.sol @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {IERC165} from "./IERC165.sol"; + +/// @title ERC-1155 Multi Token Standard +/// @dev See https://eips.ethereum.org/EIPS/eip-1155 +/// Note: The ERC-165 identifier for this interface is 0xd9b67a26. +interface IERC1155 is IERC165 { + /// @dev + /// - Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard). + /// - The `_operator` argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be msg.sender). + /// - The `_from` argument MUST be the address of the holder whose balance is decreased. + /// - The `_to` argument MUST be the address of the recipient whose balance is increased. + /// - The `_id` argument MUST be the token type being transferred. + /// - The `_value` argument MUST be the number of tokens the holder balance is decreased by and match what the recipient balance is increased by. + /// - When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address). + /// - When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address). + event TransferSingle( + address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value + ); + + /// @dev + /// - Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard). + /// - The `_operator` argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be msg.sender). + /// - The `_from` argument MUST be the address of the holder whose balance is decreased. + /// - The `_to` argument MUST be the address of the recipient whose balance is increased. + /// - The `_ids` argument MUST be the list of tokens being transferred. + /// - The `_values` argument MUST be the list of number of tokens (matching the list and order of tokens specified in _ids) the holder balance is decreased by and match what the recipient balance is increased by. + /// - When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address). + /// - When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address). + event TransferBatch( + address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values + ); + + /// @dev MUST emit when approval for a second party/operator address to manage all tokens for an owner address is enabled or disabled (absence of an event assumes disabled). + event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); + + /// @dev MUST emit when the URI is updated for a token ID. URIs are defined in RFC 3986. + /// The URI MUST point to a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema". + event URI(string _value, uint256 indexed _id); + + /// @notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call). + /// @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). + /// - MUST revert if `_to` is the zero address. + /// - MUST revert if balance of holder for token `_id` is lower than the `_value` sent. + /// - MUST revert on any other error. + /// - MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard). + /// - After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). + /// @param _from Source address + /// @param _to Target address + /// @param _id ID of the token type + /// @param _value Transfer amount + /// @param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to` + function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external; + + /// @notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call). + /// @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). + /// - MUST revert if `_to` is the zero address. + /// - MUST revert if length of `_ids` is not the same as length of `_values`. + /// - MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient. + /// - MUST revert on any other error. + /// - MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard). + /// - Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc). + /// - After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). + /// @param _from Source address + /// @param _to Target address + /// @param _ids IDs of each token type (order and length must match _values array) + /// @param _values Transfer amounts per token type (order and length must match _ids array) + /// @param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to` + function safeBatchTransferFrom( + address _from, + address _to, + uint256[] calldata _ids, + uint256[] calldata _values, + bytes calldata _data + ) external; + + /// @notice Get the balance of an account's tokens. + /// @param _owner The address of the token holder + /// @param _id ID of the token + /// @return The _owner's balance of the token type requested + function balanceOf(address _owner, uint256 _id) external view returns (uint256); + + /// @notice Get the balance of multiple account/token pairs + /// @param _owners The addresses of the token holders + /// @param _ids ID of the tokens + /// @return The _owner's balance of the token types requested (i.e. balance for each (owner, id) pair) + function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) + external + view + returns (uint256[] memory); + + /// @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens. + /// @dev MUST emit the ApprovalForAll event on success. + /// @param _operator Address to add to the set of authorized operators + /// @param _approved True if the operator is approved, false to revoke approval + function setApprovalForAll(address _operator, bool _approved) external; + + /// @notice Queries the approval status of an operator for a given owner. + /// @param _owner The owner of the tokens + /// @param _operator Address of authorized operator + /// @return True if the operator is approved, false if not + function isApprovedForAll(address _owner, address _operator) external view returns (bool); +} diff --git a/contracts/evm/lib/forge-std/src/interfaces/IERC165.sol b/contracts/evm/lib/forge-std/src/interfaces/IERC165.sol new file mode 100644 index 0000000000..fced182216 --- /dev/null +++ b/contracts/evm/lib/forge-std/src/interfaces/IERC165.sol @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +interface IERC165 { + /// @notice Query if a contract implements an interface + /// @param interfaceID The interface identifier, as specified in ERC-165 + /// @dev Interface identification is specified in ERC-165. This function + /// uses less than 30,000 gas. + /// @return `true` if the contract implements `interfaceID` and + /// `interfaceID` is not 0xffffffff, `false` otherwise + function supportsInterface(bytes4 interfaceID) external view returns (bool); +} diff --git a/contracts/evm/lib/forge-std/src/interfaces/IERC20.sol b/contracts/evm/lib/forge-std/src/interfaces/IERC20.sol new file mode 100644 index 0000000000..1a17fe1341 --- /dev/null +++ b/contracts/evm/lib/forge-std/src/interfaces/IERC20.sol @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +/// @dev Interface of the ERC20 standard as defined in the EIP. +/// @dev This includes the optional name, symbol, and decimals metadata. +interface IERC20 { + /// @dev Emitted when `value` tokens are moved from one account (`from`) to another (`to`). + event Transfer(address indexed from, address indexed to, uint256 value); + + /// @dev Emitted when the allowance of a `spender` for an `owner` is set, where `value` + /// is the new allowance. + event Approval(address indexed owner, address indexed spender, uint256 value); + + /// @notice Returns the amount of tokens in existence. + function totalSupply() external view returns (uint256); + + /// @notice Returns the amount of tokens owned by `account`. + function balanceOf(address account) external view returns (uint256); + + /// @notice Moves `amount` tokens from the caller's account to `to`. + function transfer(address to, uint256 amount) external returns (bool); + + /// @notice Returns the remaining number of tokens that `spender` is allowed + /// to spend on behalf of `owner` + function allowance(address owner, address spender) external view returns (uint256); + + /// @notice Sets `amount` as the allowance of `spender` over the caller's tokens. + /// @dev Be aware of front-running risks: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 + function approve(address spender, uint256 amount) external returns (bool); + + /// @notice Moves `amount` tokens from `from` to `to` using the allowance mechanism. + /// `amount` is then deducted from the caller's allowance. + function transferFrom(address from, address to, uint256 amount) external returns (bool); + + /// @notice Returns the name of the token. + function name() external view returns (string memory); + + /// @notice Returns the symbol of the token. + function symbol() external view returns (string memory); + + /// @notice Returns the decimals places of the token. + function decimals() external view returns (uint8); +} diff --git a/contracts/evm/lib/forge-std/src/interfaces/IERC4626.sol b/contracts/evm/lib/forge-std/src/interfaces/IERC4626.sol new file mode 100644 index 0000000000..e63fce4318 --- /dev/null +++ b/contracts/evm/lib/forge-std/src/interfaces/IERC4626.sol @@ -0,0 +1,190 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {IERC20} from "./IERC20.sol"; + +/// @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in +/// https://eips.ethereum.org/EIPS/eip-4626 +interface IERC4626 is IERC20 { + event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares); + + event Withdraw( + address indexed sender, address indexed receiver, address indexed owner, uint256 assets, uint256 shares + ); + + /// @notice Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing. + /// @dev + /// - MUST be an ERC-20 token contract. + /// - MUST NOT revert. + function asset() external view returns (address assetTokenAddress); + + /// @notice Returns the total amount of the underlying asset that is “managed” by Vault. + /// @dev + /// - SHOULD include any compounding that occurs from yield. + /// - MUST be inclusive of any fees that are charged against assets in the Vault. + /// - MUST NOT revert. + function totalAssets() external view returns (uint256 totalManagedAssets); + + /// @notice Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal + /// scenario where all the conditions are met. + /// @dev + /// - MUST NOT be inclusive of any fees that are charged against assets in the Vault. + /// - MUST NOT show any variations depending on the caller. + /// - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange. + /// - MUST NOT revert. + /// + /// NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the + /// “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and + /// from. + function convertToShares(uint256 assets) external view returns (uint256 shares); + + /// @notice Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal + /// scenario where all the conditions are met. + /// @dev + /// - MUST NOT be inclusive of any fees that are charged against assets in the Vault. + /// - MUST NOT show any variations depending on the caller. + /// - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange. + /// - MUST NOT revert. + /// + /// NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the + /// “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and + /// from. + function convertToAssets(uint256 shares) external view returns (uint256 assets); + + /// @notice Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver, + /// through a deposit call. + /// @dev + /// - MUST return a limited value if receiver is subject to some deposit limit. + /// - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited. + /// - MUST NOT revert. + function maxDeposit(address receiver) external view returns (uint256 maxAssets); + + /// @notice Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given + /// current on-chain conditions. + /// @dev + /// - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit + /// call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called + /// in the same transaction. + /// - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the + /// deposit would be accepted, regardless if the user has enough tokens approved, etc. + /// - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees. + /// - MUST NOT revert. + /// + /// NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in + /// share price or some other type of condition, meaning the depositor will lose assets by depositing. + function previewDeposit(uint256 assets) external view returns (uint256 shares); + + /// @notice Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens. + /// @dev + /// - MUST emit the Deposit event. + /// - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the + /// deposit execution, and are accounted for during deposit. + /// - MUST revert if all assets cannot be deposited (due to deposit limit being reached, slippage, the user not + /// approving enough underlying tokens to the Vault contract, etc). + /// + /// NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token. + function deposit(uint256 assets, address receiver) external returns (uint256 shares); + + /// @notice Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call. + /// @dev + /// - MUST return a limited value if receiver is subject to some mint limit. + /// - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted. + /// - MUST NOT revert. + function maxMint(address receiver) external view returns (uint256 maxShares); + + /// @notice Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given + /// current on-chain conditions. + /// @dev + /// - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call + /// in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the + /// same transaction. + /// - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint + /// would be accepted, regardless if the user has enough tokens approved, etc. + /// - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees. + /// - MUST NOT revert. + /// + /// NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in + /// share price or some other type of condition, meaning the depositor will lose assets by minting. + function previewMint(uint256 shares) external view returns (uint256 assets); + + /// @notice Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens. + /// @dev + /// - MUST emit the Deposit event. + /// - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint + /// execution, and are accounted for during mint. + /// - MUST revert if all shares cannot be minted (due to deposit limit being reached, slippage, the user not + /// approving enough underlying tokens to the Vault contract, etc). + /// + /// NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token. + function mint(uint256 shares, address receiver) external returns (uint256 assets); + + /// @notice Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the + /// Vault, through a withdrawal call. + /// @dev + /// - MUST return a limited value if owner is subject to some withdrawal limit or timelock. + /// - MUST NOT revert. + function maxWithdraw(address owner) external view returns (uint256 maxAssets); + + /// @notice Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block, + /// given current on-chain conditions. + /// @dev + /// - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw + /// call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if + /// called + /// in the same transaction. + /// - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though + /// the withdrawal would be accepted, regardless if the user has enough shares, etc. + /// - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees. + /// - MUST NOT revert. + /// + /// NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in + /// share price or some other type of condition, meaning the owner will lose assets by withdrawing. + function previewWithdraw(uint256 assets) external view returns (uint256 shares); + + /// @notice Burns shares from owner and sends exactly assets of underlying tokens to receiver. + /// @dev + /// - MUST emit the Withdraw event. + /// - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the + /// withdraw execution, and are accounted for during withdrawal. + /// - MUST revert if all assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner + /// not having enough shares, etc). + /// + /// Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed. + /// Those methods should be performed separately. + function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares); + + /// @notice Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault, + /// through a redeem call. + /// @dev + /// - MUST return a limited value if owner is subject to some withdrawal limit or timelock. + /// - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock. + /// - MUST NOT revert. + function maxRedeem(address owner) external view returns (uint256 maxShares); + + /// @notice Allows an on-chain or off-chain user to simulate the effects of their redemption at the current block, + /// given current on-chain conditions. + /// @dev + /// - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call + /// in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the + /// same transaction. + /// - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the + /// redemption would be accepted, regardless if the user has enough shares, etc. + /// - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees. + /// - MUST NOT revert. + /// + /// NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in + /// share price or some other type of condition, meaning the owner will lose assets by redeeming. + function previewRedeem(uint256 shares) external view returns (uint256 assets); + + /// @notice Burns exactly shares from owner and sends assets of underlying tokens to receiver. + /// @dev + /// - MUST emit the Withdraw event. + /// - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the + /// redeem execution, and are accounted for during redeem. + /// - MUST revert if all shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner + /// not having enough shares, etc). + /// + /// NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed. + /// Those methods should be performed separately. + function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets); +} diff --git a/contracts/evm/lib/forge-std/src/interfaces/IERC6909.sol b/contracts/evm/lib/forge-std/src/interfaces/IERC6909.sol new file mode 100644 index 0000000000..d448b0fa3f --- /dev/null +++ b/contracts/evm/lib/forge-std/src/interfaces/IERC6909.sol @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {IERC165} from "./IERC165.sol"; + +/// @dev Required interface of an ERC-6909 compliant contract, as defined in +/// https://eips.ethereum.org/EIPS/eip-6909 +interface IERC6909 is IERC165 { + /// @dev Emitted when the allowance of a `spender` for an `owner` is set for a token of type `id`. + event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount); + + /// @dev Emitted when `owner` grants or revokes operator status for a `spender`. + event OperatorSet(address indexed owner, address indexed spender, bool approved); + + /// @dev Emitted when `amount` tokens of type `id` are moved from `sender` to `receiver` initiated by `caller`. + event Transfer( + address caller, address indexed sender, address indexed receiver, uint256 indexed id, uint256 amount + ); + + ///@dev Returns the amount of tokens of type `id` owned by `owner`. + function balanceOf(address owner, uint256 id) external view returns (uint256); + + /// @dev Returns the amount of tokens of type `id` that `spender` is allowed to spend on behalf of `owner`. + /// NOTE: Does not include operator allowances. + function allowance(address owner, address spender, uint256 id) external view returns (uint256); + + /// @dev Returns true if `spender` is set as an operator for `owner`. + function isOperator(address owner, address spender) external view returns (bool); + + /// @dev Sets an approval to `spender` for `amount` tokens of type `id` from the caller's tokens. + /// Must return true. + function approve(address spender, uint256 id, uint256 amount) external returns (bool); + + /// @dev Grants or revokes unlimited transfer permission of any token id to `spender` for the caller's tokens. + /// Must return true. + function setOperator(address spender, bool approved) external returns (bool); + + /// @dev Transfers `amount` of token type `id` from the caller's account to `receiver`. + /// Must return true. + function transfer(address receiver, uint256 id, uint256 amount) external returns (bool); + + /// @dev Transfers `amount` of token type `id` from `sender` to `receiver`. + /// Must return true. + function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool); +} + +/// @dev Optional extension of {IERC6909} that adds metadata functions. +interface IERC6909Metadata is IERC6909 { + /// @dev Returns the name of the token of type `id`. + function name(uint256 id) external view returns (string memory); + + /// @dev Returns the ticker symbol of the token of type `id`. + function symbol(uint256 id) external view returns (string memory); + + /// @dev Returns the number of decimals for the token of type `id`. + function decimals(uint256 id) external view returns (uint8); +} + +/// @dev Optional extension of {IERC6909} that adds content URI functions. +interface IERC6909ContentURI is IERC6909 { + /// @dev Returns URI for the contract. + function contractURI() external view returns (string memory); + + /// @dev Returns the URI for the token of type `id`. + function tokenURI(uint256 id) external view returns (string memory); +} + +/// @dev Optional extension of {IERC6909} that adds a token supply function. +interface IERC6909TokenSupply is IERC6909 { + /// @dev Returns the total supply of the token of type `id`. + function totalSupply(uint256 id) external view returns (uint256); +} diff --git a/contracts/evm/lib/forge-std/src/interfaces/IERC721.sol b/contracts/evm/lib/forge-std/src/interfaces/IERC721.sol new file mode 100644 index 0000000000..9a03145ac2 --- /dev/null +++ b/contracts/evm/lib/forge-std/src/interfaces/IERC721.sol @@ -0,0 +1,164 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {IERC165} from "./IERC165.sol"; + +/// @title ERC-721 Non-Fungible Token Standard +/// @dev See https://eips.ethereum.org/EIPS/eip-721 +/// Note: the ERC-165 identifier for this interface is 0x80ac58cd. +interface IERC721 is IERC165 { + /// @dev This emits when ownership of any NFT changes by any mechanism. + /// This event emits when NFTs are created (`from` == 0) and destroyed + /// (`to` == 0). Exception: during contract creation, any number of NFTs + /// may be created and assigned without emitting Transfer. At the time of + /// any transfer, the approved address for that NFT (if any) is reset to none. + event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); + + /// @dev This emits when the approved address for an NFT is changed or + /// reaffirmed. The zero address indicates there is no approved address. + /// When a Transfer event emits, this also indicates that the approved + /// address for that NFT (if any) is reset to none. + event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); + + /// @dev This emits when an operator is enabled or disabled for an owner. + /// The operator can manage all NFTs of the owner. + event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); + + /// @notice Count all NFTs assigned to an owner + /// @dev NFTs assigned to the zero address are considered invalid, and this + /// function throws for queries about the zero address. + /// @param _owner An address for whom to query the balance + /// @return The number of NFTs owned by `_owner`, possibly zero + function balanceOf(address _owner) external view returns (uint256); + + /// @notice Find the owner of an NFT + /// @dev NFTs assigned to zero address are considered invalid, and queries + /// about them do throw. + /// @param _tokenId The identifier for an NFT + /// @return The address of the owner of the NFT + function ownerOf(uint256 _tokenId) external view returns (address); + + /// @notice Transfers the ownership of an NFT from one address to another address + /// @dev Throws unless `msg.sender` is the current owner, an authorized + /// operator, or the approved address for this NFT. Throws if `_from` is + /// not the current owner. Throws if `_to` is the zero address. Throws if + /// `_tokenId` is not a valid NFT. When transfer is complete, this function + /// checks if `_to` is a smart contract (code size > 0). If so, it calls + /// `onERC721Received` on `_to` and throws if the return value is not + /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. + /// @param _from The current owner of the NFT + /// @param _to The new owner + /// @param _tokenId The NFT to transfer + /// @param data Additional data with no specified format, sent in call to `_to` + function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes calldata data) external payable; + + /// @notice Transfers the ownership of an NFT from one address to another address + /// @dev This works identically to the other function with an extra data parameter, + /// except this function just sets data to "". + /// @param _from The current owner of the NFT + /// @param _to The new owner + /// @param _tokenId The NFT to transfer + function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable; + + /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE + /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE + /// THEY MAY BE PERMANENTLY LOST + /// @dev Throws unless `msg.sender` is the current owner, an authorized + /// operator, or the approved address for this NFT. Throws if `_from` is + /// not the current owner. Throws if `_to` is the zero address. Throws if + /// `_tokenId` is not a valid NFT. + /// @param _from The current owner of the NFT + /// @param _to The new owner + /// @param _tokenId The NFT to transfer + function transferFrom(address _from, address _to, uint256 _tokenId) external payable; + + /// @notice Change or reaffirm the approved address for an NFT + /// @dev The zero address indicates there is no approved address. + /// Throws unless `msg.sender` is the current NFT owner, or an authorized + /// operator of the current owner. + /// @param _approved The new approved NFT controller + /// @param _tokenId The NFT to approve + function approve(address _approved, uint256 _tokenId) external payable; + + /// @notice Enable or disable approval for a third party ("operator") to manage + /// all of `msg.sender`'s assets + /// @dev Emits the ApprovalForAll event. The contract MUST allow + /// multiple operators per owner. + /// @param _operator Address to add to the set of authorized operators + /// @param _approved True if the operator is approved, false to revoke approval + function setApprovalForAll(address _operator, bool _approved) external; + + /// @notice Get the approved address for a single NFT + /// @dev Throws if `_tokenId` is not a valid NFT. + /// @param _tokenId The NFT to find the approved address for + /// @return The approved address for this NFT, or the zero address if there is none + function getApproved(uint256 _tokenId) external view returns (address); + + /// @notice Query if an address is an authorized operator for another address + /// @param _owner The address that owns the NFTs + /// @param _operator The address that acts on behalf of the owner + /// @return True if `_operator` is an approved operator for `_owner`, false otherwise + function isApprovedForAll(address _owner, address _operator) external view returns (bool); +} + +/// @dev Note: the ERC-165 identifier for this interface is 0x150b7a02. +interface IERC721TokenReceiver { + /// @notice Handle the receipt of an NFT + /// @dev The ERC721 smart contract calls this function on the recipient + /// after a `transfer`. This function MAY throw to revert and reject the + /// transfer. Return of other than the magic value MUST result in the + /// transaction being reverted. + /// Note: the contract address is always the message sender. + /// @param _operator The address which called `safeTransferFrom` function + /// @param _from The address which previously owned the token + /// @param _tokenId The NFT identifier which is being transferred + /// @param _data Additional data with no specified format + /// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` + /// unless throwing + function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data) + external + returns (bytes4); +} + +/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension +/// @dev See https://eips.ethereum.org/EIPS/eip-721 +/// Note: the ERC-165 identifier for this interface is 0x5b5e139f. +interface IERC721Metadata is IERC721 { + /// @notice A descriptive name for a collection of NFTs in this contract + function name() external view returns (string memory _name); + + /// @notice An abbreviated name for NFTs in this contract + function symbol() external view returns (string memory _symbol); + + /// @notice A distinct Uniform Resource Identifier (URI) for a given asset. + /// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC + /// 3986. The URI may point to a JSON file that conforms to the "ERC721 + /// Metadata JSON Schema". + function tokenURI(uint256 _tokenId) external view returns (string memory); +} + +/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension +/// @dev See https://eips.ethereum.org/EIPS/eip-721 +/// Note: the ERC-165 identifier for this interface is 0x780e9d63. +interface IERC721Enumerable is IERC721 { + /// @notice Count NFTs tracked by this contract + /// @return A count of valid NFTs tracked by this contract, where each one of + /// them has an assigned and queryable owner not equal to the zero address + function totalSupply() external view returns (uint256); + + /// @notice Enumerate valid NFTs + /// @dev Throws if `_index` >= `totalSupply()`. + /// @param _index A counter less than `totalSupply()` + /// @return The token identifier for the `_index`th NFT, + /// (sort order not specified) + function tokenByIndex(uint256 _index) external view returns (uint256); + + /// @notice Enumerate NFTs assigned to an owner + /// @dev Throws if `_index` >= `balanceOf(_owner)` or if + /// `_owner` is the zero address, representing invalid NFTs. + /// @param _owner An address where we are interested in NFTs owned by them + /// @param _index A counter less than `balanceOf(_owner)` + /// @return The token identifier for the `_index`th NFT assigned to `_owner`, + /// (sort order not specified) + function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256); +} diff --git a/contracts/evm/lib/forge-std/src/interfaces/IERC7540.sol b/contracts/evm/lib/forge-std/src/interfaces/IERC7540.sol new file mode 100644 index 0000000000..3082c51818 --- /dev/null +++ b/contracts/evm/lib/forge-std/src/interfaces/IERC7540.sol @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {IERC7575} from "./IERC7575.sol"; + +/// @dev Interface of the base operator logic of ERC7540, as defined in +/// https://eips.ethereum.org/EIPS/eip-7540 +interface IERC7540Operator { + /** + * @dev The event emitted when an operator is set. + * + * @param controller The address of the controller. + * @param operator The address of the operator. + * @param approved The approval status. + */ + event OperatorSet(address indexed controller, address indexed operator, bool approved); + + /** + * @dev Sets or removes an operator for the caller. + * + * @param operator The address of the operator. + * @param approved The approval status. + * @return Whether the call was executed successfully or not + */ + function setOperator(address operator, bool approved) external returns (bool); + + /** + * @dev Returns `true` if the `operator` is approved as an operator for an `controller`. + * + * @param controller The address of the controller. + * @param operator The address of the operator. + * @return status The approval status + */ + function isOperator(address controller, address operator) external view returns (bool status); +} + +/// @dev Interface of the asynchronous deposit Vault interface of ERC7540, as defined in +/// https://eips.ethereum.org/EIPS/eip-7540 +interface IERC7540Deposit is IERC7540Operator { + event DepositRequest( + address indexed controller, address indexed owner, uint256 indexed requestId, address sender, uint256 assets + ); + /** + * @dev Transfers assets from sender into the Vault and submits a Request for asynchronous deposit. + * + * - MUST support ERC-20 approve / transferFrom on asset as a deposit Request flow. + * - MUST revert if all assets cannot be requested for deposit. + * - owner MUST be msg.sender unless some unspecified explicit approval is given by the caller, + * approval of ERC-20 tokens from owner to sender is NOT enough. + * + * @param assets the amount of deposit assets to transfer from owner + * @param controller the controller of the request who will be able to operate the request + * @param owner the source of the deposit assets + * + * NOTE: most implementations will require pre-approval of the Vault with the Vault's underlying asset token. + */ + + function requestDeposit(uint256 assets, address controller, address owner) external returns (uint256 requestId); + + /** + * @dev Returns the amount of requested assets in Pending state. + * + * - MUST NOT include any assets in Claimable state for deposit or mint. + * - MUST NOT show any variations depending on the caller. + * - MUST NOT revert unless due to integer overflow caused by an unreasonably large input. + */ + function pendingDepositRequest(uint256 requestId, address controller) external view returns (uint256 pendingAssets); + + /** + * @dev Returns the amount of requested assets in Claimable state for the controller to deposit or mint. + * + * - MUST NOT include any assets in Pending state. + * - MUST NOT show any variations depending on the caller. + * - MUST NOT revert unless due to integer overflow caused by an unreasonably large input. + */ + function claimableDepositRequest(uint256 requestId, address controller) + external + view + returns (uint256 claimableAssets); + + /** + * @dev Mints shares Vault shares to receiver by claiming the Request of the controller. + * + * - MUST emit the Deposit event. + * - controller MUST equal msg.sender unless the controller has approved the msg.sender as an operator. + */ + function deposit(uint256 assets, address receiver, address controller) external returns (uint256 shares); + + /** + * @dev Mints exactly shares Vault shares to receiver by claiming the Request of the controller. + * + * - MUST emit the Deposit event. + * - controller MUST equal msg.sender unless the controller has approved the msg.sender as an operator. + */ + function mint(uint256 shares, address receiver, address controller) external returns (uint256 assets); +} + +/// @dev Interface of the asynchronous redeem Vault interface of ERC7540, as defined in +/// https://eips.ethereum.org/EIPS/eip-7540 +interface IERC7540Redeem is IERC7540Operator { + event RedeemRequest( + address indexed controller, address indexed owner, uint256 indexed requestId, address sender, uint256 shares + ); + + /** + * @dev Assumes control of shares from owner and submits a Request for asynchronous redeem. + * + * - MUST support a redeem Request flow where the control of shares is taken from owner directly. + * - Redeem Request approval of shares for a msg.sender not equal to owner MAY come either from ERC-20 approval + * over the shares of owner or if the owner has approved the msg.sender as an operator. + * - MUST revert if all shares cannot be requested for redeem or withdraw. + * + * @param shares the amount of shares to be redeemed to transfer from owner + * @param controller the controller of the request who will be able to operate the request + * @param owner the source of the shares to be redeemed + * + * NOTE: most implementations will require pre-approval of the Vault with the Vault's share token. + */ + function requestRedeem(uint256 shares, address controller, address owner) external returns (uint256 requestId); + + /** + * @dev Returns the amount of requested shares in Pending state. + * + * - MUST NOT include any shares in Claimable state for redeem or withdraw. + * - MUST NOT show any variations depending on the caller. + * - MUST NOT revert unless due to integer overflow caused by an unreasonably large input. + */ + function pendingRedeemRequest(uint256 requestId, address controller) external view returns (uint256 pendingShares); + + /** + * @dev Returns the amount of requested shares in Claimable state for the controller to redeem or withdraw. + * + * - MUST NOT include any shares in Pending state for redeem or withdraw. + * - MUST NOT show any variations depending on the caller. + * - MUST NOT revert unless due to integer overflow caused by an unreasonably large input. + */ + function claimableRedeemRequest(uint256 requestId, address controller) + external + view + returns (uint256 claimableShares); +} + +/// @dev Interface of the fully asynchronous Vault interface of ERC7540, as defined in +/// https://eips.ethereum.org/EIPS/eip-7540 +interface IERC7540 is IERC7540Deposit, IERC7540Redeem, IERC7575 {} diff --git a/contracts/evm/lib/forge-std/src/interfaces/IERC7575.sol b/contracts/evm/lib/forge-std/src/interfaces/IERC7575.sol new file mode 100644 index 0000000000..980f766ac2 --- /dev/null +++ b/contracts/evm/lib/forge-std/src/interfaces/IERC7575.sol @@ -0,0 +1,241 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {IERC165} from "./IERC165.sol"; + +/// @dev Interface of the ERC7575 "Multi-Asset ERC-4626 Vaults", as defined in +/// https://eips.ethereum.org/EIPS/eip-7575 +interface IERC7575 is IERC165 { + event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares); + event Withdraw( + address indexed sender, address indexed receiver, address indexed owner, uint256 assets, uint256 shares + ); + + /** + * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing. + * + * - MUST be an ERC-20 token contract. + * - MUST NOT revert. + */ + function asset() external view returns (address assetTokenAddress); + + /** + * @dev Returns the address of the share token + * + * - MUST be an ERC-20 token contract. + * - MUST NOT revert. + */ + function share() external view returns (address shareTokenAddress); + + /** + * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal + * scenario where all the conditions are met. + * + * - MUST NOT be inclusive of any fees that are charged against assets in the Vault. + * - MUST NOT show any variations depending on the caller. + * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange. + * - MUST NOT revert. + * + * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the + * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and + * from. + */ + function convertToShares(uint256 assets) external view returns (uint256 shares); + + /** + * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal + * scenario where all the conditions are met. + * + * - MUST NOT be inclusive of any fees that are charged against assets in the Vault. + * - MUST NOT show any variations depending on the caller. + * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange. + * - MUST NOT revert. + * + * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the + * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and + * from. + */ + function convertToAssets(uint256 shares) external view returns (uint256 assets); + + /** + * @dev Returns the total amount of the underlying asset that is “managed” by Vault. + * + * - SHOULD include any compounding that occurs from yield. + * - MUST be inclusive of any fees that are charged against assets in the Vault. + * - MUST NOT revert. + */ + function totalAssets() external view returns (uint256 totalManagedAssets); + + /** + * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver, + * through a deposit call. + * + * - MUST return a limited value if receiver is subject to some deposit limit. + * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited. + * - MUST NOT revert. + */ + function maxDeposit(address receiver) external view returns (uint256 maxAssets); + + /** + * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given + * current on-chain conditions. + * + * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit + * call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called + * in the same transaction. + * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the + * deposit would be accepted, regardless if the user has enough tokens approved, etc. + * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees. + * - MUST NOT revert. + * + * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in + * share price or some other type of condition, meaning the depositor will lose assets by depositing. + */ + function previewDeposit(uint256 assets) external view returns (uint256 shares); + + /** + * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens. + * + * - MUST emit the Deposit event. + * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the + * deposit execution, and are accounted for during deposit. + * - MUST revert if all assets cannot be deposited (due to deposit limit being reached, slippage, the user not + * approving enough underlying tokens to the Vault contract, etc). + * + * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token. + */ + function deposit(uint256 assets, address receiver) external returns (uint256 shares); + + /** + * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call. + * - MUST return a limited value if receiver is subject to some mint limit. + * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted. + * - MUST NOT revert. + */ + function maxMint(address receiver) external view returns (uint256 maxShares); + + /** + * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given + * current on-chain conditions. + * + * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call + * in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the + * same transaction. + * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint + * would be accepted, regardless if the user has enough tokens approved, etc. + * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees. + * - MUST NOT revert. + * + * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in + * share price or some other type of condition, meaning the depositor will lose assets by minting. + */ + function previewMint(uint256 shares) external view returns (uint256 assets); + + /** + * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens. + * + * - MUST emit the Deposit event. + * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint + * execution, and are accounted for during mint. + * - MUST revert if all shares cannot be minted (due to deposit limit being reached, slippage, the user not + * approving enough underlying tokens to the Vault contract, etc). + * + * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token. + */ + function mint(uint256 shares, address receiver) external returns (uint256 assets); + + /** + * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the + * Vault, through a withdraw call. + * + * - MUST return a limited value if owner is subject to some withdrawal limit or timelock. + * - MUST NOT revert. + */ + function maxWithdraw(address owner) external view returns (uint256 maxAssets); + + /** + * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block, + * given current on-chain conditions. + * + * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw + * call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if + * called + * in the same transaction. + * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though + * the withdrawal would be accepted, regardless if the user has enough shares, etc. + * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees. + * - MUST NOT revert. + * + * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in + * share price or some other type of condition, meaning the owner will lose assets by withdrawing. + */ + function previewWithdraw(uint256 assets) external view returns (uint256 shares); + + /** + * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver. + * + * - MUST emit the Withdraw event. + * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the + * withdraw execution, and are accounted for during withdraw. + * - MUST revert if all assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner + * not having enough shares, etc). + * + * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed. + * Those methods should be performed separately. + */ + function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares); + + /** + * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault, + * through a redeem call. + * + * - MUST return a limited value if owner is subject to some withdrawal limit or timelock. + * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock. + * - MUST NOT revert. + */ + function maxRedeem(address owner) external view returns (uint256 maxShares); + + /** + * @dev Allows an on-chain or off-chain user to simulate the effects of their redemption at the current block, + * given current on-chain conditions. + * + * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call + * in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the + * same transaction. + * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the + * redemption would be accepted, regardless if the user has enough shares, etc. + * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees. + * - MUST NOT revert. + * + * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in + * share price or some other type of condition, meaning the owner will lose assets by redeeming. + */ + function previewRedeem(uint256 shares) external view returns (uint256 assets); + + /** + * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver. + * + * - MUST emit the Withdraw event. + * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the + * redeem execution, and are accounted for during redeem. + * - MUST revert if all shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner + * not having enough shares, etc). + * + * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed. + * Those methods should be performed separately. + */ + function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets); +} + +/// @dev Interface of the ERC20 share token, as defined in +/// https://eips.ethereum.org/EIPS/eip-7575 +interface IERC7575Share is IERC165 { + event VaultUpdate(address indexed asset, address vault); + + /** + * @dev Returns the address of the Vault for the given asset. + * + * @param asset the ERC-20 token to deposit with into the Vault + */ + function vault(address asset) external view returns (address); +} diff --git a/contracts/evm/lib/forge-std/src/interfaces/IMulticall3.sol b/contracts/evm/lib/forge-std/src/interfaces/IMulticall3.sol new file mode 100644 index 0000000000..6a94133e06 --- /dev/null +++ b/contracts/evm/lib/forge-std/src/interfaces/IMulticall3.sol @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +interface IMulticall3 { + struct Call { + address target; + bytes callData; + } + + struct Call3 { + address target; + bool allowFailure; + bytes callData; + } + + struct Call3Value { + address target; + bool allowFailure; + uint256 value; + bytes callData; + } + + struct Result { + bool success; + bytes returnData; + } + + function aggregate(Call[] calldata calls) external payable returns (uint256 blockNumber, bytes[] memory returnData); + + function aggregate3(Call3[] calldata calls) external payable returns (Result[] memory returnData); + + function aggregate3Value(Call3Value[] calldata calls) external payable returns (Result[] memory returnData); + + function blockAndAggregate(Call[] calldata calls) + external + payable + returns (uint256 blockNumber, bytes32 blockHash, Result[] memory returnData); + + function getBasefee() external view returns (uint256 basefee); + + function getBlockHash(uint256 blockNumber) external view returns (bytes32 blockHash); + + function getBlockNumber() external view returns (uint256 blockNumber); + + function getChainId() external view returns (uint256 chainid); + + function getCurrentBlockCoinbase() external view returns (address coinbase); + + function getCurrentBlockDifficulty() external view returns (uint256 difficulty); + + function getCurrentBlockGasLimit() external view returns (uint256 gaslimit); + + function getCurrentBlockTimestamp() external view returns (uint256 timestamp); + + function getEthBalance(address addr) external view returns (uint256 balance); + + function getLastBlockHash() external view returns (bytes32 blockHash); + + function tryAggregate(bool requireSuccess, Call[] calldata calls) + external + payable + returns (Result[] memory returnData); + + function tryBlockAndAggregate(bool requireSuccess, Call[] calldata calls) + external + payable + returns (uint256 blockNumber, bytes32 blockHash, Result[] memory returnData); +} diff --git a/contracts/evm/lib/forge-std/src/safeconsole.sol b/contracts/evm/lib/forge-std/src/safeconsole.sol new file mode 100644 index 0000000000..e12d0600a3 --- /dev/null +++ b/contracts/evm/lib/forge-std/src/safeconsole.sol @@ -0,0 +1,13248 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +/// @author philogy +/// @dev Code generated automatically by script. +library safeconsole { + uint256 constant CONSOLE_ADDR = 0x000000000000000000000000000000000000000000636F6e736F6c652e6c6f67; + + // Credit to [0age](https://twitter.com/z0age/status/1654922202930888704) and [0xdapper](https://github.com/foundry-rs/forge-std/pull/374) + // for the view-to-pure log trick. + function _sendLogPayload(uint256 offset, uint256 size) private pure { + function(uint256, uint256) internal view fnIn = _sendLogPayloadView; + function(uint256, uint256) internal pure pureSendLogPayload; + assembly ("memory-safe") { + pureSendLogPayload := fnIn + } + pureSendLogPayload(offset, size); + } + + function _sendLogPayloadView(uint256 offset, uint256 size) private view { + assembly ("memory-safe") { + pop(staticcall(gas(), CONSOLE_ADDR, offset, size, 0x0, 0x0)) + } + } + + function _memcopy(uint256 fromOffset, uint256 toOffset, uint256 length) private pure { + function(uint256, uint256, uint256) internal view fnIn = _memcopyView; + function(uint256, uint256, uint256) internal pure pureMemcopy; + assembly ("memory-safe") { + pureMemcopy := fnIn + } + pureMemcopy(fromOffset, toOffset, length); + } + + function _memcopyView(uint256 fromOffset, uint256 toOffset, uint256 length) private view { + assembly ("memory-safe") { + pop(staticcall(gas(), 0x4, fromOffset, length, toOffset, length)) + } + } + + function logMemory(uint256 offset, uint256 length) internal pure { + if (offset >= 0x60) { + // Sufficient memory before slice to prepare call header. + bytes32 m0; + bytes32 m1; + bytes32 m2; + assembly ("memory-safe") { + m0 := mload(sub(offset, 0x60)) + m1 := mload(sub(offset, 0x40)) + m2 := mload(sub(offset, 0x20)) + // Selector of `log(bytes)`. + mstore(sub(offset, 0x60), 0x0be77f56) + mstore(sub(offset, 0x40), 0x20) + mstore(sub(offset, 0x20), length) + } + _sendLogPayload(offset - 0x44, length + 0x44); + assembly ("memory-safe") { + mstore(sub(offset, 0x60), m0) + mstore(sub(offset, 0x40), m1) + mstore(sub(offset, 0x20), m2) + } + } else { + // Insufficient space, so copy slice forward, add header and reverse. + bytes32 m0; + bytes32 m1; + bytes32 m2; + uint256 endOffset = offset + length; + assembly ("memory-safe") { + m0 := mload(add(endOffset, 0x00)) + m1 := mload(add(endOffset, 0x20)) + m2 := mload(add(endOffset, 0x40)) + } + _memcopy(offset, offset + 0x60, length); + assembly ("memory-safe") { + // Selector of `log(bytes)`. + mstore(add(offset, 0x00), 0x0be77f56) + mstore(add(offset, 0x20), 0x20) + mstore(add(offset, 0x40), length) + } + _sendLogPayload(offset + 0x1c, length + 0x44); + _memcopy(offset + 0x60, offset, length); + assembly ("memory-safe") { + mstore(add(endOffset, 0x00), m0) + mstore(add(endOffset, 0x20), m1) + mstore(add(endOffset, 0x40), m2) + } + } + } + + function log(address p0) internal pure { + bytes32 m0; + bytes32 m1; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + // Selector of `log(address)`. + mstore(0x00, 0x2c2ecbc2) + mstore(0x20, p0) + } + _sendLogPayload(0x1c, 0x24); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + } + } + + function log(bool p0) internal pure { + bytes32 m0; + bytes32 m1; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + // Selector of `log(bool)`. + mstore(0x00, 0x32458eed) + mstore(0x20, p0) + } + _sendLogPayload(0x1c, 0x24); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + } + } + + function log(uint256 p0) internal pure { + bytes32 m0; + bytes32 m1; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + // Selector of `log(uint256)`. + mstore(0x00, 0xf82c50f1) + mstore(0x20, p0) + } + _sendLogPayload(0x1c, 0x24); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + } + } + + function log(bytes32 p0) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + // Selector of `log(string)`. + mstore(0x00, 0x41304fac) + mstore(0x20, 0x20) + writeString(0x40, p0) + } + _sendLogPayload(0x1c, 0x64); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + } + } + + function log(address p0, address p1) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + // Selector of `log(address,address)`. + mstore(0x00, 0xdaf0d4aa) + mstore(0x20, p0) + mstore(0x40, p1) + } + _sendLogPayload(0x1c, 0x44); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + } + } + + function log(address p0, bool p1) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + // Selector of `log(address,bool)`. + mstore(0x00, 0x75b605d3) + mstore(0x20, p0) + mstore(0x40, p1) + } + _sendLogPayload(0x1c, 0x44); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + } + } + + function log(address p0, uint256 p1) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + // Selector of `log(address,uint256)`. + mstore(0x00, 0x8309e8a8) + mstore(0x20, p0) + mstore(0x40, p1) + } + _sendLogPayload(0x1c, 0x44); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + } + } + + function log(address p0, bytes32 p1) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(address,string)`. + mstore(0x00, 0x759f86bb) + mstore(0x20, p0) + mstore(0x40, 0x40) + writeString(0x60, p1) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bool p0, address p1) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + // Selector of `log(bool,address)`. + mstore(0x00, 0x853c4849) + mstore(0x20, p0) + mstore(0x40, p1) + } + _sendLogPayload(0x1c, 0x44); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + } + } + + function log(bool p0, bool p1) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + // Selector of `log(bool,bool)`. + mstore(0x00, 0x2a110e83) + mstore(0x20, p0) + mstore(0x40, p1) + } + _sendLogPayload(0x1c, 0x44); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + } + } + + function log(bool p0, uint256 p1) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + // Selector of `log(bool,uint256)`. + mstore(0x00, 0x399174d3) + mstore(0x20, p0) + mstore(0x40, p1) + } + _sendLogPayload(0x1c, 0x44); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + } + } + + function log(bool p0, bytes32 p1) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(bool,string)`. + mstore(0x00, 0x8feac525) + mstore(0x20, p0) + mstore(0x40, 0x40) + writeString(0x60, p1) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(uint256 p0, address p1) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + // Selector of `log(uint256,address)`. + mstore(0x00, 0x69276c86) + mstore(0x20, p0) + mstore(0x40, p1) + } + _sendLogPayload(0x1c, 0x44); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + } + } + + function log(uint256 p0, bool p1) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + // Selector of `log(uint256,bool)`. + mstore(0x00, 0x1c9d7eb3) + mstore(0x20, p0) + mstore(0x40, p1) + } + _sendLogPayload(0x1c, 0x44); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + } + } + + function log(uint256 p0, uint256 p1) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + // Selector of `log(uint256,uint256)`. + mstore(0x00, 0xf666715a) + mstore(0x20, p0) + mstore(0x40, p1) + } + _sendLogPayload(0x1c, 0x44); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + } + } + + function log(uint256 p0, bytes32 p1) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(uint256,string)`. + mstore(0x00, 0x643fd0df) + mstore(0x20, p0) + mstore(0x40, 0x40) + writeString(0x60, p1) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bytes32 p0, address p1) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(string,address)`. + mstore(0x00, 0x319af333) + mstore(0x20, 0x40) + mstore(0x40, p1) + writeString(0x60, p0) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bytes32 p0, bool p1) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(string,bool)`. + mstore(0x00, 0xc3b55635) + mstore(0x20, 0x40) + mstore(0x40, p1) + writeString(0x60, p0) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bytes32 p0, uint256 p1) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(string,uint256)`. + mstore(0x00, 0xb60e72cc) + mstore(0x20, 0x40) + mstore(0x40, p1) + writeString(0x60, p0) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bytes32 p0, bytes32 p1) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(string,string)`. + mstore(0x00, 0x4b5c4277) + mstore(0x20, 0x40) + mstore(0x40, 0x80) + writeString(0x60, p0) + writeString(0xa0, p1) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(address p0, address p1, address p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + // Selector of `log(address,address,address)`. + mstore(0x00, 0x018c84c2) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + } + _sendLogPayload(0x1c, 0x64); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + } + } + + function log(address p0, address p1, bool p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + // Selector of `log(address,address,bool)`. + mstore(0x00, 0xf2a66286) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + } + _sendLogPayload(0x1c, 0x64); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + } + } + + function log(address p0, address p1, uint256 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + // Selector of `log(address,address,uint256)`. + mstore(0x00, 0x17fe6185) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + } + _sendLogPayload(0x1c, 0x64); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + } + } + + function log(address p0, address p1, bytes32 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + // Selector of `log(address,address,string)`. + mstore(0x00, 0x007150be) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x60) + writeString(0x80, p2) + } + _sendLogPayload(0x1c, 0xa4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + } + } + + function log(address p0, bool p1, address p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + // Selector of `log(address,bool,address)`. + mstore(0x00, 0xf11699ed) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + } + _sendLogPayload(0x1c, 0x64); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + } + } + + function log(address p0, bool p1, bool p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + // Selector of `log(address,bool,bool)`. + mstore(0x00, 0xeb830c92) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + } + _sendLogPayload(0x1c, 0x64); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + } + } + + function log(address p0, bool p1, uint256 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + // Selector of `log(address,bool,uint256)`. + mstore(0x00, 0x9c4f99fb) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + } + _sendLogPayload(0x1c, 0x64); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + } + } + + function log(address p0, bool p1, bytes32 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + // Selector of `log(address,bool,string)`. + mstore(0x00, 0x212255cc) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x60) + writeString(0x80, p2) + } + _sendLogPayload(0x1c, 0xa4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + } + } + + function log(address p0, uint256 p1, address p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + // Selector of `log(address,uint256,address)`. + mstore(0x00, 0x7bc0d848) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + } + _sendLogPayload(0x1c, 0x64); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + } + } + + function log(address p0, uint256 p1, bool p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + // Selector of `log(address,uint256,bool)`. + mstore(0x00, 0x678209a8) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + } + _sendLogPayload(0x1c, 0x64); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + } + } + + function log(address p0, uint256 p1, uint256 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + // Selector of `log(address,uint256,uint256)`. + mstore(0x00, 0xb69bcaf6) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + } + _sendLogPayload(0x1c, 0x64); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + } + } + + function log(address p0, uint256 p1, bytes32 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + // Selector of `log(address,uint256,string)`. + mstore(0x00, 0xa1f2e8aa) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x60) + writeString(0x80, p2) + } + _sendLogPayload(0x1c, 0xa4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + } + } + + function log(address p0, bytes32 p1, address p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + // Selector of `log(address,string,address)`. + mstore(0x00, 0xf08744e8) + mstore(0x20, p0) + mstore(0x40, 0x60) + mstore(0x60, p2) + writeString(0x80, p1) + } + _sendLogPayload(0x1c, 0xa4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + } + } + + function log(address p0, bytes32 p1, bool p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + // Selector of `log(address,string,bool)`. + mstore(0x00, 0xcf020fb1) + mstore(0x20, p0) + mstore(0x40, 0x60) + mstore(0x60, p2) + writeString(0x80, p1) + } + _sendLogPayload(0x1c, 0xa4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + } + } + + function log(address p0, bytes32 p1, uint256 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + // Selector of `log(address,string,uint256)`. + mstore(0x00, 0x67dd6ff1) + mstore(0x20, p0) + mstore(0x40, 0x60) + mstore(0x60, p2) + writeString(0x80, p1) + } + _sendLogPayload(0x1c, 0xa4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + } + } + + function log(address p0, bytes32 p1, bytes32 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + // Selector of `log(address,string,string)`. + mstore(0x00, 0xfb772265) + mstore(0x20, p0) + mstore(0x40, 0x60) + mstore(0x60, 0xa0) + writeString(0x80, p1) + writeString(0xc0, p2) + } + _sendLogPayload(0x1c, 0xe4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + } + } + + function log(bool p0, address p1, address p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + // Selector of `log(bool,address,address)`. + mstore(0x00, 0xd2763667) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + } + _sendLogPayload(0x1c, 0x64); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + } + } + + function log(bool p0, address p1, bool p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + // Selector of `log(bool,address,bool)`. + mstore(0x00, 0x18c9c746) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + } + _sendLogPayload(0x1c, 0x64); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + } + } + + function log(bool p0, address p1, uint256 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + // Selector of `log(bool,address,uint256)`. + mstore(0x00, 0x5f7b9afb) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + } + _sendLogPayload(0x1c, 0x64); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + } + } + + function log(bool p0, address p1, bytes32 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + // Selector of `log(bool,address,string)`. + mstore(0x00, 0xde9a9270) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x60) + writeString(0x80, p2) + } + _sendLogPayload(0x1c, 0xa4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + } + } + + function log(bool p0, bool p1, address p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + // Selector of `log(bool,bool,address)`. + mstore(0x00, 0x1078f68d) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + } + _sendLogPayload(0x1c, 0x64); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + } + } + + function log(bool p0, bool p1, bool p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + // Selector of `log(bool,bool,bool)`. + mstore(0x00, 0x50709698) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + } + _sendLogPayload(0x1c, 0x64); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + } + } + + function log(bool p0, bool p1, uint256 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + // Selector of `log(bool,bool,uint256)`. + mstore(0x00, 0x12f21602) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + } + _sendLogPayload(0x1c, 0x64); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + } + } + + function log(bool p0, bool p1, bytes32 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + // Selector of `log(bool,bool,string)`. + mstore(0x00, 0x2555fa46) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x60) + writeString(0x80, p2) + } + _sendLogPayload(0x1c, 0xa4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + } + } + + function log(bool p0, uint256 p1, address p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + // Selector of `log(bool,uint256,address)`. + mstore(0x00, 0x088ef9d2) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + } + _sendLogPayload(0x1c, 0x64); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + } + } + + function log(bool p0, uint256 p1, bool p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + // Selector of `log(bool,uint256,bool)`. + mstore(0x00, 0xe8defba9) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + } + _sendLogPayload(0x1c, 0x64); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + } + } + + function log(bool p0, uint256 p1, uint256 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + // Selector of `log(bool,uint256,uint256)`. + mstore(0x00, 0x37103367) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + } + _sendLogPayload(0x1c, 0x64); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + } + } + + function log(bool p0, uint256 p1, bytes32 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + // Selector of `log(bool,uint256,string)`. + mstore(0x00, 0xc3fc3970) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x60) + writeString(0x80, p2) + } + _sendLogPayload(0x1c, 0xa4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + } + } + + function log(bool p0, bytes32 p1, address p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + // Selector of `log(bool,string,address)`. + mstore(0x00, 0x9591b953) + mstore(0x20, p0) + mstore(0x40, 0x60) + mstore(0x60, p2) + writeString(0x80, p1) + } + _sendLogPayload(0x1c, 0xa4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + } + } + + function log(bool p0, bytes32 p1, bool p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + // Selector of `log(bool,string,bool)`. + mstore(0x00, 0xdbb4c247) + mstore(0x20, p0) + mstore(0x40, 0x60) + mstore(0x60, p2) + writeString(0x80, p1) + } + _sendLogPayload(0x1c, 0xa4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + } + } + + function log(bool p0, bytes32 p1, uint256 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + // Selector of `log(bool,string,uint256)`. + mstore(0x00, 0x1093ee11) + mstore(0x20, p0) + mstore(0x40, 0x60) + mstore(0x60, p2) + writeString(0x80, p1) + } + _sendLogPayload(0x1c, 0xa4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + } + } + + function log(bool p0, bytes32 p1, bytes32 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + // Selector of `log(bool,string,string)`. + mstore(0x00, 0xb076847f) + mstore(0x20, p0) + mstore(0x40, 0x60) + mstore(0x60, 0xa0) + writeString(0x80, p1) + writeString(0xc0, p2) + } + _sendLogPayload(0x1c, 0xe4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + } + } + + function log(uint256 p0, address p1, address p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + // Selector of `log(uint256,address,address)`. + mstore(0x00, 0xbcfd9be0) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + } + _sendLogPayload(0x1c, 0x64); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + } + } + + function log(uint256 p0, address p1, bool p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + // Selector of `log(uint256,address,bool)`. + mstore(0x00, 0x9b6ec042) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + } + _sendLogPayload(0x1c, 0x64); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + } + } + + function log(uint256 p0, address p1, uint256 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + // Selector of `log(uint256,address,uint256)`. + mstore(0x00, 0x5a9b5ed5) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + } + _sendLogPayload(0x1c, 0x64); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + } + } + + function log(uint256 p0, address p1, bytes32 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + // Selector of `log(uint256,address,string)`. + mstore(0x00, 0x63cb41f9) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x60) + writeString(0x80, p2) + } + _sendLogPayload(0x1c, 0xa4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + } + } + + function log(uint256 p0, bool p1, address p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + // Selector of `log(uint256,bool,address)`. + mstore(0x00, 0x35085f7b) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + } + _sendLogPayload(0x1c, 0x64); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + } + } + + function log(uint256 p0, bool p1, bool p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + // Selector of `log(uint256,bool,bool)`. + mstore(0x00, 0x20718650) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + } + _sendLogPayload(0x1c, 0x64); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + } + } + + function log(uint256 p0, bool p1, uint256 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + // Selector of `log(uint256,bool,uint256)`. + mstore(0x00, 0x20098014) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + } + _sendLogPayload(0x1c, 0x64); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + } + } + + function log(uint256 p0, bool p1, bytes32 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + // Selector of `log(uint256,bool,string)`. + mstore(0x00, 0x85775021) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x60) + writeString(0x80, p2) + } + _sendLogPayload(0x1c, 0xa4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + } + } + + function log(uint256 p0, uint256 p1, address p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + // Selector of `log(uint256,uint256,address)`. + mstore(0x00, 0x5c96b331) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + } + _sendLogPayload(0x1c, 0x64); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + } + } + + function log(uint256 p0, uint256 p1, bool p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + // Selector of `log(uint256,uint256,bool)`. + mstore(0x00, 0x4766da72) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + } + _sendLogPayload(0x1c, 0x64); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + } + } + + function log(uint256 p0, uint256 p1, uint256 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + // Selector of `log(uint256,uint256,uint256)`. + mstore(0x00, 0xd1ed7a3c) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + } + _sendLogPayload(0x1c, 0x64); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + } + } + + function log(uint256 p0, uint256 p1, bytes32 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + // Selector of `log(uint256,uint256,string)`. + mstore(0x00, 0x71d04af2) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x60) + writeString(0x80, p2) + } + _sendLogPayload(0x1c, 0xa4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + } + } + + function log(uint256 p0, bytes32 p1, address p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + // Selector of `log(uint256,string,address)`. + mstore(0x00, 0x7afac959) + mstore(0x20, p0) + mstore(0x40, 0x60) + mstore(0x60, p2) + writeString(0x80, p1) + } + _sendLogPayload(0x1c, 0xa4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + } + } + + function log(uint256 p0, bytes32 p1, bool p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + // Selector of `log(uint256,string,bool)`. + mstore(0x00, 0x4ceda75a) + mstore(0x20, p0) + mstore(0x40, 0x60) + mstore(0x60, p2) + writeString(0x80, p1) + } + _sendLogPayload(0x1c, 0xa4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + } + } + + function log(uint256 p0, bytes32 p1, uint256 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + // Selector of `log(uint256,string,uint256)`. + mstore(0x00, 0x37aa7d4c) + mstore(0x20, p0) + mstore(0x40, 0x60) + mstore(0x60, p2) + writeString(0x80, p1) + } + _sendLogPayload(0x1c, 0xa4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + } + } + + function log(uint256 p0, bytes32 p1, bytes32 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + // Selector of `log(uint256,string,string)`. + mstore(0x00, 0xb115611f) + mstore(0x20, p0) + mstore(0x40, 0x60) + mstore(0x60, 0xa0) + writeString(0x80, p1) + writeString(0xc0, p2) + } + _sendLogPayload(0x1c, 0xe4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + } + } + + function log(bytes32 p0, address p1, address p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + // Selector of `log(string,address,address)`. + mstore(0x00, 0xfcec75e0) + mstore(0x20, 0x60) + mstore(0x40, p1) + mstore(0x60, p2) + writeString(0x80, p0) + } + _sendLogPayload(0x1c, 0xa4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + } + } + + function log(bytes32 p0, address p1, bool p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + // Selector of `log(string,address,bool)`. + mstore(0x00, 0xc91d5ed4) + mstore(0x20, 0x60) + mstore(0x40, p1) + mstore(0x60, p2) + writeString(0x80, p0) + } + _sendLogPayload(0x1c, 0xa4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + } + } + + function log(bytes32 p0, address p1, uint256 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + // Selector of `log(string,address,uint256)`. + mstore(0x00, 0x0d26b925) + mstore(0x20, 0x60) + mstore(0x40, p1) + mstore(0x60, p2) + writeString(0x80, p0) + } + _sendLogPayload(0x1c, 0xa4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + } + } + + function log(bytes32 p0, address p1, bytes32 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + // Selector of `log(string,address,string)`. + mstore(0x00, 0xe0e9ad4f) + mstore(0x20, 0x60) + mstore(0x40, p1) + mstore(0x60, 0xa0) + writeString(0x80, p0) + writeString(0xc0, p2) + } + _sendLogPayload(0x1c, 0xe4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + } + } + + function log(bytes32 p0, bool p1, address p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + // Selector of `log(string,bool,address)`. + mstore(0x00, 0x932bbb38) + mstore(0x20, 0x60) + mstore(0x40, p1) + mstore(0x60, p2) + writeString(0x80, p0) + } + _sendLogPayload(0x1c, 0xa4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + } + } + + function log(bytes32 p0, bool p1, bool p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + // Selector of `log(string,bool,bool)`. + mstore(0x00, 0x850b7ad6) + mstore(0x20, 0x60) + mstore(0x40, p1) + mstore(0x60, p2) + writeString(0x80, p0) + } + _sendLogPayload(0x1c, 0xa4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + } + } + + function log(bytes32 p0, bool p1, uint256 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + // Selector of `log(string,bool,uint256)`. + mstore(0x00, 0xc95958d6) + mstore(0x20, 0x60) + mstore(0x40, p1) + mstore(0x60, p2) + writeString(0x80, p0) + } + _sendLogPayload(0x1c, 0xa4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + } + } + + function log(bytes32 p0, bool p1, bytes32 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + // Selector of `log(string,bool,string)`. + mstore(0x00, 0xe298f47d) + mstore(0x20, 0x60) + mstore(0x40, p1) + mstore(0x60, 0xa0) + writeString(0x80, p0) + writeString(0xc0, p2) + } + _sendLogPayload(0x1c, 0xe4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + } + } + + function log(bytes32 p0, uint256 p1, address p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + // Selector of `log(string,uint256,address)`. + mstore(0x00, 0x1c7ec448) + mstore(0x20, 0x60) + mstore(0x40, p1) + mstore(0x60, p2) + writeString(0x80, p0) + } + _sendLogPayload(0x1c, 0xa4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + } + } + + function log(bytes32 p0, uint256 p1, bool p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + // Selector of `log(string,uint256,bool)`. + mstore(0x00, 0xca7733b1) + mstore(0x20, 0x60) + mstore(0x40, p1) + mstore(0x60, p2) + writeString(0x80, p0) + } + _sendLogPayload(0x1c, 0xa4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + } + } + + function log(bytes32 p0, uint256 p1, uint256 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + // Selector of `log(string,uint256,uint256)`. + mstore(0x00, 0xca47c4eb) + mstore(0x20, 0x60) + mstore(0x40, p1) + mstore(0x60, p2) + writeString(0x80, p0) + } + _sendLogPayload(0x1c, 0xa4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + } + } + + function log(bytes32 p0, uint256 p1, bytes32 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + // Selector of `log(string,uint256,string)`. + mstore(0x00, 0x5970e089) + mstore(0x20, 0x60) + mstore(0x40, p1) + mstore(0x60, 0xa0) + writeString(0x80, p0) + writeString(0xc0, p2) + } + _sendLogPayload(0x1c, 0xe4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + } + } + + function log(bytes32 p0, bytes32 p1, address p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + // Selector of `log(string,string,address)`. + mstore(0x00, 0x95ed0195) + mstore(0x20, 0x60) + mstore(0x40, 0xa0) + mstore(0x60, p2) + writeString(0x80, p0) + writeString(0xc0, p1) + } + _sendLogPayload(0x1c, 0xe4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + } + } + + function log(bytes32 p0, bytes32 p1, bool p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + // Selector of `log(string,string,bool)`. + mstore(0x00, 0xb0e0f9b5) + mstore(0x20, 0x60) + mstore(0x40, 0xa0) + mstore(0x60, p2) + writeString(0x80, p0) + writeString(0xc0, p1) + } + _sendLogPayload(0x1c, 0xe4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + } + } + + function log(bytes32 p0, bytes32 p1, uint256 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + // Selector of `log(string,string,uint256)`. + mstore(0x00, 0x5821efa1) + mstore(0x20, 0x60) + mstore(0x40, 0xa0) + mstore(0x60, p2) + writeString(0x80, p0) + writeString(0xc0, p1) + } + _sendLogPayload(0x1c, 0xe4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + } + } + + function log(bytes32 p0, bytes32 p1, bytes32 p2) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + bytes32 m9; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + m9 := mload(0x120) + // Selector of `log(string,string,string)`. + mstore(0x00, 0x2ced7cef) + mstore(0x20, 0x60) + mstore(0x40, 0xa0) + mstore(0x60, 0xe0) + writeString(0x80, p0) + writeString(0xc0, p1) + writeString(0x100, p2) + } + _sendLogPayload(0x1c, 0x124); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + mstore(0x120, m9) + } + } + + function log(address p0, address p1, address p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(address,address,address,address)`. + mstore(0x00, 0x665bf134) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(address p0, address p1, address p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(address,address,address,bool)`. + mstore(0x00, 0x0e378994) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(address p0, address p1, address p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(address,address,address,uint256)`. + mstore(0x00, 0x94250d77) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(address p0, address p1, address p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(address,address,address,string)`. + mstore(0x00, 0xf808da20) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0x80) + writeString(0xa0, p3) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(address p0, address p1, bool p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(address,address,bool,address)`. + mstore(0x00, 0x9f1bc36e) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(address p0, address p1, bool p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(address,address,bool,bool)`. + mstore(0x00, 0x2cd4134a) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(address p0, address p1, bool p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(address,address,bool,uint256)`. + mstore(0x00, 0x3971e78c) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(address p0, address p1, bool p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(address,address,bool,string)`. + mstore(0x00, 0xaa6540c8) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0x80) + writeString(0xa0, p3) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(address p0, address p1, uint256 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(address,address,uint256,address)`. + mstore(0x00, 0x8da6def5) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(address p0, address p1, uint256 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(address,address,uint256,bool)`. + mstore(0x00, 0x9b4254e2) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(address p0, address p1, uint256 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(address,address,uint256,uint256)`. + mstore(0x00, 0xbe553481) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(address p0, address p1, uint256 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(address,address,uint256,string)`. + mstore(0x00, 0xfdb4f990) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0x80) + writeString(0xa0, p3) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(address p0, address p1, bytes32 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(address,address,string,address)`. + mstore(0x00, 0x8f736d16) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, p3) + writeString(0xa0, p2) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(address p0, address p1, bytes32 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(address,address,string,bool)`. + mstore(0x00, 0x6f1a594e) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, p3) + writeString(0xa0, p2) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(address p0, address p1, bytes32 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(address,address,string,uint256)`. + mstore(0x00, 0xef1cefe7) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, p3) + writeString(0xa0, p2) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(address p0, address p1, bytes32 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(address,address,string,string)`. + mstore(0x00, 0x21bdaf25) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, 0xc0) + writeString(0xa0, p2) + writeString(0xe0, p3) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(address p0, bool p1, address p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(address,bool,address,address)`. + mstore(0x00, 0x660375dd) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(address p0, bool p1, address p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(address,bool,address,bool)`. + mstore(0x00, 0xa6f50b0f) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(address p0, bool p1, address p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(address,bool,address,uint256)`. + mstore(0x00, 0xa75c59de) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(address p0, bool p1, address p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(address,bool,address,string)`. + mstore(0x00, 0x2dd778e6) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0x80) + writeString(0xa0, p3) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(address p0, bool p1, bool p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(address,bool,bool,address)`. + mstore(0x00, 0xcf394485) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(address p0, bool p1, bool p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(address,bool,bool,bool)`. + mstore(0x00, 0xcac43479) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(address p0, bool p1, bool p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(address,bool,bool,uint256)`. + mstore(0x00, 0x8c4e5de6) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(address p0, bool p1, bool p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(address,bool,bool,string)`. + mstore(0x00, 0xdfc4a2e8) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0x80) + writeString(0xa0, p3) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(address p0, bool p1, uint256 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(address,bool,uint256,address)`. + mstore(0x00, 0xccf790a1) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(address p0, bool p1, uint256 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(address,bool,uint256,bool)`. + mstore(0x00, 0xc4643e20) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(address p0, bool p1, uint256 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(address,bool,uint256,uint256)`. + mstore(0x00, 0x386ff5f4) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(address p0, bool p1, uint256 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(address,bool,uint256,string)`. + mstore(0x00, 0x0aa6cfad) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0x80) + writeString(0xa0, p3) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(address p0, bool p1, bytes32 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(address,bool,string,address)`. + mstore(0x00, 0x19fd4956) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, p3) + writeString(0xa0, p2) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(address p0, bool p1, bytes32 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(address,bool,string,bool)`. + mstore(0x00, 0x50ad461d) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, p3) + writeString(0xa0, p2) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(address p0, bool p1, bytes32 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(address,bool,string,uint256)`. + mstore(0x00, 0x80e6a20b) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, p3) + writeString(0xa0, p2) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(address p0, bool p1, bytes32 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(address,bool,string,string)`. + mstore(0x00, 0x475c5c33) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, 0xc0) + writeString(0xa0, p2) + writeString(0xe0, p3) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(address p0, uint256 p1, address p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(address,uint256,address,address)`. + mstore(0x00, 0x478d1c62) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(address p0, uint256 p1, address p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(address,uint256,address,bool)`. + mstore(0x00, 0xa1bcc9b3) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(address p0, uint256 p1, address p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(address,uint256,address,uint256)`. + mstore(0x00, 0x100f650e) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(address p0, uint256 p1, address p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(address,uint256,address,string)`. + mstore(0x00, 0x1da986ea) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0x80) + writeString(0xa0, p3) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(address p0, uint256 p1, bool p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(address,uint256,bool,address)`. + mstore(0x00, 0xa31bfdcc) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(address p0, uint256 p1, bool p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(address,uint256,bool,bool)`. + mstore(0x00, 0x3bf5e537) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(address p0, uint256 p1, bool p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(address,uint256,bool,uint256)`. + mstore(0x00, 0x22f6b999) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(address p0, uint256 p1, bool p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(address,uint256,bool,string)`. + mstore(0x00, 0xc5ad85f9) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0x80) + writeString(0xa0, p3) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(address p0, uint256 p1, uint256 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(address,uint256,uint256,address)`. + mstore(0x00, 0x20e3984d) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(address p0, uint256 p1, uint256 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(address,uint256,uint256,bool)`. + mstore(0x00, 0x66f1bc67) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(address p0, uint256 p1, uint256 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(address,uint256,uint256,uint256)`. + mstore(0x00, 0x34f0e636) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(address p0, uint256 p1, uint256 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(address,uint256,uint256,string)`. + mstore(0x00, 0x4a28c017) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0x80) + writeString(0xa0, p3) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(address p0, uint256 p1, bytes32 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(address,uint256,string,address)`. + mstore(0x00, 0x5c430d47) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, p3) + writeString(0xa0, p2) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(address p0, uint256 p1, bytes32 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(address,uint256,string,bool)`. + mstore(0x00, 0xcf18105c) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, p3) + writeString(0xa0, p2) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(address p0, uint256 p1, bytes32 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(address,uint256,string,uint256)`. + mstore(0x00, 0xbf01f891) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, p3) + writeString(0xa0, p2) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(address p0, uint256 p1, bytes32 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(address,uint256,string,string)`. + mstore(0x00, 0x88a8c406) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, 0xc0) + writeString(0xa0, p2) + writeString(0xe0, p3) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(address p0, bytes32 p1, address p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(address,string,address,address)`. + mstore(0x00, 0x0d36fa20) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p1) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(address p0, bytes32 p1, address p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(address,string,address,bool)`. + mstore(0x00, 0x0df12b76) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p1) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(address p0, bytes32 p1, address p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(address,string,address,uint256)`. + mstore(0x00, 0x457fe3cf) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p1) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(address p0, bytes32 p1, address p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(address,string,address,string)`. + mstore(0x00, 0xf7e36245) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, 0xc0) + writeString(0xa0, p1) + writeString(0xe0, p3) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(address p0, bytes32 p1, bool p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(address,string,bool,address)`. + mstore(0x00, 0x205871c2) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p1) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(address p0, bytes32 p1, bool p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(address,string,bool,bool)`. + mstore(0x00, 0x5f1d5c9f) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p1) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(address p0, bytes32 p1, bool p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(address,string,bool,uint256)`. + mstore(0x00, 0x515e38b6) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p1) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(address p0, bytes32 p1, bool p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(address,string,bool,string)`. + mstore(0x00, 0xbc0b61fe) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, 0xc0) + writeString(0xa0, p1) + writeString(0xe0, p3) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(address p0, bytes32 p1, uint256 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(address,string,uint256,address)`. + mstore(0x00, 0x63183678) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p1) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(address p0, bytes32 p1, uint256 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(address,string,uint256,bool)`. + mstore(0x00, 0x0ef7e050) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p1) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(address p0, bytes32 p1, uint256 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(address,string,uint256,uint256)`. + mstore(0x00, 0x1dc8e1b8) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p1) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(address p0, bytes32 p1, uint256 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(address,string,uint256,string)`. + mstore(0x00, 0x448830a8) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, 0xc0) + writeString(0xa0, p1) + writeString(0xe0, p3) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(address p0, bytes32 p1, bytes32 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(address,string,string,address)`. + mstore(0x00, 0xa04e2f87) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, 0xc0) + mstore(0x80, p3) + writeString(0xa0, p1) + writeString(0xe0, p2) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(address p0, bytes32 p1, bytes32 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(address,string,string,bool)`. + mstore(0x00, 0x35a5071f) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, 0xc0) + mstore(0x80, p3) + writeString(0xa0, p1) + writeString(0xe0, p2) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(address p0, bytes32 p1, bytes32 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(address,string,string,uint256)`. + mstore(0x00, 0x159f8927) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, 0xc0) + mstore(0x80, p3) + writeString(0xa0, p1) + writeString(0xe0, p2) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(address p0, bytes32 p1, bytes32 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + bytes32 m9; + bytes32 m10; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + m9 := mload(0x120) + m10 := mload(0x140) + // Selector of `log(address,string,string,string)`. + mstore(0x00, 0x5d02c50b) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, 0xc0) + mstore(0x80, 0x100) + writeString(0xa0, p1) + writeString(0xe0, p2) + writeString(0x120, p3) + } + _sendLogPayload(0x1c, 0x144); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + mstore(0x120, m9) + mstore(0x140, m10) + } + } + + function log(bool p0, address p1, address p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(bool,address,address,address)`. + mstore(0x00, 0x1d14d001) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bool p0, address p1, address p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(bool,address,address,bool)`. + mstore(0x00, 0x46600be0) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bool p0, address p1, address p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(bool,address,address,uint256)`. + mstore(0x00, 0x0c66d1be) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bool p0, address p1, address p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(bool,address,address,string)`. + mstore(0x00, 0xd812a167) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0x80) + writeString(0xa0, p3) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bool p0, address p1, bool p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(bool,address,bool,address)`. + mstore(0x00, 0x1c41a336) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bool p0, address p1, bool p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(bool,address,bool,bool)`. + mstore(0x00, 0x6a9c478b) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bool p0, address p1, bool p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(bool,address,bool,uint256)`. + mstore(0x00, 0x07831502) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bool p0, address p1, bool p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(bool,address,bool,string)`. + mstore(0x00, 0x4a66cb34) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0x80) + writeString(0xa0, p3) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bool p0, address p1, uint256 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(bool,address,uint256,address)`. + mstore(0x00, 0x136b05dd) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bool p0, address p1, uint256 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(bool,address,uint256,bool)`. + mstore(0x00, 0xd6019f1c) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bool p0, address p1, uint256 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(bool,address,uint256,uint256)`. + mstore(0x00, 0x7bf181a1) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bool p0, address p1, uint256 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(bool,address,uint256,string)`. + mstore(0x00, 0x51f09ff8) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0x80) + writeString(0xa0, p3) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bool p0, address p1, bytes32 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(bool,address,string,address)`. + mstore(0x00, 0x6f7c603e) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, p3) + writeString(0xa0, p2) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bool p0, address p1, bytes32 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(bool,address,string,bool)`. + mstore(0x00, 0xe2bfd60b) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, p3) + writeString(0xa0, p2) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bool p0, address p1, bytes32 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(bool,address,string,uint256)`. + mstore(0x00, 0xc21f64c7) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, p3) + writeString(0xa0, p2) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bool p0, address p1, bytes32 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(bool,address,string,string)`. + mstore(0x00, 0xa73c1db6) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, 0xc0) + writeString(0xa0, p2) + writeString(0xe0, p3) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bool p0, bool p1, address p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(bool,bool,address,address)`. + mstore(0x00, 0xf4880ea4) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bool p0, bool p1, address p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(bool,bool,address,bool)`. + mstore(0x00, 0xc0a302d8) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bool p0, bool p1, address p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(bool,bool,address,uint256)`. + mstore(0x00, 0x4c123d57) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bool p0, bool p1, address p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(bool,bool,address,string)`. + mstore(0x00, 0xa0a47963) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0x80) + writeString(0xa0, p3) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bool p0, bool p1, bool p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(bool,bool,bool,address)`. + mstore(0x00, 0x8c329b1a) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bool p0, bool p1, bool p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(bool,bool,bool,bool)`. + mstore(0x00, 0x3b2a5ce0) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bool p0, bool p1, bool p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(bool,bool,bool,uint256)`. + mstore(0x00, 0x6d7045c1) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bool p0, bool p1, bool p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(bool,bool,bool,string)`. + mstore(0x00, 0x2ae408d4) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0x80) + writeString(0xa0, p3) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bool p0, bool p1, uint256 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(bool,bool,uint256,address)`. + mstore(0x00, 0x54a7a9a0) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bool p0, bool p1, uint256 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(bool,bool,uint256,bool)`. + mstore(0x00, 0x619e4d0e) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bool p0, bool p1, uint256 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(bool,bool,uint256,uint256)`. + mstore(0x00, 0x0bb00eab) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bool p0, bool p1, uint256 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(bool,bool,uint256,string)`. + mstore(0x00, 0x7dd4d0e0) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0x80) + writeString(0xa0, p3) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bool p0, bool p1, bytes32 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(bool,bool,string,address)`. + mstore(0x00, 0xf9ad2b89) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, p3) + writeString(0xa0, p2) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bool p0, bool p1, bytes32 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(bool,bool,string,bool)`. + mstore(0x00, 0xb857163a) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, p3) + writeString(0xa0, p2) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bool p0, bool p1, bytes32 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(bool,bool,string,uint256)`. + mstore(0x00, 0xe3a9ca2f) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, p3) + writeString(0xa0, p2) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bool p0, bool p1, bytes32 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(bool,bool,string,string)`. + mstore(0x00, 0x6d1e8751) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, 0xc0) + writeString(0xa0, p2) + writeString(0xe0, p3) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bool p0, uint256 p1, address p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(bool,uint256,address,address)`. + mstore(0x00, 0x26f560a8) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bool p0, uint256 p1, address p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(bool,uint256,address,bool)`. + mstore(0x00, 0xb4c314ff) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bool p0, uint256 p1, address p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(bool,uint256,address,uint256)`. + mstore(0x00, 0x1537dc87) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bool p0, uint256 p1, address p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(bool,uint256,address,string)`. + mstore(0x00, 0x1bb3b09a) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0x80) + writeString(0xa0, p3) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bool p0, uint256 p1, bool p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(bool,uint256,bool,address)`. + mstore(0x00, 0x9acd3616) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bool p0, uint256 p1, bool p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(bool,uint256,bool,bool)`. + mstore(0x00, 0xceb5f4d7) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bool p0, uint256 p1, bool p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(bool,uint256,bool,uint256)`. + mstore(0x00, 0x7f9bbca2) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bool p0, uint256 p1, bool p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(bool,uint256,bool,string)`. + mstore(0x00, 0x9143dbb1) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0x80) + writeString(0xa0, p3) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bool p0, uint256 p1, uint256 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(bool,uint256,uint256,address)`. + mstore(0x00, 0x00dd87b9) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bool p0, uint256 p1, uint256 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(bool,uint256,uint256,bool)`. + mstore(0x00, 0xbe984353) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bool p0, uint256 p1, uint256 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(bool,uint256,uint256,uint256)`. + mstore(0x00, 0x374bb4b2) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(bool p0, uint256 p1, uint256 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(bool,uint256,uint256,string)`. + mstore(0x00, 0x8e69fb5d) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0x80) + writeString(0xa0, p3) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bool p0, uint256 p1, bytes32 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(bool,uint256,string,address)`. + mstore(0x00, 0xfedd1fff) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, p3) + writeString(0xa0, p2) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bool p0, uint256 p1, bytes32 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(bool,uint256,string,bool)`. + mstore(0x00, 0xe5e70b2b) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, p3) + writeString(0xa0, p2) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bool p0, uint256 p1, bytes32 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(bool,uint256,string,uint256)`. + mstore(0x00, 0x6a1199e2) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, p3) + writeString(0xa0, p2) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bool p0, uint256 p1, bytes32 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(bool,uint256,string,string)`. + mstore(0x00, 0xf5bc2249) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, 0xc0) + writeString(0xa0, p2) + writeString(0xe0, p3) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bool p0, bytes32 p1, address p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(bool,string,address,address)`. + mstore(0x00, 0x2b2b18dc) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p1) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bool p0, bytes32 p1, address p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(bool,string,address,bool)`. + mstore(0x00, 0x6dd434ca) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p1) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bool p0, bytes32 p1, address p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(bool,string,address,uint256)`. + mstore(0x00, 0xa5cada94) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p1) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bool p0, bytes32 p1, address p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(bool,string,address,string)`. + mstore(0x00, 0x12d6c788) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, 0xc0) + writeString(0xa0, p1) + writeString(0xe0, p3) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bool p0, bytes32 p1, bool p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(bool,string,bool,address)`. + mstore(0x00, 0x538e06ab) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p1) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bool p0, bytes32 p1, bool p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(bool,string,bool,bool)`. + mstore(0x00, 0xdc5e935b) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p1) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bool p0, bytes32 p1, bool p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(bool,string,bool,uint256)`. + mstore(0x00, 0x1606a393) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p1) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bool p0, bytes32 p1, bool p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(bool,string,bool,string)`. + mstore(0x00, 0x483d0416) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, 0xc0) + writeString(0xa0, p1) + writeString(0xe0, p3) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bool p0, bytes32 p1, uint256 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(bool,string,uint256,address)`. + mstore(0x00, 0x1596a1ce) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p1) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bool p0, bytes32 p1, uint256 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(bool,string,uint256,bool)`. + mstore(0x00, 0x6b0e5d53) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p1) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bool p0, bytes32 p1, uint256 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(bool,string,uint256,uint256)`. + mstore(0x00, 0x28863fcb) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p1) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bool p0, bytes32 p1, uint256 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(bool,string,uint256,string)`. + mstore(0x00, 0x1ad96de6) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, 0xc0) + writeString(0xa0, p1) + writeString(0xe0, p3) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bool p0, bytes32 p1, bytes32 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(bool,string,string,address)`. + mstore(0x00, 0x97d394d8) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, 0xc0) + mstore(0x80, p3) + writeString(0xa0, p1) + writeString(0xe0, p2) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bool p0, bytes32 p1, bytes32 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(bool,string,string,bool)`. + mstore(0x00, 0x1e4b87e5) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, 0xc0) + mstore(0x80, p3) + writeString(0xa0, p1) + writeString(0xe0, p2) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bool p0, bytes32 p1, bytes32 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(bool,string,string,uint256)`. + mstore(0x00, 0x7be0c3eb) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, 0xc0) + mstore(0x80, p3) + writeString(0xa0, p1) + writeString(0xe0, p2) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bool p0, bytes32 p1, bytes32 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + bytes32 m9; + bytes32 m10; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + m9 := mload(0x120) + m10 := mload(0x140) + // Selector of `log(bool,string,string,string)`. + mstore(0x00, 0x1762e32a) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, 0xc0) + mstore(0x80, 0x100) + writeString(0xa0, p1) + writeString(0xe0, p2) + writeString(0x120, p3) + } + _sendLogPayload(0x1c, 0x144); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + mstore(0x120, m9) + mstore(0x140, m10) + } + } + + function log(uint256 p0, address p1, address p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(uint256,address,address,address)`. + mstore(0x00, 0x2488b414) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(uint256 p0, address p1, address p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(uint256,address,address,bool)`. + mstore(0x00, 0x091ffaf5) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(uint256 p0, address p1, address p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(uint256,address,address,uint256)`. + mstore(0x00, 0x736efbb6) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(uint256 p0, address p1, address p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(uint256,address,address,string)`. + mstore(0x00, 0x031c6f73) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0x80) + writeString(0xa0, p3) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(uint256 p0, address p1, bool p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(uint256,address,bool,address)`. + mstore(0x00, 0xef72c513) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(uint256 p0, address p1, bool p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(uint256,address,bool,bool)`. + mstore(0x00, 0xe351140f) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(uint256 p0, address p1, bool p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(uint256,address,bool,uint256)`. + mstore(0x00, 0x5abd992a) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(uint256 p0, address p1, bool p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(uint256,address,bool,string)`. + mstore(0x00, 0x90fb06aa) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0x80) + writeString(0xa0, p3) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(uint256 p0, address p1, uint256 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(uint256,address,uint256,address)`. + mstore(0x00, 0x15c127b5) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(uint256 p0, address p1, uint256 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(uint256,address,uint256,bool)`. + mstore(0x00, 0x5f743a7c) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(uint256 p0, address p1, uint256 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(uint256,address,uint256,uint256)`. + mstore(0x00, 0x0c9cd9c1) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(uint256 p0, address p1, uint256 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(uint256,address,uint256,string)`. + mstore(0x00, 0xddb06521) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0x80) + writeString(0xa0, p3) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(uint256 p0, address p1, bytes32 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(uint256,address,string,address)`. + mstore(0x00, 0x9cba8fff) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, p3) + writeString(0xa0, p2) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(uint256 p0, address p1, bytes32 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(uint256,address,string,bool)`. + mstore(0x00, 0xcc32ab07) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, p3) + writeString(0xa0, p2) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(uint256 p0, address p1, bytes32 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(uint256,address,string,uint256)`. + mstore(0x00, 0x46826b5d) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, p3) + writeString(0xa0, p2) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(uint256 p0, address p1, bytes32 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(uint256,address,string,string)`. + mstore(0x00, 0x3e128ca3) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, 0xc0) + writeString(0xa0, p2) + writeString(0xe0, p3) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(uint256 p0, bool p1, address p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(uint256,bool,address,address)`. + mstore(0x00, 0xa1ef4cbb) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(uint256 p0, bool p1, address p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(uint256,bool,address,bool)`. + mstore(0x00, 0x454d54a5) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(uint256 p0, bool p1, address p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(uint256,bool,address,uint256)`. + mstore(0x00, 0x078287f5) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(uint256 p0, bool p1, address p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(uint256,bool,address,string)`. + mstore(0x00, 0xade052c7) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0x80) + writeString(0xa0, p3) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(uint256 p0, bool p1, bool p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(uint256,bool,bool,address)`. + mstore(0x00, 0x69640b59) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(uint256 p0, bool p1, bool p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(uint256,bool,bool,bool)`. + mstore(0x00, 0xb6f577a1) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(uint256 p0, bool p1, bool p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(uint256,bool,bool,uint256)`. + mstore(0x00, 0x7464ce23) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(uint256 p0, bool p1, bool p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(uint256,bool,bool,string)`. + mstore(0x00, 0xdddb9561) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0x80) + writeString(0xa0, p3) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(uint256 p0, bool p1, uint256 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(uint256,bool,uint256,address)`. + mstore(0x00, 0x88cb6041) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(uint256 p0, bool p1, uint256 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(uint256,bool,uint256,bool)`. + mstore(0x00, 0x91a02e2a) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(uint256 p0, bool p1, uint256 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(uint256,bool,uint256,uint256)`. + mstore(0x00, 0xc6acc7a8) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(uint256 p0, bool p1, uint256 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(uint256,bool,uint256,string)`. + mstore(0x00, 0xde03e774) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0x80) + writeString(0xa0, p3) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(uint256 p0, bool p1, bytes32 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(uint256,bool,string,address)`. + mstore(0x00, 0xef529018) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, p3) + writeString(0xa0, p2) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(uint256 p0, bool p1, bytes32 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(uint256,bool,string,bool)`. + mstore(0x00, 0xeb928d7f) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, p3) + writeString(0xa0, p2) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(uint256 p0, bool p1, bytes32 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(uint256,bool,string,uint256)`. + mstore(0x00, 0x2c1d0746) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, p3) + writeString(0xa0, p2) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(uint256 p0, bool p1, bytes32 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(uint256,bool,string,string)`. + mstore(0x00, 0x68c8b8bd) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, 0xc0) + writeString(0xa0, p2) + writeString(0xe0, p3) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(uint256 p0, uint256 p1, address p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(uint256,uint256,address,address)`. + mstore(0x00, 0x56a5d1b1) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(uint256 p0, uint256 p1, address p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(uint256,uint256,address,bool)`. + mstore(0x00, 0x15cac476) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(uint256 p0, uint256 p1, address p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(uint256,uint256,address,uint256)`. + mstore(0x00, 0x88f6e4b2) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(uint256 p0, uint256 p1, address p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(uint256,uint256,address,string)`. + mstore(0x00, 0x6cde40b8) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0x80) + writeString(0xa0, p3) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(uint256 p0, uint256 p1, bool p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(uint256,uint256,bool,address)`. + mstore(0x00, 0x9a816a83) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(uint256 p0, uint256 p1, bool p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(uint256,uint256,bool,bool)`. + mstore(0x00, 0xab085ae6) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(uint256 p0, uint256 p1, bool p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(uint256,uint256,bool,uint256)`. + mstore(0x00, 0xeb7f6fd2) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(uint256 p0, uint256 p1, bool p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(uint256,uint256,bool,string)`. + mstore(0x00, 0xa5b4fc99) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0x80) + writeString(0xa0, p3) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(uint256 p0, uint256 p1, uint256 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(uint256,uint256,uint256,address)`. + mstore(0x00, 0xfa8185af) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(uint256 p0, uint256 p1, uint256 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(uint256,uint256,uint256,bool)`. + mstore(0x00, 0xc598d185) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(uint256 p0, uint256 p1, uint256 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + assembly ("memory-safe") { + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + // Selector of `log(uint256,uint256,uint256,uint256)`. + mstore(0x00, 0x193fb800) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + } + _sendLogPayload(0x1c, 0x84); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + } + } + + function log(uint256 p0, uint256 p1, uint256 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(uint256,uint256,uint256,string)`. + mstore(0x00, 0x59cfcbe3) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0x80) + writeString(0xa0, p3) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(uint256 p0, uint256 p1, bytes32 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(uint256,uint256,string,address)`. + mstore(0x00, 0x42d21db7) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, p3) + writeString(0xa0, p2) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(uint256 p0, uint256 p1, bytes32 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(uint256,uint256,string,bool)`. + mstore(0x00, 0x7af6ab25) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, p3) + writeString(0xa0, p2) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(uint256 p0, uint256 p1, bytes32 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(uint256,uint256,string,uint256)`. + mstore(0x00, 0x5da297eb) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, p3) + writeString(0xa0, p2) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(uint256 p0, uint256 p1, bytes32 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(uint256,uint256,string,string)`. + mstore(0x00, 0x27d8afd2) + mstore(0x20, p0) + mstore(0x40, p1) + mstore(0x60, 0x80) + mstore(0x80, 0xc0) + writeString(0xa0, p2) + writeString(0xe0, p3) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(uint256 p0, bytes32 p1, address p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(uint256,string,address,address)`. + mstore(0x00, 0x6168ed61) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p1) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(uint256 p0, bytes32 p1, address p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(uint256,string,address,bool)`. + mstore(0x00, 0x90c30a56) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p1) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(uint256 p0, bytes32 p1, address p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(uint256,string,address,uint256)`. + mstore(0x00, 0xe8d3018d) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p1) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(uint256 p0, bytes32 p1, address p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(uint256,string,address,string)`. + mstore(0x00, 0x9c3adfa1) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, 0xc0) + writeString(0xa0, p1) + writeString(0xe0, p3) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(uint256 p0, bytes32 p1, bool p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(uint256,string,bool,address)`. + mstore(0x00, 0xae2ec581) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p1) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(uint256 p0, bytes32 p1, bool p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(uint256,string,bool,bool)`. + mstore(0x00, 0xba535d9c) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p1) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(uint256 p0, bytes32 p1, bool p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(uint256,string,bool,uint256)`. + mstore(0x00, 0xcf009880) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p1) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(uint256 p0, bytes32 p1, bool p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(uint256,string,bool,string)`. + mstore(0x00, 0xd2d423cd) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, 0xc0) + writeString(0xa0, p1) + writeString(0xe0, p3) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(uint256 p0, bytes32 p1, uint256 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(uint256,string,uint256,address)`. + mstore(0x00, 0x3b2279b4) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p1) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(uint256 p0, bytes32 p1, uint256 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(uint256,string,uint256,bool)`. + mstore(0x00, 0x691a8f74) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p1) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(uint256 p0, bytes32 p1, uint256 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(uint256,string,uint256,uint256)`. + mstore(0x00, 0x82c25b74) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p1) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(uint256 p0, bytes32 p1, uint256 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(uint256,string,uint256,string)`. + mstore(0x00, 0xb7b914ca) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, p2) + mstore(0x80, 0xc0) + writeString(0xa0, p1) + writeString(0xe0, p3) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(uint256 p0, bytes32 p1, bytes32 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(uint256,string,string,address)`. + mstore(0x00, 0xd583c602) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, 0xc0) + mstore(0x80, p3) + writeString(0xa0, p1) + writeString(0xe0, p2) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(uint256 p0, bytes32 p1, bytes32 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(uint256,string,string,bool)`. + mstore(0x00, 0xb3a6b6bd) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, 0xc0) + mstore(0x80, p3) + writeString(0xa0, p1) + writeString(0xe0, p2) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(uint256 p0, bytes32 p1, bytes32 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(uint256,string,string,uint256)`. + mstore(0x00, 0xb028c9bd) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, 0xc0) + mstore(0x80, p3) + writeString(0xa0, p1) + writeString(0xe0, p2) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(uint256 p0, bytes32 p1, bytes32 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + bytes32 m9; + bytes32 m10; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + m9 := mload(0x120) + m10 := mload(0x140) + // Selector of `log(uint256,string,string,string)`. + mstore(0x00, 0x21ad0683) + mstore(0x20, p0) + mstore(0x40, 0x80) + mstore(0x60, 0xc0) + mstore(0x80, 0x100) + writeString(0xa0, p1) + writeString(0xe0, p2) + writeString(0x120, p3) + } + _sendLogPayload(0x1c, 0x144); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + mstore(0x120, m9) + mstore(0x140, m10) + } + } + + function log(bytes32 p0, address p1, address p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(string,address,address,address)`. + mstore(0x00, 0xed8f28f6) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bytes32 p0, address p1, address p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(string,address,address,bool)`. + mstore(0x00, 0xb59dbd60) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bytes32 p0, address p1, address p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(string,address,address,uint256)`. + mstore(0x00, 0x8ef3f399) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bytes32 p0, address p1, address p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(string,address,address,string)`. + mstore(0x00, 0x800a1c67) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0xc0) + writeString(0xa0, p0) + writeString(0xe0, p3) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bytes32 p0, address p1, bool p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(string,address,bool,address)`. + mstore(0x00, 0x223603bd) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bytes32 p0, address p1, bool p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(string,address,bool,bool)`. + mstore(0x00, 0x79884c2b) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bytes32 p0, address p1, bool p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(string,address,bool,uint256)`. + mstore(0x00, 0x3e9f866a) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bytes32 p0, address p1, bool p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(string,address,bool,string)`. + mstore(0x00, 0x0454c079) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0xc0) + writeString(0xa0, p0) + writeString(0xe0, p3) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bytes32 p0, address p1, uint256 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(string,address,uint256,address)`. + mstore(0x00, 0x63fb8bc5) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bytes32 p0, address p1, uint256 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(string,address,uint256,bool)`. + mstore(0x00, 0xfc4845f0) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bytes32 p0, address p1, uint256 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(string,address,uint256,uint256)`. + mstore(0x00, 0xf8f51b1e) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bytes32 p0, address p1, uint256 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(string,address,uint256,string)`. + mstore(0x00, 0x5a477632) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0xc0) + writeString(0xa0, p0) + writeString(0xe0, p3) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bytes32 p0, address p1, bytes32 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(string,address,string,address)`. + mstore(0x00, 0xaabc9a31) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, 0xc0) + mstore(0x80, p3) + writeString(0xa0, p0) + writeString(0xe0, p2) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bytes32 p0, address p1, bytes32 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(string,address,string,bool)`. + mstore(0x00, 0x5f15d28c) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, 0xc0) + mstore(0x80, p3) + writeString(0xa0, p0) + writeString(0xe0, p2) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bytes32 p0, address p1, bytes32 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(string,address,string,uint256)`. + mstore(0x00, 0x91d1112e) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, 0xc0) + mstore(0x80, p3) + writeString(0xa0, p0) + writeString(0xe0, p2) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bytes32 p0, address p1, bytes32 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + bytes32 m9; + bytes32 m10; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + m9 := mload(0x120) + m10 := mload(0x140) + // Selector of `log(string,address,string,string)`. + mstore(0x00, 0x245986f2) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, 0xc0) + mstore(0x80, 0x100) + writeString(0xa0, p0) + writeString(0xe0, p2) + writeString(0x120, p3) + } + _sendLogPayload(0x1c, 0x144); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + mstore(0x120, m9) + mstore(0x140, m10) + } + } + + function log(bytes32 p0, bool p1, address p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(string,bool,address,address)`. + mstore(0x00, 0x33e9dd1d) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bytes32 p0, bool p1, address p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(string,bool,address,bool)`. + mstore(0x00, 0x958c28c6) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bytes32 p0, bool p1, address p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(string,bool,address,uint256)`. + mstore(0x00, 0x5d08bb05) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bytes32 p0, bool p1, address p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(string,bool,address,string)`. + mstore(0x00, 0x2d8e33a4) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0xc0) + writeString(0xa0, p0) + writeString(0xe0, p3) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bytes32 p0, bool p1, bool p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(string,bool,bool,address)`. + mstore(0x00, 0x7190a529) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bytes32 p0, bool p1, bool p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(string,bool,bool,bool)`. + mstore(0x00, 0x895af8c5) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bytes32 p0, bool p1, bool p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(string,bool,bool,uint256)`. + mstore(0x00, 0x8e3f78a9) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bytes32 p0, bool p1, bool p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(string,bool,bool,string)`. + mstore(0x00, 0x9d22d5dd) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0xc0) + writeString(0xa0, p0) + writeString(0xe0, p3) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bytes32 p0, bool p1, uint256 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(string,bool,uint256,address)`. + mstore(0x00, 0x935e09bf) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bytes32 p0, bool p1, uint256 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(string,bool,uint256,bool)`. + mstore(0x00, 0x8af7cf8a) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bytes32 p0, bool p1, uint256 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(string,bool,uint256,uint256)`. + mstore(0x00, 0x64b5bb67) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bytes32 p0, bool p1, uint256 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(string,bool,uint256,string)`. + mstore(0x00, 0x742d6ee7) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0xc0) + writeString(0xa0, p0) + writeString(0xe0, p3) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bytes32 p0, bool p1, bytes32 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(string,bool,string,address)`. + mstore(0x00, 0xe0625b29) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, 0xc0) + mstore(0x80, p3) + writeString(0xa0, p0) + writeString(0xe0, p2) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bytes32 p0, bool p1, bytes32 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(string,bool,string,bool)`. + mstore(0x00, 0x3f8a701d) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, 0xc0) + mstore(0x80, p3) + writeString(0xa0, p0) + writeString(0xe0, p2) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bytes32 p0, bool p1, bytes32 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(string,bool,string,uint256)`. + mstore(0x00, 0x24f91465) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, 0xc0) + mstore(0x80, p3) + writeString(0xa0, p0) + writeString(0xe0, p2) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bytes32 p0, bool p1, bytes32 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + bytes32 m9; + bytes32 m10; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + m9 := mload(0x120) + m10 := mload(0x140) + // Selector of `log(string,bool,string,string)`. + mstore(0x00, 0xa826caeb) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, 0xc0) + mstore(0x80, 0x100) + writeString(0xa0, p0) + writeString(0xe0, p2) + writeString(0x120, p3) + } + _sendLogPayload(0x1c, 0x144); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + mstore(0x120, m9) + mstore(0x140, m10) + } + } + + function log(bytes32 p0, uint256 p1, address p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(string,uint256,address,address)`. + mstore(0x00, 0x5ea2b7ae) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bytes32 p0, uint256 p1, address p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(string,uint256,address,bool)`. + mstore(0x00, 0x82112a42) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bytes32 p0, uint256 p1, address p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(string,uint256,address,uint256)`. + mstore(0x00, 0x4f04fdc6) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bytes32 p0, uint256 p1, address p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(string,uint256,address,string)`. + mstore(0x00, 0x9ffb2f93) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0xc0) + writeString(0xa0, p0) + writeString(0xe0, p3) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bytes32 p0, uint256 p1, bool p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(string,uint256,bool,address)`. + mstore(0x00, 0xe0e95b98) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bytes32 p0, uint256 p1, bool p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(string,uint256,bool,bool)`. + mstore(0x00, 0x354c36d6) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bytes32 p0, uint256 p1, bool p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(string,uint256,bool,uint256)`. + mstore(0x00, 0xe41b6f6f) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bytes32 p0, uint256 p1, bool p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(string,uint256,bool,string)`. + mstore(0x00, 0xabf73a98) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0xc0) + writeString(0xa0, p0) + writeString(0xe0, p3) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bytes32 p0, uint256 p1, uint256 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(string,uint256,uint256,address)`. + mstore(0x00, 0xe21de278) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bytes32 p0, uint256 p1, uint256 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(string,uint256,uint256,bool)`. + mstore(0x00, 0x7626db92) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bytes32 p0, uint256 p1, uint256 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + // Selector of `log(string,uint256,uint256,uint256)`. + mstore(0x00, 0xa7a87853) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + } + _sendLogPayload(0x1c, 0xc4); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + } + } + + function log(bytes32 p0, uint256 p1, uint256 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(string,uint256,uint256,string)`. + mstore(0x00, 0x854b3496) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, p2) + mstore(0x80, 0xc0) + writeString(0xa0, p0) + writeString(0xe0, p3) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bytes32 p0, uint256 p1, bytes32 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(string,uint256,string,address)`. + mstore(0x00, 0x7c4632a4) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, 0xc0) + mstore(0x80, p3) + writeString(0xa0, p0) + writeString(0xe0, p2) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bytes32 p0, uint256 p1, bytes32 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(string,uint256,string,bool)`. + mstore(0x00, 0x7d24491d) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, 0xc0) + mstore(0x80, p3) + writeString(0xa0, p0) + writeString(0xe0, p2) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bytes32 p0, uint256 p1, bytes32 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(string,uint256,string,uint256)`. + mstore(0x00, 0xc67ea9d1) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, 0xc0) + mstore(0x80, p3) + writeString(0xa0, p0) + writeString(0xe0, p2) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bytes32 p0, uint256 p1, bytes32 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + bytes32 m9; + bytes32 m10; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + m9 := mload(0x120) + m10 := mload(0x140) + // Selector of `log(string,uint256,string,string)`. + mstore(0x00, 0x5ab84e1f) + mstore(0x20, 0x80) + mstore(0x40, p1) + mstore(0x60, 0xc0) + mstore(0x80, 0x100) + writeString(0xa0, p0) + writeString(0xe0, p2) + writeString(0x120, p3) + } + _sendLogPayload(0x1c, 0x144); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + mstore(0x120, m9) + mstore(0x140, m10) + } + } + + function log(bytes32 p0, bytes32 p1, address p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(string,string,address,address)`. + mstore(0x00, 0x439c7bef) + mstore(0x20, 0x80) + mstore(0x40, 0xc0) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + writeString(0xe0, p1) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bytes32 p0, bytes32 p1, address p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(string,string,address,bool)`. + mstore(0x00, 0x5ccd4e37) + mstore(0x20, 0x80) + mstore(0x40, 0xc0) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + writeString(0xe0, p1) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bytes32 p0, bytes32 p1, address p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(string,string,address,uint256)`. + mstore(0x00, 0x7cc3c607) + mstore(0x20, 0x80) + mstore(0x40, 0xc0) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + writeString(0xe0, p1) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bytes32 p0, bytes32 p1, address p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + bytes32 m9; + bytes32 m10; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + m9 := mload(0x120) + m10 := mload(0x140) + // Selector of `log(string,string,address,string)`. + mstore(0x00, 0xeb1bff80) + mstore(0x20, 0x80) + mstore(0x40, 0xc0) + mstore(0x60, p2) + mstore(0x80, 0x100) + writeString(0xa0, p0) + writeString(0xe0, p1) + writeString(0x120, p3) + } + _sendLogPayload(0x1c, 0x144); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + mstore(0x120, m9) + mstore(0x140, m10) + } + } + + function log(bytes32 p0, bytes32 p1, bool p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(string,string,bool,address)`. + mstore(0x00, 0xc371c7db) + mstore(0x20, 0x80) + mstore(0x40, 0xc0) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + writeString(0xe0, p1) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bytes32 p0, bytes32 p1, bool p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(string,string,bool,bool)`. + mstore(0x00, 0x40785869) + mstore(0x20, 0x80) + mstore(0x40, 0xc0) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + writeString(0xe0, p1) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bytes32 p0, bytes32 p1, bool p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(string,string,bool,uint256)`. + mstore(0x00, 0xd6aefad2) + mstore(0x20, 0x80) + mstore(0x40, 0xc0) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + writeString(0xe0, p1) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bytes32 p0, bytes32 p1, bool p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + bytes32 m9; + bytes32 m10; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + m9 := mload(0x120) + m10 := mload(0x140) + // Selector of `log(string,string,bool,string)`. + mstore(0x00, 0x5e84b0ea) + mstore(0x20, 0x80) + mstore(0x40, 0xc0) + mstore(0x60, p2) + mstore(0x80, 0x100) + writeString(0xa0, p0) + writeString(0xe0, p1) + writeString(0x120, p3) + } + _sendLogPayload(0x1c, 0x144); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + mstore(0x120, m9) + mstore(0x140, m10) + } + } + + function log(bytes32 p0, bytes32 p1, uint256 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(string,string,uint256,address)`. + mstore(0x00, 0x1023f7b2) + mstore(0x20, 0x80) + mstore(0x40, 0xc0) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + writeString(0xe0, p1) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bytes32 p0, bytes32 p1, uint256 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(string,string,uint256,bool)`. + mstore(0x00, 0xc3a8a654) + mstore(0x20, 0x80) + mstore(0x40, 0xc0) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + writeString(0xe0, p1) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bytes32 p0, bytes32 p1, uint256 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + // Selector of `log(string,string,uint256,uint256)`. + mstore(0x00, 0xf45d7d2c) + mstore(0x20, 0x80) + mstore(0x40, 0xc0) + mstore(0x60, p2) + mstore(0x80, p3) + writeString(0xa0, p0) + writeString(0xe0, p1) + } + _sendLogPayload(0x1c, 0x104); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + } + } + + function log(bytes32 p0, bytes32 p1, uint256 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + bytes32 m9; + bytes32 m10; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + m9 := mload(0x120) + m10 := mload(0x140) + // Selector of `log(string,string,uint256,string)`. + mstore(0x00, 0x5d1a971a) + mstore(0x20, 0x80) + mstore(0x40, 0xc0) + mstore(0x60, p2) + mstore(0x80, 0x100) + writeString(0xa0, p0) + writeString(0xe0, p1) + writeString(0x120, p3) + } + _sendLogPayload(0x1c, 0x144); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + mstore(0x120, m9) + mstore(0x140, m10) + } + } + + function log(bytes32 p0, bytes32 p1, bytes32 p2, address p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + bytes32 m9; + bytes32 m10; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + m9 := mload(0x120) + m10 := mload(0x140) + // Selector of `log(string,string,string,address)`. + mstore(0x00, 0x6d572f44) + mstore(0x20, 0x80) + mstore(0x40, 0xc0) + mstore(0x60, 0x100) + mstore(0x80, p3) + writeString(0xa0, p0) + writeString(0xe0, p1) + writeString(0x120, p2) + } + _sendLogPayload(0x1c, 0x144); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + mstore(0x120, m9) + mstore(0x140, m10) + } + } + + function log(bytes32 p0, bytes32 p1, bytes32 p2, bool p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + bytes32 m9; + bytes32 m10; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + m9 := mload(0x120) + m10 := mload(0x140) + // Selector of `log(string,string,string,bool)`. + mstore(0x00, 0x2c1754ed) + mstore(0x20, 0x80) + mstore(0x40, 0xc0) + mstore(0x60, 0x100) + mstore(0x80, p3) + writeString(0xa0, p0) + writeString(0xe0, p1) + writeString(0x120, p2) + } + _sendLogPayload(0x1c, 0x144); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + mstore(0x120, m9) + mstore(0x140, m10) + } + } + + function log(bytes32 p0, bytes32 p1, bytes32 p2, uint256 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + bytes32 m9; + bytes32 m10; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + m9 := mload(0x120) + m10 := mload(0x140) + // Selector of `log(string,string,string,uint256)`. + mstore(0x00, 0x8eafb02b) + mstore(0x20, 0x80) + mstore(0x40, 0xc0) + mstore(0x60, 0x100) + mstore(0x80, p3) + writeString(0xa0, p0) + writeString(0xe0, p1) + writeString(0x120, p2) + } + _sendLogPayload(0x1c, 0x144); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + mstore(0x120, m9) + mstore(0x140, m10) + } + } + + function log(bytes32 p0, bytes32 p1, bytes32 p2, bytes32 p3) internal pure { + bytes32 m0; + bytes32 m1; + bytes32 m2; + bytes32 m3; + bytes32 m4; + bytes32 m5; + bytes32 m6; + bytes32 m7; + bytes32 m8; + bytes32 m9; + bytes32 m10; + bytes32 m11; + bytes32 m12; + assembly ("memory-safe") { + function writeString(pos, w) { + let length := 0 + for {} lt(length, 0x20) { length := add(length, 1) } { if iszero(byte(length, w)) { break } } + mstore(pos, length) + let shift := sub(256, shl(3, length)) + mstore(add(pos, 0x20), shl(shift, shr(shift, w))) + } + m0 := mload(0x00) + m1 := mload(0x20) + m2 := mload(0x40) + m3 := mload(0x60) + m4 := mload(0x80) + m5 := mload(0xa0) + m6 := mload(0xc0) + m7 := mload(0xe0) + m8 := mload(0x100) + m9 := mload(0x120) + m10 := mload(0x140) + m11 := mload(0x160) + m12 := mload(0x180) + // Selector of `log(string,string,string,string)`. + mstore(0x00, 0xde68f20a) + mstore(0x20, 0x80) + mstore(0x40, 0xc0) + mstore(0x60, 0x100) + mstore(0x80, 0x140) + writeString(0xa0, p0) + writeString(0xe0, p1) + writeString(0x120, p2) + writeString(0x160, p3) + } + _sendLogPayload(0x1c, 0x184); + assembly ("memory-safe") { + mstore(0x00, m0) + mstore(0x20, m1) + mstore(0x40, m2) + mstore(0x60, m3) + mstore(0x80, m4) + mstore(0xa0, m5) + mstore(0xc0, m6) + mstore(0xe0, m7) + mstore(0x100, m8) + mstore(0x120, m9) + mstore(0x140, m10) + mstore(0x160, m11) + mstore(0x180, m12) + } + } +} diff --git a/contracts/evm/lib/forge-std/test/CommonBase.t.sol b/contracts/evm/lib/forge-std/test/CommonBase.t.sol new file mode 100644 index 0000000000..28c91a912b --- /dev/null +++ b/contracts/evm/lib/forge-std/test/CommonBase.t.sol @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {CommonBase} from "../src/Base.sol"; +import {StdConstants} from "../src/StdConstants.sol"; +import {Test} from "../src/Test.sol"; + +contract CommonBaseTest is Test { + function testVmAddressValue() public pure { + assertEq(VM_ADDRESS, address(StdConstants.VM)); + } + + function testConsoleValue() public pure { + assertEq(CONSOLE, StdConstants.CONSOLE); + } + + function testCreate2FactoryValue() public pure { + assertEq(CREATE2_FACTORY, StdConstants.CREATE2_FACTORY); + } + + function testDefaultSenderValue() public pure { + assertEq(DEFAULT_SENDER, StdConstants.DEFAULT_SENDER); + } + + function testDefaultTestContractValue() public pure { + assertEq(DEFAULT_TEST_CONTRACT, StdConstants.DEFAULT_TEST_CONTRACT); + } + + function testMulticall3AddressValue() public pure { + assertEq(MULTICALL3_ADDRESS, address(StdConstants.MULTICALL3_ADDRESS)); + } + + function testSecp256k1OrderValue() public pure { + assertEq(SECP256K1_ORDER, StdConstants.SECP256K1_ORDER); + } + + function testUint256MaxValue() public pure { + assertEq(UINT256_MAX, type(uint256).max); + } + + function testVmValue() public pure { + assertEq(address(vm), address(StdConstants.VM)); + } +} diff --git a/contracts/evm/lib/forge-std/test/Config.t.sol b/contracts/evm/lib/forge-std/test/Config.t.sol new file mode 100644 index 0000000000..00af755074 --- /dev/null +++ b/contracts/evm/lib/forge-std/test/Config.t.sol @@ -0,0 +1,381 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity ^0.8.13; + +import {Test} from "../src/Test.sol"; +import {Config} from "../src/Config.sol"; +import {StdConfig} from "../src/StdConfig.sol"; + +contract ConfigTest is Test, Config { + function setUp() public { + vm.setEnv("MAINNET_RPC", "https://ethereum.reth.rs/rpc"); + vm.setEnv("WETH_MAINNET", "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"); + vm.setEnv("OPTIMISM_RPC", "https://mainnet.optimism.io"); + vm.setEnv("WETH_OPTIMISM", "0x4200000000000000000000000000000000000006"); + } + + function test_loadConfig() public { + // Deploy the config contract with the test fixture. + _loadConfig("./test/fixtures/config.toml", false); + + // -- MAINNET -------------------------------------------------------------- + + // Read and assert RPC URL for Mainnet (chain ID 1) + assertEq(config.getRpcUrl(1), "https://ethereum.reth.rs/rpc"); + + // Read and assert boolean values + assertTrue(config.get(1, "is_live").toBool()); + bool[] memory bool_array = config.get(1, "bool_array").toBoolArray(); + assertTrue(bool_array[0]); + assertFalse(bool_array[1]); + + // Read and assert address values + assertEq(config.get(1, "weth").toAddress(), 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); + address[] memory address_array = config.get(1, "deps").toAddressArray(); + assertEq(address_array[0], 0x0000000000000000000000000000000000000000); + assertEq(address_array[1], 0x1111111111111111111111111111111111111111); + + // Read and assert bytes32 values + assertEq(config.get(1, "word").toBytes32(), bytes32(uint256(1234))); + bytes32[] memory bytes32_array = config.get(1, "word_array").toBytes32Array(); + assertEq(bytes32_array[0], bytes32(uint256(5678))); + assertEq(bytes32_array[1], bytes32(uint256(9999))); + + // Read and assert uint values + assertEq(config.get(1, "number").toUint256(), 1234); + uint256[] memory uint_array = config.get(1, "number_array").toUint256Array(); + assertEq(uint_array[0], 5678); + assertEq(uint_array[1], 9999); + + // Read and assert int values + assertEq(config.get(1, "signed_number").toInt256(), -1234); + int256[] memory int_array = config.get(1, "signed_number_array").toInt256Array(); + assertEq(int_array[0], -5678); + assertEq(int_array[1], 9999); + + // Read and assert bytes values + assertEq(config.get(1, "b").toBytes(), hex"abcd"); + bytes[] memory bytes_array = config.get(1, "b_array").toBytesArray(); + assertEq(bytes_array[0], hex"dead"); + assertEq(bytes_array[1], hex"beef"); + + // Read and assert string values + assertEq(config.get(1, "str").toString(), "foo"); + string[] memory string_array = config.get(1, "str_array").toStringArray(); + assertEq(string_array[0], "bar"); + assertEq(string_array[1], "baz"); + + // -- OPTIMISM ------------------------------------------------------------ + + // Read and assert RPC URL for Optimism (chain ID 10) + assertEq(config.getRpcUrl(10), "https://mainnet.optimism.io"); + + // Read and assert boolean values + assertFalse(config.get(10, "is_live").toBool()); + bool_array = config.get(10, "bool_array").toBoolArray(); + assertFalse(bool_array[0]); + assertTrue(bool_array[1]); + + // Read and assert address values + assertEq(config.get(10, "weth").toAddress(), 0x4200000000000000000000000000000000000006); + address_array = config.get(10, "deps").toAddressArray(); + assertEq(address_array[0], 0x2222222222222222222222222222222222222222); + assertEq(address_array[1], 0x3333333333333333333333333333333333333333); + + // Read and assert bytes32 values + assertEq(config.get(10, "word").toBytes32(), bytes32(uint256(9999))); + bytes32_array = config.get(10, "word_array").toBytes32Array(); + assertEq(bytes32_array[0], bytes32(uint256(1234))); + assertEq(bytes32_array[1], bytes32(uint256(5678))); + + // Read and assert uint values + assertEq(config.get(10, "number").toUint256(), 9999); + uint_array = config.get(10, "number_array").toUint256Array(); + assertEq(uint_array[0], 1234); + assertEq(uint_array[1], 5678); + + // Read and assert int values + assertEq(config.get(10, "signed_number").toInt256(), 9999); + int_array = config.get(10, "signed_number_array").toInt256Array(); + assertEq(int_array[0], -1234); + assertEq(int_array[1], -5678); + + // Read and assert bytes values + assertEq(config.get(10, "b").toBytes(), hex"dcba"); + bytes_array = config.get(10, "b_array").toBytesArray(); + assertEq(bytes_array[0], hex"c0ffee"); + assertEq(bytes_array[1], hex"babe"); + + // Read and assert string values + assertEq(config.get(10, "str").toString(), "alice"); + string_array = config.get(10, "str_array").toStringArray(); + assertEq(string_array[0], "bob"); + assertEq(string_array[1], "charlie"); + } + + function test_loadConfigAndForks() public { + _loadConfigAndForks("./test/fixtures/config.toml", false); + + // assert that the map of chain id and fork ids is created and that the chain ids actually match + assertEq(forkOf[1], 0); + vm.selectFork(forkOf[1]); + assertEq(vm.getChainId(), 1); + + assertEq(forkOf[10], 1); + vm.selectFork(forkOf[10]); + assertEq(vm.getChainId(), 10); + } + + function test_configExists() public { + _loadConfig("./test/fixtures/config.toml", false); + + string[] memory keys = new string[](7); + keys[0] = "is_live"; + keys[1] = "weth"; + keys[2] = "word"; + keys[3] = "number"; + keys[4] = "signed_number"; + keys[5] = "b"; + keys[6] = "str"; + + // Read and assert RPC URL for Mainnet (chain ID 1) + assertEq(config.getRpcUrl(1), "https://ethereum.reth.rs/rpc"); + + for (uint256 i = 0; i < keys.length; ++i) { + assertTrue(config.exists(1, keys[i])); + assertFalse(config.exists(1, string.concat(keys[i], "_"))); + } + + // Assert RPC URL for Optimism (chain ID 10) + assertEq(config.getRpcUrl(10), "https://mainnet.optimism.io"); + + for (uint256 i = 0; i < keys.length; ++i) { + assertTrue(config.exists(10, keys[i])); + assertFalse(config.exists(10, string.concat(keys[i], "_"))); + } + } + + function test_writeConfig() public { + // Create a temporary copy of the config file to avoid modifying the original. + string memory originalConfig = "./test/fixtures/config.toml"; + string memory testConfig = "./test/fixtures/config.t.toml"; + vm.copyFile(originalConfig, testConfig); + + // Deploy the config contract with the temporary fixture. + _loadConfig(testConfig, false); + + // Enable writing to file bypassing the context check. + vm.store(address(config), bytes32(uint256(5)), bytes32(uint256(1))); + + { + // Update a single boolean value and verify the change. + config.set(1, "is_live", false); + + assertFalse(config.get(1, "is_live").toBool()); + + string memory content = vm.readFile(testConfig); + assertFalse(vm.parseTomlBool(content, "$.mainnet.bool.is_live")); + + // Update a single address value and verify the change. + address new_addr = 0xDeaDbeefdEAdbeefdEadbEEFdeadbeEFdEaDbeeF; + config.set(1, "weth", new_addr); + + assertEq(config.get(1, "weth").toAddress(), new_addr); + + content = vm.readFile(testConfig); + assertEq(vm.parseTomlAddress(content, "$.mainnet.address.weth"), new_addr); + + // Update a uint array and verify the change. + uint256[] memory new_numbers = new uint256[](3); + new_numbers[0] = 1; + new_numbers[1] = 2; + new_numbers[2] = 3; + config.set(10, "number_array", new_numbers); + + uint256[] memory updated_numbers_mem = config.get(10, "number_array").toUint256Array(); + assertEq(updated_numbers_mem.length, 3); + assertEq(updated_numbers_mem[0], 1); + assertEq(updated_numbers_mem[1], 2); + assertEq(updated_numbers_mem[2], 3); + + content = vm.readFile(testConfig); + uint256[] memory updated_numbers_disk = vm.parseTomlUintArray(content, "$.optimism.uint.number_array"); + assertEq(updated_numbers_disk.length, 3); + assertEq(updated_numbers_disk[0], 1); + assertEq(updated_numbers_disk[1], 2); + assertEq(updated_numbers_disk[2], 3); + + // Update a string array and verify the change. + string[] memory new_strings = new string[](2); + new_strings[0] = "hello"; + new_strings[1] = "world"; + config.set(1, "str_array", new_strings); + + string[] memory updated_strings_mem = config.get(1, "str_array").toStringArray(); + assertEq(updated_strings_mem.length, 2); + assertEq(updated_strings_mem[0], "hello"); + assertEq(updated_strings_mem[1], "world"); + + content = vm.readFile(testConfig); + string[] memory updated_strings_disk = vm.parseTomlStringArray(content, "$.mainnet.string.str_array"); + assertEq(updated_strings_disk.length, 2); + assertEq(updated_strings_disk[0], "hello"); + assertEq(updated_strings_disk[1], "world"); + + // Create a new uint variable and verify the change. + config.set(1, "new_uint", uint256(42)); + + assertEq(config.get(1, "new_uint").toUint256(), 42); + + content = vm.readFile(testConfig); + assertEq(vm.parseTomlUint(content, "$.mainnet.uint.new_uint"), 42); + + // Create a new int variable and verify the change. + config.set(1, "new_int", int256(-42)); + + assertEq(config.get(1, "new_int").toInt256(), -42); + + content = vm.readFile(testConfig); + assertEq(vm.parseTomlInt(content, "$.mainnet.int.new_int"), -42); + + // Create a new int array and verify the change. + int256[] memory new_ints = new int256[](2); + new_ints[0] = -100; + new_ints[1] = 200; + config.set(10, "new_ints", new_ints); + + int256[] memory updated_ints_mem = config.get(10, "new_ints").toInt256Array(); + assertEq(updated_ints_mem.length, 2); + assertEq(updated_ints_mem[0], -100); + assertEq(updated_ints_mem[1], 200); + + content = vm.readFile(testConfig); + int256[] memory updated_ints_disk = vm.parseTomlIntArray(content, "$.optimism.int.new_ints"); + assertEq(updated_ints_disk.length, 2); + assertEq(updated_ints_disk[0], -100); + assertEq(updated_ints_disk[1], 200); + + // Create a new bytes32 array and verify the change. + bytes32[] memory new_words = new bytes32[](2); + new_words[0] = bytes32(uint256(0xDEAD)); + new_words[1] = bytes32(uint256(0xBEEF)); + config.set(10, "new_words", new_words); + + bytes32[] memory updated_words_mem = config.get(10, "new_words").toBytes32Array(); + assertEq(updated_words_mem.length, 2); + assertEq(updated_words_mem[0], new_words[0]); + assertEq(updated_words_mem[1], new_words[1]); + + content = vm.readFile(testConfig); + bytes32[] memory updated_words_disk = vm.parseTomlBytes32Array(content, "$.optimism.bytes32.new_words"); + assertEq(updated_words_disk.length, 2); + assertEq(vm.toString(updated_words_disk[0]), vm.toString(new_words[0])); + assertEq(vm.toString(updated_words_disk[1]), vm.toString(new_words[1])); + } + + // Clean up the temporary file. + vm.removeFile(testConfig); + } + + function test_writeUpdatesBackToFile() public { + // Create a temporary copy of the config file to avoid modifying the original. + string memory originalConfig = "./test/fixtures/config.toml"; + string memory testConfig = "./test/fixtures/write_config.t.toml"; + vm.copyFile(originalConfig, testConfig); + + // Deploy the config contract with `writeToFile = false` (disabled). + _loadConfig(testConfig, false); + + // Update a single boolean value and verify the file is NOT changed. + config.set(1, "is_live", false); + string memory content = vm.readFile(testConfig); + assertTrue(vm.parseTomlBool(content, "$.mainnet.bool.is_live"), "File should not be updated yet"); + + // Enable writing to file bypassing the context check. + vm.store(address(config), bytes32(uint256(5)), bytes32(uint256(1))); + + // Update the value again and verify the file IS changed. + config.set(1, "is_live", false); + content = vm.readFile(testConfig); + assertFalse(vm.parseTomlBool(content, "$.mainnet.bool.is_live"), "File should be updated now"); + + // Disable writing to file. + config.writeUpdatesBackToFile(false); + + // Update the value again and verify the file is NOT changed. + config.set(1, "is_live", true); + content = vm.readFile(testConfig); + assertFalse(vm.parseTomlBool(content, "$.mainnet.bool.is_live"), "File should not be updated again"); + + // Clean up the temporary file. + vm.removeFile(testConfig); + } + + function testRevert_WriteToFileInForbiddenCtxt() public { + // Cannot initialize enabling writing to file unless we are in SCRIPT mode. + vm.expectRevert(StdConfig.WriteToFileInForbiddenCtxt.selector); + _loadConfig("./test/fixtures/config.toml", true); + + // Initialize with `writeToFile = false`. + _loadConfig("./test/fixtures/config.toml", false); + + // Cannot enable writing to file unless we are in SCRIPT mode. + vm.expectRevert(StdConfig.WriteToFileInForbiddenCtxt.selector); + config.writeUpdatesBackToFile(true); + } + + function testRevert_InvalidChainKey() public { + // Create a fixture with an invalid chain key + string memory invalidChainConfig = "./test/fixtures/config_invalid_chain.toml"; + vm.writeFile( + invalidChainConfig, + string.concat( + "[mainnet]\n", + "endpoint_url = \"https://ethereum.reth.rs/rpc\"\n", + "\n", + "[mainnet.uint]\n", + "valid_number = 123\n", + "\n", + "# Invalid chain key (not a number and not a valid alias)\n", + "[invalid_chain]\n", + "endpoint_url = \"https://invalid.com\"\n", + "\n", + "[invalid_chain_9999.uint]\n", + "some_value = 456\n" + ) + ); + + vm.expectRevert(abi.encodeWithSelector(StdConfig.InvalidChainKey.selector, "invalid_chain")); + new StdConfig(invalidChainConfig, false); + vm.removeFile(invalidChainConfig); + } + + function testRevert_ChainNotInitialized() public { + _loadConfig("./test/fixtures/config.toml", false); + + // Enable writing to file bypassing the context check. + vm.store(address(config), bytes32(uint256(5)), bytes32(uint256(1))); + + // Try to write a value for a non-existent chain ID + vm.expectRevert(abi.encodeWithSelector(StdConfig.ChainNotInitialized.selector, uint256(999999))); + config.set(999999, "some_key", uint256(123)); + } + + function testRevert_UnableToParseVariable() public { + // Create a temporary fixture with an unparsable variable + string memory badParseConfig = "./test/fixtures/config_bad_parse.toml"; + vm.writeFile( + badParseConfig, + string.concat( + "[mainnet]\n", + "endpoint_url = \"https://ethereum.reth.rs/rpc\"\n", + "\n", + "[mainnet.uint]\n", + "bad_value = \"not_a_number\"\n" + ) + ); + + vm.expectRevert(abi.encodeWithSelector(StdConfig.UnableToParseVariable.selector, "bad_value")); + new StdConfig(badParseConfig, false); + vm.removeFile(badParseConfig); + } +} diff --git a/contracts/evm/lib/forge-std/test/LibVariable.t.sol b/contracts/evm/lib/forge-std/test/LibVariable.t.sol new file mode 100644 index 0000000000..abd515cc47 --- /dev/null +++ b/contracts/evm/lib/forge-std/test/LibVariable.t.sol @@ -0,0 +1,452 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity ^0.8.13; + +import {Test} from "../src/Test.sol"; +import {Variable, Type, TypeKind, LibVariable} from "../src/LibVariable.sol"; + +contract LibVariableTest is Test { + using LibVariable for Type; + using LibVariable for TypeKind; + + LibVariableHelper internal helper; + + bytes internal expectedErr; + Variable internal uninitVar; + Variable internal boolVar; + Variable internal addressVar; + Variable internal bytes32Var; + Variable internal uintVar; + Variable internal intVar; + Variable internal stringVar; + Variable internal bytesVar; + Variable internal boolArrayVar; + Variable internal addressArrayVar; + Variable internal bytes32ArrayVar; + Variable internal uintArrayVar; + Variable internal intArrayVar; + Variable internal stringArrayVar; + Variable internal bytesArrayVar; + + function setUp() public { + helper = new LibVariableHelper(); + + // UNINITIALIZED + uninitVar = Variable(Type(TypeKind.None, false), ""); + + // SINGLE VALUES + boolVar = Variable(Type(TypeKind.Bool, false), abi.encode(true)); + addressVar = Variable(Type(TypeKind.Address, false), abi.encode(address(0xdeadbeef))); + bytes32Var = Variable(Type(TypeKind.Bytes32, false), abi.encode(bytes32(uint256(42)))); + uintVar = Variable(Type(TypeKind.Uint256, false), abi.encode(uint256(123))); + intVar = Variable(Type(TypeKind.Int256, false), abi.encode(int256(-123))); + stringVar = Variable(Type(TypeKind.String, false), abi.encode("hello world")); + bytesVar = Variable(Type(TypeKind.Bytes, false), abi.encode(hex"c0ffee")); + + // ARRAY VALUES + bool[] memory bools = new bool[](2); + bools[0] = true; + bools[1] = false; + boolArrayVar = Variable(Type(TypeKind.Bool, true), abi.encode(bools)); + + address[] memory addrs = new address[](2); + addrs[0] = address(0x1); + addrs[1] = address(0x2); + addressArrayVar = Variable(Type(TypeKind.Address, true), abi.encode(addrs)); + + bytes32[] memory b32s = new bytes32[](2); + b32s[0] = bytes32(uint256(1)); + b32s[1] = bytes32(uint256(2)); + bytes32ArrayVar = Variable(Type(TypeKind.Bytes32, true), abi.encode(b32s)); + + uint256[] memory uints = new uint256[](2); + uints[0] = 1; + uints[1] = 2; + uintArrayVar = Variable(Type(TypeKind.Uint256, true), abi.encode(uints)); + + int256[] memory ints = new int256[](2); + ints[0] = -1; + ints[1] = 2; + intArrayVar = Variable(Type(TypeKind.Int256, true), abi.encode(ints)); + + string[] memory strings = new string[](2); + strings[0] = "one"; + strings[1] = "two"; + stringArrayVar = Variable(Type(TypeKind.String, true), abi.encode(strings)); + + bytes[] memory b = new bytes[](2); + b[0] = hex"01"; + b[1] = hex"02"; + bytesArrayVar = Variable(Type(TypeKind.Bytes, true), abi.encode(b)); + } + + // -- SUCCESS CASES -------------------------------------------------------- + + function test_TypeHelpers() public view { + // TypeKind.toString() + assertEq(TypeKind.None.toString(), "none"); + assertEq(TypeKind.Bool.toString(), "bool"); + assertEq(TypeKind.Address.toString(), "address"); + assertEq(TypeKind.Bytes32.toString(), "bytes32"); + assertEq(TypeKind.Uint256.toString(), "uint256"); + assertEq(TypeKind.Int256.toString(), "int256"); + assertEq(TypeKind.String.toString(), "string"); + assertEq(TypeKind.Bytes.toString(), "bytes"); + + // TypeKind.toTomlKey() + assertEq(TypeKind.Uint256.toTomlKey(), "uint"); + assertEq(TypeKind.Int256.toTomlKey(), "int"); + assertEq(TypeKind.Bytes32.toTomlKey(), "bytes32"); + + // Type.toString() + assertEq(boolVar.ty.toString(), "bool"); + assertEq(boolArrayVar.ty.toString(), "bool[]"); + assertEq(uintVar.ty.toString(), "uint256"); + assertEq(uintArrayVar.ty.toString(), "uint256[]"); + assertEq(uninitVar.ty.toString(), "none"); + + // Type.isEqual() + assertTrue(boolVar.ty.isEqual(Type(TypeKind.Bool, false))); + assertFalse(boolVar.ty.isEqual(Type(TypeKind.Bool, true))); + assertFalse(boolVar.ty.isEqual(Type(TypeKind.Address, false))); + + // Type.assertEq() + boolVar.ty.assertEq(Type(TypeKind.Bool, false)); + uintArrayVar.ty.assertEq(Type(TypeKind.Uint256, true)); + } + + function test_Coercion() public view { + // Single values + assertTrue(helper.toBool(boolVar)); + assertEq(helper.toAddress(addressVar), address(0xdeadbeef)); + assertEq(helper.toBytes32(bytes32Var), bytes32(uint256(42))); + assertEq(helper.toUint256(uintVar), 123); + assertEq(helper.toInt256(intVar), -123); + assertEq(helper.toString(stringVar), "hello world"); + assertEq(helper.toBytes(bytesVar), hex"c0ffee"); + + // Bool array + bool[] memory bools = helper.toBoolArray(boolArrayVar); + assertEq(bools.length, 2); + assertTrue(bools[0]); + assertFalse(bools[1]); + + // Address array + address[] memory addrs = helper.toAddressArray(addressArrayVar); + assertEq(addrs.length, 2); + assertEq(addrs[0], address(0x1)); + assertEq(addrs[1], address(0x2)); + + // String array + string[] memory strings = helper.toStringArray(stringArrayVar); + assertEq(strings.length, 2); + assertEq(strings[0], "one"); + assertEq(strings[1], "two"); + + // Bytes32 array + bytes32[] memory b32s = helper.toBytes32Array(bytes32ArrayVar); + assertEq(b32s.length, 2); + assertEq(b32s[0], bytes32(uint256(1))); + assertEq(b32s[1], bytes32(uint256(2))); + + // Int array + int256[] memory ints = helper.toInt256Array(intArrayVar); + assertEq(ints.length, 2); + assertEq(ints[0], -1); + assertEq(ints[1], 2); + + // Bytes array + bytes[] memory b = helper.toBytesArray(bytesArrayVar); + assertEq(b.length, 2); + assertEq(b[0], hex"01"); + assertEq(b[1], hex"02"); + } + + function test_Downcasting() public view { + // Uint downcasting + Variable memory v_uint_small = Variable(Type(TypeKind.Uint256, false), abi.encode(uint256(100))); + assertEq(helper.toUint128(v_uint_small), 100); + assertEq(helper.toUint64(v_uint_small), 100); + assertEq(helper.toUint32(v_uint_small), 100); + assertEq(helper.toUint16(v_uint_small), 100); + assertEq(helper.toUint8(v_uint_small), 100); + + // Uint array downcasting + uint256[] memory small_uints = new uint256[](2); + small_uints[0] = 10; + small_uints[1] = 20; + Variable memory v_uint_array_small = Variable(Type(TypeKind.Uint256, true), abi.encode(small_uints)); + uint8[] memory u8_array = helper.toUint8Array(v_uint_array_small); + assertEq(u8_array[0], 10); + assertEq(u8_array[1], 20); + + // Int downcasting + Variable memory v_int_small_pos = Variable(Type(TypeKind.Int256, false), abi.encode(int256(100))); + Variable memory v_int_small_neg = Variable(Type(TypeKind.Int256, false), abi.encode(int256(-100))); + assertEq(helper.toInt128(v_int_small_pos), 100); + assertEq(helper.toInt64(v_int_small_neg), -100); + assertEq(helper.toInt32(v_int_small_pos), 100); + assertEq(helper.toInt16(v_int_small_neg), -100); + assertEq(helper.toInt8(v_int_small_pos), 100); + + // Int array downcasting + int256[] memory small_ints = new int256[](2); + small_ints[0] = -10; + small_ints[1] = 20; + Variable memory intArraySmall = Variable(Type(TypeKind.Int256, true), abi.encode(small_ints)); + int8[] memory i8_array = helper.toInt8Array(intArraySmall); + assertEq(i8_array[0], -10); + assertEq(i8_array[1], 20); + } + + // -- REVERT CASES --------------------------------------------------------- + + function testRevert_NotInitialized() public { + vm.expectRevert(LibVariable.NotInitialized.selector); + helper.toBool(uninitVar); + + vm.expectRevert(LibVariable.NotInitialized.selector); + helper.toAddressArray(uninitVar); + } + + function testRevert_assertExists() public { + vm.expectRevert(LibVariable.NotInitialized.selector); + helper.assertExists(uninitVar); + } + + function testRevert_TypeMismatch() public { + // Single values + vm.expectRevert(abi.encodeWithSelector(LibVariable.TypeMismatch.selector, "uint256", "bool")); + helper.toUint256(boolVar); + + vm.expectRevert(abi.encodeWithSelector(LibVariable.TypeMismatch.selector, "address", "string")); + helper.toAddress(stringVar); + + // Arrays + vm.expectRevert(abi.encodeWithSelector(LibVariable.TypeMismatch.selector, "uint256[]", "bool[]")); + helper.toUint256Array(boolArrayVar); + + vm.expectRevert(abi.encodeWithSelector(LibVariable.TypeMismatch.selector, "address[]", "string[]")); + helper.toAddressArray(stringArrayVar); + + // Single value to array + vm.expectRevert(abi.encodeWithSelector(LibVariable.TypeMismatch.selector, "bool[]", "bool")); + helper.toBoolArray(boolVar); + + // Array to single value + vm.expectRevert(abi.encodeWithSelector(LibVariable.TypeMismatch.selector, "bool", "bool[]")); + helper.toBool(boolArrayVar); + + // assertEq reverts + vm.expectRevert(abi.encodeWithSelector(LibVariable.TypeMismatch.selector, "uint256", "bool")); + helper.assertEq(boolVar.ty, Type(TypeKind.Uint256, false)); + } + + function testRevert_UnsafeCast() public { + // uint overflow + Variable memory uintLarge = Variable(Type(TypeKind.Uint256, false), abi.encode(uint256(type(uint128).max) + 1)); + expectedErr = abi.encodeWithSelector(LibVariable.UnsafeCast.selector, "value does not fit in 'uint128'"); + vm.expectRevert(expectedErr); + helper.toUint128(uintLarge); + + // int overflow + Variable memory intLarge = Variable(Type(TypeKind.Int256, false), abi.encode(int256(type(int128).max) + 1)); + expectedErr = abi.encodeWithSelector(LibVariable.UnsafeCast.selector, "value does not fit in 'int128'"); + + vm.expectRevert(expectedErr); + helper.toInt128(intLarge); + + // int underflow + Variable memory intSmall = Variable(Type(TypeKind.Int256, false), abi.encode(int256(type(int128).min) - 1)); + expectedErr = abi.encodeWithSelector(LibVariable.UnsafeCast.selector, "value does not fit in 'int128'"); + + vm.expectRevert(expectedErr); + helper.toInt128(intSmall); + + // uint array overflow + uint256[] memory uintArray = new uint256[](2); + uintArray[0] = 10; + uintArray[1] = uint256(type(uint64).max) + 1; + Variable memory uintArrayLarge = Variable(Type(TypeKind.Uint256, true), abi.encode(uintArray)); + expectedErr = abi.encodeWithSelector(LibVariable.UnsafeCast.selector, "value in array does not fit in 'uint64'"); + + vm.expectRevert(expectedErr); + helper.toUint64Array(uintArrayLarge); + + // int array overflow + int256[] memory intArray = new int256[](2); + intArray[0] = 10; + intArray[1] = int256(type(int64).max) + 1; + Variable memory intArrayLarge = Variable(Type(TypeKind.Int256, true), abi.encode(intArray)); + expectedErr = abi.encodeWithSelector(LibVariable.UnsafeCast.selector, "value in array does not fit in 'int64'"); + + vm.expectRevert(expectedErr); + helper.toInt64Array(intArrayLarge); + + // int array underflow + intArray[0] = 10; + intArray[1] = int256(type(int64).min) - 1; + Variable memory intArraySmall = Variable(Type(TypeKind.Int256, true), abi.encode(intArray)); + expectedErr = abi.encodeWithSelector(LibVariable.UnsafeCast.selector, "value in array does not fit in 'int64'"); + + vm.expectRevert(expectedErr); + helper.toInt64Array(intArraySmall); + } +} + +/// @dev We must use an external helper contract to ensure proper call depth for `vm.expectRevert`, +/// as direct library calls are inlined by the compiler, causing call depth issues. +contract LibVariableHelper { + using LibVariable for Type; + using LibVariable for TypeKind; + + // Assertions + function assertExists(Variable memory v) external pure { + v.assertExists(); + } + + function assertEq(Type memory t1, Type memory t2) external pure { + t1.assertEq(t2); + } + + // Single Value Coercion + function toBool(Variable memory v) external pure returns (bool) { + return v.toBool(); + } + + function toAddress(Variable memory v) external pure returns (address) { + return v.toAddress(); + } + + function toBytes32(Variable memory v) external pure returns (bytes32) { + return v.toBytes32(); + } + + function toUint256(Variable memory v) external pure returns (uint256) { + return v.toUint256(); + } + + function toInt256(Variable memory v) external pure returns (int256) { + return v.toInt256(); + } + + function toString(Variable memory v) external pure returns (string memory) { + return v.toString(); + } + + function toBytes(Variable memory v) external pure returns (bytes memory) { + return v.toBytes(); + } + + // Array Coercion + function toBoolArray(Variable memory v) external pure returns (bool[] memory) { + return v.toBoolArray(); + } + + function toAddressArray(Variable memory v) external pure returns (address[] memory) { + return v.toAddressArray(); + } + + function toBytes32Array(Variable memory v) external pure returns (bytes32[] memory) { + return v.toBytes32Array(); + } + + function toUint256Array(Variable memory v) external pure returns (uint256[] memory) { + return v.toUint256Array(); + } + + function toInt256Array(Variable memory v) external pure returns (int256[] memory) { + return v.toInt256Array(); + } + + function toStringArray(Variable memory v) external pure returns (string[] memory) { + return v.toStringArray(); + } + + function toBytesArray(Variable memory v) external pure returns (bytes[] memory) { + return v.toBytesArray(); + } + + // Uint Downcasting + function toUint128(Variable memory v) external pure returns (uint128) { + return v.toUint128(); + } + + function toUint64(Variable memory v) external pure returns (uint64) { + return v.toUint64(); + } + + function toUint32(Variable memory v) external pure returns (uint32) { + return v.toUint32(); + } + + function toUint16(Variable memory v) external pure returns (uint16) { + return v.toUint16(); + } + + function toUint8(Variable memory v) external pure returns (uint8) { + return v.toUint8(); + } + + // Int Downcasting + function toInt128(Variable memory v) external pure returns (int128) { + return v.toInt128(); + } + + function toInt64(Variable memory v) external pure returns (int64) { + return v.toInt64(); + } + + function toInt32(Variable memory v) external pure returns (int32) { + return v.toInt32(); + } + + function toInt16(Variable memory v) external pure returns (int16) { + return v.toInt16(); + } + + function toInt8(Variable memory v) external pure returns (int8) { + return v.toInt8(); + } + + // Uint Array Downcasting + function toUint128Array(Variable memory v) external pure returns (uint128[] memory) { + return v.toUint128Array(); + } + + function toUint64Array(Variable memory v) external pure returns (uint64[] memory) { + return v.toUint64Array(); + } + + function toUint32Array(Variable memory v) external pure returns (uint32[] memory) { + return v.toUint32Array(); + } + + function toUint16Array(Variable memory v) external pure returns (uint16[] memory) { + return v.toUint16Array(); + } + + function toUint8Array(Variable memory v) external pure returns (uint8[] memory) { + return v.toUint8Array(); + } + + // Int Array Downcasting + function toInt128Array(Variable memory v) external pure returns (int128[] memory) { + return v.toInt128Array(); + } + + function toInt64Array(Variable memory v) external pure returns (int64[] memory) { + return v.toInt64Array(); + } + + function toInt32Array(Variable memory v) external pure returns (int32[] memory) { + return v.toInt32Array(); + } + + function toInt16Array(Variable memory v) external pure returns (int16[] memory) { + return v.toInt16Array(); + } + + function toInt8Array(Variable memory v) external pure returns (int8[] memory) { + return v.toInt8Array(); + } +} diff --git a/contracts/evm/lib/forge-std/test/StdAssertions.t.sol b/contracts/evm/lib/forge-std/test/StdAssertions.t.sol new file mode 100644 index 0000000000..3d670cb7e4 --- /dev/null +++ b/contracts/evm/lib/forge-std/test/StdAssertions.t.sol @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {StdAssertions} from "../src/StdAssertions.sol"; +import {Vm} from "../src/Vm.sol"; + +interface VmInternal is Vm { + function _expectCheatcodeRevert(bytes memory message) external; +} + +contract StdAssertionsTest is StdAssertions { + string constant errorMessage = "User provided message"; + uint256 constant maxDecimals = 77; + + bool constant SHOULD_REVERT = true; + bool constant SHOULD_RETURN = false; + + bool constant STRICT_REVERT_DATA = true; + bool constant NON_STRICT_REVERT_DATA = false; + + VmInternal constant vm = VmInternal(address(uint160(uint256(keccak256("hevm cheat code"))))); + + function testFuzz_AssertEqCall_Return_Pass( + bytes memory callDataA, + bytes memory callDataB, + bytes memory returnData, + bool strictRevertData + ) external { + address targetA = address(new TestMockCall(returnData, SHOULD_RETURN)); + address targetB = address(new TestMockCall(returnData, SHOULD_RETURN)); + + assertEqCall(targetA, callDataA, targetB, callDataB, strictRevertData); + } + + function testFuzz_RevertWhenCalled_AssertEqCall_Return_Fail( + bytes memory callDataA, + bytes memory callDataB, + bytes memory returnDataA, + bytes memory returnDataB, + bool strictRevertData + ) external { + vm.assume(keccak256(returnDataA) != keccak256(returnDataB)); + + address targetA = address(new TestMockCall(returnDataA, SHOULD_RETURN)); + address targetB = address(new TestMockCall(returnDataB, SHOULD_RETURN)); + + vm._expectCheatcodeRevert( + bytes( + string.concat( + "Call return data does not match: ", vm.toString(returnDataA), " != ", vm.toString(returnDataB) + ) + ) + ); + assertEqCall(targetA, callDataA, targetB, callDataB, strictRevertData); + } + + function testFuzz_AssertEqCall_Revert_Pass( + bytes memory callDataA, + bytes memory callDataB, + bytes memory revertDataA, + bytes memory revertDataB + ) external { + address targetA = address(new TestMockCall(revertDataA, SHOULD_REVERT)); + address targetB = address(new TestMockCall(revertDataB, SHOULD_REVERT)); + + assertEqCall(targetA, callDataA, targetB, callDataB, NON_STRICT_REVERT_DATA); + } + + function testFuzz_RevertWhenCalled_AssertEqCall_Revert_Fail( + bytes memory callDataA, + bytes memory callDataB, + bytes memory revertDataA, + bytes memory revertDataB + ) external { + vm.assume(keccak256(revertDataA) != keccak256(revertDataB)); + + address targetA = address(new TestMockCall(revertDataA, SHOULD_REVERT)); + address targetB = address(new TestMockCall(revertDataB, SHOULD_REVERT)); + + vm._expectCheatcodeRevert( + bytes( + string.concat( + "Call revert data does not match: ", vm.toString(revertDataA), " != ", vm.toString(revertDataB) + ) + ) + ); + assertEqCall(targetA, callDataA, targetB, callDataB, STRICT_REVERT_DATA); + } + + function testFuzz_RevertWhenCalled_AssertEqCall_Fail( + bytes memory callDataA, + bytes memory callDataB, + bytes memory returnDataA, + bytes memory returnDataB, + bool strictRevertData + ) external { + address targetA = address(new TestMockCall(returnDataA, SHOULD_RETURN)); + address targetB = address(new TestMockCall(returnDataB, SHOULD_REVERT)); + + vm.expectRevert(bytes("assertion failed")); + this.assertEqCallExternal(targetA, callDataA, targetB, callDataB, strictRevertData); + + vm.expectRevert(bytes("assertion failed")); + this.assertEqCallExternal(targetB, callDataB, targetA, callDataA, strictRevertData); + } + + // Helper function to test outcome of assertEqCall via `expect` cheatcodes + function assertEqCallExternal( + address targetA, + bytes memory callDataA, + address targetB, + bytes memory callDataB, + bool strictRevertData + ) public { + assertEqCall(targetA, callDataA, targetB, callDataB, strictRevertData); + } +} + +contract TestMockCall { + bytes returnData; + bool shouldRevert; + + constructor(bytes memory returnData_, bool shouldRevert_) { + returnData = returnData_; + shouldRevert = shouldRevert_; + } + + fallback() external payable { + bytes memory returnData_ = returnData; + + if (shouldRevert) { + assembly { + revert(add(returnData_, 0x20), mload(returnData_)) + } + } else { + assembly { + return(add(returnData_, 0x20), mload(returnData_)) + } + } + } +} diff --git a/contracts/evm/lib/forge-std/test/StdChains.t.sol b/contracts/evm/lib/forge-std/test/StdChains.t.sol new file mode 100644 index 0000000000..bee1f9923a --- /dev/null +++ b/contracts/evm/lib/forge-std/test/StdChains.t.sol @@ -0,0 +1,227 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {Test} from "../src/Test.sol"; + +contract StdChainsMock is Test { + function exposedGetChain(string memory chainAlias) public returns (Chain memory) { + return getChain(chainAlias); + } + + function exposedGetChain(uint256 chainId) public returns (Chain memory) { + return getChain(chainId); + } + + function exposedSetChain(string memory chainAlias, ChainData memory chainData) public { + setChain(chainAlias, chainData); + } + + function exposedSetFallbackToDefaultRpcUrls(bool useDefault) public { + setFallbackToDefaultRpcUrls(useDefault); + } +} + +contract StdChainsTest is Test { + function test_ChainRpcInitialization() public { + // RPCs specified in `foundry.toml` should be updated. + assertEq(getChain(1).rpcUrl, "https://ethereum.reth.rs/rpc"); + assertEq(getChain("optimism_sepolia").rpcUrl, "https://sepolia.optimism.io/"); + assertEq(getChain("arbitrum_one_sepolia").rpcUrl, "https://sepolia-rollup.arbitrum.io/rpc/"); + + // Environment variables should be the next fallback + assertEq(getChain("arbitrum_nova").rpcUrl, "https://nova.arbitrum.io/rpc"); + vm.setEnv("ARBITRUM_NOVA_RPC_URL", "myoverride"); + assertEq(getChain("arbitrum_nova").rpcUrl, "myoverride"); + vm.setEnv("ARBITRUM_NOVA_RPC_URL", "https://nova.arbitrum.io/rpc"); + + // Cannot override RPCs defined in `foundry.toml` + vm.setEnv("MAINNET_RPC_URL", "myoverride2"); + assertEq(getChain("mainnet").rpcUrl, "https://ethereum.reth.rs/rpc"); + + // Other RPCs should remain unchanged. + assertEq(getChain(31337).rpcUrl, "http://127.0.0.1:8545"); + assertEq(getChain("sepolia").rpcUrl, "https://sepolia.infura.io/v3/b9794ad1ddf84dfb8c34d6bb5dca2001"); + } + + // Named with a leading underscore to clarify this is not intended to be run as a normal test, + // and is intended to be used in the below `test_Rpcs` test. + function _testRpc(string memory rpcAlias) internal { + string memory rpcUrl = getChain(rpcAlias).rpcUrl; + vm.createSelectFork(rpcUrl); + } + + // Ensure we can connect to the default RPC URL for each chain. + // Currently commented out since this is slow and public RPCs are flaky, often resulting in failing CI. + // function test_Rpcs() public { + // _testRpc("mainnet"); + // _testRpc("sepolia"); + // _testRpc("holesky"); + // _testRpc("optimism"); + // _testRpc("optimism_sepolia"); + // _testRpc("arbitrum_one"); + // _testRpc("arbitrum_one_sepolia"); + // _testRpc("arbitrum_nova"); + // _testRpc("polygon"); + // _testRpc("polygon_amoy"); + // _testRpc("avalanche"); + // _testRpc("avalanche_fuji"); + // _testRpc("bnb_smart_chain"); + // _testRpc("bnb_smart_chain_testnet"); + // _testRpc("gnosis_chain"); + // _testRpc("moonbeam"); + // _testRpc("moonriver"); + // _testRpc("moonbase"); + // _testRpc("base_sepolia"); + // _testRpc("base"); + // _testRpc("blast_sepolia"); + // _testRpc("blast"); + // _testRpc("fantom_opera"); + // _testRpc("fantom_opera_testnet"); + // _testRpc("fraxtal"); + // _testRpc("fraxtal_testnet"); + // _testRpc("berachain_bartio_testnet"); + // _testRpc("flare"); + // _testRpc("flare_coston2"); + // } + + function test_RevertIf_ChainNotFound() public { + // We deploy a mock to properly test the revert. + StdChainsMock stdChainsMock = new StdChainsMock(); + + vm.expectRevert("StdChains getChain(string): Chain with alias \"does_not_exist\" not found."); + stdChainsMock.exposedGetChain("does_not_exist"); + } + + function test_RevertIf_SetChain_ChainIdExist_FirstTest() public { + // We deploy a mock to properly test the revert. + StdChainsMock stdChainsMock = new StdChainsMock(); + + vm.expectRevert("StdChains setChain(string,ChainData): Chain ID 31337 already used by \"anvil\"."); + stdChainsMock.exposedSetChain("anvil2", ChainData("Anvil", 31337, "URL")); + } + + function test_RevertIf_ChainBubbleUp() public { + // We deploy a mock to properly test the revert. + StdChainsMock stdChainsMock = new StdChainsMock(); + + stdChainsMock.exposedSetChain("needs_undefined_env_var", ChainData("", 123456789, "")); + // Forge environment variable error. + vm.expectRevert(); + stdChainsMock.exposedGetChain("needs_undefined_env_var"); + } + + function test_RevertIf_SetChain_ChainIdExists_SecondTest() public { + // We deploy a mock to properly test the revert. + StdChainsMock stdChainsMock = new StdChainsMock(); + + stdChainsMock.exposedSetChain("custom_chain", ChainData("Custom Chain", 123456789, "https://custom.chain/")); + + vm.expectRevert('StdChains setChain(string,ChainData): Chain ID 123456789 already used by "custom_chain".'); + + stdChainsMock.exposedSetChain("another_custom_chain", ChainData("", 123456789, "")); + } + + function test_SetChain() public { + setChain("custom_chain", ChainData("Custom Chain", 123456789, "https://custom.chain/")); + Chain memory customChain = getChain("custom_chain"); + assertEq(customChain.name, "Custom Chain"); + assertEq(customChain.chainId, 123456789); + assertEq(customChain.chainAlias, "custom_chain"); + assertEq(customChain.rpcUrl, "https://custom.chain/"); + Chain memory chainById = getChain(123456789); + assertEq(chainById.name, customChain.name); + assertEq(chainById.chainId, customChain.chainId); + assertEq(chainById.chainAlias, customChain.chainAlias); + assertEq(chainById.rpcUrl, customChain.rpcUrl); + customChain.name = "Another Custom Chain"; + customChain.chainId = 987654321; + setChain("another_custom_chain", customChain); + Chain memory anotherCustomChain = getChain("another_custom_chain"); + assertEq(anotherCustomChain.name, "Another Custom Chain"); + assertEq(anotherCustomChain.chainId, 987654321); + assertEq(anotherCustomChain.chainAlias, "another_custom_chain"); + assertEq(anotherCustomChain.rpcUrl, "https://custom.chain/"); + // Verify the first chain data was not overwritten + chainById = getChain(123456789); + assertEq(chainById.name, "Custom Chain"); + assertEq(chainById.chainId, 123456789); + } + + function test_RevertIf_SetEmptyAlias() public { + // We deploy a mock to properly test the revert. + StdChainsMock stdChainsMock = new StdChainsMock(); + + vm.expectRevert("StdChains setChain(string,ChainData): Chain alias cannot be the empty string."); + stdChainsMock.exposedSetChain("", ChainData("", 123456789, "")); + } + + function test_RevertIf_SetNoChainId0() public { + // We deploy a mock to properly test the revert. + StdChainsMock stdChainsMock = new StdChainsMock(); + + vm.expectRevert("StdChains setChain(string,ChainData): Chain ID cannot be 0."); + stdChainsMock.exposedSetChain("alias", ChainData("", 0, "")); + } + + function test_RevertIf_GetNoChainId0() public { + // We deploy a mock to properly test the revert. + StdChainsMock stdChainsMock = new StdChainsMock(); + + vm.expectRevert("StdChains getChain(uint256): Chain ID cannot be 0."); + stdChainsMock.exposedGetChain(0); + } + + function test_RevertIf_GetNoEmptyAlias() public { + // We deploy a mock to properly test the revert. + StdChainsMock stdChainsMock = new StdChainsMock(); + + vm.expectRevert("StdChains getChain(string): Chain alias cannot be the empty string."); + stdChainsMock.exposedGetChain(""); + } + + function test_RevertIf_ChainNotInitialized() public { + // We deploy a mock to properly test the revert. + StdChainsMock stdChainsMock = new StdChainsMock(); + + vm.expectRevert("StdChains getChain(string): Chain with alias \"no_such_alias\" not found."); + stdChainsMock.exposedGetChain("no_such_alias"); + } + + function test_RevertIf_ChainAliasNotFound() public { + // We deploy a mock to properly test the revert. + StdChainsMock stdChainsMock = new StdChainsMock(); + + vm.expectRevert("StdChains getChain(uint256): Chain with ID 321 not found."); + + stdChainsMock.exposedGetChain(321); + } + + function test_SetChain_ExistingOne() public { + // We deploy a mock to properly test the revert. + StdChainsMock stdChainsMock = new StdChainsMock(); + + setChain("custom_chain", ChainData("Custom Chain", 123456789, "https://custom.chain/")); + assertEq(getChain(123456789).chainId, 123456789); + + setChain("custom_chain", ChainData("Modified Chain", 9999999999999999999, "https://modified.chain/")); + vm.expectRevert("StdChains getChain(uint256): Chain with ID 123456789 not found."); + stdChainsMock.exposedGetChain(123456789); + + Chain memory modifiedChain = getChain(9999999999999999999); + assertEq(modifiedChain.name, "Modified Chain"); + assertEq(modifiedChain.chainId, 9999999999999999999); + assertEq(modifiedChain.rpcUrl, "https://modified.chain/"); + } + + function test_RevertIf_DontUseDefaultRpcUrl() public { + // We deploy a mock to properly test the revert. + StdChainsMock stdChainsMock = new StdChainsMock(); + + // Should error if default RPCs flag is set to false. + stdChainsMock.exposedSetFallbackToDefaultRpcUrls(false); + vm.expectRevert(); + stdChainsMock.exposedGetChain(31337); + vm.expectRevert(); + stdChainsMock.exposedGetChain("sepolia"); + } +} diff --git a/contracts/evm/lib/forge-std/test/StdCheats.t.sol b/contracts/evm/lib/forge-std/test/StdCheats.t.sol new file mode 100644 index 0000000000..868829dd74 --- /dev/null +++ b/contracts/evm/lib/forge-std/test/StdCheats.t.sol @@ -0,0 +1,695 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {StdCheats} from "../src/StdCheats.sol"; +import {Test} from "../src/Test.sol"; +import {stdJson} from "../src/StdJson.sol"; +import {stdToml} from "../src/StdToml.sol"; +import {IERC20} from "../src/interfaces/IERC20.sol"; + +contract StdCheatsTest is Test { + Bar test; + + using stdJson for string; + + function setUp() public { + test = new Bar(); + } + + function test_Skip() public { + vm.warp(100); + skip(25); + assertEq(block.timestamp, 125); + } + + function test_Rewind() public { + vm.warp(100); + rewind(25); + assertEq(block.timestamp, 75); + } + + function test_Hoax() public { + hoax(address(1337)); + test.bar{value: 100}(address(1337)); + } + + function test_HoaxOrigin() public { + hoax(address(1337), address(1337)); + test.origin{value: 100}(address(1337)); + } + + function test_HoaxDifferentAddresses() public { + hoax(address(1337), address(7331)); + test.origin{value: 100}(address(1337), address(7331)); + } + + function test_StartHoax() public { + startHoax(address(1337)); + test.bar{value: 100}(address(1337)); + test.bar{value: 100}(address(1337)); + vm.stopPrank(); + test.bar(address(this)); + } + + function test_StartHoaxOrigin() public { + startHoax(address(1337), address(1337)); + test.origin{value: 100}(address(1337)); + test.origin{value: 100}(address(1337)); + vm.stopPrank(); + test.bar(address(this)); + } + + function test_ChangePrankMsgSender() public { + vm.startPrank(address(1337)); + test.bar(address(1337)); + changePrank(address(0xdead)); + test.bar(address(0xdead)); + changePrank(address(1337)); + test.bar(address(1337)); + vm.stopPrank(); + } + + function test_ChangePrankMsgSenderAndTxOrigin() public { + vm.startPrank(address(1337), address(1338)); + test.origin(address(1337), address(1338)); + changePrank(address(0xdead), address(0xbeef)); + test.origin(address(0xdead), address(0xbeef)); + changePrank(address(1337), address(1338)); + test.origin(address(1337), address(1338)); + vm.stopPrank(); + } + + function test_MakeAccountEquivalence() public { + Account memory account = makeAccount("1337"); + (address addr, uint256 key) = makeAddrAndKey("1337"); + assertEq(account.addr, addr); + assertEq(account.key, key); + } + + function test_MakeAddrEquivalence() public { + (address addr,) = makeAddrAndKey("1337"); + assertEq(makeAddr("1337"), addr); + } + + function test_MakeAddrSigning() public { + (address addr, uint256 key) = makeAddrAndKey("1337"); + bytes32 hash = keccak256("some_message"); + + (uint8 v, bytes32 r, bytes32 s) = vm.sign(key, hash); + assertEq(ecrecover(hash, v, r, s), addr); + } + + function test_Deal() public { + deal(address(this), 1 ether); + assertEq(address(this).balance, 1 ether); + } + + function test_DealToken() public { + Bar barToken = new Bar(); + address bar = address(barToken); + deal(bar, address(this), 10000e18); + assertEq(barToken.balanceOf(address(this)), 10000e18); + } + + function test_DealTokenAdjustTotalSupply() public { + Bar barToken = new Bar(); + address bar = address(barToken); + deal(bar, address(this), 10000e18, true); + assertEq(barToken.balanceOf(address(this)), 10000e18); + assertEq(barToken.totalSupply(), 20000e18); + deal(bar, address(this), 0, true); + assertEq(barToken.balanceOf(address(this)), 0); + assertEq(barToken.totalSupply(), 10000e18); + } + + function test_DealERC1155Token() public { + BarERC1155 barToken = new BarERC1155(); + address bar = address(barToken); + dealERC1155(bar, address(this), 0, 10000e18, false); + assertEq(barToken.balanceOf(address(this), 0), 10000e18); + } + + function test_DealERC1155TokenAdjustTotalSupply() public { + BarERC1155 barToken = new BarERC1155(); + address bar = address(barToken); + dealERC1155(bar, address(this), 0, 10000e18, true); + assertEq(barToken.balanceOf(address(this), 0), 10000e18); + assertEq(barToken.totalSupply(0), 20000e18); + dealERC1155(bar, address(this), 0, 0, true); + assertEq(barToken.balanceOf(address(this), 0), 0); + assertEq(barToken.totalSupply(0), 10000e18); + } + + function test_DealERC721Token() public { + BarERC721 barToken = new BarERC721(); + address bar = address(barToken); + dealERC721(bar, address(2), 1); + assertEq(barToken.balanceOf(address(2)), 1); + assertEq(barToken.balanceOf(address(1)), 0); + dealERC721(bar, address(1), 2); + assertEq(barToken.balanceOf(address(1)), 1); + assertEq(barToken.balanceOf(bar), 1); + } + + function test_DeployCode() public { + address deployed = deployCode("StdCheats.t.sol:Bar", bytes("")); + assertEq(string(getCode(deployed)), string(getCode(address(test)))); + } + + function test_DestroyAccount() public { + // deploy something to destroy it + BarERC721 barToken = new BarERC721(); + address bar = address(barToken); + vm.setNonce(bar, 10); + deal(bar, 100); + + uint256 prevThisBalance = address(this).balance; + uint256 size; + assembly { + size := extcodesize(bar) + } + + assertGt(size, 0); + assertEq(bar.balance, 100); + assertEq(vm.getNonce(bar), 10); + + destroyAccount(bar, address(this)); + assembly { + size := extcodesize(bar) + } + assertEq(address(this).balance, prevThisBalance + 100); + assertEq(vm.getNonce(bar), 0); + assertEq(size, 0); + assertEq(bar.balance, 0); + } + + function test_DeployCodeNoArgs() public { + address deployed = deployCode("StdCheats.t.sol:Bar"); + assertEq(string(getCode(deployed)), string(getCode(address(test)))); + } + + function test_DeployCodeVal() public { + address deployed = deployCode("StdCheats.t.sol:Bar", bytes(""), 1 ether); + assertEq(string(getCode(deployed)), string(getCode(address(test)))); + assertEq(deployed.balance, 1 ether); + } + + function test_DeployCodeValNoArgs() public { + address deployed = deployCode("StdCheats.t.sol:Bar", 1 ether); + assertEq(string(getCode(deployed)), string(getCode(address(test)))); + assertEq(deployed.balance, 1 ether); + } + + // We need this so we can call "this.deployCode" rather than "deployCode" directly + function deployCodeHelper(string memory what) external { + deployCode(what); + } + + function test_RevertIf_DeployCodeFail() public { + vm.expectRevert(bytes("StdCheats deployCode(string): Deployment failed.")); + this.deployCodeHelper("StdCheats.t.sol:RevertingContract"); + } + + function getCode(address who) internal view returns (bytes memory o_code) { + assembly ("memory-safe") { + // retrieve the size of the code, this needs assembly + let size := extcodesize(who) + // allocate output byte array - this could also be done without assembly + // by using o_code = new bytes(size) + o_code := mload(0x40) + // new "memory end" including padding + mstore(0x40, add(o_code, and(add(add(size, 0x20), 0x1f), not(0x1f)))) + // store length in memory + mstore(o_code, size) + // actually retrieve the code, this needs assembly + extcodecopy(who, add(o_code, 0x20), 0, size) + } + } + + function test_DeriveRememberKey() public { + string memory mnemonic = "test test test test test test test test test test test junk"; + + (address deployer, uint256 privateKey) = deriveRememberKey(mnemonic, 0); + assertEq(deployer, 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266); + assertEq(privateKey, 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80); + } + + function test_BytesToUint() public pure { + assertEq(3, bytesToUint_test(hex"03")); + assertEq(2, bytesToUint_test(hex"02")); + assertEq(255, bytesToUint_test(hex"ff")); + assertEq(29625, bytesToUint_test(hex"73b9")); + } + + function test_ParseJsonTxDetail() public view { + string memory root = vm.projectRoot(); + string memory path = string.concat(root, "/test/fixtures/broadcast.log.json"); + string memory json = vm.readFile(path); + bytes memory transactionDetails = json.parseRaw(".transactions[0].tx"); + RawTx1559Detail memory rawTxDetail = abi.decode(transactionDetails, (RawTx1559Detail)); + Tx1559Detail memory txDetail = rawToConvertedEIP1559Detail(rawTxDetail); + assertEq(txDetail.from, 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266); + assertEq(txDetail.to, 0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512); + assertEq( + txDetail.data, + hex"23e99187000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000013370000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000000000000000000000000000000000004" + ); + assertEq(txDetail.nonce, 3); + assertEq(txDetail.txType, 2); + assertEq(txDetail.gas, 29625); + assertEq(txDetail.value, 0); + } + + function test_ReadEIP1559Transaction() public view { + string memory root = vm.projectRoot(); + string memory path = string.concat(root, "/test/fixtures/broadcast.log.json"); + uint256 index = 0; + Tx1559 memory transaction = readTx1559(path, index); + transaction; + } + + function test_ReadEIP1559Transactions() public view { + string memory root = vm.projectRoot(); + string memory path = string.concat(root, "/test/fixtures/broadcast.log.json"); + Tx1559[] memory transactions = readTx1559s(path); + transactions; + } + + function test_ReadReceipt() public view { + string memory root = vm.projectRoot(); + string memory path = string.concat(root, "/test/fixtures/broadcast.log.json"); + uint256 index = 5; + Receipt memory receipt = readReceipt(path, index); + assertEq( + receipt.logsBloom, + hex"00000000000800000000000000000010000000000000000000000000000180000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100" + ); + } + + function test_ReadReceipts() public view { + string memory root = vm.projectRoot(); + string memory path = string.concat(root, "/test/fixtures/broadcast.log.json"); + Receipt[] memory receipts = readReceipts(path); + receipts; + } + + function test_GasMeteringModifier() public { + uint256 gas_start_normal = gasleft(); + addInLoop(); + uint256 gas_used_normal = gas_start_normal - gasleft(); + + uint256 gas_start_single = gasleft(); + addInLoopNoGas(); + uint256 gas_used_single = gas_start_single - gasleft(); + + uint256 gas_start_double = gasleft(); + addInLoopNoGasNoGas(); + uint256 gas_used_double = gas_start_double - gasleft(); + + assertTrue(gas_used_double + gas_used_single < gas_used_normal); + } + + function addInLoop() internal pure returns (uint256) { + uint256 b; + for (uint256 i; i < 10000; i++) { + b += i; + } + return b; + } + + function addInLoopNoGas() internal noGasMetering returns (uint256) { + return addInLoop(); + } + + function addInLoopNoGasNoGas() internal noGasMetering returns (uint256) { + return addInLoopNoGas(); + } + + function bytesToUint_test(bytes memory b) private pure returns (uint256) { + uint256 number; + for (uint256 i = 0; i < b.length; i++) { + number = number + uint256(uint8(b[i])) * (2 ** (8 * (b.length - (i + 1)))); + } + return number; + } + + function testFuzz_AssumeAddressIsNot(address addr) external { + // skip over Payable and NonPayable enums + for (uint8 i = 2; i < uint8(type(AddressType).max); i++) { + assumeAddressIsNot(addr, AddressType(i)); + } + assertTrue(addr != address(0)); + assertTrue(addr < address(1) || addr > address(9)); + assertTrue(addr != address(vm) || addr != 0x000000000000000000636F6e736F6c652e6c6f67); + } + + function test_AssumePayable() external { + // We deploy a mock version so we can properly test the revert. + StdCheatsMock stdCheatsMock = new StdCheatsMock(); + + // all should revert since these addresses are not payable + + // VM address + vm.expectRevert(); + stdCheatsMock.exposedAssumePayable(0x7109709ECfa91a80626fF3989D68f67F5b1DD12D); + + // Console address + vm.expectRevert(); + stdCheatsMock.exposedAssumePayable(0x000000000000000000636F6e736F6c652e6c6f67); + + // Create2Deployer + vm.expectRevert(); + stdCheatsMock.exposedAssumePayable(0x4e59b44847b379578588920cA78FbF26c0B4956C); + + // all should pass since these addresses are payable + + // vitalik.eth + stdCheatsMock.exposedAssumePayable(0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045); + + // mock payable contract + MockContractPayable cp = new MockContractPayable(); + stdCheatsMock.exposedAssumePayable(address(cp)); + } + + function test_AssumeNotPayable() external { + // We deploy a mock version so we can properly test the revert. + StdCheatsMock stdCheatsMock = new StdCheatsMock(); + + // all should pass since these addresses are not payable + + // VM address + stdCheatsMock.exposedAssumeNotPayable(0x7109709ECfa91a80626fF3989D68f67F5b1DD12D); + + // Console address + stdCheatsMock.exposedAssumeNotPayable(0x000000000000000000636F6e736F6c652e6c6f67); + + // Create2Deployer + stdCheatsMock.exposedAssumeNotPayable(0x4e59b44847b379578588920cA78FbF26c0B4956C); + + // all should revert since these addresses are payable + + // vitalik.eth + vm.expectRevert(); + stdCheatsMock.exposedAssumeNotPayable(0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045); + + // mock payable contract + MockContractPayable cp = new MockContractPayable(); + vm.expectRevert(); + stdCheatsMock.exposedAssumeNotPayable(address(cp)); + } + + function testFuzz_AssumeNotPrecompile(address addr) external { + assumeNotPrecompile(addr, getChain("optimism_sepolia").chainId); + assertTrue( + addr < address(1) || (addr > address(9) && addr < address(0x4200000000000000000000000000000000000000)) + || addr > address(0x4200000000000000000000000000000000000800) + ); + } + + function testFuzz_AssumeNotForgeAddress(address addr) external pure { + assumeNotForgeAddress(addr); + assertTrue( + addr != address(vm) && addr != 0x000000000000000000636F6e736F6c652e6c6f67 + && addr != 0x4e59b44847b379578588920cA78FbF26c0B4956C + ); + } + + function test_RevertIf_CannotDeployCodeTo() external { + vm.expectRevert("StdCheats deployCodeTo(string,bytes,uint256,address): Failed to create runtime bytecode."); + this._revertDeployCodeTo(); + } + + function _revertDeployCodeTo() external { + deployCodeTo("StdCheats.t.sol:RevertingContract", address(0)); + } + + function test_DeployCodeTo() external { + address arbitraryAddress = makeAddr("arbitraryAddress"); + + deployCodeTo( + "StdCheats.t.sol:MockContractWithConstructorArgs", + abi.encode(uint256(6), true, bytes20(arbitraryAddress)), + 1 ether, + arbitraryAddress + ); + + MockContractWithConstructorArgs ct = MockContractWithConstructorArgs(arbitraryAddress); + + assertEq(arbitraryAddress.balance, 1 ether); + assertEq(ct.x(), 6); + assertTrue(ct.y()); + assertEq(ct.z(), bytes20(arbitraryAddress)); + } + + function test_ExpectAndMockCall() public { + bytes memory data = abi.encodeWithSignature("balanceOf(address)", address(this)); + bytes memory returnData = abi.encode(uint256(100)); + expectAndMockCall(address(test), data, returnData); + + assertEq(test.balanceOf(address(this)), 100); + } + + function test_ExpectAndMockCall_Count() public { + bytes memory data = abi.encodeWithSignature("balanceOf(address)", address(this)); + bytes memory returnData = abi.encode(uint256(100)); + expectAndMockCall(address(test), data, 2, returnData); + + assertEq(test.balanceOf(address(this)), 100); + assertEq(test.balanceOf(address(this)), 100); + } + + function test_ExpectAndMockCall_MsgValue() public { + bytes memory data = abi.encodeWithSignature("payableBar()"); + bytes memory returnData = abi.encode(uint256(100)); + expectAndMockCall(address(test), 1 ether, data, returnData); + + assertEq(test.payableBar{value: 1 ether}(), 100); + } + + function test_ExpectAndMockCall_MsgValueAndCount() public { + bytes memory data = abi.encodeWithSignature("payableBar()"); + bytes memory returnData = abi.encode(uint256(100)); + expectAndMockCall(address(test), 1 ether, data, 2, returnData); + + assertEq(test.payableBar{value: 1 ether}(), 100); + assertEq(test.payableBar{value: 1 ether}(), 100); + } + + function test_ExpectAndMockCall_Gas() public { + bytes memory data = abi.encodeWithSignature("payableBar()"); + bytes memory returnData = abi.encode(uint256(100)); + uint64 gas = 30_000; + expectAndMockCall(address(test), 1 ether, gas, data, returnData); + + assertEq(test.payableBar{value: 1 ether, gas: gas}(), 100); + } + + function test_ExpectAndMockCall_GasAndCount() public { + bytes memory data = abi.encodeWithSignature("payableBar()"); + bytes memory returnData = abi.encode(uint256(100)); + uint64 gas = 30_000; + expectAndMockCall(address(test), 1 ether, gas, data, 2, returnData); + + assertEq(test.payableBar{value: 1 ether, gas: gas}(), 100); + assertEq(test.payableBar{value: 1 ether, gas: gas}(), 100); + } +} + +contract StdCheatsMock is StdCheats { + function exposedAssumePayable(address addr) external { + assumePayable(addr); + } + + function exposedAssumeNotPayable(address addr) external { + assumeNotPayable(addr); + } + + // We deploy a mock version so we can properly test expected reverts. + function exposedAssumeNotBlacklisted(address token, address addr) external view { + return assumeNotBlacklisted(token, addr); + } +} + +contract StdCheatsForkTest is Test { + address internal constant USDC_BLACKLISTED_USER = 0x1E34A77868E19A6647b1f2F47B51ed72dEDE95DD; + address internal constant USDT_BLACKLISTED_USER = 0x8f8a8F4B54a2aAC7799d7bc81368aC27b852822A; + + MockUSDT public USDT; + MockUSDC public USDC; + + function setUp() public { + USDT = new MockUSDT(); + USDC = new MockUSDC(); + + USDC.setBlacklisted(USDC_BLACKLISTED_USER, true); + USDT.setBlacklisted(USDT_BLACKLISTED_USER, true); + } + + function test_RevertIf_CannotAssumeNoBlacklisted_EOA() external { + // We deploy a mock version so we can properly test the revert. + StdCheatsMock stdCheatsMock = new StdCheatsMock(); + address eoa = vm.addr({privateKey: 1}); + vm.expectRevert("StdCheats assumeNotBlacklisted(address,address): Token address is not a contract."); + stdCheatsMock.exposedAssumeNotBlacklisted(eoa, address(0)); + } + + function testFuzz_AssumeNotBlacklisted_TokenWithoutBlacklist(address addr) external view { + assumeNotBlacklisted(address(USDC), addr); + assumeNotBlacklisted(address(USDT), addr); + assertTrue(true); + } + + function test_RevertIf_AssumeNoBlacklisted_USDC() external { + // We deploy a mock version so we can properly test the revert. + StdCheatsMock stdCheatsMock = new StdCheatsMock(); + vm.expectRevert(); + stdCheatsMock.exposedAssumeNotBlacklisted(address(USDC), USDC_BLACKLISTED_USER); + } + + function testFuzz_AssumeNotBlacklisted_USDC(address addr) external view { + assumeNotBlacklisted(address(USDC), addr); + assertFalse(USDCLike(USDC).isBlacklisted(addr)); + } + + function test_RevertIf_AssumeNoBlacklisted_USDT() external { + // We deploy a mock version so we can properly test the revert. + StdCheatsMock stdCheatsMock = new StdCheatsMock(); + vm.expectRevert(); + stdCheatsMock.exposedAssumeNotBlacklisted(address(USDT), USDT_BLACKLISTED_USER); + } + + function testFuzz_AssumeNotBlacklisted_USDT(address addr) external view { + assumeNotBlacklisted(address(USDT), addr); + assertFalse(USDTLike(USDT).isBlackListed(addr)); + } +} + +/// @dev https://etherscan.io/token/0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48#readProxyContract +interface USDCLike { + function isBlacklisted(address) external view returns (bool); +} + +/// @dev https://etherscan.io/token/0xdac17f958d2ee523a2206206994597c13d831ec7#readContract +interface USDTLike { + function isBlackListed(address) external view returns (bool); +} + +contract MockUSDT is USDTLike { + mapping(address => bool) private blacklist; + + function isBlackListed(address addr) external view returns (bool) { + return blacklist[addr]; + } + + function setBlacklisted(address addr, bool value) external { + blacklist[addr] = value; + } +} + +contract MockUSDC is USDCLike { + mapping(address => bool) private blacklist; + + function isBlacklisted(address addr) external view returns (bool) { + return blacklist[addr]; + } + + function setBlacklisted(address addr, bool value) external { + blacklist[addr] = value; + } +} + +contract Bar { + constructor() payable { + /// `DEAL` STDCHEAT + totalSupply = 10000e18; + balanceOf[address(this)] = totalSupply; + } + + /// `HOAX` and `CHANGEPRANK` STDCHEATS + function bar(address expectedSender) public payable { + require(msg.sender == expectedSender, "!prank"); + } + + function origin(address expectedSender) public payable { + require(msg.sender == expectedSender, "!prank"); + require(tx.origin == expectedSender, "!prank"); + } + + function origin(address expectedSender, address expectedOrigin) public payable { + require(msg.sender == expectedSender, "!prank"); + require(tx.origin == expectedOrigin, "!prank"); + } + + function payableBar() public payable returns (uint256) { + return 0; + } + + /// `DEAL` STDCHEAT + mapping(address => uint256) public balanceOf; + uint256 public totalSupply; +} + +contract BarERC1155 { + constructor() payable { + /// `DEALERC1155` STDCHEAT + _totalSupply[0] = 10000e18; + _balances[0][address(this)] = _totalSupply[0]; + } + + function balanceOf(address account, uint256 id) public view virtual returns (uint256) { + return _balances[id][account]; + } + + function totalSupply(uint256 id) public view virtual returns (uint256) { + return _totalSupply[id]; + } + + /// `DEALERC1155` STDCHEAT + mapping(uint256 => mapping(address => uint256)) private _balances; + mapping(uint256 => uint256) private _totalSupply; +} + +contract BarERC721 { + constructor() payable { + /// `DEALERC721` STDCHEAT + _owners[1] = address(1); + _balances[address(1)] = 1; + _owners[2] = address(this); + _owners[3] = address(this); + _balances[address(this)] = 2; + } + + function balanceOf(address owner) public view virtual returns (uint256) { + return _balances[owner]; + } + + function ownerOf(uint256 tokenId) public view virtual returns (address) { + address owner = _owners[tokenId]; + return owner; + } + + mapping(uint256 => address) private _owners; + mapping(address => uint256) private _balances; +} + +contract RevertingContract { + constructor() { + revert(); + } +} + +contract MockContractWithConstructorArgs { + uint256 public immutable x; + bool public y; + bytes20 public z; + + constructor(uint256 _x, bool _y, bytes20 _z) payable { + x = _x; + y = _y; + z = _z; + } +} + +contract MockContractPayable { + receive() external payable {} +} diff --git a/contracts/evm/lib/forge-std/test/StdConstants.t.sol b/contracts/evm/lib/forge-std/test/StdConstants.t.sol new file mode 100644 index 0000000000..8ed524ecde --- /dev/null +++ b/contracts/evm/lib/forge-std/test/StdConstants.t.sol @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {StdConstants} from "../src/StdConstants.sol"; +import {Test} from "../src/Test.sol"; + +contract StdConstantsTest is Test { + function testVm() public view { + assertEq(StdConstants.VM.getBlockNumber(), 1); + } + + function testVmDerivation() public pure { + assertEq(address(StdConstants.VM), address(uint160(uint256(keccak256("hevm cheat code"))))); + } + + function testConsoleDerivation() public pure { + assertEq(StdConstants.CONSOLE, address(uint160(uint88(bytes11("console.log"))))); + } + + function testDefaultSender() public view { + assertEq(StdConstants.DEFAULT_SENDER, msg.sender); + } + + function testDefaultSenderDerivation() public pure { + assertEq(StdConstants.DEFAULT_SENDER, address(uint160(uint256(keccak256("foundry default caller"))))); + } + + function testDefaultTestContract() public { + assertEq(StdConstants.DEFAULT_TEST_CONTRACT, address(new Dummy())); + } + + function testDefaultTestContractDerivation() public view { + assertEq(address(this), StdConstants.VM.computeCreateAddress(StdConstants.DEFAULT_SENDER, 1)); + assertEq(StdConstants.DEFAULT_TEST_CONTRACT, StdConstants.VM.computeCreateAddress(address(this), 1)); + } +} + +contract Dummy {} diff --git a/contracts/evm/lib/forge-std/test/StdError.t.sol b/contracts/evm/lib/forge-std/test/StdError.t.sol new file mode 100644 index 0000000000..7553ce4acc --- /dev/null +++ b/contracts/evm/lib/forge-std/test/StdError.t.sol @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {stdError} from "../src/StdError.sol"; +import {Test} from "../src/Test.sol"; + +contract StdErrorsTest is Test { + ErrorsTest test; + + function setUp() public { + test = new ErrorsTest(); + } + + function test_RevertIf_AssertionError() public { + vm.expectRevert(stdError.assertionError); + test.assertionError(); + } + + function test_RevertIf_ArithmeticError() public { + vm.expectRevert(stdError.arithmeticError); + test.arithmeticError(10); + } + + function test_RevertIf_DivisionError() public { + vm.expectRevert(stdError.divisionError); + test.divError(0); + } + + function test_RevertIf_ModError() public { + vm.expectRevert(stdError.divisionError); + test.modError(0); + } + + function test_RevertIf_EnumConversionError() public { + vm.expectRevert(stdError.enumConversionError); + test.enumConversion(1); + } + + function test_RevertIf_EncodeStgError() public { + vm.expectRevert(stdError.encodeStorageError); + test.encodeStgError(); + } + + function test_RevertIf_PopError() public { + vm.expectRevert(stdError.popError); + test.pop(); + } + + function test_RevertIf_IndexOOBError() public { + vm.expectRevert(stdError.indexOOBError); + test.indexOOBError(1); + } + + function test_RevertIf_MemOverflowError() public { + vm.expectRevert(stdError.memOverflowError); + test.mem(); + } + + function test_RevertIf_InternError() public { + vm.expectRevert(stdError.zeroVarError); + test.intern(); + } +} + +contract ErrorsTest { + enum T { + T1 + } + + uint256[] public someArr; + bytes someBytes; + + function assertionError() public pure { + assert(false); + } + + function arithmeticError(uint256 a) public pure { + a -= 100; + } + + function divError(uint256 a) public pure { + 100 / a; + } + + function modError(uint256 a) public pure { + 100 % a; + } + + function enumConversion(uint256 a) public pure { + T(a); + } + + function encodeStgError() public { + assembly ("memory-safe") { + sstore(someBytes.slot, 1) + } + keccak256(someBytes); + } + + function pop() public { + someArr.pop(); + } + + function indexOOBError(uint256 a) public pure { + uint256[] memory t = new uint256[](0); + t[a]; + } + + function mem() public pure { + uint256 l = 2 ** 256 / 32; + new uint256[](l); + } + + function intern() public returns (uint256) { + function(uint256) internal returns (uint256) x; + x(2); + return 7; + } +} diff --git a/contracts/evm/lib/forge-std/test/StdJson.t.sol b/contracts/evm/lib/forge-std/test/StdJson.t.sol new file mode 100644 index 0000000000..5594a54a8a --- /dev/null +++ b/contracts/evm/lib/forge-std/test/StdJson.t.sol @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {Test, stdJson} from "../src/Test.sol"; + +contract StdJsonTest is Test { + using stdJson for string; + + string root; + string path; + + function setUp() public { + root = vm.projectRoot(); + path = string.concat(root, "/test/fixtures/test.json"); + } + + struct SimpleJson { + uint256 a; + string b; + } + + struct NestedJson { + uint256 a; + string b; + SimpleJson c; + } + + function test_readJson() public view { + string memory json = vm.readFile(path); + assertEq(json.readUint(".a"), 123); + } + + function test_writeJson() public { + string memory json = "json"; + json.serialize("a", uint256(123)); + string memory semiFinal = json.serialize("b", string("test")); + string memory finalJson = json.serialize("c", semiFinal); + finalJson.write(path); + + string memory json_ = vm.readFile(path); + bytes memory data = json_.parseRaw("$"); + NestedJson memory decodedData = abi.decode(data, (NestedJson)); + + assertEq(decodedData.a, 123); + assertEq(decodedData.b, "test"); + assertEq(decodedData.c.a, 123); + assertEq(decodedData.c.b, "test"); + } +} diff --git a/contracts/evm/lib/forge-std/test/StdMath.t.sol b/contracts/evm/lib/forge-std/test/StdMath.t.sol new file mode 100644 index 0000000000..c7a36ed4dc --- /dev/null +++ b/contracts/evm/lib/forge-std/test/StdMath.t.sol @@ -0,0 +1,202 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {stdMath} from "../src/StdMath.sol"; +import {Test, stdError} from "../src/Test.sol"; + +contract StdMathMock is Test { + function exposedPercentDelta(uint256 a, uint256 b) public pure returns (uint256) { + return stdMath.percentDelta(a, b); + } + + function exposedPercentDelta(int256 a, int256 b) public pure returns (uint256) { + return stdMath.percentDelta(a, b); + } +} + +contract StdMathTest is Test { + function test_GetAbs() external pure { + assertEq(stdMath.abs(-50), 50); + assertEq(stdMath.abs(50), 50); + assertEq(stdMath.abs(-1337), 1337); + assertEq(stdMath.abs(0), 0); + + assertEq(stdMath.abs(type(int256).min), (type(uint256).max >> 1) + 1); + assertEq(stdMath.abs(type(int256).max), (type(uint256).max >> 1)); + } + + function testFuzz_GetAbs(int256 a) external pure { + uint256 manualAbs = getAbs(a); + + uint256 abs = stdMath.abs(a); + + assertEq(abs, manualAbs); + } + + function test_GetDelta_Uint() external pure { + assertEq(stdMath.delta(uint256(0), uint256(0)), 0); + assertEq(stdMath.delta(uint256(0), uint256(1337)), 1337); + assertEq(stdMath.delta(uint256(0), type(uint64).max), type(uint64).max); + assertEq(stdMath.delta(uint256(0), type(uint128).max), type(uint128).max); + assertEq(stdMath.delta(uint256(0), type(uint256).max), type(uint256).max); + + assertEq(stdMath.delta(0, uint256(0)), 0); + assertEq(stdMath.delta(1337, uint256(0)), 1337); + assertEq(stdMath.delta(type(uint64).max, uint256(0)), type(uint64).max); + assertEq(stdMath.delta(type(uint128).max, uint256(0)), type(uint128).max); + assertEq(stdMath.delta(type(uint256).max, uint256(0)), type(uint256).max); + + assertEq(stdMath.delta(1337, uint256(1337)), 0); + assertEq(stdMath.delta(type(uint256).max, type(uint256).max), 0); + assertEq(stdMath.delta(5000, uint256(1250)), 3750); + } + + function testFuzz_GetDelta_Uint(uint256 a, uint256 b) external pure { + uint256 manualDelta = a > b ? a - b : b - a; + + uint256 delta = stdMath.delta(a, b); + + assertEq(delta, manualDelta); + } + + function test_GetDelta_Int() external pure { + assertEq(stdMath.delta(int256(0), int256(0)), 0); + assertEq(stdMath.delta(int256(0), int256(1337)), 1337); + assertEq(stdMath.delta(int256(0), type(int64).max), type(uint64).max >> 1); + assertEq(stdMath.delta(int256(0), type(int128).max), type(uint128).max >> 1); + assertEq(stdMath.delta(int256(0), type(int256).max), type(uint256).max >> 1); + + assertEq(stdMath.delta(0, int256(0)), 0); + assertEq(stdMath.delta(1337, int256(0)), 1337); + assertEq(stdMath.delta(type(int64).max, int256(0)), type(uint64).max >> 1); + assertEq(stdMath.delta(type(int128).max, int256(0)), type(uint128).max >> 1); + assertEq(stdMath.delta(type(int256).max, int256(0)), type(uint256).max >> 1); + + assertEq(stdMath.delta(-0, int256(0)), 0); + assertEq(stdMath.delta(-1337, int256(0)), 1337); + assertEq(stdMath.delta(type(int64).min, int256(0)), (type(uint64).max >> 1) + 1); + assertEq(stdMath.delta(type(int128).min, int256(0)), (type(uint128).max >> 1) + 1); + assertEq(stdMath.delta(type(int256).min, int256(0)), (type(uint256).max >> 1) + 1); + + assertEq(stdMath.delta(int256(0), -0), 0); + assertEq(stdMath.delta(int256(0), -1337), 1337); + assertEq(stdMath.delta(int256(0), type(int64).min), (type(uint64).max >> 1) + 1); + assertEq(stdMath.delta(int256(0), type(int128).min), (type(uint128).max >> 1) + 1); + assertEq(stdMath.delta(int256(0), type(int256).min), (type(uint256).max >> 1) + 1); + + assertEq(stdMath.delta(1337, int256(1337)), 0); + assertEq(stdMath.delta(type(int256).max, type(int256).max), 0); + assertEq(stdMath.delta(type(int256).min, type(int256).min), 0); + assertEq(stdMath.delta(type(int256).min, type(int256).max), type(uint256).max); + assertEq(stdMath.delta(5000, int256(1250)), 3750); + } + + function testFuzz_GetDelta_Int(int256 a, int256 b) external pure { + uint256 absA = getAbs(a); + uint256 absB = getAbs(b); + uint256 absDelta = absA > absB ? absA - absB : absB - absA; + + uint256 manualDelta; + if ((a >= 0 && b >= 0) || (a < 0 && b < 0)) { + manualDelta = absDelta; + } + // (a < 0 && b >= 0) || (a >= 0 && b < 0) + else { + manualDelta = absA + absB; + } + + uint256 delta = stdMath.delta(a, b); + + assertEq(delta, manualDelta); + } + + function test_GetPercentDelta_Uint() external { + StdMathMock stdMathMock = new StdMathMock(); + + assertEq(stdMath.percentDelta(uint256(0), uint256(1337)), 1e18); + assertEq(stdMath.percentDelta(uint256(0), type(uint64).max), 1e18); + assertEq(stdMath.percentDelta(uint256(0), type(uint128).max), 1e18); + assertEq(stdMath.percentDelta(uint256(0), type(uint192).max), 1e18); + + assertEq(stdMath.percentDelta(1337, uint256(1337)), 0); + assertEq(stdMath.percentDelta(type(uint192).max, type(uint192).max), 0); + assertEq(stdMath.percentDelta(0, uint256(2500)), 1e18); + assertEq(stdMath.percentDelta(2500, uint256(2500)), 0); + assertEq(stdMath.percentDelta(5000, uint256(2500)), 1e18); + assertEq(stdMath.percentDelta(7500, uint256(2500)), 2e18); + + vm.expectRevert("stdMath percentDelta(uint256,uint256): Divisor is zero"); + stdMathMock.exposedPercentDelta(uint256(1), 0); + } + + function testFuzz_GetPercentDelta_Uint(uint192 a, uint192 b) external pure { + vm.assume(b != 0); + uint256 manualDelta = a > b ? a - b : b - a; + + uint256 manualPercentDelta = manualDelta * 1e18 / b; + uint256 percentDelta = stdMath.percentDelta(a, b); + + assertEq(percentDelta, manualPercentDelta); + } + + function test_GetPercentDelta_Int() external { + // We deploy a mock version so we can properly test the revert. + StdMathMock stdMathMock = new StdMathMock(); + + assertEq(stdMath.percentDelta(int256(0), int256(1337)), 1e18); + assertEq(stdMath.percentDelta(int256(0), -1337), 1e18); + assertEq(stdMath.percentDelta(int256(0), type(int64).min), 1e18); + assertEq(stdMath.percentDelta(int256(0), type(int128).min), 1e18); + assertEq(stdMath.percentDelta(int256(0), type(int192).min), 1e18); + assertEq(stdMath.percentDelta(int256(0), type(int64).max), 1e18); + assertEq(stdMath.percentDelta(int256(0), type(int128).max), 1e18); + assertEq(stdMath.percentDelta(int256(0), type(int192).max), 1e18); + + assertEq(stdMath.percentDelta(1337, int256(1337)), 0); + assertEq(stdMath.percentDelta(type(int192).max, type(int192).max), 0); + assertEq(stdMath.percentDelta(type(int192).min, type(int192).min), 0); + + assertEq(stdMath.percentDelta(type(int192).min, type(int192).max), 2e18); // rounds the 1 wei diff down + assertEq(stdMath.percentDelta(type(int192).max, type(int192).min), 2e18 - 1); // rounds the 1 wei diff down + assertEq(stdMath.percentDelta(0, int256(2500)), 1e18); + assertEq(stdMath.percentDelta(2500, int256(2500)), 0); + assertEq(stdMath.percentDelta(5000, int256(2500)), 1e18); + assertEq(stdMath.percentDelta(7500, int256(2500)), 2e18); + + vm.expectRevert("stdMath percentDelta(int256,int256): Divisor is zero"); + stdMathMock.exposedPercentDelta(int256(1), 0); + } + + function testFuzz_GetPercentDelta_Int(int192 a, int192 b) external pure { + vm.assume(b != 0); + uint256 absA = getAbs(a); + uint256 absB = getAbs(b); + uint256 absDelta = absA > absB ? absA - absB : absB - absA; + + uint256 manualDelta; + if ((a >= 0 && b >= 0) || (a < 0 && b < 0)) { + manualDelta = absDelta; + } + // (a < 0 && b >= 0) || (a >= 0 && b < 0) + else { + manualDelta = absA + absB; + } + + uint256 manualPercentDelta = manualDelta * 1e18 / absB; + uint256 percentDelta = stdMath.percentDelta(a, b); + + assertEq(percentDelta, manualPercentDelta); + } + + /*////////////////////////////////////////////////////////////////////////// + HELPERS + //////////////////////////////////////////////////////////////////////////*/ + + function getAbs(int256 a) private pure returns (uint256) { + if (a < 0) { + return a == type(int256).min ? uint256(type(int256).max) + 1 : uint256(-a); + } + + return uint256(a); + } +} diff --git a/contracts/evm/lib/forge-std/test/StdStorage.t.sol b/contracts/evm/lib/forge-std/test/StdStorage.t.sol new file mode 100644 index 0000000000..34782ac1c4 --- /dev/null +++ b/contracts/evm/lib/forge-std/test/StdStorage.t.sol @@ -0,0 +1,589 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {stdStorage, StdStorage} from "../src/StdStorage.sol"; +import {Test} from "../src/Test.sol"; + +contract StdStorageTest is Test { + using stdStorage for StdStorage; + + StorageTest internal test; + + function setUp() public { + test = new StorageTest(); + } + + function test_StorageHidden() public { + assertEq(uint256(keccak256("my.random.var")), stdstore.target(address(test)).sig("hidden()").find()); + } + + function test_StorageObvious() public { + assertEq(uint256(0), stdstore.target(address(test)).sig("exists()").find()); + } + + function test_StorageExtraSload() public { + assertEq(16, stdstore.target(address(test)).sig(test.extra_sload.selector).find()); + } + + function test_StorageCheckedWriteHidden() public { + stdstore.target(address(test)).sig(test.hidden.selector).checked_write(100); + assertEq(uint256(test.hidden()), 100); + } + + function test_StorageCheckedWriteObvious() public { + stdstore.target(address(test)).sig(test.exists.selector).checked_write(100); + assertEq(test.exists(), 100); + } + + function test_StorageCheckedWriteSignedIntegerHidden() public { + stdstore.target(address(test)).sig(test.hidden.selector).checked_write_int(-100); + assertEq(int256(uint256(test.hidden())), -100); + } + + function test_StorageCheckedWriteSignedIntegerObvious() public { + stdstore.target(address(test)).sig(test.tG.selector).checked_write_int(-100); + assertEq(test.tG(), -100); + } + + function test_StorageMapStructA() public { + uint256 slot = + stdstore.target(address(test)).sig(test.map_struct.selector).with_key(address(this)).depth(0).find(); + assertEq(uint256(keccak256(abi.encode(address(this), 4))), slot); + } + + function test_StorageMapStructB() public { + uint256 slot = + stdstore.target(address(test)).sig(test.map_struct.selector).with_key(address(this)).depth(1).find(); + assertEq(uint256(keccak256(abi.encode(address(this), 4))) + 1, slot); + } + + function test_StorageDeepMap() public { + uint256 slot = stdstore.target(address(test)).sig(test.deep_map.selector).with_key(address(this)) + .with_key(address(this)).find(); + assertEq(uint256(keccak256(abi.encode(address(this), keccak256(abi.encode(address(this), uint256(5)))))), slot); + } + + function test_StorageCheckedWriteDeepMap() public { + stdstore.target(address(test)).sig(test.deep_map.selector).with_key(address(this)).with_key(address(this)) + .checked_write(100); + assertEq(100, test.deep_map(address(this), address(this))); + } + + function test_StorageDeepMapStructA() public { + uint256 slot = stdstore.target(address(test)).sig(test.deep_map_struct.selector).with_key(address(this)) + .with_key(address(this)).depth(0).find(); + assertEq( + bytes32( + uint256(keccak256(abi.encode(address(this), keccak256(abi.encode(address(this), uint256(6)))))) + 0 + ), + bytes32(slot) + ); + } + + function test_StorageDeepMapStructB() public { + uint256 slot = stdstore.target(address(test)).sig(test.deep_map_struct.selector).with_key(address(this)) + .with_key(address(this)).depth(1).find(); + assertEq( + bytes32( + uint256(keccak256(abi.encode(address(this), keccak256(abi.encode(address(this), uint256(6)))))) + 1 + ), + bytes32(slot) + ); + } + + function test_StorageCheckedWriteDeepMapStructA() public { + stdstore.target(address(test)).sig(test.deep_map_struct.selector).with_key(address(this)) + .with_key(address(this)).depth(0).checked_write(100); + (uint256 a, uint256 b) = test.deep_map_struct(address(this), address(this)); + assertEq(100, a); + assertEq(0, b); + } + + function test_StorageCheckedWriteDeepMapStructB() public { + stdstore.target(address(test)).sig(test.deep_map_struct.selector).with_key(address(this)) + .with_key(address(this)).depth(1).checked_write(100); + (uint256 a, uint256 b) = test.deep_map_struct(address(this), address(this)); + assertEq(0, a); + assertEq(100, b); + } + + function test_StorageCheckedWriteMapStructA() public { + stdstore.target(address(test)).sig(test.map_struct.selector).with_key(address(this)).depth(0).checked_write(100); + (uint256 a, uint256 b) = test.map_struct(address(this)); + assertEq(a, 100); + assertEq(b, 0); + } + + function test_StorageCheckedWriteMapStructB() public { + stdstore.target(address(test)).sig(test.map_struct.selector).with_key(address(this)).depth(1).checked_write(100); + (uint256 a, uint256 b) = test.map_struct(address(this)); + assertEq(a, 0); + assertEq(b, 100); + } + + function test_StorageStructA() public { + uint256 slot = stdstore.target(address(test)).sig(test.basic.selector).depth(0).find(); + assertEq(uint256(7), slot); + } + + function test_StorageStructB() public { + uint256 slot = stdstore.target(address(test)).sig(test.basic.selector).depth(1).find(); + assertEq(uint256(7) + 1, slot); + } + + function test_StorageCheckedWriteStructA() public { + stdstore.target(address(test)).sig(test.basic.selector).depth(0).checked_write(100); + (uint256 a, uint256 b) = test.basic(); + assertEq(a, 100); + assertEq(b, 1337); + } + + function test_StorageCheckedWriteStructB() public { + stdstore.target(address(test)).sig(test.basic.selector).depth(1).checked_write(100); + (uint256 a, uint256 b) = test.basic(); + assertEq(a, 1337); + assertEq(b, 100); + } + + function test_StorageMapAddrFound() public { + uint256 slot = stdstore.target(address(test)).sig(test.map_addr.selector).with_key(address(this)).find(); + assertEq(uint256(keccak256(abi.encode(address(this), uint256(1)))), slot); + } + + function test_StorageMapAddrRoot() public { + (uint256 slot, bytes32 key) = + stdstore.target(address(test)).sig(test.map_addr.selector).with_key(address(this)).parent(); + assertEq(address(uint160(uint256(key))), address(this)); + assertEq(uint256(1), slot); + slot = stdstore.target(address(test)).sig(test.map_addr.selector).with_key(address(this)).root(); + assertEq(uint256(1), slot); + } + + function test_StorageMapUintFound() public { + uint256 slot = stdstore.target(address(test)).sig(test.map_uint.selector).with_key(100).find(); + assertEq(uint256(keccak256(abi.encode(100, uint256(2)))), slot); + } + + function test_StorageCheckedWriteMapUint() public { + stdstore.target(address(test)).sig(test.map_uint.selector).with_key(100).checked_write(100); + assertEq(100, test.map_uint(100)); + } + + function test_StorageCheckedWriteMapAddr() public { + stdstore.target(address(test)).sig(test.map_addr.selector).with_key(address(this)).checked_write(100); + assertEq(100, test.map_addr(address(this))); + } + + function test_StorageCheckedWriteMapBool() public { + stdstore.target(address(test)).sig(test.map_bool.selector).with_key(address(this)).checked_write(true); + assertTrue(test.map_bool(address(this))); + } + + function testFuzz_StorageCheckedWriteMapPacked(address addr, uint128 value) public { + stdstore.enable_packed_slots().target(address(test)).sig(test.read_struct_lower.selector).with_key(addr) + .checked_write(value); + assertEq(test.read_struct_lower(addr), value); + + stdstore.enable_packed_slots().target(address(test)).sig(test.read_struct_upper.selector).with_key(addr) + .checked_write(value); + assertEq(test.read_struct_upper(addr), value); + } + + function test_StorageCheckedWriteMapPackedFullSuccess() public { + uint256 full = test.map_packed(address(1337)); + // keep upper 128, set lower 128 to 1337 + full = (full & (uint256((1 << 128) - 1) << 128)) | 1337; + stdstore.target(address(test)).sig(test.map_packed.selector).with_key(address(uint160(1337))) + .checked_write(full); + assertEq(1337, test.read_struct_lower(address(1337))); + } + + function test_RevertStorageConst() public { + StorageTestTarget target = new StorageTestTarget(test); + + vm.expectRevert("stdStorage find(StdStorage): No storage use detected for target."); + target.expectRevertStorageConst(); + } + + function testFuzz_StorageNativePack(uint248 val1, uint248 val2, bool boolVal1, bool boolVal2) public { + stdstore.enable_packed_slots().target(address(test)).sig(test.tA.selector).checked_write(val1); + stdstore.enable_packed_slots().target(address(test)).sig(test.tB.selector).checked_write(boolVal1); + stdstore.enable_packed_slots().target(address(test)).sig(test.tC.selector).checked_write(boolVal2); + stdstore.enable_packed_slots().target(address(test)).sig(test.tD.selector).checked_write(val2); + + assertEq(test.tA(), val1); + assertEq(test.tB(), boolVal1); + assertEq(test.tC(), boolVal2); + assertEq(test.tD(), val2); + } + + function test_StorageReadBytes32() public { + bytes32 val = stdstore.target(address(test)).sig(test.tE.selector).read_bytes32(); + assertEq(val, hex"1337"); + } + + function test_StorageReadBool_False() public { + bool val = stdstore.target(address(test)).sig(test.tB.selector).read_bool(); + assertEq(val, false); + } + + function test_StorageReadBool_True() public { + bool val = stdstore.target(address(test)).sig(test.tH.selector).read_bool(); + assertEq(val, true); + } + + function test_RevertIf_ReadingNonBoolValue() public { + vm.expectRevert("stdStorage read_bool(StdStorage): Cannot decode. Make sure you are reading a bool."); + this.readNonBoolValue(); + } + + function readNonBoolValue() public { + stdstore.target(address(test)).sig(test.tE.selector).read_bool(); + } + + function test_StorageReadAddress() public { + address val = stdstore.target(address(test)).sig(test.tF.selector).read_address(); + assertEq(val, address(1337)); + } + + function test_StorageReadUint() public { + uint256 val = stdstore.target(address(test)).sig(test.exists.selector).read_uint(); + assertEq(val, 1); + } + + function test_StorageReadInt() public { + int256 val = stdstore.target(address(test)).sig(test.tG.selector).read_int(); + assertEq(val, type(int256).min); + } + + function testFuzz_Packed(uint256 val, uint8 elemToGet) public { + // This function tries an assortment of packed slots, shifts meaning number of elements + // that are packed. Shiftsizes are the size of each element, i.e. 8 means a data type that is 8 bits, 16 == 16 bits, etc. + // Combined, these determine how a slot is packed. Making it random is too hard to avoid global rejection limit + // and make it performant. + + // change the number of shifts + for (uint256 i = 1; i < 5; i++) { + uint256 shifts = i; + + elemToGet = uint8(bound(elemToGet, 0, shifts - 1)); + + uint256[] memory shiftSizes = new uint256[](shifts); + for (uint256 j; j < shifts; j++) { + shiftSizes[j] = 8 * (j + 1); + } + + test.setRandomPacking(val); + + uint256 leftBits; + uint256 rightBits; + for (uint256 j; j < shiftSizes.length; j++) { + if (j < elemToGet) { + leftBits += shiftSizes[j]; + } else if (elemToGet != j) { + rightBits += shiftSizes[j]; + } + } + + // we may have some right bits unaccounted for + leftBits += 256 - (leftBits + shiftSizes[elemToGet] + rightBits); + // clear left bits, then clear right bits and realign + uint256 expectedValToRead = (val << leftBits) >> (leftBits + rightBits); + + uint256 readVal = stdstore.target(address(test)).enable_packed_slots() + .sig("getRandomPacked(uint8,uint8[],uint8)").with_calldata(abi.encode(shifts, shiftSizes, elemToGet)) + .read_uint(); + + assertEq(readVal, expectedValToRead); + } + } + + function testFuzz_Packed2(uint256 nvars, uint256 seed) public { + // Number of random variables to generate. + nvars = bound(nvars, 1, 20); + + // This will decrease as we generate values in the below loop. + uint256 bitsRemaining = 256; + + // Generate a random value and size for each variable. + uint256[] memory vals = new uint256[](nvars); + uint256[] memory sizes = new uint256[](nvars); + uint256[] memory offsets = new uint256[](nvars); + + for (uint256 i = 0; i < nvars; i++) { + // Generate a random value and size. + offsets[i] = i == 0 ? 0 : offsets[i - 1] + sizes[i - 1]; + + uint256 nvarsRemaining = nvars - i; + uint256 maxVarSize = bitsRemaining - nvarsRemaining + 1; + sizes[i] = bound(uint256(keccak256(abi.encodePacked(seed, i + 256))), 1, maxVarSize); + bitsRemaining -= sizes[i]; + + uint256 maxVal; + uint256 varSize = sizes[i]; + assembly { + // mask = (1 << varSize) - 1 + maxVal := sub(shl(varSize, 1), 1) + } + vals[i] = bound(uint256(keccak256(abi.encodePacked(seed, i))), 0, maxVal); + } + + // Pack all values into the slot. + for (uint256 i = 0; i < nvars; i++) { + stdstore.enable_packed_slots().target(address(test)).sig("getRandomPacked(uint256,uint256)") + .with_key(sizes[i]).with_key(offsets[i]).checked_write(vals[i]); + } + + // Verify the read data matches. + for (uint256 i = 0; i < nvars; i++) { + uint256 readVal = stdstore.enable_packed_slots().target(address(test)) + .sig("getRandomPacked(uint256,uint256)").with_key(sizes[i]).with_key(offsets[i]).read_uint(); + + uint256 retVal = test.getRandomPacked(sizes[i], offsets[i]); + + assertEq(readVal, vals[i]); + assertEq(retVal, vals[i]); + } + } + + function testEdgeCaseArray() public { + stdstore.target(address(test)).sig("edgeCaseArray(uint256)").with_key(uint256(0)).checked_write(1); + assertEq(test.edgeCaseArray(0), 1); + } + + // Regression tests for https://github.com/foundry-rs/forge-std/issues/345 + function test_StorageFindShortString() public { + ShortBytesStorage target = new ShortBytesStorage(); + assertEq(stdstore.target(address(target)).sig(target.exists.selector).find(), 0); + } + + function test_StorageFindShortBytesWithDirtyPadding() public { + ShortBytesStorage target = new ShortBytesStorage(); + bytes32 slot = bytes32(uint256(1)); + bytes32 dirtyValue = vm.load(address(target), slot) | bytes32(uint256(0xDEADBE) << 8); + vm.store(address(target), slot, dirtyValue); + assertEq(target.data(), hex"616263"); + assertEq(stdstore.target(address(target)).sig(target.data.selector).find(), 1); + assertEq(vm.load(address(target), slot), dirtyValue); + } + + function test_StorageFindCanonicalLookingStaticReturn() public { + CanonicalLookingStaticReturn target = new CanonicalLookingStaticReturn(); + assertEq(stdstore.target(address(target)).sig(target.values.selector).depth(0).find(), 0); + assertEq(stdstore.target(address(target)).sig(target.values.selector).depth(1).find(), 1); + } + + function test_RevertStorageFindRestoresFailedShortBytesProbe() public { + RevertingEmptyString target = new RevertingEmptyString(); + vm.expectRevert(bytes("stdStorage find(StdStorage): Slot(s) not found.")); + this.findSlot(address(target), target.value.selector); + assertEq(target.value(), "A"); + } + + function findSlot(address target, bytes4 sig) external { + stdstore.target(target).sig(sig).find(); + } + + // Regression test for https://github.com/foundry-rs/forge-std/issues/740 + // `find()` used to infinite-loop on tokens whose `balanceOf` reads multiple + // storage slots and returns a derived value (reflection tokens). + function test_RevertFindOnReflectionToken() public { + MockReflectionToken token = new MockReflectionToken(); + ReflectionTokenTarget target = new ReflectionTokenTarget(token); + vm.expectRevert("stdStorage find(StdStorage): Slot(s) not found."); + target.findBalanceOf(address(this)); + } +} + +contract StorageTestTarget { + using stdStorage for StdStorage; + + StdStorage internal stdstore; + StorageTest internal test; + + constructor(StorageTest test_) { + test = test_; + } + + function expectRevertStorageConst() public { + stdstore.target(address(test)).sig("const()").find(); + } +} + +contract ShortBytesStorage { + string public exists = "thequickbrownfoxjumpsoverthelaz"; + bytes public data = hex"616263"; +} + +contract CanonicalLookingStaticReturn { + uint256 private first = 32; + uint256 private second = 1; + bytes32 private decoy = bytes32("A") | bytes32(uint256(2)); + + function values() public view returns (uint256, uint256, bytes32) { + return (first, second, decoy & ~bytes32(uint256(0xFF))); + } +} + +contract RevertingEmptyString { + string private storedValue = "A"; + + function value() public view returns (string memory) { + require(bytes(storedValue).length != 0); + return storedValue; + } +} + +contract ReflectionTokenTarget { + using stdStorage for StdStorage; + + StdStorage internal stdstore; + MockReflectionToken internal token; + + constructor(MockReflectionToken token_) { + token = token_; + } + + function findBalanceOf(address who) public { + stdstore.target(address(token)).sig("balanceOf(address)").with_key(who).find(); + } +} + +contract StorageTest { + uint256 public exists = 1; + mapping(address => uint256) public map_addr; + mapping(uint256 => uint256) public map_uint; + mapping(address => uint256) public map_packed; + mapping(address => UnpackedStruct) public map_struct; + mapping(address => mapping(address => uint256)) public deep_map; + mapping(address => mapping(address => UnpackedStruct)) public deep_map_struct; + UnpackedStruct public basic; + + uint248 public tA; + bool public tB; + + bool public tC = false; + uint248 public tD = 1; + + struct UnpackedStruct { + uint256 a; + uint256 b; + } + + mapping(address => bool) public map_bool; + + bytes32 public tE = hex"1337"; + address public tF = address(1337); + int256 public tG = type(int256).min; + bool public tH = true; + bytes32 private tI = ~bytes32(hex"1337"); + + uint256 randomPacking; + + // Array with length matching values of elements. + uint256[] public edgeCaseArray = [3, 3, 3]; + + constructor() { + basic = UnpackedStruct({a: 1337, b: 1337}); + + uint256 two = (1 << 128) | 1; + map_packed[msg.sender] = two; + map_packed[address(uint160(1337))] = 1 << 128; + } + + function read_struct_upper(address who) public view returns (uint256) { + return map_packed[who] >> 128; + } + + function read_struct_lower(address who) public view returns (uint256) { + return map_packed[who] & ((1 << 128) - 1); + } + + function hidden() public view returns (bytes32 t) { + bytes32 slot = keccak256("my.random.var"); + assembly ("memory-safe") { + t := sload(slot) + } + } + + function const() public pure returns (bytes32 t) { + t = bytes32(hex"1337"); + } + + function extra_sload() public view returns (bytes32 t) { + // trigger read on slot `tE`, and make a staticcall to make sure compiler doesn't optimize this SLOAD away + assembly { + pop(staticcall(gas(), sload(tE.slot), 0, 0, 0, 0)) + } + t = tI; + } + + function setRandomPacking(uint256 val) public { + randomPacking = val; + } + + function _getMask(uint256 size) internal pure returns (uint256 mask) { + assembly { + // mask = (1 << size) - 1 + mask := sub(shl(size, 1), 1) + } + } + + function setRandomPacking(uint256 val, uint256 size, uint256 offset) public { + // Generate mask based on the size of the value + uint256 mask = _getMask(size); + // Zero out all bits for the word we're about to set + uint256 cleanedWord = randomPacking & ~(mask << offset); + // Place val in the correct spot of the cleaned word + randomPacking = cleanedWord | val << offset; + } + + function getRandomPacked(uint256 size, uint256 offset) public view returns (uint256) { + // Generate mask based on the size of the value + uint256 mask = _getMask(size); + // Shift to place the bits in the correct position, and use mask to zero out remaining bits + return (randomPacking >> offset) & mask; + } + + function getRandomPacked(uint8 shifts, uint8[] memory shiftSizes, uint8 elem) public view returns (uint256) { + require(elem < shifts, "!elem"); + uint256 leftBits; + uint256 rightBits; + + for (uint256 i; i < shiftSizes.length; i++) { + if (i < elem) { + leftBits += shiftSizes[i]; + } else if (elem != i) { + rightBits += shiftSizes[i]; + } + } + + // we may have some right bits unaccounted for + leftBits += 256 - (leftBits + shiftSizes[elem] + rightBits); + + // clear left bits, then clear right bits and realign + return (randomPacking << leftBits) >> (leftBits + rightBits); + } +} + +// Minimal mock of a reflection token: `balanceOf` reads many storage slots +// and always returns a constant, so no single slot mutation can change its +// return value and stdStorage can never find a matching slot. +contract MockReflectionToken { + uint256 internal _a = 1; + uint256 internal _b = 2; + uint256 internal _c = 3; + mapping(address => uint256) internal _balances; + + constructor() { + _balances[msg.sender] = 1000 ether; + } + + // Reads _a, _b, _c, and _balances[account] but always returns a constant. + // This means mutating any single slot won't change the return value. + function balanceOf(address account) public view returns (uint256) { + uint256 x = _a + _b + _c + _balances[account]; + x; // suppress unused warning + return 42; + } +} diff --git a/contracts/evm/lib/forge-std/test/StdStyle.t.sol b/contracts/evm/lib/forge-std/test/StdStyle.t.sol new file mode 100644 index 0000000000..1146a8df55 --- /dev/null +++ b/contracts/evm/lib/forge-std/test/StdStyle.t.sol @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {Test, console2, StdStyle} from "../src/Test.sol"; + +contract StdStyleTest is Test { + function test_StyleColor() public pure { + console2.log(StdStyle.red("StdStyle.red String Test")); + console2.log(StdStyle.red(uint256(10e18))); + console2.log(StdStyle.red(int256(-10e18))); + console2.log(StdStyle.red(true)); + console2.log(StdStyle.red(address(0))); + console2.log(StdStyle.redBytes(hex"7109709ECfa91a80626fF3989D68f67F5b1DD12D")); + console2.log(StdStyle.redBytes32("StdStyle.redBytes32")); + console2.log(StdStyle.green("StdStyle.green String Test")); + console2.log(StdStyle.green(uint256(10e18))); + console2.log(StdStyle.green(int256(-10e18))); + console2.log(StdStyle.green(true)); + console2.log(StdStyle.green(address(0))); + console2.log(StdStyle.greenBytes(hex"7109709ECfa91a80626fF3989D68f67F5b1DD12D")); + console2.log(StdStyle.greenBytes32("StdStyle.greenBytes32")); + console2.log(StdStyle.yellow("StdStyle.yellow String Test")); + console2.log(StdStyle.yellow(uint256(10e18))); + console2.log(StdStyle.yellow(int256(-10e18))); + console2.log(StdStyle.yellow(true)); + console2.log(StdStyle.yellow(address(0))); + console2.log(StdStyle.yellowBytes(hex"7109709ECfa91a80626fF3989D68f67F5b1DD12D")); + console2.log(StdStyle.yellowBytes32("StdStyle.yellowBytes32")); + console2.log(StdStyle.blue("StdStyle.blue String Test")); + console2.log(StdStyle.blue(uint256(10e18))); + console2.log(StdStyle.blue(int256(-10e18))); + console2.log(StdStyle.blue(true)); + console2.log(StdStyle.blue(address(0))); + console2.log(StdStyle.blueBytes(hex"7109709ECfa91a80626fF3989D68f67F5b1DD12D")); + console2.log(StdStyle.blueBytes32("StdStyle.blueBytes32")); + console2.log(StdStyle.magenta("StdStyle.magenta String Test")); + console2.log(StdStyle.magenta(uint256(10e18))); + console2.log(StdStyle.magenta(int256(-10e18))); + console2.log(StdStyle.magenta(true)); + console2.log(StdStyle.magenta(address(0))); + console2.log(StdStyle.magentaBytes(hex"7109709ECfa91a80626fF3989D68f67F5b1DD12D")); + console2.log(StdStyle.magentaBytes32("StdStyle.magentaBytes32")); + console2.log(StdStyle.cyan("StdStyle.cyan String Test")); + console2.log(StdStyle.cyan(uint256(10e18))); + console2.log(StdStyle.cyan(int256(-10e18))); + console2.log(StdStyle.cyan(true)); + console2.log(StdStyle.cyan(address(0))); + console2.log(StdStyle.cyanBytes(hex"7109709ECfa91a80626fF3989D68f67F5b1DD12D")); + console2.log(StdStyle.cyanBytes32("StdStyle.cyanBytes32")); + } + + function test_StyleFontWeight() public pure { + console2.log(StdStyle.bold("StdStyle.bold String Test")); + console2.log(StdStyle.bold(uint256(10e18))); + console2.log(StdStyle.bold(int256(-10e18))); + console2.log(StdStyle.bold(address(0))); + console2.log(StdStyle.bold(true)); + console2.log(StdStyle.boldBytes(hex"7109709ECfa91a80626fF3989D68f67F5b1DD12D")); + console2.log(StdStyle.boldBytes32("StdStyle.boldBytes32")); + console2.log(StdStyle.dim("StdStyle.dim String Test")); + console2.log(StdStyle.dim(uint256(10e18))); + console2.log(StdStyle.dim(int256(-10e18))); + console2.log(StdStyle.dim(address(0))); + console2.log(StdStyle.dim(true)); + console2.log(StdStyle.dimBytes(hex"7109709ECfa91a80626fF3989D68f67F5b1DD12D")); + console2.log(StdStyle.dimBytes32("StdStyle.dimBytes32")); + console2.log(StdStyle.italic("StdStyle.italic String Test")); + console2.log(StdStyle.italic(uint256(10e18))); + console2.log(StdStyle.italic(int256(-10e18))); + console2.log(StdStyle.italic(address(0))); + console2.log(StdStyle.italic(true)); + console2.log(StdStyle.italicBytes(hex"7109709ECfa91a80626fF3989D68f67F5b1DD12D")); + console2.log(StdStyle.italicBytes32("StdStyle.italicBytes32")); + console2.log(StdStyle.underline("StdStyle.underline String Test")); + console2.log(StdStyle.underline(uint256(10e18))); + console2.log(StdStyle.underline(int256(-10e18))); + console2.log(StdStyle.underline(address(0))); + console2.log(StdStyle.underline(true)); + console2.log(StdStyle.underlineBytes(hex"7109709ECfa91a80626fF3989D68f67F5b1DD12D")); + console2.log(StdStyle.underlineBytes32("StdStyle.underlineBytes32")); + console2.log(StdStyle.inverse("StdStyle.inverse String Test")); + console2.log(StdStyle.inverse(uint256(10e18))); + console2.log(StdStyle.inverse(int256(-10e18))); + console2.log(StdStyle.inverse(address(0))); + console2.log(StdStyle.inverse(true)); + console2.log(StdStyle.inverseBytes(hex"7109709ECfa91a80626fF3989D68f67F5b1DD12D")); + console2.log(StdStyle.inverseBytes32("StdStyle.inverseBytes32")); + } + + function test_StyleCombined() public pure { + console2.log(StdStyle.red(StdStyle.bold("Red Bold String Test"))); + console2.log(StdStyle.green(StdStyle.dim(uint256(10e18)))); + console2.log(StdStyle.yellow(StdStyle.italic(int256(-10e18)))); + console2.log(StdStyle.blue(StdStyle.underline(address(0)))); + console2.log(StdStyle.magenta(StdStyle.inverse(true))); + } + + function test_StyleCustom() public pure { + console2.log(h1("Custom Style 1")); + console2.log(h2("Custom Style 2")); + } + + function h1(string memory a) private pure returns (string memory) { + return StdStyle.cyan(StdStyle.inverse(StdStyle.bold(a))); + } + + function h2(string memory a) private pure returns (string memory) { + return StdStyle.magenta(StdStyle.bold(StdStyle.underline(a))); + } +} diff --git a/contracts/evm/lib/forge-std/test/StdToml.t.sol b/contracts/evm/lib/forge-std/test/StdToml.t.sol new file mode 100644 index 0000000000..306dda99fc --- /dev/null +++ b/contracts/evm/lib/forge-std/test/StdToml.t.sol @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {Test, stdToml} from "../src/Test.sol"; + +contract StdTomlTest is Test { + using stdToml for string; + + string root; + string path; + + function setUp() public { + root = vm.projectRoot(); + path = string.concat(root, "/test/fixtures/test.toml"); + } + + struct SimpleToml { + uint256 a; + string b; + } + + struct NestedToml { + uint256 a; + string b; + SimpleToml c; + } + + function test_readToml() public view { + string memory json = vm.readFile(path); + assertEq(json.readUint(".a"), 123); + } + + function test_writeToml() public { + string memory json = "json"; + json.serialize("a", uint256(123)); + string memory semiFinal = json.serialize("b", string("test")); + string memory finalJson = json.serialize("c", semiFinal); + finalJson.write(path); + + string memory toml = vm.readFile(path); + bytes memory data = toml.parseRaw("$"); + NestedToml memory decodedData = abi.decode(data, (NestedToml)); + + assertEq(decodedData.a, 123); + assertEq(decodedData.b, "test"); + assertEq(decodedData.c.a, 123); + assertEq(decodedData.c.b, "test"); + } +} diff --git a/contracts/evm/lib/forge-std/test/StdUtils.t.sol b/contracts/evm/lib/forge-std/test/StdUtils.t.sol new file mode 100644 index 0000000000..c0a3d3acf0 --- /dev/null +++ b/contracts/evm/lib/forge-std/test/StdUtils.t.sol @@ -0,0 +1,342 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {Test, StdUtils} from "../src/Test.sol"; + +contract StdUtilsMock is StdUtils { + // We deploy a mock version so we can properly test expected reverts. + function exposedGetTokenBalances(address token, address[] memory addresses) + external + returns (uint256[] memory balances) + { + return getTokenBalances(token, addresses); + } + + function exposedBound(int256 num, int256 min, int256 max) external pure returns (int256) { + return bound(num, min, max); + } + + function exposedBound(uint256 num, uint256 min, uint256 max) external pure returns (uint256) { + return bound(num, min, max); + } + + function exposedBytesToUint(bytes memory b) external pure returns (uint256) { + return bytesToUint(b); + } +} + +contract StdUtilsTest is Test { + /*////////////////////////////////////////////////////////////////////////// + BOUND UINT + //////////////////////////////////////////////////////////////////////////*/ + + function test_Bound() public pure { + assertEq(bound(uint256(5), 0, 4), 0); + assertEq(bound(uint256(0), 69, 69), 69); + assertEq(bound(uint256(0), 68, 69), 68); + assertEq(bound(uint256(10), 150, 190), 174); + assertEq(bound(uint256(300), 2800, 3200), 3107); + assertEq(bound(uint256(9999), 1337, 6666), 4669); + } + + function test_Bound_WithinRange() public pure { + assertEq(bound(uint256(51), 50, 150), 51); + assertEq(bound(uint256(51), 50, 150), bound(bound(uint256(51), 50, 150), 50, 150)); + assertEq(bound(uint256(149), 50, 150), 149); + assertEq(bound(uint256(149), 50, 150), bound(bound(uint256(149), 50, 150), 50, 150)); + } + + function test_Bound_EdgeCoverage() public pure { + assertEq(bound(uint256(0), 50, 150), 50); + assertEq(bound(uint256(1), 50, 150), 51); + assertEq(bound(uint256(2), 50, 150), 52); + assertEq(bound(uint256(3), 50, 150), 53); + assertEq(bound(type(uint256).max, 50, 150), 150); + assertEq(bound(type(uint256).max - 1, 50, 150), 149); + assertEq(bound(type(uint256).max - 2, 50, 150), 148); + assertEq(bound(type(uint256).max - 3, 50, 150), 147); + } + + function testFuzz_Bound_DistributionIsEven(uint256 min, uint256 size) public pure { + size = size % 100 + 1; + min = bound(min, UINT256_MAX / 2, UINT256_MAX / 2 + size); + uint256 max = min + size - 1; + uint256 result; + + for (uint256 i = 1; i <= size * 4; ++i) { + // x > max + result = bound(max + i, min, max); + assertEq(result, min + (i - 1) % size); + // x < min + result = bound(min - i, min, max); + assertEq(result, max - (i - 1) % size); + } + } + + function testFuzz_Bound(uint256 num, uint256 min, uint256 max) public pure { + if (min > max) (min, max) = (max, min); + + uint256 result = bound(num, min, max); + + assertGe(result, min); + assertLe(result, max); + assertEq(result, bound(result, min, max)); + if (num >= min && num <= max) assertEq(result, num); + } + + function test_BoundUint256Max() public pure { + assertEq(bound(0, type(uint256).max - 1, type(uint256).max), type(uint256).max - 1); + assertEq(bound(1, type(uint256).max - 1, type(uint256).max), type(uint256).max); + } + + function test_RevertIf_BoundMaxLessThanMin() public { + // We deploy a mock version so we can properly test the revert. + StdUtilsMock stdUtils = new StdUtilsMock(); + + vm.expectRevert(bytes("StdUtils bound(uint256,uint256,uint256): Max is less than min.")); + stdUtils.exposedBound(uint256(5), 100, 10); + } + + function testFuzz_RevertIf_BoundMaxLessThanMin(uint256 num, uint256 min, uint256 max) public { + // We deploy a mock version so we can properly test the revert. + StdUtilsMock stdUtils = new StdUtilsMock(); + + vm.assume(min > max); + vm.expectRevert(bytes("StdUtils bound(uint256,uint256,uint256): Max is less than min.")); + stdUtils.exposedBound(num, min, max); + } + + /*////////////////////////////////////////////////////////////////////////// + BOUND INT + //////////////////////////////////////////////////////////////////////////*/ + + function test_BoundInt() public pure { + assertEq(bound(-3, 0, 4), 2); + assertEq(bound(0, -69, -69), -69); + assertEq(bound(0, -69, -68), -68); + assertEq(bound(-10, 150, 190), 154); + assertEq(bound(-300, 2800, 3200), 2908); + assertEq(bound(9999, -1337, 6666), 1995); + } + + function test_BoundInt_WithinRange() public pure { + assertEq(bound(51, -50, 150), 51); + assertEq(bound(51, -50, 150), bound(bound(51, -50, 150), -50, 150)); + assertEq(bound(149, -50, 150), 149); + assertEq(bound(149, -50, 150), bound(bound(149, -50, 150), -50, 150)); + } + + function test_BoundInt_EdgeCoverage() public pure { + assertEq(bound(type(int256).min, -50, 150), -50); + assertEq(bound(type(int256).min + 1, -50, 150), -49); + assertEq(bound(type(int256).min + 2, -50, 150), -48); + assertEq(bound(type(int256).min + 3, -50, 150), -47); + assertEq(bound(type(int256).min, 10, 150), 10); + assertEq(bound(type(int256).min + 1, 10, 150), 11); + assertEq(bound(type(int256).min + 2, 10, 150), 12); + assertEq(bound(type(int256).min + 3, 10, 150), 13); + + assertEq(bound(type(int256).max, -50, 150), 150); + assertEq(bound(type(int256).max - 1, -50, 150), 149); + assertEq(bound(type(int256).max - 2, -50, 150), 148); + assertEq(bound(type(int256).max - 3, -50, 150), 147); + assertEq(bound(type(int256).max, -50, -10), -10); + assertEq(bound(type(int256).max - 1, -50, -10), -11); + assertEq(bound(type(int256).max - 2, -50, -10), -12); + assertEq(bound(type(int256).max - 3, -50, -10), -13); + } + + function testFuzz_BoundInt_DistributionIsEven(int256 min, uint256 size) public pure { + size = size % 100 + 1; + min = bound(min, -int256(size / 2), int256(size - size / 2)); + int256 max = min + int256(size) - 1; + int256 result; + + for (uint256 i = 1; i <= size * 4; ++i) { + // x > max + result = bound(max + int256(i), min, max); + assertEq(result, min + int256((i - 1) % size)); + // x < min + result = bound(min - int256(i), min, max); + assertEq(result, max - int256((i - 1) % size)); + } + } + + function testFuzz_BoundInt(int256 num, int256 min, int256 max) public pure { + if (min > max) (min, max) = (max, min); + + int256 result = bound(num, min, max); + + assertGe(result, min); + assertLe(result, max); + assertEq(result, bound(result, min, max)); + if (num >= min && num <= max) assertEq(result, num); + } + + function test_BoundIntInt256Max() public pure { + assertEq(bound(0, type(int256).max - 1, type(int256).max), type(int256).max - 1); + assertEq(bound(1, type(int256).max - 1, type(int256).max), type(int256).max); + } + + function test_BoundIntInt256Min() public pure { + assertEq(bound(0, type(int256).min, type(int256).min + 1), type(int256).min); + assertEq(bound(1, type(int256).min, type(int256).min + 1), type(int256).min + 1); + } + + function test_RevertIf_BoundIntMaxLessThanMin() public { + // We deploy a mock version so we can properly test the revert. + StdUtilsMock stdUtils = new StdUtilsMock(); + + vm.expectRevert(bytes("StdUtils bound(int256,int256,int256): Max is less than min.")); + stdUtils.exposedBound(-5, 100, 10); + } + + function testFuzz_RevertIf_BoundIntMaxLessThanMin(int256 num, int256 min, int256 max) public { + // We deploy a mock version so we can properly test the revert. + StdUtilsMock stdUtils = new StdUtilsMock(); + + vm.assume(min > max); + vm.expectRevert(bytes("StdUtils bound(int256,int256,int256): Max is less than min.")); + stdUtils.exposedBound(num, min, max); + } + + /*////////////////////////////////////////////////////////////////////////// + BOUND PRIVATE KEY + //////////////////////////////////////////////////////////////////////////*/ + + function test_BoundPrivateKey() public pure { + assertEq(boundPrivateKey(0), 1); + assertEq(boundPrivateKey(1), 1); + assertEq(boundPrivateKey(300), 300); + assertEq(boundPrivateKey(9999), 9999); + assertEq(boundPrivateKey(SECP256K1_ORDER - 1), SECP256K1_ORDER - 1); + assertEq(boundPrivateKey(SECP256K1_ORDER), 1); + assertEq(boundPrivateKey(SECP256K1_ORDER + 1), 2); + assertEq(boundPrivateKey(UINT256_MAX), UINT256_MAX & SECP256K1_ORDER - 1); // x&y is equivalent to x-x%y + } + + /*////////////////////////////////////////////////////////////////////////// + BYTES TO UINT + //////////////////////////////////////////////////////////////////////////*/ + + function test_BytesToUint() external pure { + bytes memory maxUint = hex"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; + bytes memory two = hex"02"; + bytes memory millionEther = hex"d3c21bcecceda1000000"; + + assertEq(bytesToUint(maxUint), type(uint256).max); + assertEq(bytesToUint(two), 2); + assertEq(bytesToUint(millionEther), 1_000_000 ether); + } + + function test_RevertIf_BytesLengthExceeds32() external { + // We deploy a mock version so we can properly test the revert. + StdUtilsMock stdUtils = new StdUtilsMock(); + + bytes memory thirty3Bytes = hex"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; + vm.expectRevert("StdUtils bytesToUint(bytes): Bytes length exceeds 32."); + stdUtils.exposedBytesToUint(thirty3Bytes); + } + + /*////////////////////////////////////////////////////////////////////////// + COMPUTE CREATE ADDRESS + //////////////////////////////////////////////////////////////////////////*/ + + function test_ComputeCreateAddress() external pure { + address deployer = 0x6C9FC64A53c1b71FB3f9Af64d1ae3A4931A5f4E9; + uint256 nonce = 14; + address createAddress = computeCreateAddress(deployer, nonce); + assertEq(createAddress, 0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45); + } + + /*////////////////////////////////////////////////////////////////////////// + COMPUTE CREATE2 ADDRESS + //////////////////////////////////////////////////////////////////////////*/ + + function test_ComputeCreate2Address() external pure { + bytes32 salt = bytes32(uint256(31415)); + bytes32 initcodeHash = keccak256(abi.encode(0x6080)); + address deployer = 0x6C9FC64A53c1b71FB3f9Af64d1ae3A4931A5f4E9; + address create2Address = computeCreate2Address(salt, initcodeHash, deployer); + assertEq(create2Address, 0xB147a5d25748fda14b463EB04B111027C290f4d3); + } + + function test_ComputeCreate2AddressWithDefaultDeployer() external pure { + bytes32 salt = 0xc290c670fde54e5ef686f9132cbc8711e76a98f0333a438a92daa442c71403c0; + bytes32 initcodeHash = hashInitCode(hex"6080", ""); + assertEq(initcodeHash, 0x1a578b7a4b0b5755db6d121b4118d4bc68fe170dca840c59bc922f14175a76b0); + address create2Address = computeCreate2Address(salt, initcodeHash); + assertEq(create2Address, 0xc0ffEe2198a06235aAbFffe5Db0CacF1717f5Ac6); + } +} + +contract StdUtilsForkTest is Test { + /*////////////////////////////////////////////////////////////////////////// + GET TOKEN BALANCES + //////////////////////////////////////////////////////////////////////////*/ + + address internal SHIB = 0x95aD61b0a150d79219dCF64E1E6Cc01f0B64C4cE; + address internal SHIB_HOLDER_0 = 0x855F5981e831D83e6A4b4EBFCAdAa68D92333170; + address internal SHIB_HOLDER_1 = 0x8F509A90c2e47779cA408Fe00d7A72e359229AdA; + address internal SHIB_HOLDER_2 = 0x0e3bbc0D04fF62211F71f3e4C45d82ad76224385; + + address internal USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; + address internal USDC_HOLDER_0 = 0xDa9CE944a37d218c3302F6B82a094844C6ECEb17; + address internal USDC_HOLDER_1 = 0x3e67F4721E6d1c41a015f645eFa37BEd854fcf52; + + function setUp() public { + // All tests of the `getTokenBalances` method are fork tests using live contracts. + vm.createSelectFork({urlOrAlias: "mainnet", blockNumber: 16_428_900}); + } + + function test_RevertIf_CannotGetTokenBalances_NonTokenContract() external { + // We deploy a mock version so we can properly test the revert. + StdUtilsMock stdUtils = new StdUtilsMock(); + + // The UniswapV2Factory contract has neither a `balanceOf` function nor a fallback function, + // so the `balanceOf` call should revert. + address token = address(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); + address[] memory addresses = new address[](1); + addresses[0] = USDC_HOLDER_0; + + vm.expectRevert("Multicall3: call failed"); + stdUtils.exposedGetTokenBalances(token, addresses); + } + + function test_RevertIf_CannotGetTokenBalances_EOA() external { + // We deploy a mock version so we can properly test the revert. + StdUtilsMock stdUtils = new StdUtilsMock(); + + address eoa = vm.addr({privateKey: 1}); + address[] memory addresses = new address[](1); + addresses[0] = USDC_HOLDER_0; + vm.expectRevert("StdUtils getTokenBalances(address,address[]): Token address is not a contract."); + stdUtils.exposedGetTokenBalances(eoa, addresses); + } + + function test_GetTokenBalances_Empty() external { + address[] memory addresses = new address[](0); + uint256[] memory balances = getTokenBalances(USDC, addresses); + assertEq(balances.length, 0); + } + + function test_GetTokenBalances_USDC() external { + address[] memory addresses = new address[](2); + addresses[0] = USDC_HOLDER_0; + addresses[1] = USDC_HOLDER_1; + uint256[] memory balances = getTokenBalances(USDC, addresses); + assertEq(balances[0], 159_000_000_000_000); + assertEq(balances[1], 131_350_000_000_000); + } + + function test_GetTokenBalances_SHIB() external { + address[] memory addresses = new address[](3); + addresses[0] = SHIB_HOLDER_0; + addresses[1] = SHIB_HOLDER_1; + addresses[2] = SHIB_HOLDER_2; + uint256[] memory balances = getTokenBalances(SHIB, addresses); + assertEq(balances[0], 3_323_256_285_484.42e18); + assertEq(balances[1], 1_271_702_771_149.99999928e18); + assertEq(balances[2], 606_357_106_247e18); + } +} diff --git a/contracts/evm/lib/forge-std/test/Vm.t.sol b/contracts/evm/lib/forge-std/test/Vm.t.sol new file mode 100644 index 0000000000..7fd702f690 --- /dev/null +++ b/contracts/evm/lib/forge-std/test/Vm.t.sol @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {Test} from "../src/Test.sol"; +import {Vm, VmSafe} from "../src/Vm.sol"; + +// These tests ensure that functions are never accidentally removed from a Vm interface, or +// inadvertently moved between Vm and VmSafe. These tests must be updated each time a function is +// added to or removed from Vm or VmSafe. +contract VmTest is Test { + function test_VmInterfaceId() public pure { + assertEq(type(Vm).interfaceId, bytes4(0xaa0b360f), "Vm"); + } + + function test_VmSafeInterfaceId() public pure { + assertEq(type(VmSafe).interfaceId, bytes4(0x82f5a341), "VmSafe"); + } +} diff --git a/contracts/evm/lib/forge-std/test/compilation/CompilationScript.sol b/contracts/evm/lib/forge-std/test/compilation/CompilationScript.sol new file mode 100644 index 0000000000..6efbfa6581 --- /dev/null +++ b/contracts/evm/lib/forge-std/test/compilation/CompilationScript.sol @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {Script} from "../../src/Script.sol"; + +// The purpose of this contract is to benchmark compilation time to avoid accidentally introducing +// a change that results in very long compilation times with via-ir. See https://github.com/foundry-rs/forge-std/issues/207 +contract CompilationScript is Script {} diff --git a/contracts/evm/lib/forge-std/test/compilation/CompilationScriptBase.sol b/contracts/evm/lib/forge-std/test/compilation/CompilationScriptBase.sol new file mode 100644 index 0000000000..75329739d3 --- /dev/null +++ b/contracts/evm/lib/forge-std/test/compilation/CompilationScriptBase.sol @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {ScriptBase} from "../../src/Script.sol"; + +// The purpose of this contract is to benchmark compilation time to avoid accidentally introducing +// a change that results in very long compilation times with via-ir. See https://github.com/foundry-rs/forge-std/issues/207 +contract CompilationScriptBase is ScriptBase {} diff --git a/contracts/evm/lib/forge-std/test/compilation/CompilationTest.sol b/contracts/evm/lib/forge-std/test/compilation/CompilationTest.sol new file mode 100644 index 0000000000..5ba888e8c1 --- /dev/null +++ b/contracts/evm/lib/forge-std/test/compilation/CompilationTest.sol @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {Test} from "../../src/Test.sol"; + +// The purpose of this contract is to benchmark compilation time to avoid accidentally introducing +// a change that results in very long compilation times with via-ir. See https://github.com/foundry-rs/forge-std/issues/207 +contract CompilationTest is Test {} diff --git a/contracts/evm/lib/forge-std/test/compilation/CompilationTestBase.sol b/contracts/evm/lib/forge-std/test/compilation/CompilationTestBase.sol new file mode 100644 index 0000000000..9c081f7897 --- /dev/null +++ b/contracts/evm/lib/forge-std/test/compilation/CompilationTestBase.sol @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pragma solidity >=0.8.13 <0.9.0; + +import {TestBase} from "../../src/Test.sol"; + +// The purpose of this contract is to benchmark compilation time to avoid accidentally introducing +// a change that results in very long compilation times with via-ir. See https://github.com/foundry-rs/forge-std/issues/207 +contract CompilationTestBase is TestBase {} diff --git a/contracts/evm/lib/forge-std/test/fixtures/broadcast.log.json b/contracts/evm/lib/forge-std/test/fixtures/broadcast.log.json new file mode 100644 index 0000000000..0a0200bca9 --- /dev/null +++ b/contracts/evm/lib/forge-std/test/fixtures/broadcast.log.json @@ -0,0 +1,187 @@ +{ + "transactions": [ + { + "hash": "0xc6006863c267735a11476b7f15b15bc718e117e2da114a2be815dd651e1a509f", + "type": "CALL", + "contractName": "Test", + "contractAddress": "0xe7f1725e7734ce288f8367e1bb143e90bb3f0512", + "function": "multiple_arguments(uint256,address,uint256[]):(uint256)", + "arguments": ["1", "0000000000000000000000000000000000001337", "[3,4]"], + "tx": { + "type": "0x02", + "from": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266", + "to": "0xe7f1725e7734ce288f8367e1bb143e90bb3f0512", + "gas": "0x73b9", + "value": "0x0", + "data": "0x23e99187000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000013370000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000000000000000000000000000000000004", + "nonce": "0x3", + "accessList": [] + } + }, + { + "hash": "0xedf2b38d8d896519a947a1acf720f859bb35c0c5ecb8dd7511995b67b9853298", + "type": "CALL", + "contractName": "Test", + "contractAddress": "0xe7f1725e7734ce288f8367e1bb143e90bb3f0512", + "function": "inc():(uint256)", + "arguments": [], + "tx": { + "type": "0x02", + "from": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266", + "to": "0xe7f1725e7734ce288f8367e1bb143e90bb3f0512", + "gas": "0xdcb2", + "value": "0x0", + "data": "0x371303c0", + "nonce": "0x4", + "accessList": [] + } + }, + { + "hash": "0xa57e8e3981a6c861442e46c9471bd19cb3e21f9a8a6c63a72e7b5c47c6675a7c", + "type": "CALL", + "contractName": "Test", + "contractAddress": "0x7c6b4bbe207d642d98d5c537142d85209e585087", + "function": "t(uint256):(uint256)", + "arguments": ["1"], + "tx": { + "type": "0x02", + "from": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266", + "to": "0x7c6b4bbe207d642d98d5c537142d85209e585087", + "gas": "0x8599", + "value": "0x0", + "data": "0xafe29f710000000000000000000000000000000000000000000000000000000000000001", + "nonce": "0x5", + "accessList": [] + } + } + ], + "receipts": [ + { + "transactionHash": "0x481dc86e40bba90403c76f8e144aa9ff04c1da2164299d0298573835f0991181", + "transactionIndex": "0x0", + "blockHash": "0xef0730448490304e5403be0fa8f8ce64f118e9adcca60c07a2ae1ab921d748af", + "blockNumber": "0x1", + "from": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266", + "to": null, + "cumulativeGasUsed": "0x13f3a", + "gasUsed": "0x13f3a", + "contractAddress": "0x5fbdb2315678afecb367f032d93f642f64180aa3", + "logs": [], + "status": "0x1", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "effectiveGasPrice": "0xee6b2800" + }, + { + "transactionHash": "0x6a187183545b8a9e7f1790e847139379bf5622baff2cb43acf3f5c79470af782", + "transactionIndex": "0x0", + "blockHash": "0xf3acb96a90071640c2a8c067ae4e16aad87e634ea8d8bbbb5b352fba86ba0148", + "blockNumber": "0x2", + "from": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266", + "to": null, + "cumulativeGasUsed": "0x45d80", + "gasUsed": "0x45d80", + "contractAddress": "0xe7f1725e7734ce288f8367e1bb143e90bb3f0512", + "logs": [], + "status": "0x1", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "effectiveGasPrice": "0xee6b2800" + }, + { + "transactionHash": "0x064ad173b4867bdef2fb60060bbdaf01735fbf10414541ea857772974e74ea9d", + "transactionIndex": "0x0", + "blockHash": "0x8373d02109d3ee06a0225f23da4c161c656ccc48fe0fcee931d325508ae73e58", + "blockNumber": "0x3", + "from": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266", + "to": "0x4e59b44847b379578588920ca78fbf26c0b4956c", + "cumulativeGasUsed": "0x45feb", + "gasUsed": "0x45feb", + "contractAddress": null, + "logs": [], + "status": "0x1", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "effectiveGasPrice": "0xee6b2800" + }, + { + "transactionHash": "0xc6006863c267735a11476b7f15b15bc718e117e2da114a2be815dd651e1a509f", + "transactionIndex": "0x0", + "blockHash": "0x16712fae5c0e18f75045f84363fb6b4d9a9fe25e660c4ce286833a533c97f629", + "blockNumber": "0x4", + "from": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266", + "to": "0xe7f1725e7734ce288f8367e1bb143e90bb3f0512", + "cumulativeGasUsed": "0x5905", + "gasUsed": "0x5905", + "contractAddress": null, + "logs": [], + "status": "0x1", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "effectiveGasPrice": "0xee6b2800" + }, + { + "transactionHash": "0xedf2b38d8d896519a947a1acf720f859bb35c0c5ecb8dd7511995b67b9853298", + "transactionIndex": "0x0", + "blockHash": "0x156b88c3eb9a1244ba00a1834f3f70de735b39e3e59006dd03af4fe7d5480c11", + "blockNumber": "0x5", + "from": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266", + "to": "0xe7f1725e7734ce288f8367e1bb143e90bb3f0512", + "cumulativeGasUsed": "0xa9c4", + "gasUsed": "0xa9c4", + "contractAddress": null, + "logs": [], + "status": "0x1", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "effectiveGasPrice": "0xee6b2800" + }, + { + "transactionHash": "0xa57e8e3981a6c861442e46c9471bd19cb3e21f9a8a6c63a72e7b5c47c6675a7c", + "transactionIndex": "0x0", + "blockHash": "0xcf61faca67dbb2c28952b0b8a379e53b1505ae0821e84779679390cb8571cadb", + "blockNumber": "0x6", + "from": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266", + "to": "0x7c6b4bbe207d642d98d5c537142d85209e585087", + "cumulativeGasUsed": "0x66c5", + "gasUsed": "0x66c5", + "contractAddress": null, + "logs": [ + { + "address": "0x7c6b4bbe207d642d98d5c537142d85209e585087", + "topics": [ + "0x0b2e13ff20ac7b474198655583edf70dedd2c1dc980e329c4fbb2fc0748b796b" + ], + "data": "0x000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000046865726500000000000000000000000000000000000000000000000000000000", + "blockHash": "0xcf61faca67dbb2c28952b0b8a379e53b1505ae0821e84779679390cb8571cadb", + "blockNumber": "0x6", + "transactionHash": "0xa57e8e3981a6c861442e46c9471bd19cb3e21f9a8a6c63a72e7b5c47c6675a7c", + "transactionIndex": "0x1", + "logIndex": "0x0", + "transactionLogIndex": "0x0", + "removed": false + } + ], + "status": "0x1", + "logsBloom": "0x00000000000800000000000000000010000000000000000000000000000180000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100", + "effectiveGasPrice": "0xee6b2800" + }, + { + "transactionHash": "0x11fbb10230c168ca1e36a7e5c69a6dbcd04fd9e64ede39d10a83e36ee8065c16", + "transactionIndex": "0x0", + "blockHash": "0xf1e0ed2eda4e923626ec74621006ed50b3fc27580dc7b4cf68a07ca77420e29c", + "blockNumber": "0x7", + "from": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266", + "to": "0x0000000000000000000000000000000000001337", + "cumulativeGasUsed": "0x5208", + "gasUsed": "0x5208", + "contractAddress": null, + "logs": [], + "status": "0x1", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "effectiveGasPrice": "0xee6b2800" + } + ], + "libraries": [ + "src/Broadcast.t.sol:F:0x5fbdb2315678afecb367f032d93f642f64180aa3" + ], + "pending": [], + "path": "broadcast/Broadcast.t.sol/31337/run-latest.json", + "returns": {}, + "timestamp": 1655140035 +} diff --git a/contracts/evm/lib/forge-std/test/fixtures/config.toml b/contracts/evm/lib/forge-std/test/fixtures/config.toml new file mode 100644 index 0000000000..e6dcccca58 --- /dev/null +++ b/contracts/evm/lib/forge-std/test/fixtures/config.toml @@ -0,0 +1,81 @@ +# ------------------------------------------------ +# EXAMPLE DEPLOYMENT CONFIG +# ------------------------------------------------ + +# -- MAINNET ------------------------------------- + +[mainnet] +endpoint_url = "${MAINNET_RPC}" + +[mainnet.bool] +is_live = true +bool_array = [true, false] + +[mainnet.address] +weth = "${WETH_MAINNET}" +deps = [ + "0x0000000000000000000000000000000000000000", + "0x1111111111111111111111111111111111111111", +] + +[mainnet.uint] +number = 1234 +number_array = [5678, 9999] + +[mainnet.int] +signed_number = -1234 +signed_number_array = [-5678, 9999] + +[mainnet.bytes32] +word = "0x00000000000000000000000000000000000000000000000000000000000004d2" # 1234 +word_array = [ + "0x000000000000000000000000000000000000000000000000000000000000162e", # 5678 + "0x000000000000000000000000000000000000000000000000000000000000270f", # 9999 +] + +[mainnet.bytes] +b = "0xabcd" +b_array = ["0xdead", "0xbeef"] + +[mainnet.string] +str = "foo" +str_array = ["bar", "baz"] + +# -- OPTIMISM ------------------------------------ + +[optimism] +endpoint_url = "${OPTIMISM_RPC}" + +[optimism.bool] +is_live = false +bool_array = [false, true] + +[optimism.address] +weth = "${WETH_OPTIMISM}" +deps = [ + "0x2222222222222222222222222222222222222222", + "0x3333333333333333333333333333333333333333", +] + +[optimism.uint] +number = 9999 +number_array = [1234, 5678] + +[optimism.int] +signed_number = 9999 +signed_number_array = [-1234, -5678] + +[optimism.bytes32] +word = "0x000000000000000000000000000000000000000000000000000000000000270f" # 9999 +word_array = [ + "0x00000000000000000000000000000000000000000000000000000000000004d2", # 1234 + "0x000000000000000000000000000000000000000000000000000000000000162e", # 5678 +] + +[optimism.bytes] +b = "0xdcba" +b_array = ["0xc0ffee", "0xbabe"] + +[optimism.string] +str = "alice" +str_array = ["bob", "charlie"] diff --git a/contracts/evm/lib/forge-std/test/fixtures/test.json b/contracts/evm/lib/forge-std/test/fixtures/test.json new file mode 100644 index 0000000000..caebf6d965 --- /dev/null +++ b/contracts/evm/lib/forge-std/test/fixtures/test.json @@ -0,0 +1,8 @@ +{ + "a": 123, + "b": "test", + "c": { + "a": 123, + "b": "test" + } +} \ No newline at end of file diff --git a/contracts/evm/lib/forge-std/test/fixtures/test.toml b/contracts/evm/lib/forge-std/test/fixtures/test.toml new file mode 100644 index 0000000000..60692bc750 --- /dev/null +++ b/contracts/evm/lib/forge-std/test/fixtures/test.toml @@ -0,0 +1,6 @@ +a = 123 +b = "test" + +[c] +a = 123 +b = "test" diff --git a/contracts/evm/script/DeployBase.s.sol b/contracts/evm/script/DeployBase.s.sol new file mode 100644 index 0000000000..9ddfc7430e --- /dev/null +++ b/contracts/evm/script/DeployBase.s.sol @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.24; + +import {Script} from "forge-std/Script.sol"; +import {console2} from "forge-std/console2.sol"; +import {Chutes} from "../src/Chutes.sol"; +import {MockUSDC} from "../src/MockUSDC.sol"; +import {RailsPortal} from "../src/RailsPortal.sol"; + +/// Deploys the fake-Base (anvil) side: mock USDC, the buy/sell portal, and +/// one rebasing share token per catalog subnet. Hub wiring (configureHub, +/// setToken, setHubReleaser) happens in deploy-contracts.sh once the hub +/// facts are known. +/// Env: RAILS_OWNER, RAILS_MAILBOX (Hyperlane mailbox on anvil), +/// RAILS_HUB_DOMAIN (Bittensor domain id), RAILS_GATEWAY (Gateway address on +/// the Bittensor EVM), RAILS_USD_ASSET_ID, RAILS_SALT, and RAILS_TOKENS as +/// "Name|SYMBOL,Name|SYMBOL,..." in catalog order. +contract DeployBase is Script { + function run() external { + address owner = vm.envAddress("RAILS_OWNER"); + address mailbox = vm.envAddress("RAILS_MAILBOX"); + uint32 hubDomain = uint32(vm.envUint("RAILS_HUB_DOMAIN")); + address gateway = vm.envAddress("RAILS_GATEWAY"); + uint32 usdAssetId = uint32(vm.envOr("RAILS_USD_ASSET_ID", uint256(0))); + bytes32 salt = keccak256(bytes(vm.envOr("RAILS_SALT", string("rails-local-v1")))); + string memory tokens = vm.envOr("RAILS_TOKENS", string("Chutes|CHUTES")); + + vm.startBroadcast(); + MockUSDC usdc = new MockUSDC{salt: salt}(); + RailsPortal portal = new RailsPortal{salt: salt}( + owner, + address(usdc), + mailbox, + hubDomain, + usdAssetId, + bytes32(uint256(uint160(gateway))) + ); + + // Consumed by the rig manifest writer. + console2.log("MOCK_USDC", address(usdc)); + console2.log("PORTAL", address(portal)); + + // One share token per "Name|SYMBOL" entry; the salt folds in the + // symbol so every token gets a stable CREATE2 address. + string[] memory entries = split(tokens, ","); + for (uint256 i = 0; i < entries.length; i++) { + string[] memory parts = split(entries[i], "|"); + require(parts.length == 2, "bad RAILS_TOKENS entry"); + Chutes token = new Chutes{salt: keccak256(abi.encodePacked(salt, parts[1]))}( + owner, parts[0], parts[1] + ); + console2.log(string.concat("TOKEN_", vm.toString(i)), address(token)); + } + vm.stopBroadcast(); + } + + function split(string memory input, string memory sep) + internal + pure + returns (string[] memory parts) + { + bytes memory data = bytes(input); + bytes1 delim = bytes(sep)[0]; + uint256 count = 1; + for (uint256 i = 0; i < data.length; i++) { + if (data[i] == delim) count++; + } + parts = new string[](count); + uint256 part = 0; + uint256 start = 0; + for (uint256 i = 0; i <= data.length; i++) { + if (i == data.length || data[i] == delim) { + bytes memory chunk = new bytes(i - start); + for (uint256 j = start; j < i; j++) { + chunk[j - start] = data[j]; + } + parts[part++] = string(chunk); + start = i + 1; + } + } + } +} diff --git a/contracts/evm/script/DeployBittensor.s.sol b/contracts/evm/script/DeployBittensor.s.sol new file mode 100644 index 0000000000..eff32f20ba --- /dev/null +++ b/contracts/evm/script/DeployBittensor.s.sol @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.24; + +import {Script} from "forge-std/Script.sol"; +import {console2} from "forge-std/console2.sol"; +import {CanonicalShareToken} from "../src/CanonicalShareToken.sol"; +import {Gateway} from "../src/Gateway.sol"; + +/// Deploys the Bittensor-EVM side: canonical USD token + Gateway. +/// Env: RAILS_OWNER, RAILS_MAILBOX (Hyperlane mailbox on Bittensor EVM), +/// RAILS_PSM_ESCROW (H160 mirror of the pallet escrow), RAILS_SALT. +contract DeployBittensor is Script { + function run() external { + address owner = vm.envAddress("RAILS_OWNER"); + address mailbox = vm.envAddress("RAILS_MAILBOX"); + address psmEscrow = vm.envAddress("RAILS_PSM_ESCROW"); + bytes32 salt = keccak256(bytes(vm.envOr("RAILS_SALT", string("rails-local-v1")))); + + vm.startBroadcast(); + CanonicalShareToken canonicalUsd = + new CanonicalShareToken{salt: salt}("Canonical USD", "cUSD", owner); + Gateway gateway = + new Gateway{salt: salt}(owner, mailbox, address(canonicalUsd), psmEscrow); + vm.stopBroadcast(); + + // Consumed by the rig manifest writer. + console2.log("CANONICAL_USD", address(canonicalUsd)); + console2.log("GATEWAY", address(gateway)); + } +} diff --git a/contracts/evm/src/BaseERC20.sol b/contracts/evm/src/BaseERC20.sol new file mode 100644 index 0000000000..7f8940efda --- /dev/null +++ b/contracts/evm/src/BaseERC20.sol @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.24; + +/// @notice Minimal ERC-20 base for the local rails rig. Production +/// deployments replace this with the audited xERC-20 reference +/// implementation; the external surface is kept compatible. +abstract contract BaseERC20 { + string public name; + string public symbol; + + /// @dev Rails rule: 9 decimals for every canonical asset on every chain. + uint8 public constant decimals = 9; + + uint256 public totalSupply; + mapping(address => uint256) public balanceOf; + mapping(address => mapping(address => uint256)) public allowance; + + event Transfer(address indexed from, address indexed to, uint256 value); + event Approval(address indexed owner, address indexed spender, uint256 value); + + constructor(string memory name_, string memory symbol_) { + name = name_; + symbol = symbol_; + } + + function transfer(address to, uint256 value) external returns (bool) { + _transfer(msg.sender, to, value); + return true; + } + + function approve(address spender, uint256 value) external returns (bool) { + allowance[msg.sender][spender] = value; + emit Approval(msg.sender, spender, value); + return true; + } + + function transferFrom(address from, address to, uint256 value) external returns (bool) { + uint256 allowed = allowance[from][msg.sender]; + if (allowed != type(uint256).max) { + require(allowed >= value, "ERC20: insufficient allowance"); + allowance[from][msg.sender] = allowed - value; + } + _transfer(from, to, value); + return true; + } + + function _transfer(address from, address to, uint256 value) internal { + require(to != address(0), "ERC20: transfer to zero"); + uint256 fromBalance = balanceOf[from]; + require(fromBalance >= value, "ERC20: insufficient balance"); + unchecked { + balanceOf[from] = fromBalance - value; + balanceOf[to] += value; + } + emit Transfer(from, to, value); + } + + function _mint(address to, uint256 value) internal { + require(to != address(0), "ERC20: mint to zero"); + totalSupply += value; + unchecked { + balanceOf[to] += value; + } + emit Transfer(address(0), to, value); + } + + function _burn(address from, uint256 value) internal { + uint256 fromBalance = balanceOf[from]; + require(fromBalance >= value, "ERC20: burn exceeds balance"); + unchecked { + balanceOf[from] = fromBalance - value; + totalSupply -= value; + } + emit Transfer(from, address(0), value); + } +} diff --git a/contracts/evm/src/CanonicalShareToken.sol b/contracts/evm/src/CanonicalShareToken.sol new file mode 100644 index 0000000000..c1519336c5 --- /dev/null +++ b/contracts/evm/src/CanonicalShareToken.sol @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.24; + +import {BaseERC20} from "./BaseERC20.sol"; +import {RateLimits} from "./RateLimits.sol"; + +/// @notice Chain-owned canonical token: rate-limited multi-minter ERC-20 +/// (xERC-20 style). Used as the canonical USD backing token on the Bittensor +/// EVM, minted by the Gateway when portal deposits arrive. +/// +/// Trust model: the owner (chain governance; locally the deployer) grants +/// each bridge adapter a linear-refill mint window. A compromised minter is +/// bounded by its window and revocable instantly. +contract CanonicalShareToken is BaseERC20 { + using RateLimits for RateLimits.Window; + + address public owner; + + /// Per-minter mint windows for local bridge adapters. + mapping(address => RateLimits.Window) public minterWindows; + mapping(address => bool) public isMinter; + + event MinterLimitsSet(address indexed minter, uint64 limit, uint64 refillPerSecond); + event MinterRemoved(address indexed minter); + + modifier onlyOwner() { + require(msg.sender == owner, "not owner"); + _; + } + + constructor(string memory name_, string memory symbol_, address owner_) + BaseERC20(name_, symbol_) + { + require(owner_ != address(0), "owner zero"); + owner = owner_; + } + + // ---------------------------------------------------------------- admin + + function transferOwnership(address next) external onlyOwner { + require(next != address(0), "owner zero"); + owner = next; + } + + /// @notice Grant or update a bridge adapter's mint window. + function setMinterLimits(address minter, uint64 limit, uint64 refillPerSecond) + external + onlyOwner + { + isMinter[minter] = true; + RateLimits.Window storage w = minterWindows[minter]; + w.limit = limit; + w.refillPerTick = refillPerSecond; + w.lastTick = uint64(block.timestamp); + emit MinterLimitsSet(minter, limit, refillPerSecond); + } + + /// @notice Instantly revoke a minter (the emergency path). + function removeMinter(address minter) external onlyOwner { + isMinter[minter] = false; + delete minterWindows[minter]; + emit MinterRemoved(minter); + } + + // -------------------------------------------------------------- minting + + /// @notice Mint within the caller's rate window. + function mint(address to, uint64 amount) external { + require(isMinter[msg.sender], "not minter"); + require( + minterWindows[msg.sender].tryReserve(uint64(block.timestamp), amount), + "mint rate limited" + ); + _mint(to, amount); + } + + /// @notice Burn from `from` with allowance semantics (bridge withdraws). + function burnFrom(address from, uint64 amount) external { + require(isMinter[msg.sender], "not minter"); + if (from != msg.sender) { + uint256 allowed = allowance[from][msg.sender]; + require(allowed >= amount, "burn allowance"); + if (allowed != type(uint256).max) { + allowance[from][msg.sender] = allowed - amount; + } + } + _burn(from, amount); + // Burning frees mint headroom for the adapter that owns the flow. + minterWindows[msg.sender].release(uint64(block.timestamp), amount); + } + +} diff --git a/contracts/evm/src/Chutes.sol b/contracts/evm/src/Chutes.sol new file mode 100644 index 0000000000..48c3bd9c44 --- /dev/null +++ b/contracts/evm/src/Chutes.sol @@ -0,0 +1,204 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.24; + +import {EnvelopeLib} from "./EnvelopeLib.sol"; +import {IMailbox} from "./interfaces/IMailbox.sol"; +import {IMessageRecipient} from "./interfaces/IMessageRecipient.sol"; +import {RailsPortal} from "./RailsPortal.sol"; + +/// @notice The canonical share token for one subnet's staked alpha, held in +/// the hub escrow on Bittensor (name/symbol per subnet, e.g. Chutes/CHUTES +/// for netuid 64). Rebasing display (stETH-style): +/// accounts hold shares, `balanceOf` returns `shares * indexE9 / 1e9`, and +/// the index — escrowed alpha per share — only ever moves via hub messages, +/// so the wallet balance ticks upward as the escrow earns emissions. +/// +/// There is no owner-settable price and no local mint authority: shares are +/// minted exclusively by hub message (a completed buy) and burned by +/// `sell()`, which dispatches the sell envelope to the hub. +contract Chutes is IMessageRecipient { + string public name; + string public symbol; + uint8 public constant decimals = 9; + + address public owner; + + /// Hyperlane wiring: mint/index messages come from the keyless runtime + /// identity (`hubSender`); sell envelopes go to the Gateway contract on + /// the hub (`hubRecipient`). + IMailbox public mailbox; + uint32 public hubDomain; + bytes32 public hubSender; + bytes32 public hubRecipient; + /// The portal on this chain: shared sequential-nonce source (the hub + /// executes envelopes in strict nonce order across buys and sells). + RailsPortal public portal; + /// The one subnet this token wraps. + uint16 public netuid; + /// PSM asset released on sells (the portal's USDC). + uint32 public usdAssetId; + + /// Share index in 1e9 fixed point: alpha per share at the hub. Rises as + /// the escrow earns emissions; set only via hub message in `handle`. + uint64 public indexE9 = 1_000_000_000; + + mapping(address => uint256) public sharesOf; + uint256 public totalShares; + mapping(address => mapping(address => uint256)) public allowance; + + event Transfer(address indexed from, address indexed to, uint256 value); + event Approval(address indexed owner, address indexed spender, uint256 value); + event HubConfigured( + address mailbox, + uint32 hubDomain, + bytes32 hubSender, + bytes32 hubRecipient, + address portal, + uint16 netuid, + uint32 usdAssetId + ); + event HubMint(address indexed to, uint64 shares, uint64 indexE9); + event IndexUpdated(uint64 indexE9); + event SoldToHub( + address indexed from, uint64 shares, uint64 minUsd, uint64 indexed nonce, bytes32 messageId + ); + + modifier onlyOwner() { + require(msg.sender == owner, "not owner"); + _; + } + + constructor(address owner_, string memory name_, string memory symbol_) { + require(owner_ != address(0), "owner zero"); + require(bytes(name_).length > 0 && bytes(symbol_).length > 0, "name empty"); + owner = owner_; + name = name_; + symbol = symbol_; + } + + // ---------------------------------------------------------------- admin + + function transferOwnership(address next) external onlyOwner { + require(next != address(0), "owner zero"); + owner = next; + } + + /// @notice Wire the hub path. Deployment-time only; there is no other + /// admin surface (no local mint, no owner-set index). + function configureHub( + address mailbox_, + uint32 hubDomain_, + bytes32 hubSender_, + bytes32 hubRecipient_, + address portal_, + uint16 netuid_, + uint32 usdAssetId_ + ) external onlyOwner { + mailbox = IMailbox(mailbox_); + hubDomain = hubDomain_; + hubSender = hubSender_; + hubRecipient = hubRecipient_; + portal = RailsPortal(portal_); + netuid = netuid_; + usdAssetId = usdAssetId_; + emit HubConfigured( + mailbox_, hubDomain_, hubSender_, hubRecipient_, portal_, netuid_, usdAssetId_ + ); + } + + // ------------------------------------------------------ rebasing ERC-20 + + /// @notice Display balance: shares priced at the current hub index. + function balanceOf(address account) public view returns (uint256) { + return (sharesOf[account] * uint256(indexE9)) / 1e9; + } + + function totalSupply() external view returns (uint256) { + return (totalShares * uint256(indexE9)) / 1e9; + } + + /// @notice Shares represented by a display `amount` at the current index. + function sharesForAmount(uint256 amount) public view returns (uint256) { + return (amount * 1e9) / uint256(indexE9); + } + + function transfer(address to, uint256 amount) external returns (bool) { + _transfer(msg.sender, to, amount); + return true; + } + + function approve(address spender, uint256 amount) external returns (bool) { + allowance[msg.sender][spender] = amount; + emit Approval(msg.sender, spender, amount); + return true; + } + + function transferFrom(address from, address to, uint256 amount) external returns (bool) { + uint256 allowed = allowance[from][msg.sender]; + if (allowed != type(uint256).max) { + require(allowed >= amount, "ERC20: insufficient allowance"); + allowance[from][msg.sender] = allowed - amount; + } + _transfer(from, to, amount); + return true; + } + + function _transfer(address from, address to, uint256 amount) internal { + require(to != address(0), "ERC20: transfer to zero"); + uint256 shares = sharesForAmount(amount); + uint256 fromShares = sharesOf[from]; + require(fromShares >= shares, "ERC20: insufficient balance"); + unchecked { + sharesOf[from] = fromShares - shares; + sharesOf[to] += shares; + } + emit Transfer(from, to, amount); + } + + // ------------------------------------------------------------- hub path + + /// @notice Hyperlane delivery from the hub. Body: + /// abi.encode(address to, uint64 shares, uint64 indexE9). A zero `to` + /// with zero shares is a pure index heartbeat. This is the only way the + /// index moves. + function handle(uint32 origin, bytes32 sender, bytes calldata body) external payable override { + require(msg.sender == address(mailbox), "not mailbox"); + require(origin == hubDomain && sender == hubSender, "untrusted hub"); + (address to, uint64 shares, uint64 newIndexE9) = + abi.decode(body, (address, uint64, uint64)); + if (newIndexE9 > 0) { + indexE9 = newIndexE9; + emit IndexUpdated(newIndexE9); + } + if (shares > 0 && to != address(0)) { + sharesOf[to] += shares; + totalShares += shares; + emit HubMint(to, shares, indexE9); + emit Transfer(address(0), to, (uint256(shares) * uint256(indexE9)) / 1e9); + } + } + + /// @notice Burn `shares` and dispatch the sell envelope: the hub + /// unstakes escrow alpha, swaps to USD, and releases USDC to the caller + /// through the portal on this chain. Use `sharesOf(you)` to sell all. + function sell(uint64 shares, uint64 minUsd) external payable returns (bytes32 messageId) { + require(address(mailbox) != address(0) && hubRecipient != bytes32(0), "hub not configured"); + require(shares > 0, "shares zero"); + uint256 fromShares = sharesOf[msg.sender]; + require(fromShares >= shares, "sell exceeds balance"); + unchecked { + sharesOf[msg.sender] = fromShares - shares; + totalShares -= shares; + } + emit Transfer(msg.sender, address(0), (uint256(shares) * uint256(indexE9)) / 1e9); + + uint64 nonce = portal.assignNonce(); + bytes memory envelope = EnvelopeLib.sellShares( + netuid, shares, msg.sender, usdAssetId, minUsd, mailbox.localDomain(), nonce + ); + messageId = mailbox.dispatch{value: msg.value}( + hubDomain, hubRecipient, abi.encode(uint64(shares), envelope) + ); + emit SoldToHub(msg.sender, shares, minUsd, nonce, messageId); + } +} diff --git a/contracts/evm/src/EnvelopeLib.sol b/contracts/evm/src/EnvelopeLib.sol new file mode 100644 index 0000000000..a72464634e --- /dev/null +++ b/contracts/evm/src/EnvelopeLib.sol @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.24; + +/// @notice SCALE encoders for the runtime's v1 gateway envelope, built +/// on-chain so buys and sells are single-transaction UX. Byte-for-byte +/// mirror of `subtensor_runtime_common::rails::GatewayEnvelope::to_wire` +/// (see the golden vectors in `common/src/rails.rs` and +/// `ts-tests/suites/rails/fixtures/golden-envelopes.json`). +/// +/// Layout: [version=1] ++ SCALE(asset, amount, dest, action, nonce), with +/// all integers little-endian and `dest` a raw 32-byte account (zero for +/// buy/sell: the runtime derives the fallback destination from the EVM +/// recipient). +library EnvelopeLib { + /// AssetId::Usd(id) codec index. + uint8 internal constant ASSET_USD = 3; + /// AssetId::Alpha(netuid) codec index. + uint8 internal constant ASSET_ALPHA = 2; + /// GatewayAction::BuyShares codec index. + uint8 internal constant ACTION_BUY_SHARES = 4; + /// GatewayAction::SellShares codec index. + uint8 internal constant ACTION_SELL_SHARES = 5; + + function u16le(uint16 v) internal pure returns (bytes2) { + return bytes2(uint16((v >> 8) | (v << 8))); + } + + function u32le(uint32 v) internal pure returns (bytes4) { + v = ((v >> 8) & 0x00FF00FF) | ((v & 0x00FF00FF) << 8); + v = (v >> 16) | (v << 16); + return bytes4(v); + } + + function u64le(uint64 v) internal pure returns (bytes8) { + v = ((v >> 8) & 0x00FF00FF00FF00FF) | ((v & 0x00FF00FF00FF00FF) << 8); + v = ((v >> 16) & 0x0000FFFF0000FFFF) | ((v & 0x0000FFFF0000FFFF) << 16); + v = (v >> 32) | (v << 32); + return bytes8(v); + } + + /// @notice BuyShares envelope: USD deposit -> staked alpha -> shares + /// minted to `recipient` on `domain` (the spoke chain's own domain). + function buyShares( + uint32 usdAssetId, + uint64 amountUsd, + uint16 netuid, + address recipient, + uint64 minAlpha, + uint32 domain, + uint64 nonce + ) internal pure returns (bytes memory) { + return abi.encodePacked( + uint8(1), // envelope version + ASSET_USD, + u32le(usdAssetId), + u64le(amountUsd), + bytes32(0), // dest: runtime uses the recipient's mirror account + ACTION_BUY_SHARES, + u16le(netuid), + recipient, + u64le(minAlpha), + u32le(domain), + u64le(nonce) + ); + } + + /// @notice SellShares envelope: `shares` were burned on the spoke; the + /// runtime unstakes escrow alpha and releases USD to `recipient` on + /// `domain`. + function sellShares( + uint16 netuid, + uint64 shares, + address recipient, + uint32 usdAssetId, + uint64 minUsd, + uint32 domain, + uint64 nonce + ) internal pure returns (bytes memory) { + return abi.encodePacked( + uint8(1), // envelope version + ASSET_ALPHA, + u16le(netuid), + u64le(shares), + bytes32(0), + ACTION_SELL_SHARES, + u16le(netuid), + recipient, + u32le(usdAssetId), + u64le(minUsd), + u32le(domain), + u64le(nonce) + ); + } +} diff --git a/contracts/evm/src/Gateway.sol b/contracts/evm/src/Gateway.sol new file mode 100644 index 0000000000..fdd63feb7c --- /dev/null +++ b/contracts/evm/src/Gateway.sol @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.24; + +import {CanonicalShareToken} from "./CanonicalShareToken.sol"; +import {IMessageRecipient} from "./interfaces/IMessageRecipient.sol"; +import {IUsdRails, IUSD_RAILS_ADDRESS} from "./interfaces/IUsdRails.sol"; + +/// @notice The single inbound door on the Bittensor EVM. Receives Hyperlane +/// messages, secures the deposit (mints canonical USD to the PSM escrow for +/// portal deposits), then hands the opaque SCALE envelope to the runtime via +/// the 0x814 precompile. +/// +/// Failure discipline: this contract only reverts while funds are still safe +/// at origin (untrusted sender, rate-limited mint) — Hyperlane retries +/// delivery. Once `gatewayExecute` is reached, the runtime never reverts: +/// action failures fall back to a tUSD credit. +contract Gateway is IMessageRecipient { + enum SenderKind { + None, + UsdPortal, // origin locks USD; we mint canonical USD backing here + RemoteToken // origin burned canonical shares; runtime releases escrow + } + + address public owner; + address public mailbox; + CanonicalShareToken public canonicalUsd; + /// Keyless PSM escrow account (H160 mirror of the pallet escrow). + address public psmEscrow; + + /// Trusted remote senders per (origin domain, sender address). + mapping(uint32 => mapping(bytes32 => SenderKind)) public trustedSenders; + + event TrustedSenderSet(uint32 indexed origin, bytes32 indexed sender, SenderKind kind); + event InboundExecuted(uint32 indexed origin, bytes32 indexed sender, uint64 amount); + + modifier onlyOwner() { + require(msg.sender == owner, "not owner"); + _; + } + + constructor(address owner_, address mailbox_, address canonicalUsd_, address psmEscrow_) { + require(owner_ != address(0), "owner zero"); + owner = owner_; + mailbox = mailbox_; + canonicalUsd = CanonicalShareToken(canonicalUsd_); + psmEscrow = psmEscrow_; + } + + function setTrustedSender(uint32 origin, bytes32 sender, SenderKind kind) external onlyOwner { + trustedSenders[origin][sender] = kind; + emit TrustedSenderSet(origin, sender, kind); + } + + /// @notice Hyperlane delivery. Body: abi.encode(uint64 amount, bytes envelope). + function handle(uint32 origin, bytes32 sender, bytes calldata body) external payable override { + require(msg.sender == mailbox, "not mailbox"); + SenderKind kind = trustedSenders[origin][sender]; + require(kind != SenderKind.None, "untrusted sender"); + + (uint64 amount, bytes memory envelope) = abi.decode(body, (uint64, bytes)); + + if (kind == SenderKind.UsdPortal && amount > 0) { + // Secure the backing first: canonical USD into the PSM escrow. + // Reverts here (e.g. mint window exhausted) leave funds locked at + // origin and let the relayer retry later. + canonicalUsd.mint(psmEscrow, amount); + } + + IUsdRails(IUSD_RAILS_ADDRESS).gatewayExecute(amount, envelope); + emit InboundExecuted(origin, sender, amount); + } +} diff --git a/contracts/evm/src/MockUSDC.sol b/contracts/evm/src/MockUSDC.sol new file mode 100644 index 0000000000..7fed4e9862 --- /dev/null +++ b/contracts/evm/src/MockUSDC.sol @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.24; + +import {BaseERC20} from "./BaseERC20.sol"; + +/// @notice Test-only stand-in for USDC on the fake Base chain (anvil). +/// Anyone can mint; 9 decimals per the rails rule (a production portal for +/// real 6-decimal USDC carries a decimal adapter instead). +contract MockUSDC is BaseERC20 { + constructor() BaseERC20("Mock USDC", "USDC") {} + + function mint(address to, uint256 amount) external { + _mint(to, amount); + } +} diff --git a/contracts/evm/src/RailsPortal.sol b/contracts/evm/src/RailsPortal.sol new file mode 100644 index 0000000000..f611ca3bc7 --- /dev/null +++ b/contracts/evm/src/RailsPortal.sol @@ -0,0 +1,138 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.24; + +import {BaseERC20} from "./BaseERC20.sol"; +import {EnvelopeLib} from "./EnvelopeLib.sol"; +import {IMailbox} from "./interfaces/IMailbox.sol"; +import {IMessageRecipient} from "./interfaces/IMessageRecipient.sol"; + +/// @notice Origin-chain (Base) gateway: `buy()` locks USDC and sends a +/// BuyShares envelope to the Bittensor hub in one transaction; the hub +/// releases locked USDC back through `handle()` when shares are sold. +/// +/// This contract owns the sequential envelope nonce for its chain: the hub +/// executes envelopes in strict nonce order, so every dispatcher (buys here, +/// sells on the subnet share tokens) draws from this one counter. +contract RailsPortal is IMessageRecipient { + address public owner; + BaseERC20 public immutable usd; + IMailbox public immutable mailbox; + uint32 public immutable hubDomain; + /// PSM asset id of `usd` on the hub. + uint32 public immutable usdAssetId; + /// The Gateway contract on the Bittensor EVM, as bytes32. + bytes32 public gateway; + /// The hub-side sender allowed to release collateral (the keyless + /// runtime identity), as bytes32. + bytes32 public hubReleaser; + /// Subnet share tokens on this chain (may draw nonces for sell + /// envelopes), keyed by token address. + mapping(address => bool) public isToken; + + /// Next sequential envelope nonce; mirrors the hub's NextNonce. + uint64 public nextNonce; + + event Bought( + address indexed from, + uint64 amountUsd, + uint16 netuid, + uint64 indexed nonce, + bytes32 messageId + ); + event Deposited( + address indexed from, uint64 amount, uint64 indexed nonce, bytes32 messageId + ); + event Released(address indexed to, uint64 amount); + + modifier onlyOwner() { + require(msg.sender == owner, "not owner"); + _; + } + + constructor( + address owner_, + address usd_, + address mailbox_, + uint32 hubDomain_, + uint32 usdAssetId_, + bytes32 gateway_ + ) { + require(owner_ != address(0), "owner zero"); + owner = owner_; + usd = BaseERC20(usd_); + mailbox = IMailbox(mailbox_); + hubDomain = hubDomain_; + usdAssetId = usdAssetId_; + gateway = gateway_; + } + + function setGateway(bytes32 gateway_) external onlyOwner { + gateway = gateway_; + } + + function setHubReleaser(bytes32 releaser) external onlyOwner { + hubReleaser = releaser; + } + + function setToken(address token, bool allowed) external onlyOwner { + isToken[token] = allowed; + } + + /// @notice Draw the next sequential envelope nonce. Only registered + /// share tokens may call (an open counter would let anyone burn nonces + /// and stall the hub's strict ordering). + function assignNonce() external returns (uint64 nonce) { + require(isToken[msg.sender], "not token"); + nonce = nextNonce++; + } + + /// @notice Buy CHUTES with USDC in one transaction: locks `amountUsd`, + /// builds the BuyShares envelope, and dispatches it to the hub. The hub + /// mints tUSD, swaps to TAO, stakes into the escrow, and messages the + /// share mint back to `msg.sender` on this chain. + function buy(uint64 amountUsd, uint16 netuid, uint64 minAlpha) + external + payable + returns (bytes32 messageId, uint64 nonce) + { + require(amountUsd > 0, "amount zero"); + require(usd.transferFrom(msg.sender, address(this), amountUsd), "lock failed"); + nonce = nextNonce++; + bytes memory envelope = EnvelopeLib.buyShares( + usdAssetId, amountUsd, netuid, msg.sender, minAlpha, mailbox.localDomain(), nonce + ); + messageId = mailbox.dispatch{value: msg.value}( + hubDomain, gateway, abi.encode(amountUsd, envelope) + ); + emit Bought(msg.sender, amountUsd, netuid, nonce, messageId); + } + + /// @notice Generic deposit door (kept for drills and the tUSD-credit + /// fallback path): locks `amount` USD and dispatches `envelopePrefix` + /// with the portal-assigned sequential nonce appended. The prefix is the + /// SCALE envelope minus its trailing u64 nonce. + function deposit(uint64 amount, bytes calldata envelopePrefix) + external + payable + returns (bytes32 messageId, uint64 nonce) + { + require(amount > 0, "amount zero"); + require(usd.transferFrom(msg.sender, address(this), amount), "lock failed"); + nonce = nextNonce++; + bytes memory envelope = abi.encodePacked(envelopePrefix, EnvelopeLib.u64le(nonce)); + messageId = mailbox.dispatch{value: msg.value}( + hubDomain, gateway, abi.encode(amount, envelope) + ); + emit Deposited(msg.sender, amount, nonce, messageId); + } + + /// @notice Hub releases locked collateral (sell proceeds). + /// Body: abi.encode(address to, uint64 amount). + function handle(uint32 origin, bytes32 sender, bytes calldata body) external payable override { + require(msg.sender == address(mailbox), "not mailbox"); + require(origin == hubDomain && sender == hubReleaser, "untrusted releaser"); + (address to, uint64 amount) = abi.decode(body, (address, uint64)); + require(usd.transfer(to, amount), "release failed"); + emit Released(to, amount); + } +} diff --git a/contracts/evm/src/RateLimits.sol b/contracts/evm/src/RateLimits.sol new file mode 100644 index 0000000000..f70dc67693 --- /dev/null +++ b/contracts/evm/src/RateLimits.sol @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.24; + +/// @notice The single rails rate-limit algorithm: a linearly-refilling +/// window. This mirrors `subtensor_runtime_common::rails::RateWindow` exactly +/// (saturating semantics), with "ticks" abstract: the runtime uses block +/// numbers, contracts use `block.timestamp` seconds. +library RateLimits { + struct Window { + uint64 limit; + uint64 used; + uint64 refillPerTick; + uint64 lastTick; + } + + /// @notice Decay `used` according to elapsed ticks (saturating). + function refresh(Window storage w, uint64 nowTick) internal { + uint64 last = w.lastTick; + uint64 elapsed = nowTick > last ? nowTick - last : 0; + uint256 refill = uint256(elapsed) * uint256(w.refillPerTick); + uint64 used = w.used; + // Safe: in the false branch refill < used <= u64::MAX. + // forge-lint: disable-next-line(unsafe-typecast) + w.used = refill >= used ? 0 : used - uint64(refill); + w.lastTick = nowTick; + } + + /// @notice Headroom available at `nowTick` without mutating storage. + function available(Window storage w, uint64 nowTick) internal view returns (uint64) { + uint64 last = w.lastTick; + uint64 elapsed = nowTick > last ? nowTick - last : 0; + uint256 refill = uint256(elapsed) * uint256(w.refillPerTick); + uint64 used = w.used; + // Safe: in the false branch refill < used <= u64::MAX. + // forge-lint: disable-next-line(unsafe-typecast) + uint64 decayed = refill >= used ? 0 : used - uint64(refill); + uint64 limit = w.limit; + return limit > decayed ? limit - decayed : 0; + } + + /// @notice Atomically consume headroom; returns false if insufficient. + function tryReserve(Window storage w, uint64 nowTick, uint64 amount) internal returns (bool) { + refresh(w, nowTick); + uint256 next = uint256(w.used) + uint256(amount); + if (next > w.limit) { + return false; + } + // Safe: next <= w.limit which is a uint64. + // forge-lint: disable-next-line(unsafe-typecast) + w.used = uint64(next); + return true; + } + + /// @notice Release previously consumed headroom (saturating). + function release(Window storage w, uint64 nowTick, uint64 amount) internal { + refresh(w, nowTick); + uint64 used = w.used; + w.used = amount >= used ? 0 : used - amount; + } +} diff --git a/contracts/evm/src/interfaces/IMailbox.sol b/contracts/evm/src/interfaces/IMailbox.sol new file mode 100644 index 0000000000..5e3e99ef2d --- /dev/null +++ b/contracts/evm/src/interfaces/IMailbox.sol @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.24; + +/// @notice Minimal Hyperlane Mailbox surface used by the rails contracts. +interface IMailbox { + function dispatch(uint32 destinationDomain, bytes32 recipientAddress, bytes calldata messageBody) + external + payable + returns (bytes32 messageId); + + function quoteDispatch(uint32 destinationDomain, bytes32 recipientAddress, bytes calldata messageBody) + external + view + returns (uint256 fee); + + function localDomain() external view returns (uint32); +} diff --git a/contracts/evm/src/interfaces/IMessageRecipient.sol b/contracts/evm/src/interfaces/IMessageRecipient.sol new file mode 100644 index 0000000000..d4daf1f7ab --- /dev/null +++ b/contracts/evm/src/interfaces/IMessageRecipient.sol @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.24; + +/// @notice Hyperlane message recipient interface. +interface IMessageRecipient { + function handle(uint32 origin, bytes32 sender, bytes calldata messageBody) external payable; +} diff --git a/contracts/evm/src/interfaces/IUsdRails.sol b/contracts/evm/src/interfaces/IUsdRails.sol new file mode 100644 index 0000000000..a68dbad4a1 --- /dev/null +++ b/contracts/evm/src/interfaces/IUsdRails.sol @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.24; + +/// @notice Interface of the USD rails precompile at address 0x814 on the +/// Bittensor EVM. The envelope is an opaque, SCALE-encoded, versioned byte +/// string defined by the runtime (`subtensor_runtime_common::rails`); +/// Solidity never parses its internals. +/// +/// All amounts are in rails units: 9 decimals, matching rao. +interface IUsdRails { + /// @notice Execute an inbound gateway envelope. Callable only by the + /// registered Gateway contract. `amount` must equal the envelope's + /// internal amount; the runtime cross-checks and reverts on mismatch. + function gatewayExecute(uint64 amount, bytes calldata envelope) external; + + /// @notice Quote tUSD -> TAO through the canonical pool. + function simSwapUsdForTao(uint64 amountUsd) external view returns (uint64 taoOut); + + /// @notice Quote TAO -> tUSD through the canonical pool. + function simSwapTaoForUsd(uint64 amountTao) external view returns (uint64 usdOut); + + /// @notice tUSD ledger balance of a substrate account (public key bytes). + function tusdBalanceOf(bytes32 account) external view returns (uint64); + + /// @notice Canonical pool state: (taoReserve, tusdReserve, feeBps). + function poolState() external view returns (uint64, uint64, uint16); + + /// @notice The ERC-20 backing a registered PSM asset (zero if unknown). + function assetErc20(uint32 assetId) external view returns (address); + + /// @notice Share index (1e9 fixed point) for a subnet's canonical shares. + function shareIndexE9(uint16 netuid) external view returns (uint64); + + /// @notice Next inbound envelope nonce expected by the sequential guard. + function nextNonce() external view returns (uint64); +} + +address constant IUSD_RAILS_ADDRESS = 0x0000000000000000000000000000000000000814; diff --git a/contracts/evm/test/CanonicalShareToken.t.sol b/contracts/evm/test/CanonicalShareToken.t.sol new file mode 100644 index 0000000000..a6a2d45c8b --- /dev/null +++ b/contracts/evm/test/CanonicalShareToken.t.sol @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.24; + +import {Test} from "forge-std/Test.sol"; +import {CanonicalShareToken} from "../src/CanonicalShareToken.sol"; + +contract CanonicalShareTokenTest is Test { + CanonicalShareToken token; + + address owner = makeAddr("owner"); + address bridgeA = makeAddr("bridgeA"); + address user = makeAddr("user"); + + function setUp() public { + token = new CanonicalShareToken("Canonical USD", "cUSD", owner); + vm.prank(owner); + token.setMinterLimits(bridgeA, 1_000, 10); + } + + function testMinterWindowEnforced() public { + vm.startPrank(bridgeA); + token.mint(user, 1_000); + vm.expectRevert("mint rate limited"); + token.mint(user, 1); + // 10 seconds refill 100 units. + vm.warp(block.timestamp + 10); + token.mint(user, 100); + vm.stopPrank(); + assertEq(token.balanceOf(user), 1_100); + } + + function testRevokedMinterCannotMint() public { + vm.prank(owner); + token.removeMinter(bridgeA); + vm.prank(bridgeA); + vm.expectRevert("not minter"); + token.mint(user, 1); + } + + function testBurnReleasesMintHeadroom() public { + vm.startPrank(bridgeA); + token.mint(bridgeA, 1_000); + vm.expectRevert("mint rate limited"); + token.mint(bridgeA, 1); + token.burnFrom(bridgeA, 400); + token.mint(bridgeA, 400); + vm.stopPrank(); + assertEq(token.balanceOf(bridgeA), 1_000); + } +} diff --git a/contracts/evm/test/Chutes.t.sol b/contracts/evm/test/Chutes.t.sol new file mode 100644 index 0000000000..46bb0c70c3 --- /dev/null +++ b/contracts/evm/test/Chutes.t.sol @@ -0,0 +1,139 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.24; + +import {Test} from "forge-std/Test.sol"; +import {Chutes} from "../src/Chutes.sol"; +import {MockUSDC} from "../src/MockUSDC.sol"; +import {RailsPortal} from "../src/RailsPortal.sol"; +import {MockMailbox} from "./mocks/MockMailbox.sol"; + +/// CHUTES rebasing display, hub-only index, sell path, and the Solidity +/// envelope encoders replayed against the Rust golden vectors +/// (`common/src/rails.rs::envelope_golden_vectors`). +contract ChutesTest is Test { + uint32 constant BASE_DOMAIN = 8453; + uint32 constant HUB_DOMAIN = 964; + uint16 constant NETUID = 64; + + MockMailbox mailbox; + MockUSDC usdc; + RailsPortal portal; + Chutes chutes; + + address owner = makeAddr("owner"); + address user = makeAddr("user"); + address other = makeAddr("other"); + /// Anvil account #0: the recipient pinned in the Rust golden vectors. + address golden = 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266; + + bytes32 hubSender = bytes32(uint256(uint160(makeAddr("hubSystem")))); + bytes32 hubGateway = bytes32(uint256(uint160(makeAddr("hubGateway")))); + + function setUp() public { + mailbox = new MockMailbox(BASE_DOMAIN); + usdc = new MockUSDC(); + portal = new RailsPortal( + owner, address(usdc), address(mailbox), HUB_DOMAIN, 0, hubGateway + ); + chutes = new Chutes(owner, "Chutes", "CHUTES"); + vm.startPrank(owner); + chutes.configureHub( + address(mailbox), HUB_DOMAIN, hubSender, hubGateway, address(portal), NETUID, 0 + ); + portal.setToken(address(chutes), true); + vm.stopPrank(); + } + + function mintShares(address to, uint64 shares, uint64 indexE9) internal { + mailbox.deliver(address(chutes), HUB_DOMAIN, hubSender, abi.encode(to, shares, indexE9)); + } + + function testHubMintAndRebasingBalance() public { + mintShares(user, 100_000_000_000, 1_000_000_000); + assertEq(chutes.sharesOf(user), 100_000_000_000); + assertEq(chutes.balanceOf(user), 100_000_000_000); + + // Heartbeat: index rises, balance ticks up with zero transfers. + mailbox.deliver( + address(chutes), + HUB_DOMAIN, + hubSender, + abi.encode(address(0), uint64(0), uint64(1_500_000_000)) + ); + assertEq(chutes.sharesOf(user), 100_000_000_000); + assertEq(chutes.balanceOf(user), 150_000_000_000); + assertEq(chutes.totalSupply(), 150_000_000_000); + } + + function testIndexOnlySettableByHubMessage() public { + bytes memory body = abi.encode(address(0), uint64(0), uint64(2_000_000_000)); + vm.expectRevert("untrusted hub"); + mailbox.deliver(address(chutes), HUB_DOMAIN, bytes32(uint256(1)), body); + + vm.expectRevert("not mailbox"); + chutes.handle(HUB_DOMAIN, hubSender, body); + + assertEq(chutes.indexE9(), 1_000_000_000); + } + + function testTransfersMoveShares() public { + mintShares(user, 100_000_000_000, 2_000_000_000); + assertEq(chutes.balanceOf(user), 200_000_000_000); + + vm.prank(user); + chutes.transfer(other, 100_000_000_000); // display units + assertEq(chutes.sharesOf(user), 50_000_000_000); + assertEq(chutes.sharesOf(other), 50_000_000_000); + assertEq(chutes.balanceOf(other), 100_000_000_000); + } + + function testSellBurnsSharesAndDispatches() public { + mintShares(user, 100_000_000_000, 1_000_000_000); + vm.prank(user); + chutes.sell(40_000_000_000, 0); + + assertEq(chutes.sharesOf(user), 60_000_000_000); + assertEq(chutes.totalShares(), 60_000_000_000); + assertEq(mailbox.lastDestination(), HUB_DOMAIN); + assertEq(mailbox.lastRecipient(), hubGateway); + (uint64 amount, bytes memory env) = abi.decode(mailbox.lastBody(), (uint64, bytes)); + assertEq(amount, 40_000_000_000); + assertGt(env.length, 0); + } + + function testAssignNonceOnlyRegisteredTokens() public { + vm.prank(user); + vm.expectRevert("not token"); + portal.assignNonce(); + } + + /// The Solidity encoders must reproduce the Rust golden vectors + /// byte-for-byte: buy at nonce 0, sell at nonce 1, sharing one counter. + function testGoldenEnvelopes() public { + usdc.mint(golden, 500_000_000_000); + vm.startPrank(golden); + usdc.approve(address(portal), type(uint256).max); + (, uint64 buyNonce) = portal.buy(500_000_000_000, NETUID, 1); + vm.stopPrank(); + assertEq(buyNonce, 0); + (uint64 buyAmount, bytes memory buyEnv) = + abi.decode(mailbox.lastBody(), (uint64, bytes)); + assertEq(buyAmount, 500_000_000_000); + assertEq( + buyEnv, + hex"0103000000000088526a740000000000000000000000000000000000000000000000000000000000000000000000044000f39fd6e51aad88f6f4ce6ab8827279cfffb922660100000000000000052100000000000000000000" + ); + + mintShares(golden, 2_000_000_000, 1_000_000_000); + vm.prank(golden); + chutes.sell(2_000_000_000, 1_000_000_000); + (uint64 sellAmount, bytes memory sellEnv) = + abi.decode(mailbox.lastBody(), (uint64, bytes)); + assertEq(sellAmount, 2_000_000_000); + assertEq( + sellEnv, + hex"0102400000943577000000000000000000000000000000000000000000000000000000000000000000000000054000f39fd6e51aad88f6f4ce6ab8827279cfffb922660000000000ca9a3b00000000052100000100000000000000" + ); + assertEq(portal.nextNonce(), 2); + } +} diff --git a/contracts/evm/test/GatewayPortal.t.sol b/contracts/evm/test/GatewayPortal.t.sol new file mode 100644 index 0000000000..c7cfa30dc7 --- /dev/null +++ b/contracts/evm/test/GatewayPortal.t.sol @@ -0,0 +1,150 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.24; + +import {Test} from "forge-std/Test.sol"; +import {CanonicalShareToken} from "../src/CanonicalShareToken.sol"; +import {Gateway} from "../src/Gateway.sol"; +import {MockUSDC} from "../src/MockUSDC.sol"; +import {RailsPortal} from "../src/RailsPortal.sol"; +import {IUSD_RAILS_ADDRESS} from "../src/interfaces/IUsdRails.sol"; +import {MockMailbox} from "./mocks/MockMailbox.sol"; +import {MockUsdRails} from "./mocks/MockUsdRails.sol"; + +/// End-to-end inbound flow over mock mailboxes: portal (Base) locks USDC and +/// dispatches; gateway (Bittensor EVM) mints canonical USD backing to the PSM +/// escrow and forwards the envelope to the 0x814 stub. +contract GatewayPortalTest is Test { + uint32 constant BASE_DOMAIN = 8453; + uint32 constant BT_DOMAIN = 964; + + MockMailbox baseMailbox; + MockMailbox btMailbox; + MockUSDC usdc; + RailsPortal portal; + CanonicalShareToken canonicalUsd; + Gateway gateway; + MockUsdRails rails; + + address owner = makeAddr("owner"); + address alice = makeAddr("alice"); + address psmEscrow = makeAddr("psmEscrow"); + + function setUp() public { + baseMailbox = new MockMailbox(BASE_DOMAIN); + btMailbox = new MockMailbox(BT_DOMAIN); + + // Etch the recording stub at the precompile address. + MockUsdRails impl = new MockUsdRails(); + vm.etch(IUSD_RAILS_ADDRESS, address(impl).code); + rails = MockUsdRails(IUSD_RAILS_ADDRESS); + + usdc = new MockUSDC(); + canonicalUsd = new CanonicalShareToken("Canonical USD", "cUSD", owner); + gateway = new Gateway(owner, address(btMailbox), address(canonicalUsd), psmEscrow); + portal = new RailsPortal( + owner, address(usdc), address(baseMailbox), BT_DOMAIN, 0, addr32(address(gateway)) + ); + + vm.startPrank(owner); + canonicalUsd.setMinterLimits(address(gateway), 1_000_000, 0); + gateway.setTrustedSender( + BASE_DOMAIN, addr32(address(portal)), Gateway.SenderKind.UsdPortal + ); + vm.stopPrank(); + + usdc.mint(alice, 500); + } + + function addr32(address a) internal pure returns (bytes32) { + return bytes32(uint256(uint160(a))); + } + + function testDepositLocksAndDispatchesWithSequentialNonce() public { + bytes memory prefix = hex"01aa"; + vm.startPrank(alice); + usdc.approve(address(portal), 500); + (, uint64 nonce) = portal.deposit(500, prefix); + vm.stopPrank(); + + assertEq(nonce, 0); + assertEq(portal.nextNonce(), 1); + assertEq(usdc.balanceOf(alice), 0); + assertEq(usdc.balanceOf(address(portal)), 500); + assertEq(baseMailbox.lastDestination(), BT_DOMAIN); + assertEq(baseMailbox.lastRecipient(), addr32(address(gateway))); + // The dispatched envelope is the prefix plus the little-endian nonce. + (, bytes memory env) = abi.decode(baseMailbox.lastBody(), (uint64, bytes)); + assertEq(env, abi.encodePacked(prefix, hex"0000000000000000")); + } + + function testBuyLocksAndDispatchesEnvelope() public { + vm.startPrank(alice); + usdc.approve(address(portal), 500); + (, uint64 nonce) = portal.buy(500, 64, 1); + vm.stopPrank(); + + assertEq(nonce, 0); + assertEq(usdc.balanceOf(address(portal)), 500); + assertEq(baseMailbox.lastRecipient(), addr32(address(gateway))); + (uint64 amount, bytes memory env) = abi.decode(baseMailbox.lastBody(), (uint64, bytes)); + assertEq(amount, 500); + assertGt(env.length, 0); + } + + function testInboundDeliveryMintsBackingAndCallsPrecompile() public { + bytes memory envelope = hex"01beef"; + bytes memory body = abi.encode(uint64(500), envelope); + + btMailbox.deliver(address(gateway), BASE_DOMAIN, addr32(address(portal)), body); + + assertEq(canonicalUsd.balanceOf(psmEscrow), 500); + assertEq(rails.gatewayExecuteCalls(), 1); + assertEq(rails.lastAmount(), 500); + assertEq(rails.lastEnvelope(), envelope); + assertEq(rails.lastCaller(), address(gateway)); + } + + function testZeroAmountPingSkipsMint() public { + // The walking-skeleton ping: amount 0, no backing minted. + bytes memory body = abi.encode(uint64(0), bytes(hex"01")); + btMailbox.deliver(address(gateway), BASE_DOMAIN, addr32(address(portal)), body); + assertEq(canonicalUsd.totalSupply(), 0); + assertEq(rails.gatewayExecuteCalls(), 1); + assertEq(rails.lastAmount(), 0); + } + + function testUntrustedSenderReverts() public { + bytes memory body = abi.encode(uint64(1), bytes(hex"01")); + vm.expectRevert("untrusted sender"); + btMailbox.deliver(address(gateway), BASE_DOMAIN, bytes32(uint256(0xbad)), body); + } + + function testMintWindowExhaustionRevertsDelivery() public { + // Delivery must revert (so the relayer retries) when the gateway's + // mint window cannot cover the deposit. + vm.prank(owner); + canonicalUsd.setMinterLimits(address(gateway), 100, 0); + bytes memory body = abi.encode(uint64(500), bytes(hex"01")); + vm.expectRevert("mint rate limited"); + btMailbox.deliver(address(gateway), BASE_DOMAIN, addr32(address(portal)), body); + } + + function testHubReleasePaysOutLockedCollateral() public { + // Lock collateral first. + bytes memory prefix = hex"01aa"; + vm.startPrank(alice); + usdc.approve(address(portal), 500); + portal.deposit(500, prefix); + vm.stopPrank(); + + bytes32 releaser = addr32(makeAddr("hubSystem")); + vm.prank(owner); + portal.setHubReleaser(releaser); + + baseMailbox.deliver( + address(portal), BT_DOMAIN, releaser, abi.encode(alice, uint64(200)) + ); + assertEq(usdc.balanceOf(alice), 200); + assertEq(usdc.balanceOf(address(portal)), 300); + } +} diff --git a/contracts/evm/test/RateLimits.t.sol b/contracts/evm/test/RateLimits.t.sol new file mode 100644 index 0000000000..1f0db3ee5c --- /dev/null +++ b/contracts/evm/test/RateLimits.t.sol @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.24; + +import {Test} from "forge-std/Test.sol"; +import {RateLimits} from "../src/RateLimits.sol"; + +/// Harness exposing the library on a storage window. +contract WindowHarness { + using RateLimits for RateLimits.Window; + + RateLimits.Window public w; + + constructor(uint64 limit, uint64 refill) { + w.limit = limit; + w.refillPerTick = refill; + } + + function tryReserve(uint64 nowTick, uint64 amount) external returns (bool) { + return w.tryReserve(nowTick, amount); + } + + function available(uint64 nowTick) external view returns (uint64) { + return w.available(nowTick); + } + + function release(uint64 nowTick, uint64 amount) external { + w.release(nowTick, amount); + } +} + +/// Mirrors the Rust unit tests in common/src/rails.rs so both sides of the +/// bridge provably run the same algorithm. +contract RateLimitsTest is Test { + function testReserveAndRefillParity() public { + WindowHarness h = new WindowHarness(100, 10); + assertTrue(h.tryReserve(0, 100)); + assertFalse(h.tryReserve(0, 1)); + // 5 ticks refill 50 units. + assertEq(h.available(5), 50); + assertTrue(h.tryReserve(5, 50)); + assertFalse(h.tryReserve(5, 1)); + // Full refill after long idle; never exceeds limit. + assertEq(h.available(1000), 100); + } + + function testReleaseParity() public { + WindowHarness h = new WindowHarness(100, 0); + assertTrue(h.tryReserve(0, 80)); + h.release(0, 30); + assertEq(h.available(0), 50); + // Releasing more than used saturates to zero used. + h.release(0, 1000); + assertEq(h.available(0), 100); + } +} diff --git a/contracts/evm/test/mocks/MockMailbox.sol b/contracts/evm/test/mocks/MockMailbox.sol new file mode 100644 index 0000000000..3d5a0597a9 --- /dev/null +++ b/contracts/evm/test/mocks/MockMailbox.sol @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.24; + +import {IMailbox} from "../../src/interfaces/IMailbox.sol"; +import {IMessageRecipient} from "../../src/interfaces/IMessageRecipient.sol"; + +/// @notice Test mailbox: records dispatches and can synchronously deliver a +/// message to a local recipient (playing both chains' mailboxes). +contract MockMailbox is IMailbox { + uint32 public immutable domain; + uint256 public dispatchCount; + + uint32 public lastDestination; + bytes32 public lastRecipient; + bytes public lastBody; + + constructor(uint32 domain_) { + domain = domain_; + } + + function dispatch(uint32 destinationDomain, bytes32 recipientAddress, bytes calldata body) + external + payable + returns (bytes32) + { + dispatchCount += 1; + lastDestination = destinationDomain; + lastRecipient = recipientAddress; + lastBody = body; + return keccak256(abi.encode(dispatchCount, destinationDomain, recipientAddress, body)); + } + + function quoteDispatch(uint32, bytes32, bytes calldata) external pure returns (uint256) { + return 0; + } + + function localDomain() external view returns (uint32) { + return domain; + } + + /// @notice Deliver a message as if relayed from (origin, sender). + function deliver(address recipient, uint32 origin, bytes32 sender, bytes calldata body) + external + { + IMessageRecipient(recipient).handle(origin, sender, body); + } +} diff --git a/contracts/evm/test/mocks/MockUsdRails.sol b/contracts/evm/test/mocks/MockUsdRails.sol new file mode 100644 index 0000000000..98ce7339af --- /dev/null +++ b/contracts/evm/test/mocks/MockUsdRails.sol @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.24; + +/// @notice Recording stub etched at the 0x814 precompile address in tests. +contract MockUsdRails { + uint256 public gatewayExecuteCalls; + uint64 public lastAmount; + bytes public lastEnvelope; + address public lastCaller; + bool public shouldRevert; + + function setShouldRevert(bool v) external { + shouldRevert = v; + } + + function gatewayExecute(uint64 amount, bytes calldata envelope) external { + require(!shouldRevert, "usd rails: forced revert"); + gatewayExecuteCalls += 1; + lastAmount = amount; + lastEnvelope = envelope; + lastCaller = msg.sender; + } +} diff --git a/demo/index.html b/demo/index.html new file mode 100644 index 0000000000..c6987df121 --- /dev/null +++ b/demo/index.html @@ -0,0 +1,1061 @@ + + + + + +Subnet tokens — staked alpha in your wallet + + + + +
+ +
Subnet tokens · rails demo
+
local
+
+ +
+
+

Every subnet in your wallet

+

+ One ERC-20 per subnet, each backed by real staked alpha on Bittensor. + Names, descriptions and logos come from the chain's subnet identities. + Buy with USDC on Base; balances tick upward as emissions accrue. + Sell any time; USDC comes back. +

+
+ +
+
1 · connect wallet
+
+ +

+ Adds the local Base network (anvil) and unlocks trading below. +

+
+
+ + + + + +
+
+ + + + diff --git a/docs/canonical-rails-design.md b/docs/canonical-rails-design.md new file mode 100644 index 0000000000..9bc3d93e53 --- /dev/null +++ b/docs/canonical-rails-design.md @@ -0,0 +1,284 @@ +# Canonical Rails: USD → TAO → Alpha Settlement Layer + +**Status:** Draft for review +**Date:** 2026-08-21 +**Scope:** Runtime pallets, EVM precompiles, external token contracts, bridge topology, CLI/SDK surface + +--- + +## 1. Summary + +Bittensor's subnet AMMs already clear roughly **$38M/day** of alpha trading volume. Meanwhile, every external product that tried to connect outside dollars to that demand has failed at the same point: distribution shipped, liquidity never did (TaoFi: ~$78K TVL; the official Solana TAO mint: ~$16K of pool depth; total stablecoins on Bittensor EVM: ~$500). + +This document specifies the **canonical rails**: a chain-owned settlement layer that connects external dollars to TAO and alpha, such that: + +1. Every dollar that enters becomes TAO buy pressure, then alpha buy pressure, by construction. +2. The chain provides first-class, permanent liquidity that no third party has ever supplied. +3. Alpha exposure is exported to other chains as yield-bearing tokens with keyless custody. +4. Subnet service revenue settles through the same route, making revenue → token demand mechanical and auditable. + +The design principle throughout: **be the mint and the redemption window — never the storefront, never the wire.** The chain owns the token contracts, the swap venue, and the trust; it rents bridges as rate-limited couriers and leaves consumer UX to partners. + +--- + +## 2. Topology + +```text + [Bittensor runtime — the hub] [Base — spoke #1] + ┌─────────────────────────────────────┐ ┌──────────────────┐ + in → │ USDC_bridged ⇄ tUSD (PSM: caps, │ │ USDC (origin) │ + │ haircuts) │ │ │ + │ tUSD ⇄ TAO (canonical pool, │◄─Hyperlane─► TAO (1:1) │ + │ protocol-owned depth) │ validator │ wALPHA_i (share)│ + │ TAO ⇄ α_i (existing subnet AMMs) │ quorum │ wBETA_v (share) │ + │ α_i → shares (v441 basket engine) │ ISM │ │ + └─────────────────────────────────────┘ └──────────────────┘ + registry · per-block supply attestation · rate limits · Gateway +``` + +- **Mint path (demand):** USDC on Base → bridge → PSM → tUSD → TAO → alpha/basket → share. +- **Redeem path (exit):** share → alpha → TAO → tUSD → USDC delivered back on Base. +- Both directions cross the chain-owned tUSD/TAO pool. There is no other door. + +### 2.1 The narrow waist + +Many things above (Base, later Solana/other chains, CEX market makers, ETP custodians), many things below (128+ subnets, validator baskets, a future index). One thin interface in the middle that everything must pass through. This gives: + +- **Universality** — an integrator needs two function calls and a registry lookup. +- **The design law enforced by construction** — a symmetric, freely-arbitraged USD↔alpha market drains TAO (arbitrage after alpha buys runs USD→alpha→TAO→USD, selling TAO). Because the atomic entry point is the only way in, every USD→alpha path physically routes through the TAO pool. +- **Fee and burn capture at one chokepoint** every flow crosses. + +--- + +## 3. Components + +### 3.1 tUSD and the PSM (`pallets/usd-psm`, new) + +tUSD is the runtime's internal dollar **unit of account**. It is deliberately **not a product**: + +- **Non-transferable and non-holdable.** tUSD exists only inside atomic transactions (PSM → pool → stake). Users never hold a tUSD balance. There is no ERC-20 view of it and it never leaves the runtime. +- Why: a holdable tUSD would inevitably be paired against alpha tokens on the chain's own EVM, creating the symmetric USD↔alpha bypass internally — the exact structure this design exists to prevent. Non-holdable tUSD makes the one-door invariant airtight. It also means the chain has no on-chain dollar parking lot: de-risking means leaving (exit to USDC on Base), not sitting in stables inside the ecosystem. + +The **PSM** (Peg Stability Module, after Maker's pattern) is the front door for dollars: + +- A governance-managed registry of accepted USD assets (bridged USDC variants; Circle-native USDC via CCTP when available). +- Per-asset **cap** (maximum exposure to that bridge/issuer) and **haircut** (conversion discount for less-trusted assets). +- Converts accepted assets 1:1 (minus haircut) into internal tUSD; holds reserves 1:1. Reserves are never rehypothecated into the pool — the dollar leg must not become TAO-correlated. + +### 3.2 The canonical tUSD/TAO pool (`pallets/swap`, extended) + +One new pair in the existing swap pallet: + +- **Protocol-owned liquidity (POL):** permanent, never withdrawn, fee-compounding. +- **Policy hooks as parameters, not code:** published asymmetric fee curve (cheaper in than out), protected TWAP execution for large exits, all tunable by governance in storage. +- Quotes come from **one runtime API** consumed identically by the precompile, RPC, and CLI. + +### 3.3 Atomic entry/exit (`pallets/subtensor`, extended) + +Two composition extrinsics (plus invoice settlement, §3.8): + +- `swap_usd_and_stake(usd_asset, amount, netuid, hotkey, min_alpha_out)` — PSM → pool → existing `add_stake` / basket-deposit path. +- `unstake_and_swap_to_usd(...)` → tUSD → PSM redemption → outbound bridge message; USDC arrives at the user's address on the spoke chain. + +These reuse the shipped staking paths and the v441 basket engine (slippage-aware NAV, keyless escrow, full-NAV share minting, pro-rata claims). + +### 3.4 Exported tokens (chain-owned contracts on spokes) + +Standard **ERC-20** tokens on Base/Ethereum, with three extensions: + +| Extension | Purpose | +|---|---| +| ERC-2612 (permit) | Gasless approvals | +| xERC-20 (ERC-7281) | Only registered bridges may mint, each within a rate limit; owner (the chain) can add/revoke minters | +| ERC-4626 read surface (shares only) | DeFi integrations can price the share; actual mint/redeem is cross-chain | + +Three token classes: + +- **TAO (spoke ticker: `TAO`)** — plain 1:1 wrapper; the money leg, collateral leg, and the migration target for the legacy single-operator wTAO. +- **wALPHA_i** — appreciating share of staked alpha in subnet *i*. Escrowed alpha remains staked; emissions accrue to escrow; each share redeems for a growing amount of alpha (wstETH model — balances never rebase). +- **wBETA_v** — appreciating share of validator *v*'s v441 basket (diversified subnet exposure). Because baskets are per-validator, any validator's basket can be promoted to a wBETA — third parties join the canonical rail natively. + +Deployment rules: one audited implementation per VM; **CREATE2** so the address is identical on every EVM chain; **9 decimals for every asset on every chain** (matching rao — no conversion math means no conversion bugs); supply invariant: Σ spoke supply ≤ hub escrow, published per block (§3.6). + +### 3.5 Bridge topology: rent transport, supply the trust + +- **Verification is never built in-house.** Bridge hacks are unbounded (Ronin $625M, Wormhole $326M, Nomad $190M); a rented, rate-limited bridge failing costs at most its cap. +- **Day-one corridor: Hyperlane** (permissionless at every layer; already live on Bittensor EVM). The destination **ISM quorum is the chain's own validator roster**: validators run the stock Hyperlane validator agent as a **pinned sidecar** in the validator deployment (compose profile — never inside the node process, never as an off-chain worker). Canonical mints on Base therefore require Bittensor's own validators' signatures — no new trust assumption beyond chain consensus itself. +- **Accountability on-chain:** validators register their agent's signing key against their hotkey; signed checkpoints that diverge from finalized state are portable fraud proofs; the runtime **slashes TAO** on proof. Roster changes propagate through the control plane. +- **Aggregation:** the ISM requires the validator quorum AND one external validator set (code diversity against agent/infra bugs — the KelpDAO lesson: $292M lost through one compromised 1-of-1 verifier). +- **Second courier (phase 2):** a chain-operated **LayerZero DVN** (the endpoint is already live on Subtensor EVM, EID 30374), making the validator roster a mandatory co-signer on the second rail too. +- **Inbound (money arriving):** tiered confirmation. Small deposits clear on the rented rail alone; deposits above a threshold additionally require a native validator-observer quorum (off-chain workers polling operator-run foreign nodes — never third-party RPCs alone). Upgrade path: Snowbridge-style Ethereum light client pallet, which replaces committee trust with Ethereum's own cryptography. +- **Control plane:** admin operations (limits, minters, roster) originate as extrinsics, are delivered to spokes by **two independent bridges**, and obey an asymmetric timelock — **48h to escalate, instant to revoke**. + +### 3.6 Registry and supply attestation (`pallets/token-registry`, new) + +The registry is what makes "canonical" a queryable fact instead of a marketing claim: + +- Per asset, per chain: canonical contract address, deployment standard, status (`canonical | migrating | deprecated → successor`), registered minters with live rate-limit windows and pending timelocked changes. +- **Per-block supply attestation:** hub-escrowed amount vs. sum of spoke supplies. Proof-of-reserve as a chain primitive — "check the invariant" replaces "trust the issuer." +- Exposed via precompile and public API; wallets and aggregators resolve it instead of guessing between competing mints. + +### 3.7 The Gateway (chain-owned EVM contract) + +The single Hyperlane recipient on Bittensor EVM. Its message envelope is the system's wire format: + +```rust +struct GatewayEnvelope { + version: u8, // adaptability lives here + asset: AssetId, // non-exhaustive enum: Tao | TUsd | Alpha(netuid) | BasketShare(hotkey) | ... + amount: u64, // 9 decimals, always + dest: AccountId32, // the "account pairing": just a field, no ceremony + action: GatewayAction, // CreditClaim | SwapToTao | Stake{netuid, hotkey, min} | PayInvoice{...} + nonce: u64, // replay protection via processed-set +} +``` + +**The Gateway never reverts.** If the requested action cannot execute (bad netuid, rate limit hit, pool paused), delivery still lands as a **claim record** — non-transferable, resolvable three ways: retry the action, convert to TAO, or bridge back out as USDC (with optional auto-return after N days). This collapses the cross-chain failure space to two states: *undelivered* (retryable; funds safe in origin escrow) or *delivered* (the user holds something spendable). "No stuck money" is a type-level invariant, inherited by every UI. + +Outbound, the runtime dispatches Mailbox calls itself from a keyless system account (pallet-evm call) — users sign one Substrate extrinsic and never need an EVM key. + +### 3.8 Service payments (`PayInvoice`) + +Subnets price services in dollars; buyers pay in USDC (or ETH etc., swapped origin-side); settlement runs the full route: + +```text +USDC (Base) → PSM → tUSD → TAO (canonical pool) → alpha (subnet AMM) + → split: payee hotkey (100 − burn_bps) / burn (burn_bps) +``` + +- `burn_bps` is subnet-owner-configurable and public — the guaranteed net-demand slice; both swap legs additionally pay fees into protocol-owned liquidity. +- The receipt event `{invoice_id, usd_amount, alpha_delivered, block}` is watched by the subnet's API to unlock service — and doubles as **auditable per-subnet revenue**, enabling revenue-weighted baskets/indices and giving issuers a number auditors can verify. +- Designed for machine payments (x402 pattern): AI agents holding USDC pay subnet APIs programmatically. +- **One settlement path only.** Direct USDC-to-subnet payment lanes are explicitly out: they recreate the off-chain status quo where revenue never touches TAO. + +--- + +## 4. Liquidity: how the chain funds the USD side + +The chain never sells TAO for dollars. Three sources, in sequence: + +1. **Treasury TAO seeds the TAO side.** Day one the pool is deep for buyers, shallow for sellers — acceptable for a demand rail; exits run through protected TWAP until the USD side matures. +2. **Selling claims on yield, never the base asset:** + - **Alpha bootstrap auctions** — protocol-held alpha auctioned for USDC; existing alpha demand funds the dollar depth. + - **Share bonds** — wALPHA/wBETA sold at a small discount for upfront USDC, vesting over weeks; forward-selling the product itself. +3. **Organic fill** — every inbound deposit swaps tUSD → TAO, accumulating tUSD (i.e., USD reserves) in the pool; usage builds the exit liquidity. + +"First-class" means: **permanent** (POL is never withdrawn), **compounding** (fees recycle into depth), **published** (weekly depth/slippage scoreboard; the launch announcement is the depth number). + +--- + +## 5. User experience + +### 5.1 End user (btcli) + +Five verbs. The bridge is invisible; the EVM layer never appears. + +```text +$ btcli bridge deposit --from base --amount 1000 --then stake --netuid 64 --hotkey 5F... + 1/3 Base tx confirmed 0x8a2f… + 2/3 Hyperlane in transit msg 0x77c1… (~90s) + 3/3 Executed ✓ staked 47.2 α on SN64 + +$ btcli exit --amount 5 --to base:0xYourAddr # TAO → USDC lands on Base +$ btcli wrap alpha --netuid 64 --amount 50 --dest base --to 0x… # one Substrate signature +$ btcli bridge status 0x77c1… # one state machine, human-readable next steps +$ btcli registry list | attestation # canonical addresses, live backing proof +``` + +Failure UX is a product guarantee: every failed action ends as a resolvable claim, never a stuck balance. + +### 5.2 Integrator (storefronts, wallets, issuers) + +Resolve the registry → call `swapUsdAndStake` / `unstakeAndSwapToUsd` (versioned precompile; released selectors are permanent) → poll one `transferStatus` object. Issuers additionally get in-kind create/redeem against shares and the attestation feed. + +### 5.3 Validator operator + +`compose up` brings up node + pinned Hyperlane agent sidecar; register the signing key once; a stipend pays for the duty; the watchdog and slashing enforce it. + +--- + +## 6. Locked decisions and invariants + +| Decision | Consequence | +|---|---| +| One door: the atomic extrinsic is the only entry/exit | No second pipe, ever, including for the chain itself | +| tUSD is non-holdable, non-transferable, internal-only | No on-chain USD↔alpha bypass; no stablecoin product surface | +| Gateway never reverts; fallback = claim record | "No stuck money" as a type-level invariant | +| 9 decimals, every asset, every chain | No conversion math anywhere (permanent commitment) | +| Versioned envelope; append-only ABIs; non-exhaustive enums | New assets/actions are one-variant diffs, never breaking changes | +| One rate-limit algorithm (linear-refill window) in PSM and xERC-20 | Auditors verify one algorithm, not two dialects | +| Token contracts immutable; parameters and periphery evolve | Holders trust bytecode; Gateway v2 deploys beside v1 | +| Escalate slow (48h timelock), revoke instant | Safety asymmetry in the control plane | +| Neutrality: policy is published rules, never discretion | The chain formally renounces front-running its own flow; neutrality is why everyone routes through the waist | +| Hub-and-spoke; spokes never mint against each other | Simplicity over mesh topology (permanent commitment) | + +**Renounced (as load-bearing as the builds):** no in-house verification layer; no consumer swap UI; no tUSD export as a stablecoin; no emissions-paid mercenary liquidity; no PSM reserve rehypothecation. + +--- + +## 7. Build plan (monorepo) + +| ID | Component | Location | +|---|---|---| +| A1 | tUSD ledger + PSM | `pallets/usd-psm` (new; modeled on `pallets/alpha-assets`) | +| A2 | tUSD/TAO pair + POL + policy hooks | `pallets/swap` (extend) | +| A3 | Atomic extrinsics (incl. `PayInvoice` settlement) | `pallets/subtensor` | +| A4 | Registry + supply attestation + hub escrow | `pallets/token-registry` (new; escrow per `claim_root.rs` pattern) | +| B1 | USD action precompile + ERC-20 custody adapter | `precompiles/src/usd.rs` (+ `.sol`/`.abi`) | +| B2 | Registry read precompile | `precompiles/src/token_registry.rs` | +| C1 | xERC-20 suite, ShareToken, Lockbox, MigrationSwap, CREATE2 scripts | `contracts/evm` (new Foundry workspace) | +| C2 | Gateway (Hyperlane recipient, action router) | `contracts/evm` | +| D1 | Hyperlane corridor: warp config, validator-quorum ISM, sidecar packaging | `contracts/evm` + validator compose profile | +| D2 | Control plane (2-bridge-attested admin messages, asymmetric timelock) | `pallets/token-registry` + relayer script | +| E1 | E2E harness: localnet + anvil + local Hyperlane; golden CLI transcripts; failure drills | `ts-tests`, `justfile` | +| E2 | SDK client + btcli verbs | `sdk/`, btcli plugin | +| E3 | CI, invariant fuzzing, external audits | workflows | + +**Milestones:** M1 kernel (A1→A2→A3→B1; localnet demo of one-call USDC→basket) → M2 registry+hub → M3 export layer + corridors (parallel once the standard freezes) → M4 hardening + audits, which **gates** liquidity seeding and any announcement. + +**Scaffold order:** shared types in `primitives/` first (every phase imports them); walking skeleton second (a do-nothing envelope traversing Base → Gateway → runtime event); golden transcripts as CI fixtures third; then logic fills the skeleton. + +The entire pipeline is locally testable with zero external dependencies: localnet subtensor + anvil (as Base, with free ETH) + Hyperlane core deployed and operated locally via its CLI + a mock USDC. Failure drills (rate-limit breach, minter revocation, relayer outage, forged checkpoint) run in the same rig. + +--- + +## 8. What we cannot build (external dependencies) + +| Dependency | Nature | Strategy | +|---|---|---| +| Native USDC (CCTP) | Circle's code and compliance process | Open the conversation at M1 — longest lead time, no substitute | +| Bridge committees' honesty | External organizations | Cap (rate limits), diversify (two corridors), watch (attestation), slash (own roster) | +| Cross-chain atomicity | Physics of two consensus systems | Hide it: interchain accounts, claims, later intent/solver fast-fills | +| Wallet/aggregator adoption | Phantom/Jupiter/MetaMask product decisions | Earn with depth; registry makes canonical status provable | + +--- + +## 9. Rollout + +1. **Depth before noise.** No announcement until the pool absorbs a $250K order under 1% slippage. +2. **One corridor, one storefront.** Base only; partner storefront (e.g., TaoFi) rebased onto canonical rails, keeping its own fees. +3. **The yield product.** wALPHA for a handful of top-revenue subnets + wBETA baskets. Mint/redeem permissionless so secondary markets anywhere pin to NAV and all net flow settles through the hub. +4. **Index + institutions.** Revenue-weighted index (fed by PayInvoice receipts); in-kind creation/redemption for ETP issuers. +5. **Weekly public scoreboard:** stablecoin float, pool depth, net USD→TAO flow, TAO burned, canonical vault TVL. + +Cheap wins alongside: migration path for the legacy wTAO ($23M single-operator honeypot — risk removal and launch TVL in one move); consolidation of the Solana dual-mint when the Solana corridor opens. + +--- + +## 10. Risks + +- **The chain becomes the headline risk.** Mitigation: minimal owned surface (~6 audited artifacts), immutable tokens, formal verification of the supply invariant, published attestation. +- **Provider sell-back neutralizes PayInvoice demand.** Mitigation: burn_bps floor + both-leg fees to POL; honest accounting in all public materials. +- **Thin exit liquidity early.** Mitigation: TWAP-protected exits, published depth targets, bootstrap instruments (§4). +- **Regulatory surface of yield shares.** Mitigation: issuers (ETPs) package the regulated wrapper; the chain ships neutral infrastructure with in-kind redemption. +- **Bridge compromise.** Bounded by rate limits; detected by attestation; recovered by instant revoke + claims process. + +--- + +## 11. Open questions + +1. Validator roster size and stipend level for the ISM quorum (proposal: 9–15 named operators, quarterly rotation). +2. burn_bps default and bounds for PayInvoice (proposal: default 5%, range 0–20%). +3. Which subnets get wALPHA at launch (proposal: top 3–5 by verifiable revenue once receipts exist; baskets first). +4. Exit-side fee curve parameters and the USD-depth threshold that retires TWAP protection. +5. Timing and terms of the legacy wTAO wind-down negotiation. diff --git a/justfile b/justfile index caf54a7f1d..25811a7355 100644 --- a/justfile +++ b/justfile @@ -51,3 +51,33 @@ lint: production: @echo "Running cargo build with metadata-hash generation..." cargo build --profile production --features="metadata-hash" + +# --- Canonical rails local rig --------------------------------------------- + +# Bring up the full rig: localnet + anvil + hyperlane core + agents + contracts. +rails-up: + bash scripts/rails/up.sh + +# Tear the rig down (pass --purge via `just rails-down --purge` to wipe state). +rails-down *ARGS: + bash scripts/rails/down.sh {{ARGS}} + +# Walking-skeleton end-to-end ping (gate G1). +rails-ping: + bash scripts/rails/ping.sh + +# Serve the CHUTES MetaMask demo page against the live rig. +rails-demo: + bash scripts/rails/demo.sh + +# Tail the hyperlane agent logs. +rails-agent-logs: + bash scripts/rails/agents.sh logs + +# Run the Solidity unit tests for the rails contracts. +rails-forge-test: + forge test --root contracts/evm + +# Rebuild contracts and export ABIs/bytecode for ts-tests and btcli. +rails-export: + bash contracts/evm/export-artifacts.sh diff --git a/node/Cargo.toml b/node/Cargo.toml index 0d465eb5c0..624ba63ca6 100644 --- a/node/Cargo.toml +++ b/node/Cargo.toml @@ -131,6 +131,8 @@ subtensor-custom-rpc = { workspace = true, features = ["std"] } subtensor-custom-rpc-runtime-api = { workspace = true, features = ["std"] } pallet-subtensor-swap-rpc = { workspace = true, features = ["std"] } pallet-subtensor-swap-runtime-api = { workspace = true, features = ["std"] } +pallet-usd-psm-rpc = { workspace = true } +pallet-usd-psm-runtime-api = { workspace = true, features = ["std"] } subtensor-macros.workspace = true # Optional global allocator (off by default). Archive nodes serving sustained RPC load show diff --git a/node/src/rpc.rs b/node/src/rpc.rs index e34826462f..394c80c39c 100644 --- a/node/src/rpc.rs +++ b/node/src/rpc.rs @@ -121,6 +121,7 @@ where CT: fp_rpc::ConvertTransaction<::Extrinsic> + Send + Sync + Clone + 'static, { use pallet_subtensor_swap_rpc::{Swap, SwapRpcApiServer}; + use pallet_usd_psm_rpc::{Rails, RailsRpcApiServer}; use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer}; use sc_consensus_manual_seal::rpc::{ManualSeal, ManualSealApiServer}; use substrate_frame_rpc_system::{System, SystemApiServer}; @@ -140,6 +141,9 @@ where // Swap RPC module.merge(Swap::new(client.clone()).into_rpc())?; + // Canonical rails RPC + module.merge(Rails::new(client.clone()).into_rpc())?; + module.merge(System::new(client.clone(), pool.clone()).into_rpc())?; module.merge(TransactionPayment::new(client.clone()).into_rpc())?; diff --git a/pallets/admin-utils/src/lib.rs b/pallets/admin-utils/src/lib.rs index 1fed8d67ea..21af1983d9 100644 --- a/pallets/admin-utils/src/lib.rs +++ b/pallets/admin-utils/src/lib.rs @@ -222,6 +222,8 @@ pub mod pallet { RuntimeConfiguration, /// Precompile lifecycle and availability registry PrecompileRegistry, + /// USD rails (canonical PSM + tUSD/TAO pool) precompile + UsdRails, } #[pallet::type_value] diff --git a/pallets/usd-psm/Cargo.toml b/pallets/usd-psm/Cargo.toml new file mode 100644 index 0000000000..8c1e42829c --- /dev/null +++ b/pallets/usd-psm/Cargo.toml @@ -0,0 +1,39 @@ +[package] +name = "pallet-usd-psm" +version = "0.1.0" +edition.workspace = true +publish = false + +[lints] +workspace = true + +[dependencies] +codec = { workspace = true, features = ["derive"] } +frame-support.workspace = true +frame-system.workspace = true +log.workspace = true +scale-info = { workspace = true, features = ["derive"] } +sp-core.workspace = true +sp-io.workspace = true +sp-runtime.workspace = true +subtensor-macros.workspace = true +subtensor-runtime-common.workspace = true + +[dev-dependencies] +pallet-balances.workspace = true + +[features] +default = ["std"] +std = [ + "codec/std", + "frame-support/std", + "frame-system/std", + "log/std", + "pallet-balances/std", + "scale-info/std", + "sp-core/std", + "sp-io/std", + "sp-runtime/std", + "subtensor-runtime-common/std", +] +try-runtime = ["frame-support/try-runtime"] diff --git a/pallets/usd-psm/rpc/Cargo.toml b/pallets/usd-psm/rpc/Cargo.toml new file mode 100644 index 0000000000..086193207b --- /dev/null +++ b/pallets/usd-psm/rpc/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "pallet-usd-psm-rpc" +publish = false +version = "0.1.0" +description = "RPC interface for the canonical rails (USD PSM pallet)" +edition.workspace = true + +[lints] +workspace = true + +[dependencies] +jsonrpsee = { workspace = true, features = ["client-core", "macros", "server"] } +pallet-usd-psm-runtime-api = { path = "../runtime-api" } +sp-api.workspace = true +sp-blockchain.workspace = true +sp-core.workspace = true +sp-runtime.workspace = true diff --git a/pallets/usd-psm/rpc/src/lib.rs b/pallets/usd-psm/rpc/src/lib.rs new file mode 100644 index 0000000000..e0dd7ae92c --- /dev/null +++ b/pallets/usd-psm/rpc/src/lib.rs @@ -0,0 +1,159 @@ +//! RPC interface for the canonical rails (USD PSM pallet). + +use std::sync::Arc; + +use jsonrpsee::{ + core::RpcResult, + proc_macros::rpc, + types::{ErrorObjectOwned, error::ErrorObject}, +}; +use sp_api::ProvideRuntimeApi; +use sp_blockchain::HeaderBackend; +use sp_core::H160; +use sp_core::crypto::AccountId32; +use sp_runtime::traits::Block as BlockT; + +pub use pallet_usd_psm_runtime_api::{ + RailsAlphaAttestation, RailsAssetInfo, RailsHubInfo, RailsPoolState, RailsRuntimeApi, +}; + +#[rpc(client, server)] +pub trait RailsRpcApi { + /// Quote tUSD -> TAO through the canonical pool. + #[method(name = "rails_quoteUsdToTao")] + fn quote_usd_to_tao(&self, amount: u64, at: Option) -> RpcResult>; + /// Quote TAO -> tUSD through the canonical pool. + #[method(name = "rails_quoteTaoToUsd")] + fn quote_tao_to_usd(&self, amount: u64, at: Option) -> RpcResult>; + /// Canonical pool reserves and fee. + #[method(name = "rails_poolState")] + fn pool_state(&self, at: Option) -> RpcResult; + /// Registered PSM assets. + #[method(name = "rails_assets")] + fn assets(&self, at: Option) -> RpcResult>; + /// The registered Gateway contract. + #[method(name = "rails_gateway")] + fn gateway(&self, at: Option) -> RpcResult>; + /// tUSD balance of an account. + #[method(name = "rails_tusdBalance")] + fn tusd_balance(&self, account: AccountId32, at: Option) -> RpcResult; + /// Supply attestation for a subnet's wrapped alpha. + #[method(name = "rails_alphaAttestation")] + fn alpha_attestation( + &self, + netuid: u16, + at: Option, + ) -> RpcResult; + /// Outbound hub configuration. + #[method(name = "rails_hubInfo")] + fn hub_info(&self, at: Option) -> RpcResult; +} + +/// Error type of this RPC api. +pub enum Error { + /// The call to runtime failed. + RuntimeError(String), +} + +impl From for ErrorObjectOwned { + fn from(e: Error) -> Self { + match e { + Error::RuntimeError(e) => ErrorObject::owned(1, e, None::<()>), + } + } +} + +/// RPC handler. +pub struct Rails { + client: Arc, + _marker: std::marker::PhantomData

, +} + +impl Rails { + /// Create a new handler backed by `client`. + pub fn new(client: Arc) -> Self { + Self { + client, + _marker: Default::default(), + } + } +} + +impl RailsRpcApiServer<::Hash> for Rails +where + Block: BlockT, + C: ProvideRuntimeApi + HeaderBackend + Send + Sync + 'static, + C::Api: RailsRuntimeApi, +{ + fn quote_usd_to_tao( + &self, + amount: u64, + at: Option<::Hash>, + ) -> RpcResult> { + let api = self.client.runtime_api(); + let at = at.unwrap_or_else(|| self.client.info().best_hash); + api.rails_quote_usd_to_tao(at, amount) + .map_err(|e| Error::RuntimeError(format!("unable to quote: {e:?}")).into()) + } + + fn quote_tao_to_usd( + &self, + amount: u64, + at: Option<::Hash>, + ) -> RpcResult> { + let api = self.client.runtime_api(); + let at = at.unwrap_or_else(|| self.client.info().best_hash); + api.rails_quote_tao_to_usd(at, amount) + .map_err(|e| Error::RuntimeError(format!("unable to quote: {e:?}")).into()) + } + + fn pool_state(&self, at: Option<::Hash>) -> RpcResult { + let api = self.client.runtime_api(); + let at = at.unwrap_or_else(|| self.client.info().best_hash); + api.rails_pool_state(at) + .map_err(|e| Error::RuntimeError(format!("unable to read pool: {e:?}")).into()) + } + + fn assets(&self, at: Option<::Hash>) -> RpcResult> { + let api = self.client.runtime_api(); + let at = at.unwrap_or_else(|| self.client.info().best_hash); + api.rails_assets(at) + .map_err(|e| Error::RuntimeError(format!("unable to read assets: {e:?}")).into()) + } + + fn gateway(&self, at: Option<::Hash>) -> RpcResult> { + let api = self.client.runtime_api(); + let at = at.unwrap_or_else(|| self.client.info().best_hash); + api.rails_gateway(at) + .map_err(|e| Error::RuntimeError(format!("unable to read gateway: {e:?}")).into()) + } + + fn tusd_balance( + &self, + account: AccountId32, + at: Option<::Hash>, + ) -> RpcResult { + let api = self.client.runtime_api(); + let at = at.unwrap_or_else(|| self.client.info().best_hash); + api.rails_tusd_balance(at, account) + .map_err(|e| Error::RuntimeError(format!("unable to read balance: {e:?}")).into()) + } + + fn alpha_attestation( + &self, + netuid: u16, + at: Option<::Hash>, + ) -> RpcResult { + let api = self.client.runtime_api(); + let at = at.unwrap_or_else(|| self.client.info().best_hash); + api.rails_alpha_attestation(at, netuid) + .map_err(|e| Error::RuntimeError(format!("unable to read attestation: {e:?}")).into()) + } + + fn hub_info(&self, at: Option<::Hash>) -> RpcResult { + let api = self.client.runtime_api(); + let at = at.unwrap_or_else(|| self.client.info().best_hash); + api.rails_hub_info(at) + .map_err(|e| Error::RuntimeError(format!("unable to read hub info: {e:?}")).into()) + } +} diff --git a/pallets/usd-psm/runtime-api/Cargo.toml b/pallets/usd-psm/runtime-api/Cargo.toml new file mode 100644 index 0000000000..d443afff99 --- /dev/null +++ b/pallets/usd-psm/runtime-api/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "pallet-usd-psm-runtime-api" +publish = false +version = "0.1.0" +description = "Runtime API for the canonical rails (USD PSM pallet)" +edition.workspace = true + +[lints] +workspace = true + +[dependencies] +codec = { workspace = true, features = ["derive"] } +frame-support.workspace = true +scale-info.workspace = true +serde.workspace = true +sp-api.workspace = true +sp-core.workspace = true +sp-std.workspace = true +subtensor-macros.workspace = true +subtensor-runtime-common = { workspace = true, default-features = false } + +[features] +default = ["std"] +std = [ + "codec/std", + "frame-support/std", + "scale-info/std", + "serde/std", + "sp-api/std", + "sp-core/std", + "sp-std/std", + "subtensor-runtime-common/std", +] diff --git a/pallets/usd-psm/runtime-api/src/lib.rs b/pallets/usd-psm/runtime-api/src/lib.rs new file mode 100644 index 0000000000..a96319fa27 --- /dev/null +++ b/pallets/usd-psm/runtime-api/src/lib.rs @@ -0,0 +1,89 @@ +//! Runtime API for the canonical rails: the single quote and state source +//! consumed by the RPC layer, the USD precompile, and btcli. + +#![cfg_attr(not(feature = "std"), no_std)] + +use codec::{Decode, Encode}; +use scale_info::TypeInfo; +use serde::{Deserialize, Serialize}; +use sp_core::H160; +use sp_std::vec::Vec; +use subtensor_macros::freeze_struct; + +/// State of the canonical tUSD/TAO pool. +#[freeze_struct("7545405eb292b50c")] +#[derive(Decode, Deserialize, Encode, PartialEq, Eq, Clone, Debug, Serialize, TypeInfo)] +pub struct RailsPoolState { + /// TAO reserve (rao). + pub tao_reserve: u64, + /// tUSD reserve (9 decimals). + pub tusd_reserve: u64, + /// Swap fee in basis points. + pub fee_bps: u16, +} + +/// Supply attestation for one subnet's canonical shares. +#[freeze_struct("5546774173f27e8e")] +#[derive(Decode, Deserialize, Encode, PartialEq, Eq, Clone, Debug, Serialize, TypeInfo)] +pub struct RailsAlphaAttestation { + /// Live alpha in the hub escrow (rao-scale, 9 decimals). Grows with + /// emissions. + pub escrowed_alpha: u64, + /// Canonical shares outstanding across spokes. + pub shares_outstanding: u64, + /// Share index in 1e9 fixed point (escrowed alpha per share). + pub index_e9: u64, +} + +/// Outbound hub configuration. +#[freeze_struct("9a789215c814f751")] +#[derive(Decode, Deserialize, Encode, PartialEq, Eq, Clone, Debug, Serialize, TypeInfo)] +pub struct RailsHubInfo { + /// The keyless EVM identity dispatching outbound messages (the trusted + /// `hubSender` on remote canonical share tokens). + pub hub_sender: H160, + /// The Bittensor-EVM Mailbox used for outbound messages, if configured. + pub mailbox: Option, + /// Next inbound envelope nonce expected by the sequential guard. + pub next_nonce: u64, +} + +/// Public view of a PSM-registered USD asset. +#[freeze_struct("ecc97f3d44576ea2")] +#[derive(Decode, Deserialize, Encode, PartialEq, Eq, Clone, Debug, Serialize, TypeInfo)] +pub struct RailsAssetInfo { + /// PSM asset id. + pub asset_id: u32, + /// ERC-20 contract on the Bittensor EVM. + pub erc20: H160, + /// Reserves currently backing tUSD. + pub reserves: u64, + /// Rate window headroom right now. + pub available: u64, + /// Haircut in basis points. + pub haircut_bps: u16, + /// Deposits enabled. + pub enabled: bool, +} + +sp_api::decl_runtime_apis! { + /// Quotes and registry views for the canonical rails. + pub trait RailsRuntimeApi { + /// Quote tUSD -> TAO through the canonical pool. + fn rails_quote_usd_to_tao(amount: u64) -> Option; + /// Quote TAO -> tUSD through the canonical pool. + fn rails_quote_tao_to_usd(amount: u64) -> Option; + /// Canonical pool state. + fn rails_pool_state() -> RailsPoolState; + /// All registered PSM assets. + fn rails_assets() -> Vec; + /// The registered Gateway contract (H160), if set. + fn rails_gateway() -> Option; + /// tUSD ledger balance of an account. + fn rails_tusd_balance(account: sp_core::crypto::AccountId32) -> u64; + /// Supply attestation for a subnet's wrapped alpha. + fn rails_alpha_attestation(netuid: u16) -> RailsAlphaAttestation; + /// Outbound hub configuration (hub sender identity + mailbox). + fn rails_hub_info() -> RailsHubInfo; + } +} diff --git a/pallets/usd-psm/src/lib.rs b/pallets/usd-psm/src/lib.rs new file mode 100644 index 0000000000..3e36857877 --- /dev/null +++ b/pallets/usd-psm/src/lib.rs @@ -0,0 +1,1292 @@ +//! # USD PSM pallet +//! +//! The runtime kernel of the canonical rails: a tUSD accounting ledger, a peg +//! stability module (PSM) registry of external USD assets, and the single +//! canonical tUSD/TAO constant-product pool. +//! +//! Entry point: the **gateway path**. The USD rails precompile calls +//! [`Pallet::do_gateway_execute`] with the caller's H160; only the registered +//! Gateway contract passes. Envelopes carry sequential nonces and execute in +//! strict order. +//! +//! The one product is canonical shares (CHUTES): [`GatewayAction::BuyShares`] +//! turns a USD deposit into staked alpha in the hub escrow and mints shares +//! on the spoke; [`GatewayAction::SellShares`] unwinds it back to USD. The +//! share index (escrowed alpha / shares outstanding) rises as the escrow +//! earns emissions and is pushed to the spoke on every mint plus a periodic +//! heartbeat. +//! +//! Once a deposit's backing is secured, the requested action never reverts — +//! failures fall back to a plain tUSD credit ([`FallbackReason`]). The +//! canonical tUSD/TAO pool is internal-only: there are no public swap +//! extrinsics; the pool exists to price buys and sells. +//! +//! tUSD is non-transferable in v1: it exists only as ledger entries moved by +//! this pallet's operations. + +#![cfg_attr(not(feature = "std"), no_std)] + +#[cfg(test)] +mod mock; +#[cfg(test)] +mod tests; + +use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen}; +use frame_support::PalletId; +use frame_support::pallet_prelude::*; +use frame_support::storage::with_storage_layer; +use frame_support::traits::fungible::{Inspect, Mutate}; +use frame_support::traits::tokens::Preservation; +use frame_system::pallet_prelude::*; +use scale_info::TypeInfo; +use sp_core::H160; +use sp_runtime::traits::AccountIdConversion; +use sp_runtime::{AccountId32, Vec}; +use subtensor_macros::freeze_struct; +use subtensor_runtime_common::rails::{ + AssetId, FallbackReason, GatewayAction, GatewayEnvelope, InboundReceipt, RateWindow, + UsdAssetId, +}; +use subtensor_runtime_common::{AlphaBalance, NetUid, TaoBalance}; + +pub use pallet::*; + +/// Loose coupling to the staking engine in `pallet-subtensor`; implemented in +/// the runtime to avoid a crate cycle (subtensor must not depend on this +/// pallet, and vice versa). +pub trait RailsStaking { + /// Stake `tao` from `coldkey`'s free balance into (`netuid`, `hotkey`). + /// Fails if the alpha received is below `min_alpha`. + fn stake( + coldkey: &AccountId, + hotkey: &AccountId, + netuid: NetUid, + tao: TaoBalance, + min_alpha: AlphaBalance, + ) -> Result; + + /// Unstake `alpha` from (`netuid`, `hotkey`), crediting TAO to `coldkey`'s + /// free balance. Fails if the TAO received is below `min_tao`. + fn unstake( + coldkey: &AccountId, + hotkey: &AccountId, + netuid: NetUid, + alpha: AlphaBalance, + min_tao: TaoBalance, + ) -> Result; + + /// Current alpha staked by `coldkey` under (`hotkey`, `netuid`). This is + /// the live escrow reading that drives the share index: it grows as the + /// stake earns emissions. + fn stake_of(hotkey: &AccountId, coldkey: &AccountId, netuid: NetUid) -> u64; +} + +impl RailsStaking for () { + fn stake( + _coldkey: &AccountId, + _hotkey: &AccountId, + _netuid: NetUid, + _tao: TaoBalance, + _min_alpha: AlphaBalance, + ) -> Result { + Err(DispatchError::Unavailable) + } + + fn unstake( + _coldkey: &AccountId, + _hotkey: &AccountId, + _netuid: NetUid, + _alpha: AlphaBalance, + _min_tao: TaoBalance, + ) -> Result { + Err(DispatchError::Unavailable) + } + + fn stake_of(_hotkey: &AccountId, _coldkey: &AccountId, _netuid: NetUid) -> u64 { + 0 + } +} + +/// Loose coupling to the outbound bridge leg: dispatching a Hyperlane +/// message from the runtime's keyless hub identity through the Bittensor-EVM +/// Mailbox. Implemented in the runtime (via `pallet-ethereum` with an +/// already-authenticated origin, so the dispatch lands in a real Ethereum +/// block and bridge agents can index its logs); mocked in tests. +pub trait RailsOutbound { + /// Call `mailbox.dispatch(dest_domain, recipient, body)` with `sender` as + /// the EVM transaction origin. + fn dispatch_mailbox( + mailbox: H160, + sender: H160, + dest_domain: u32, + recipient: [u8; 32], + body: Vec, + ) -> DispatchResult; +} + +impl RailsOutbound for () { + fn dispatch_mailbox( + _mailbox: H160, + _sender: H160, + _dest_domain: u32, + _recipient: [u8; 32], + _body: Vec, + ) -> DispatchResult { + Err(DispatchError::Unavailable) + } +} + +/// An external USD asset registered in the PSM. +#[freeze_struct("3ad6fadd2b61882a")] +#[derive( + Clone, Copy, Debug, PartialEq, Eq, Encode, Decode, DecodeWithMemTracking, MaxEncodedLen, + TypeInfo, +)] +pub struct PsmAsset { + /// The canonical ERC-20 contract of this asset on the Bittensor EVM. + pub erc20: H160, + /// Inflow rate limit (per-block refill). + pub window: RateWindow, + /// Haircut applied on deposit, in basis points. + pub haircut_bps: u16, + /// Reserves currently attributed to this asset (ERC-20 units held by the + /// escrow that back outstanding tUSD). + pub reserves: u64, + /// Deposits enabled. + pub enabled: bool, +} + +#[deny(missing_docs)] +#[frame_support::pallet] +#[allow(clippy::expect_used)] +pub mod pallet { + use super::*; + + #[pallet::pallet] + pub struct Pallet(_); + + /// Configuration trait. + #[pallet::config] + pub trait Config: frame_system::Config { + /// TAO currency (the Balances pallet). + type Currency: Inspect + + Mutate; + + /// Staking engine bridge, implemented in the runtime over + /// `pallet-subtensor`. + type Staking: RailsStaking; + + /// Outbound bridge leg, implemented in the runtime over + /// `pallet-ethereum`. + type Outbound: RailsOutbound; + + /// Origin allowed to administer the PSM (register assets, set the + /// gateway, initialize the pool). + type AdminOrigin: EnsureOrigin; + + /// Pallet account holding the pool's TAO side (protocol-owned + /// liquidity). + #[pallet::constant] + type PalletId: Get; + } + + /// Per-account tUSD balances (9 decimals). Non-transferable in v1. + #[pallet::storage] + pub type TUsdBalances = + StorageMap<_, Blake2_128Concat, T::AccountId, u64, ValueQuery>; + + /// Total tUSD issued (user ledger + pool reserve). + #[pallet::storage] + pub type TUsdTotalIssuance = StorageValue<_, u64, ValueQuery>; + + /// PSM asset registry. + #[pallet::storage] + pub type PsmAssets = StorageMap<_, Twox64Concat, UsdAssetId, PsmAsset, OptionQuery>; + + /// The registered Gateway contract on the Bittensor EVM. Only calls + /// relayed by this contract may execute gateway envelopes. + #[pallet::storage] + pub type Gateway = StorageValue<_, H160, OptionQuery>; + + /// The next inbound envelope nonce expected. Envelopes execute in strict + /// nonce order: lower nonces are replays, higher nonces wait (delivery + /// reverts and the relayer retries once the gap fills). + #[pallet::storage] + pub type NextNonce = StorageValue<_, u64, ValueQuery>; + + /// Receipts of executed inbound envelopes, keyed by nonce (for status + /// queries; the ordering guard is [`NextNonce`]). + #[pallet::storage] + pub type ProcessedNonces = StorageMap<_, Twox64Concat, u64, InboundReceipt, OptionQuery>; + + /// TAO reserve of the canonical pool (mirrors the pallet account balance). + #[pallet::storage] + pub type PoolTaoReserve = StorageValue<_, u64, ValueQuery>; + + /// tUSD reserve of the canonical pool. + #[pallet::storage] + pub type PoolTUsdReserve = StorageValue<_, u64, ValueQuery>; + + /// Pool swap fee in basis points. + #[pallet::storage] + pub type PoolFeeBps = StorageValue<_, u16, ValueQuery>; + + /// The Hyperlane Mailbox contract on the Bittensor EVM used for + /// runtime-originated (outbound) messages. + #[pallet::storage] + pub type HubMailbox = StorageValue<_, H160, OptionQuery>; + + /// Outbound routes: (destination domain, netuid) -> remote canonical + /// share token (bytes32 Hyperlane recipient). + #[pallet::storage] + pub type RemoteRoutes = + StorageDoubleMap<_, Twox64Concat, u32, Twox64Concat, NetUid, [u8; 32], OptionQuery>; + + /// Canonical shares outstanding per netuid. The share index is + /// `escrowed alpha / shares outstanding` where escrowed alpha is read + /// live from the staking engine (so it grows with emissions). + #[pallet::storage] + pub type SharesOutstanding = StorageMap<_, Twox64Concat, NetUid, u64, ValueQuery>; + + /// The hotkey the hub escrow stakes into, per netuid. Buys stake here; + /// sells unstake from here. + #[pallet::storage] + pub type EscrowHotkeys = + StorageMap<_, Twox64Concat, NetUid, T::AccountId, OptionQuery>; + + /// USD release routes: destination domain -> the spoke contract (bytes32 + /// Hyperlane recipient) that pays out USD on sells. + #[pallet::storage] + pub type UsdReleaseRoutes = StorageMap<_, Twox64Concat, u32, [u8; 32], OptionQuery>; + + /// Default heartbeat interval (blocks) for pushing the share index. + #[pallet::type_value] + pub fn DefaultHeartbeatInterval() -> u32 { + 10 + } + + /// How often (in blocks) the share index is pushed to spokes without a + /// triggering mint or burn. + #[pallet::storage] + pub type HeartbeatInterval = + StorageValue<_, u32, ValueQuery, DefaultHeartbeatInterval>; + + /// Outbound messages queued for dispatch in `on_idle`. Gateway envelopes + /// execute inside an inbound EVM transaction (Mailbox -> Gateway -> + /// precompile), and pallet-evm's reentrancy guard forbids dispatching a + /// second EVM transaction from that context. Each entry is + /// `(mailbox, destination domain, recipient route, message body)`. + #[pallet::storage] + #[pallet::unbounded] + pub type OutboundQueue = + StorageValue<_, Vec<(H160, u32, [u8; 32], Vec)>, ValueQuery>; + + /// Events. + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + pub enum Event { + /// A USD asset was registered or updated in the PSM. + UsdAssetRegistered { + /// PSM asset id. + asset_id: UsdAssetId, + /// ERC-20 contract address. + erc20: H160, + }, + /// The Gateway contract address was set. + GatewaySet { + /// Gateway H160. + gateway: H160, + }, + /// The canonical pool was initialized. + PoolInitialized { + /// TAO side. + tao: u64, + /// tUSD side. + tusd: u64, + /// Swap fee in basis points. + fee_bps: u16, + }, + /// tUSD was credited to an account. + TUsdCredited { + /// Beneficiary. + who: T::AccountId, + /// Amount credited. + amount: u64, + }, + /// tUSD was debited from an account. + TUsdDebited { + /// Account debited. + who: T::AccountId, + /// Amount debited. + amount: u64, + }, + /// tUSD was swapped for TAO through the canonical pool. + SwappedTUsdForTao { + /// Swapper. + who: T::AccountId, + /// tUSD in. + tusd_in: u64, + /// TAO out. + tao_out: u64, + }, + /// TAO was swapped for tUSD through the canonical pool. + SwappedTaoForTUsd { + /// Swapper. + who: T::AccountId, + /// TAO in. + tao_in: u64, + /// tUSD out. + tusd_out: u64, + }, + /// An inbound gateway envelope was executed. + GatewayExecuted { + /// Envelope nonce. + nonce: u64, + /// Destination account. + dest: T::AccountId, + /// Amount deposited (gross, before haircut). + amount: u64, + /// `None` if the requested action ran; `Some` if the fallback + /// credited tUSD instead. + fallback: Option, + }, + /// The hub Mailbox address was set. + HubMailboxSet { + /// Mailbox H160 on the Bittensor EVM. + mailbox: H160, + }, + /// An outbound route was set. + OutboundRouteSet { + /// Destination Hyperlane domain. + domain: u32, + /// Subnet whose alpha the remote token wraps. + netuid: NetUid, + /// Remote canonical share token (bytes32 recipient). + recipient: [u8; 32], + }, + /// A USD release route was set for a domain. + UsdRouteSet { + /// Destination Hyperlane domain. + domain: u32, + /// Spoke contract (bytes32 recipient) paying out USD on sells. + recipient: [u8; 32], + }, + /// The escrow hotkey for a netuid was set. + EscrowHotkeySet { + /// Subnet. + netuid: NetUid, + /// Hotkey the hub escrow stakes into. + hotkey: T::AccountId, + }, + /// The heartbeat interval was set. + HeartbeatIntervalSet { + /// Blocks between index pushes. + blocks: u32, + }, + /// A buy executed: USD in, alpha staked into escrow, shares minted + /// on the spoke. + SharesBought { + /// EVM address receiving the shares on the spoke. + recipient: H160, + /// Subnet. + netuid: NetUid, + /// tUSD consumed (post-haircut deposit). + usd_in: u64, + /// Alpha staked into the hub escrow. + alpha_staked: u64, + /// Shares minted. + shares: u64, + /// Share index (1e9 fixed point) after the buy. + index_e9: u64, + /// Destination domain. + domain: u32, + }, + /// A sell executed: shares burned on the spoke, alpha unstaked, + /// USD released. + SharesSold { + /// EVM address receiving the USD on the spoke. + recipient: H160, + /// Subnet. + netuid: NetUid, + /// Shares burned. + shares: u64, + /// Alpha unstaked from the hub escrow. + alpha_unstaked: u64, + /// USD released to the spoke. + usd_out: u64, + /// Destination domain. + domain: u32, + }, + /// The share index was pushed to a spoke (heartbeat). + IndexPushed { + /// Subnet. + netuid: NetUid, + /// Destination domain. + domain: u32, + /// Share index (1e9 fixed point). + index_e9: u64, + }, + } + + /// Errors. + #[pallet::error] + pub enum Error { + /// The PSM asset id is not registered. + AssetUnknown, + /// The PSM asset is disabled. + AssetDisabled, + /// The inflow rate window has no headroom for this amount. + CapExceeded, + /// The envelope nonce is below the sequential counter (replay). + NonceReplayed, + /// The envelope nonce is ahead of the sequential counter; delivery + /// reverts and the relayer retries once the gap fills. + NonceOutOfOrder, + /// The envelope bytes could not be decoded. + BadEnvelope, + /// The envelope's internal amount does not match the secured amount. + AmountMismatch, + /// No Gateway contract is registered. + GatewayNotSet, + /// The caller is not the registered Gateway contract. + NotGateway, + /// The canonical pool has not been initialized. + PoolNotInitialized, + /// The pool is already initialized. + PoolAlreadyInitialized, + /// The account's tUSD balance is insufficient. + InsufficientTUsd, + /// The pool cannot cover the requested output. + InsufficientLiquidity, + /// The swap output is below the caller's minimum. + SlippageExceeded, + /// PSM reserves cannot cover the requested withdrawal. + InsufficientReserves, + /// Amounts must be non-zero. + AmountZero, + /// Arithmetic overflow in pool math. + Overflow, + /// No hub Mailbox is configured for outbound messages. + HubNotConfigured, + /// No outbound route exists for this (domain, netuid). + RouteNotSet, + /// No escrow hotkey is configured for this netuid. + EscrowHotkeyNotSet, + /// The sell burns more shares than are outstanding. + InsufficientShares, + } + + #[pallet::hooks] + impl Hooks> for Pallet { + /// Flush queued outbound messages (minted shares, USD releases) and + /// push the live share index to every routed spoke on a fixed block + /// cadence, so rebasing balances tick without any user action. + fn on_idle(now: BlockNumberFor, _remaining_weight: Weight) -> Weight { + Self::flush_outbound().saturating_add(Self::heartbeat(now)) + } + } + + /// Dispatchable calls. + #[pallet::call] + impl Pallet { + /// Register (or update) a USD asset in the PSM. + #[pallet::call_index(0)] + #[pallet::weight((Weight::from_parts(20_000_000, 0), DispatchClass::Operational))] + pub fn register_usd_asset( + origin: OriginFor, + asset_id: UsdAssetId, + erc20: H160, + cap_limit: u64, + refill_per_block: u64, + haircut_bps: u16, + ) -> DispatchResult { + T::AdminOrigin::ensure_origin(origin)?; + PsmAssets::::mutate(asset_id, |slot| { + let reserves = slot.map(|a| a.reserves).unwrap_or_default(); + let mut window = RateWindow::new(cap_limit, refill_per_block); + if let Some(existing) = slot { + window.used = existing.window.used; + window.last_update_block = existing.window.last_update_block; + } + *slot = Some(PsmAsset { + erc20, + window, + haircut_bps, + reserves, + enabled: true, + }); + }); + Self::deposit_event(Event::UsdAssetRegistered { asset_id, erc20 }); + Ok(()) + } + + /// Enable or disable deposits for a PSM asset. + #[pallet::call_index(1)] + #[pallet::weight((Weight::from_parts(15_000_000, 0), DispatchClass::Operational))] + pub fn set_asset_enabled( + origin: OriginFor, + asset_id: UsdAssetId, + enabled: bool, + ) -> DispatchResult { + T::AdminOrigin::ensure_origin(origin)?; + PsmAssets::::try_mutate(asset_id, |slot| { + let asset = slot.as_mut().ok_or(Error::::AssetUnknown)?; + asset.enabled = enabled; + Ok(()) + }) + } + + /// Register the Gateway contract address. + #[pallet::call_index(2)] + #[pallet::weight((Weight::from_parts(15_000_000, 0), DispatchClass::Operational))] + pub fn set_gateway(origin: OriginFor, gateway: H160) -> DispatchResult { + T::AdminOrigin::ensure_origin(origin)?; + Gateway::::put(gateway); + Self::deposit_event(Event::GatewaySet { gateway }); + Ok(()) + } + + /// Initialize the canonical tUSD/TAO pool with protocol-owned + /// liquidity: TAO is moved from `funder` to the pool account and the + /// tUSD side is issued as a protocol liability backed by that TAO. + #[pallet::call_index(3)] + #[pallet::weight((Weight::from_parts(50_000_000, 0), DispatchClass::Operational))] + pub fn init_pool( + origin: OriginFor, + funder: T::AccountId, + tao: u64, + tusd: u64, + fee_bps: u16, + ) -> DispatchResult { + T::AdminOrigin::ensure_origin(origin)?; + ensure!(tao > 0 && tusd > 0, Error::::AmountZero); + ensure!( + PoolTaoReserve::::get() == 0 && PoolTUsdReserve::::get() == 0, + Error::::PoolAlreadyInitialized + ); + ensure!(fee_bps < 10_000, Error::::Overflow); + + T::Currency::transfer( + &funder, + &Self::pool_account(), + TaoBalance::from(tao), + Preservation::Expendable, + )?; + PoolTaoReserve::::put(tao); + PoolTUsdReserve::::put(tusd); + TUsdTotalIssuance::::mutate(|total| *total = total.saturating_add(tusd)); + PoolFeeBps::::put(fee_bps); + Self::deposit_event(Event::PoolInitialized { tao, tusd, fee_bps }); + Ok(()) + } + + // Call indices 4-7 retired: public pool swaps and hub-side products + // (swap_tusd_for_tao, swap_tao_for_tusd, swap_usd_and_stake, + // unstake_and_swap_to_usd). The pool is internal-only now. + + /// Set the Bittensor-EVM Mailbox used for outbound messages. + #[pallet::call_index(8)] + #[pallet::weight((Weight::from_parts(15_000_000, 0), DispatchClass::Operational))] + pub fn set_hub_mailbox(origin: OriginFor, mailbox: H160) -> DispatchResult { + T::AdminOrigin::ensure_origin(origin)?; + HubMailbox::::put(mailbox); + Self::deposit_event(Event::HubMailboxSet { mailbox }); + Ok(()) + } + + /// Set the outbound route for (`domain`, `netuid`): the remote + /// canonical share token to mint on wrap. + #[pallet::call_index(9)] + #[pallet::weight((Weight::from_parts(15_000_000, 0), DispatchClass::Operational))] + pub fn set_outbound_route( + origin: OriginFor, + domain: u32, + netuid: NetUid, + recipient: [u8; 32], + ) -> DispatchResult { + T::AdminOrigin::ensure_origin(origin)?; + RemoteRoutes::::insert(domain, netuid, recipient); + Self::deposit_event(Event::OutboundRouteSet { + domain, + netuid, + recipient, + }); + Ok(()) + } + + /// Set the USD release route for a domain: the spoke contract that + /// pays out USD on sells. + #[pallet::call_index(10)] + #[pallet::weight((Weight::from_parts(15_000_000, 0), DispatchClass::Operational))] + pub fn set_usd_route( + origin: OriginFor, + domain: u32, + recipient: [u8; 32], + ) -> DispatchResult { + T::AdminOrigin::ensure_origin(origin)?; + UsdReleaseRoutes::::insert(domain, recipient); + Self::deposit_event(Event::UsdRouteSet { domain, recipient }); + Ok(()) + } + + /// Set the hotkey the hub escrow stakes into for `netuid`. + #[pallet::call_index(11)] + #[pallet::weight((Weight::from_parts(15_000_000, 0), DispatchClass::Operational))] + pub fn set_escrow_hotkey( + origin: OriginFor, + netuid: NetUid, + hotkey: T::AccountId, + ) -> DispatchResult { + T::AdminOrigin::ensure_origin(origin)?; + EscrowHotkeys::::insert(netuid, &hotkey); + Self::deposit_event(Event::EscrowHotkeySet { netuid, hotkey }); + Ok(()) + } + + /// Set the heartbeat interval (blocks) for index pushes. + #[pallet::call_index(12)] + #[pallet::weight((Weight::from_parts(15_000_000, 0), DispatchClass::Operational))] + pub fn set_heartbeat_interval(origin: OriginFor, blocks: u32) -> DispatchResult { + T::AdminOrigin::ensure_origin(origin)?; + ensure!(blocks > 0, Error::::AmountZero); + HeartbeatInterval::::put(blocks); + Self::deposit_event(Event::HeartbeatIntervalSet { blocks }); + Ok(()) + } + } +} + +impl Pallet { + /// The pool's protocol-owned-liquidity account. + pub fn pool_account() -> T::AccountId { + T::PalletId::get().into_account_truncating() + } + + /// The hub escrow account: its staked alpha backs all remote share + /// supply. + pub fn hub_account() -> T::AccountId { + T::PalletId::get().into_sub_account_truncating(b"hub_") + } + + /// The keyless EVM identity of the runtime hub: the `from` address of + /// outbound Mailbox transactions and the trusted `hubSender` configured + /// on remote canonical share tokens. + pub fn hub_evm_address() -> H160 { + H160::from_slice( + sp_io::hashing::blake2_256(b"rails/hub-evm") + .get(..20) + .expect("blake2_256 output is 32 bytes; qed"), + ) + } + + /// ABI-encode the spoke share-token message: + /// `abi.encode(address to, uint64 shares, uint64 indexE9)`. A zero `to` + /// with zero `shares` is a pure index update (heartbeat). + fn abi_encode_share_msg(to: H160, shares: u64, index_e9: u64) -> Vec { + let mut body = Vec::with_capacity(96); + body.extend_from_slice(&[0u8; 12]); + body.extend_from_slice(to.as_bytes()); + body.extend_from_slice(&[0u8; 24]); + body.extend_from_slice(&shares.to_be_bytes()); + body.extend_from_slice(&[0u8; 24]); + body.extend_from_slice(&index_e9.to_be_bytes()); + body + } + + /// ABI-encode the spoke USD-release body: `abi.encode(address, uint64)`. + fn abi_encode_usd_release(to: H160, amount: u64) -> Vec { + let mut body = Vec::with_capacity(64); + body.extend_from_slice(&[0u8; 12]); + body.extend_from_slice(to.as_bytes()); + body.extend_from_slice(&[0u8; 24]); + body.extend_from_slice(&amount.to_be_bytes()); + body + } + + /// Live alpha in the hub escrow for `netuid` (grows with emissions). + pub fn escrowed_alpha(netuid: NetUid) -> u64 { + match EscrowHotkeys::::get(netuid) { + Some(hotkey) => T::Staking::stake_of(&hotkey, &Self::hub_account(), netuid), + None => 0, + } + } + + /// The share index in 1e9 fixed point: escrowed alpha per share. With no + /// shares outstanding the index is 1.0 (1e9). + pub fn share_index_e9(netuid: NetUid) -> u64 { + let shares = SharesOutstanding::::get(netuid); + if shares == 0 { + return 1_000_000_000; + } + u128::from(Self::escrowed_alpha(netuid)) + .saturating_mul(1_000_000_000) + .checked_div(u128::from(shares)) + .and_then(|x| u64::try_from(x).ok()) + .unwrap_or(u64::MAX) + } + + /// Supply attestation for `netuid`: (live escrowed alpha, shares + /// outstanding, share index). Escrowed alpha >= shares * index / 1e9 + /// always holds (rounding aside), and the surplus is the yield not yet + /// captured by an index push. + pub fn alpha_attestation(netuid: NetUid) -> (u64, u64, u64) { + ( + Self::escrowed_alpha(netuid), + SharesOutstanding::::get(netuid), + Self::share_index_e9(netuid), + ) + } + + /// Next expected inbound envelope nonce. + pub fn next_nonce() -> u64 { + NextNonce::::get() + } + + /// Queue an outbound mailbox message for dispatch in the next `on_idle`. + /// Gateway actions run inside an inbound EVM transaction, where a nested + /// EVM dispatch would trip pallet-evm's reentrancy guard. + fn queue_outbound(mailbox: H160, domain: u32, recipient: [u8; 32], body: Vec) { + OutboundQueue::::mutate(|q| q.push((mailbox, domain, recipient, body))); + } + + /// Dispatch every queued outbound message. Failures stay queued and are + /// retried next block (the queue only ever holds messages the runtime + /// itself produced, so a persistent failure means the rig is miswired). + fn flush_outbound() -> Weight { + let base = Weight::from_parts(10_000_000, 0); + let queued = OutboundQueue::::take(); + if queued.is_empty() { + return base; + } + let mut weight = base; + let mut retry: Vec<(H160, u32, [u8; 32], Vec)> = Vec::new(); + for (mailbox, domain, recipient, body) in queued { + weight = weight.saturating_add(Weight::from_parts(200_000_000, 0)); + if let Err(e) = T::Outbound::dispatch_mailbox( + mailbox, + Self::hub_evm_address(), + domain, + recipient, + body.clone(), + ) { + log::warn!(target: "rails", "outbound dispatch to domain {domain} failed, retrying next block: {e:?}"); + retry.push((mailbox, domain, recipient, body)); + } + } + if !retry.is_empty() { + OutboundQueue::::put(retry); + } + weight + } + + /// Push the current share index to every routed spoke every + /// [`HeartbeatInterval`] blocks. + fn heartbeat(now: BlockNumberFor) -> Weight { + let base = Weight::from_parts(10_000_000, 0); + let interval = HeartbeatInterval::::get().max(1); + let now_u32: u32 = now.try_into().unwrap_or_default(); + if !now_u32.is_multiple_of(interval) { + return base; + } + let Some(mailbox) = HubMailbox::::get() else { + return base; + }; + let mut weight = base; + for (domain, netuid, route) in RemoteRoutes::::iter() { + weight = weight.saturating_add(Weight::from_parts(200_000_000, 0)); + if SharesOutstanding::::get(netuid) == 0 { + continue; + } + let index_e9 = Self::share_index_e9(netuid); + let body = Self::abi_encode_share_msg(H160::zero(), 0, index_e9); + if T::Outbound::dispatch_mailbox( + mailbox, + Self::hub_evm_address(), + domain, + route, + body, + ) + .is_ok() + { + Self::deposit_event(Event::IndexPushed { + netuid, + domain, + index_e9, + }); + } + } + weight + } + + /// Frontier's `HashedAddressMapping`: the substrate account owned by an + /// EVM address. + pub fn evm_account(address: &H160) -> T::AccountId { + let mut data = [0u8; 24]; + if let Some(prefix) = data.get_mut(..4) { + prefix.copy_from_slice(b"evm:"); + } + if let Some(body) = data.get_mut(4..) { + body.copy_from_slice(address.as_bytes()); + } + AccountId32::new(sp_io::hashing::blake2_256(&data)) + } + + /// tUSD balance of an account. + pub fn tusd_balance(who: &T::AccountId) -> u64 { + TUsdBalances::::get(who) + } + + /// PSM asset lookup (for the precompile: which ERC-20 backs an asset id). + pub fn psm_asset(asset_id: UsdAssetId) -> Option { + PsmAssets::::get(asset_id) + } + + /// The registered Gateway contract. + pub fn gateway() -> Option { + Gateway::::get() + } + + /// Quote tUSD -> TAO through the canonical pool. + pub fn quote_tusd_for_tao(amount_in: u64) -> Option { + Self::quote( + PoolTUsdReserve::::get(), + PoolTaoReserve::::get(), + amount_in, + ) + } + + /// Quote TAO -> tUSD through the canonical pool. + pub fn quote_tao_for_tusd(amount_in: u64) -> Option { + Self::quote( + PoolTaoReserve::::get(), + PoolTUsdReserve::::get(), + amount_in, + ) + } + + /// Constant-product quote with the pool fee applied on input. + fn quote(reserve_in: u64, reserve_out: u64, amount_in: u64) -> Option { + if reserve_in == 0 || reserve_out == 0 || amount_in == 0 { + return None; + } + let fee_bps = u128::from(PoolFeeBps::::get()); + let in_net = u128::from(amount_in) + .checked_mul(10_000u128.checked_sub(fee_bps)?)? + .checked_div(10_000)?; + let numerator = u128::from(reserve_out).checked_mul(in_net)?; + let denominator = u128::from(reserve_in).checked_add(in_net)?; + let out = numerator.checked_div(denominator)?; + u64::try_from(out).ok() + } + + fn credit_tusd(who: &T::AccountId, amount: u64) { + if amount == 0 { + return; + } + TUsdBalances::::mutate(who, |b| *b = b.saturating_add(amount)); + TUsdTotalIssuance::::mutate(|total| *total = total.saturating_add(amount)); + Self::deposit_event(Event::TUsdCredited { + who: who.clone(), + amount, + }); + } + + fn debit_tusd(who: &T::AccountId, amount: u64) -> DispatchResult { + TUsdBalances::::try_mutate(who, |b| { + *b = b.checked_sub(amount).ok_or(Error::::InsufficientTUsd)?; + Ok::<(), DispatchError>(()) + })?; + TUsdTotalIssuance::::mutate(|total| *total = total.saturating_sub(amount)); + Self::deposit_event(Event::TUsdDebited { + who: who.clone(), + amount, + }); + Ok(()) + } + + /// Swap tUSD (ledger) for TAO (free balance). Returns TAO out. + pub fn do_swap_tusd_for_tao( + who: &T::AccountId, + amount_in: u64, + min_out: u64, + ) -> Result { + ensure!(amount_in > 0, Error::::AmountZero); + let reserve_tusd = PoolTUsdReserve::::get(); + let reserve_tao = PoolTaoReserve::::get(); + ensure!( + reserve_tusd > 0 && reserve_tao > 0, + Error::::PoolNotInitialized + ); + let out = Self::quote(reserve_tusd, reserve_tao, amount_in).ok_or(Error::::Overflow)?; + ensure!(out >= min_out, Error::::SlippageExceeded); + ensure!(out < reserve_tao, Error::::InsufficientLiquidity); + + Self::debit_tusd(who, amount_in)?; + // Debited tUSD becomes pool reserve (still issued, owned by the pool). + TUsdTotalIssuance::::mutate(|total| *total = total.saturating_add(amount_in)); + PoolTUsdReserve::::put(reserve_tusd.saturating_add(amount_in)); + PoolTaoReserve::::put(reserve_tao.saturating_sub(out)); + T::Currency::transfer( + &Self::pool_account(), + who, + TaoBalance::from(out), + Preservation::Expendable, + )?; + Self::deposit_event(Event::SwappedTUsdForTao { + who: who.clone(), + tusd_in: amount_in, + tao_out: out, + }); + Ok(out) + } + + /// Swap TAO (free balance) for tUSD (ledger). Returns tUSD out. + pub fn do_swap_tao_for_tusd( + who: &T::AccountId, + amount_in: u64, + min_out: u64, + ) -> Result { + ensure!(amount_in > 0, Error::::AmountZero); + let reserve_tao = PoolTaoReserve::::get(); + let reserve_tusd = PoolTUsdReserve::::get(); + ensure!( + reserve_tusd > 0 && reserve_tao > 0, + Error::::PoolNotInitialized + ); + let out = Self::quote(reserve_tao, reserve_tusd, amount_in).ok_or(Error::::Overflow)?; + ensure!(out >= min_out, Error::::SlippageExceeded); + ensure!(out < reserve_tusd, Error::::InsufficientLiquidity); + + T::Currency::transfer( + who, + &Self::pool_account(), + TaoBalance::from(amount_in), + Preservation::Expendable, + )?; + PoolTaoReserve::::put(reserve_tao.saturating_add(amount_in)); + PoolTUsdReserve::::put(reserve_tusd.saturating_sub(out)); + // Pool reserve tUSD leaves the pool ledger and enters the user ledger: + // net issuance change is zero (debit pool bucket, credit user). + TUsdTotalIssuance::::mutate(|total| *total = total.saturating_sub(out)); + Self::credit_tusd(who, out); + Self::deposit_event(Event::SwappedTaoForTUsd { + who: who.clone(), + tao_in: amount_in, + tusd_out: out, + }); + Ok(out) + } + + /// Execute an inbound gateway envelope. `caller` is the EVM address that + /// invoked the precompile — it must be the registered Gateway contract. + /// + /// Errors returned here revert the bridge delivery (funds remain secured + /// at origin / the mint is rolled back with the EVM frame, and the + /// relayer retries). Once the deposit is accounted, the requested action + /// never reverts: failures fall back to a plain tUSD credit. + pub fn do_gateway_execute(caller: H160, amount: u64, envelope_bytes: &[u8]) -> DispatchResult { + let gateway = Gateway::::get().ok_or(Error::::GatewayNotSet)?; + ensure!(caller == gateway, Error::::NotGateway); + + let envelope = + GatewayEnvelope::from_wire(envelope_bytes).map_err(|_| Error::::BadEnvelope)?; + ensure!(envelope.amount == amount, Error::::AmountMismatch); + + // Sequential ordering guard: the envelope must carry exactly the + // next expected nonce. Replays and gaps both revert the delivery + // (the relayer retries out-of-order messages until the gap fills). + let next = NextNonce::::get(); + ensure!(envelope.nonce >= next, Error::::NonceReplayed); + ensure!(envelope.nonce == next, Error::::NonceOutOfOrder); + + let (dest, fallback) = match &envelope.action { + GatewayAction::SellShares { + netuid, + recipient, + usd_asset, + min_usd, + domain, + } => { + // Sell path: shares were already burned on the spoke; the + // envelope amount is the share count, no USD is deposited. + // A failure is recorded in the receipt for follow-up. + let recipient = H160::from(*recipient); + let fb = Self::run_sell_shares( + recipient, *netuid, amount, *usd_asset, *min_usd, *domain, + ); + (Self::evm_account(&recipient), fb) + } + action => { + // Deposit path: secure the accounting (asset window + + // reserves + haircut), credit tUSD, then run the action. + // From the credit on, never revert: failures fall back to + // the tUSD credit. Buys credit the buyer's mirror account so + // a failed buy stays recoverable from MetaMask. + let dest: T::AccountId = match action { + GatewayAction::BuyShares { recipient, .. } => { + Self::evm_account(&H160::from(*recipient)) + } + _ => envelope.dest.clone(), + }; + let credited = if amount > 0 { + let AssetId::Usd(asset_id) = envelope.asset else { + return Err(Error::::AssetUnknown.into()); + }; + Self::psm_account_inflow(asset_id, amount)? + } else { + 0 + }; + Self::credit_tusd(&dest, credited); + let fb = Self::run_gateway_action(&dest, credited, action); + (dest, fb) + } + }; + + NextNonce::::put(next.saturating_add(1)); + let now = frame_system::Pallet::::block_number() + .try_into() + .unwrap_or_default(); + ProcessedNonces::::insert( + envelope.nonce, + InboundReceipt { + block: now, + fallback, + }, + ); + Self::deposit_event(Event::GatewayExecuted { + nonce: envelope.nonce, + dest, + amount, + fallback, + }); + Ok(()) + } + + /// Run the envelope's requested action on top of the tUSD credit. + /// Returns `None` on success or the fallback reason (tUSD stays credited). + fn run_gateway_action( + dest: &T::AccountId, + credited: u64, + action: &GatewayAction, + ) -> Option { + match action { + GatewayAction::CreditTUsd => None, + GatewayAction::Stake { + netuid, + hotkey, + min_alpha, + } => { + let hotkey: T::AccountId = hotkey.clone(); + let result: DispatchResult = with_storage_layer(|| { + let tao_out = Self::do_swap_tusd_for_tao(dest, credited, 0)?; + T::Staking::stake(dest, &hotkey, *netuid, TaoBalance::from(tao_out), *min_alpha)?; + Ok(()) + }); + result.err().map(|e| { + log::warn!(target: "rails", "gateway stake failed: {e:?}"); + FallbackReason::StakeFailed + }) + } + GatewayAction::BuyShares { + netuid, + recipient, + min_alpha, + domain, + } => { + let result: DispatchResult = with_storage_layer(|| { + Self::run_buy_shares( + dest, + H160::from(*recipient), + *netuid, + credited, + *min_alpha, + *domain, + ) + }); + result.err().map(|e| { + log::warn!(target: "rails", "gateway buy failed: {e:?}"); + FallbackReason::BuyFailed + }) + } + // Handled before the deposit path in `do_gateway_execute`. + GatewayAction::SellShares { .. } => Some(FallbackReason::UnknownAction), + // Forward compatibility: an action variant added by a newer + // client falls back to the tUSD credit instead of bouncing. + _ => Some(FallbackReason::UnknownAction), + } + } + + /// The buy pipeline, on top of tUSD already credited to `buyer` (the + /// recipient's mirror account): pool swap -> stake into the hub escrow + /// -> mint shares at the pre-stake index -> dispatch the mint (with the + /// post-stake index) to the spoke token. + fn run_buy_shares( + buyer: &T::AccountId, + recipient: H160, + netuid: NetUid, + credited: u64, + min_alpha: AlphaBalance, + domain: u32, + ) -> DispatchResult { + ensure!(credited > 0, Error::::AmountZero); + let mailbox = HubMailbox::::get().ok_or(Error::::HubNotConfigured)?; + let route = RemoteRoutes::::get(domain, netuid).ok_or(Error::::RouteNotSet)?; + let escrow_hotkey = + EscrowHotkeys::::get(netuid).ok_or(Error::::EscrowHotkeyNotSet)?; + + let hub = Self::hub_account(); + let tao_out = Self::do_swap_tusd_for_tao(buyer, credited, 0)?; + T::Currency::transfer( + buyer, + &hub, + TaoBalance::from(tao_out), + Preservation::Expendable, + )?; + + // Shares are priced at the index *before* this stake lands, so the + // buyer pays the current alpha-per-share; the new alpha then backs + // exactly the new shares. + let index_before = Self::share_index_e9(netuid).max(1); + let alpha: u64 = T::Staking::stake( + &hub, + &escrow_hotkey, + netuid, + TaoBalance::from(tao_out), + min_alpha, + )? + .into(); + let shares = u128::from(alpha) + .saturating_mul(1_000_000_000) + .checked_div(u128::from(index_before)) + .and_then(|x| u64::try_from(x).ok()) + .ok_or(Error::::Overflow)?; + ensure!(shares > 0, Error::::AmountZero); + SharesOutstanding::::mutate(netuid, |s| *s = s.saturating_add(shares)); + + let index_after = Self::share_index_e9(netuid); + Self::queue_outbound( + mailbox, + domain, + route, + Self::abi_encode_share_msg(recipient, shares, index_after), + ); + + Self::deposit_event(Event::SharesBought { + recipient, + netuid, + usd_in: credited, + alpha_staked: alpha, + shares, + index_e9: index_after, + domain, + }); + Ok(()) + } + + /// The sell pipeline: unstake escrowed alpha worth `shares` at the + /// current index, swap TAO -> tUSD, burn the tUSD against PSM reserves, + /// and dispatch a USD release to the spoke. Returns the fallback reason + /// on failure (shares were already burned remotely; nothing is credited + /// and the receipt records it). + fn run_sell_shares( + recipient: H160, + netuid: NetUid, + shares: u64, + usd_asset: UsdAssetId, + min_usd: u64, + domain: u32, + ) -> Option { + let result: DispatchResult = with_storage_layer(|| { + ensure!(shares > 0, Error::::AmountZero); + let mailbox = HubMailbox::::get().ok_or(Error::::HubNotConfigured)?; + let usd_route = + UsdReleaseRoutes::::get(domain).ok_or(Error::::RouteNotSet)?; + let escrow_hotkey = + EscrowHotkeys::::get(netuid).ok_or(Error::::EscrowHotkeyNotSet)?; + let outstanding = SharesOutstanding::::get(netuid); + ensure!(shares <= outstanding, Error::::InsufficientShares); + + let index_e9 = Self::share_index_e9(netuid); + let alpha = u128::from(shares) + .saturating_mul(u128::from(index_e9)) + .checked_div(1_000_000_000) + .and_then(|x| u64::try_from(x).ok()) + .ok_or(Error::::Overflow)?; + ensure!(alpha > 0, Error::::AmountZero); + + let hub = Self::hub_account(); + let tao_out = T::Staking::unstake( + &hub, + &escrow_hotkey, + netuid, + AlphaBalance::from(alpha), + TaoBalance::from(0u64), + )?; + let tusd_out = Self::do_swap_tao_for_tusd(&hub, tao_out.into(), min_usd)?; + Self::debit_tusd(&hub, tusd_out)?; + Self::psm_account_outflow(usd_asset, tusd_out)?; + SharesOutstanding::::mutate(netuid, |s| *s = s.saturating_sub(shares)); + + Self::queue_outbound( + mailbox, + domain, + usd_route, + Self::abi_encode_usd_release(recipient, tusd_out), + ); + + Self::deposit_event(Event::SharesSold { + recipient, + netuid, + shares, + alpha_unstaked: alpha, + usd_out: tusd_out, + domain, + }); + Ok(()) + }); + result.err().map(|e| { + log::warn!(target: "rails", "gateway sell failed: {e:?}"); + FallbackReason::SellFailed + }) + } + + /// Account a PSM inflow: rate window, reserves, haircut. Returns the tUSD + /// amount to credit. + fn psm_account_inflow(asset_id: UsdAssetId, amount: u64) -> Result { + let now: u32 = frame_system::Pallet::::block_number() + .try_into() + .unwrap_or_default(); + PsmAssets::::try_mutate(asset_id, |slot| { + let asset = slot.as_mut().ok_or(Error::::AssetUnknown)?; + ensure!(asset.enabled, Error::::AssetDisabled); + ensure!( + asset.window.try_reserve(now, amount), + Error::::CapExceeded + ); + asset.reserves = asset.reserves.saturating_add(amount); + let haircut = u128::from(amount) + .checked_mul(u128::from(asset.haircut_bps)) + .and_then(|x| x.checked_div(10_000)) + .and_then(|x| u64::try_from(x).ok()) + .ok_or(Error::::Overflow)?; + Ok(amount.saturating_sub(haircut)) + }) + } + + /// Account a PSM outflow: reserves down, window headroom released. + fn psm_account_outflow(asset_id: UsdAssetId, amount: u64) -> DispatchResult { + let now: u32 = frame_system::Pallet::::block_number() + .try_into() + .unwrap_or_default(); + PsmAssets::::try_mutate(asset_id, |slot| { + let asset = slot.as_mut().ok_or(Error::::AssetUnknown)?; + asset.reserves = asset + .reserves + .checked_sub(amount) + .ok_or(Error::::InsufficientReserves)?; + asset.window.release(now, amount); + Ok(()) + }) + } + +} diff --git a/pallets/usd-psm/src/mock.rs b/pallets/usd-psm/src/mock.rs new file mode 100644 index 0000000000..15f495c751 --- /dev/null +++ b/pallets/usd-psm/src/mock.rs @@ -0,0 +1,222 @@ +#![allow(clippy::arithmetic_side_effects, clippy::expect_used, clippy::unwrap_used)] + +use std::cell::RefCell; +use std::collections::HashMap; + +use frame_support::traits::fungible::Mutate; +use frame_support::traits::tokens::Preservation; +use frame_support::{PalletId, derive_impl, parameter_types}; +use frame_system as system; +use sp_core::H256; +use sp_runtime::traits::{BlakeTwo256, IdentityLookup}; +use sp_runtime::{AccountId32, BuildStorage, DispatchError}; +use subtensor_runtime_common::{AlphaBalance, NetUid, TaoBalance}; + +use sp_core::H160; + +use crate::{RailsOutbound, RailsStaking}; + +type Block = frame_system::mocking::MockBlock; + +frame_support::construct_runtime!( + pub enum Test { + System: frame_system = 1, + Balances: pallet_balances = 2, + UsdPsm: crate = 3, + } +); + +#[derive_impl(frame_system::config_preludes::TestDefaultConfig)] +impl system::Config for Test { + type BaseCallFilter = frame_support::traits::Everything; + type BlockWeights = (); + type BlockLength = (); + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type Hash = H256; + type Hashing = BlakeTwo256; + type AccountId = AccountId32; + type Lookup = IdentityLookup; + type RuntimeEvent = RuntimeEvent; + type BlockHashCount = frame_support::traits::ConstU64<250>; + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = pallet_balances::AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = frame_support::traits::ConstU16<42>; + type OnSetCode = (); + type MaxConsumers = frame_support::traits::ConstU32<16>; + type Nonce = u64; + type Block = Block; +} + +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] +impl pallet_balances::Config for Test { + type Balance = TaoBalance; + type AccountStore = System; + type ExistentialDeposit = ExistentialDeposit; +} + +parameter_types! { + pub const UsdPsmPalletId: PalletId = PalletId(*b"sn/rails"); + pub const ExistentialDeposit: TaoBalance = TaoBalance::new(1); +} + +/// Deterministic mock staking engine: 1 TAO buys 2 alpha; unstaking pays +/// 1 TAO per 2 alpha. Netuid 99 always fails (fallback drills). +pub struct MockStaking; + +thread_local! { + static STAKES: RefCell> = + RefCell::new(HashMap::new()); +} + +pub fn staked_alpha(coldkey: &AccountId32, hotkey: &AccountId32, netuid: NetUid) -> u64 { + STAKES.with(|s| { + s.borrow() + .get(&(coldkey.clone(), hotkey.clone(), netuid)) + .copied() + .unwrap_or_default() + }) +} + +pub const FAILING_NETUID: u16 = 99; + +/// Seed stake directly (e.g. simulating emissions landing on the escrow). +pub fn set_staked_alpha(coldkey: &AccountId32, hotkey: &AccountId32, netuid: NetUid, alpha: u64) { + STAKES.with(|s| { + s.borrow_mut() + .insert((coldkey.clone(), hotkey.clone(), netuid), alpha); + }); +} + +impl RailsStaking for MockStaking { + fn stake( + coldkey: &AccountId32, + hotkey: &AccountId32, + netuid: NetUid, + tao: TaoBalance, + min_alpha: AlphaBalance, + ) -> Result { + if netuid == NetUid::from(FAILING_NETUID) { + return Err(DispatchError::Other("mock staking failure")); + } + let tao_u64: u64 = tao.into(); + let alpha = tao_u64 * 2; + let min_alpha_u64: u64 = min_alpha.into(); + if alpha < min_alpha_u64 { + return Err(DispatchError::Other("min alpha")); + } + // Burn the TAO from the coldkey (the real engine moves it to the + // subnet account). + Balances::burn_from( + coldkey, + tao, + Preservation::Expendable, + frame_support::traits::tokens::Precision::Exact, + frame_support::traits::tokens::Fortitude::Polite, + )?; + STAKES.with(|s| { + *s.borrow_mut() + .entry((coldkey.clone(), hotkey.clone(), netuid)) + .or_default() += alpha; + }); + Ok(AlphaBalance::from(alpha)) + } + + fn unstake( + coldkey: &AccountId32, + hotkey: &AccountId32, + netuid: NetUid, + alpha: AlphaBalance, + min_tao: TaoBalance, + ) -> Result { + if netuid == NetUid::from(FAILING_NETUID) { + return Err(DispatchError::Other("mock staking failure")); + } + let alpha_u64: u64 = alpha.into(); + let tao = alpha_u64 / 2; + let min_tao_u64: u64 = min_tao.into(); + if tao < min_tao_u64 { + return Err(DispatchError::Other("min tao")); + } + STAKES.with(|s| { + let mut map = s.borrow_mut(); + let entry = map + .get_mut(&(coldkey.clone(), hotkey.clone(), netuid)) + .ok_or(DispatchError::Other("no stake"))?; + *entry = entry + .checked_sub(alpha_u64) + .ok_or(DispatchError::Other("insufficient stake"))?; + Ok::<(), DispatchError>(()) + })?; + Balances::mint_into(coldkey, TaoBalance::from(tao))?; + Ok(TaoBalance::from(tao)) + } + + fn stake_of(hotkey: &AccountId32, coldkey: &AccountId32, netuid: NetUid) -> u64 { + staked_alpha(coldkey, hotkey, netuid) + } +} + +/// Recording mock for the outbound bridge leg. +pub struct MockOutbound; + +thread_local! { + static DISPATCHES: RefCell)>> = + RefCell::new(Vec::new()); +} + +pub fn outbound_dispatches() -> Vec<(H160, H160, u32, [u8; 32], Vec)> { + DISPATCHES.with(|d| d.borrow().clone()) +} + +impl RailsOutbound for MockOutbound { + fn dispatch_mailbox( + mailbox: H160, + sender: H160, + dest_domain: u32, + recipient: [u8; 32], + body: Vec, + ) -> Result<(), DispatchError> { + DISPATCHES.with(|d| { + d.borrow_mut() + .push((mailbox, sender, dest_domain, recipient, body)) + }); + Ok(()) + } +} + +impl crate::pallet::Config for Test { + type Currency = Balances; + type Staking = MockStaking; + type Outbound = MockOutbound; + type AdminOrigin = frame_system::EnsureRoot; + type PalletId = UsdPsmPalletId; +} + +pub fn account(byte: u8) -> AccountId32 { + AccountId32::new([byte; 32]) +} + +pub fn new_test_ext() -> sp_io::TestExternalities { + STAKES.with(|s| s.borrow_mut().clear()); + DISPATCHES.with(|d| d.borrow_mut().clear()); + let mut storage = frame_system::GenesisConfig::::default() + .build_storage() + .expect("frame_system storage should build"); + pallet_balances::GenesisConfig:: { + balances: vec![ + (account(1), TaoBalance::from(1_000_000_000_000u64)), + (account(2), TaoBalance::from(1_000_000_000_000u64)), + ], + ..Default::default() + } + .assimilate_storage(&mut storage) + .expect("balances storage should build"); + let mut ext = sp_io::TestExternalities::new(storage); + ext.execute_with(|| System::set_block_number(1)); + ext +} diff --git a/pallets/usd-psm/src/tests.rs b/pallets/usd-psm/src/tests.rs new file mode 100644 index 0000000000..73f2d5db05 --- /dev/null +++ b/pallets/usd-psm/src/tests.rs @@ -0,0 +1,565 @@ +#![allow(clippy::arithmetic_side_effects, clippy::expect_used, clippy::unwrap_used)] + +use frame_support::traits::Hooks; +use frame_support::{assert_err, assert_ok}; +use sp_core::H160; +use sp_runtime::AccountId32; +use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::rails::{ + AssetId, FallbackReason, GatewayAction, GatewayEnvelope, +}; + +use crate::mock::*; +use crate::{ + Error, NextNonce, PoolTUsdReserve, PoolTaoReserve, ProcessedNonces, SharesOutstanding, + TUsdBalances, pallet, +}; + +type UsdPsmError = Error; + +const USDC: u32 = 0; +const BASE_DOMAIN: u32 = 8453; +const NETUID: u16 = 1; + +fn gateway_h160() -> H160 { + H160::from_low_u64_be(0xbeef) +} + +fn buyer_h160() -> H160 { + H160::from_low_u64_be(0xd00d) +} + +fn chutes_recipient() -> [u8; 32] { + let mut r = [0u8; 32]; + r[31] = 0x77; + r +} + +fn portal_recipient() -> [u8; 32] { + let mut r = [0u8; 32]; + r[31] = 0x88; + r +} + +fn escrow_hotkey() -> AccountId32 { + account(9) +} + +fn setup_psm_and_pool() { + assert_ok!(UsdPsm::register_usd_asset( + RuntimeOrigin::root(), + USDC, + H160::from_low_u64_be(0xcafe), + 1_000_000_000_000, // cap + 0, // no refill + 0, // no haircut + )); + assert_ok!(UsdPsm::set_gateway(RuntimeOrigin::root(), gateway_h160())); + // 1000 TAO : 100_000 tUSD => 1 TAO = 100 tUSD. + assert_ok!(UsdPsm::init_pool( + RuntimeOrigin::root(), + account(1), + 1_000_000_000_000, // 1000 TAO + 100_000_000_000_000, // 100k tUSD + 0, // no fee for easy math + )); +} + +fn setup_outbound() { + assert_ok!(UsdPsm::set_hub_mailbox( + RuntimeOrigin::root(), + H160::from_low_u64_be(0x1111) + )); + assert_ok!(UsdPsm::set_outbound_route( + RuntimeOrigin::root(), + BASE_DOMAIN, + NetUid::from(NETUID), + chutes_recipient(), + )); + assert_ok!(UsdPsm::set_usd_route( + RuntimeOrigin::root(), + BASE_DOMAIN, + portal_recipient(), + )); + assert_ok!(UsdPsm::set_escrow_hotkey( + RuntimeOrigin::root(), + NetUid::from(NETUID), + escrow_hotkey(), + )); +} + +fn envelope(action: GatewayAction, amount: u64, nonce: u64) -> Vec { + GatewayEnvelope { + asset: AssetId::Usd(USDC), + amount, + dest: account(7), + action, + nonce, + } + .to_wire() +} + +fn buy_envelope(amount: u64, nonce: u64) -> Vec { + GatewayEnvelope { + asset: AssetId::Usd(USDC), + amount, + dest: AccountId32::new([0u8; 32]), + action: GatewayAction::BuyShares { + netuid: NetUid::from(NETUID), + recipient: buyer_h160().0, + min_alpha: 0u64.into(), + domain: BASE_DOMAIN, + }, + nonce, + } + .to_wire() +} + +fn sell_envelope(shares: u64, nonce: u64) -> Vec { + GatewayEnvelope { + asset: AssetId::Alpha(NetUid::from(NETUID)), + amount: shares, + dest: AccountId32::new([0u8; 32]), + action: GatewayAction::SellShares { + netuid: NetUid::from(NETUID), + recipient: buyer_h160().0, + usd_asset: USDC, + min_usd: 0, + domain: BASE_DOMAIN, + }, + nonce, + } + .to_wire() +} + +fn execute(amount: u64, env: &[u8]) { + assert_ok!(pallet::Pallet::::do_gateway_execute( + gateway_h160(), + amount, + env + )); + // Outbound messages are queued (inline dispatch would re-enter the EVM); + // flush them the way the runtime does, via `on_idle` on an off-heartbeat + // block. + UsdPsm::on_idle(1, frame_support::weights::Weight::MAX); +} + +fn hub_escrow_alpha() -> u64 { + staked_alpha( + &pallet::Pallet::::hub_account(), + &escrow_hotkey(), + NetUid::from(NETUID), + ) +} + +#[test] +fn init_pool_moves_tao_and_sets_reserves() { + new_test_ext().execute_with(|| { + setup_psm_and_pool(); + assert_eq!(PoolTaoReserve::::get(), 1_000_000_000_000); + assert_eq!(PoolTUsdReserve::::get(), 100_000_000_000_000); + assert_err!( + UsdPsm::init_pool(RuntimeOrigin::root(), account(1), 1, 1, 0), + UsdPsmError::PoolAlreadyInitialized + ); + }); +} + +#[test] +fn internal_pool_swaps_round_trip() { + new_test_ext().execute_with(|| { + setup_psm_and_pool(); + // Buy tUSD with 10 TAO: out = 100000e9 * 10e9 / (1000e9 + 10e9) ≈ 990.09 tUSD. + let tusd = + pallet::Pallet::::do_swap_tao_for_tusd(&account(2), 10_000_000_000, 0) + .expect("swap works"); + assert_eq!(tusd, 990_099_009_900); + assert_eq!(TUsdBalances::::get(account(2)), tusd); + + // Swap it back; with zero fees we get ~10 TAO back (minus rounding). + let tao = pallet::Pallet::::do_swap_tusd_for_tao(&account(2), tusd, 9_990_000_000) + .expect("swap back works"); + assert!(tao >= 9_990_000_000); + assert_eq!(TUsdBalances::::get(account(2)), 0); + + // Slippage guard still applies internally. + assert_err!( + pallet::Pallet::::do_swap_tao_for_tusd(&account(2), 10_000_000_000, u64::MAX), + UsdPsmError::SlippageExceeded + ); + }); +} + +#[test] +fn gateway_execute_rejects_bad_callers_and_envelopes() { + new_test_ext().execute_with(|| { + setup_psm_and_pool(); + let env = envelope(GatewayAction::CreditTUsd, 100, 0); + + // Wrong caller. + assert_err!( + pallet::Pallet::::do_gateway_execute(H160::zero(), 100, &env), + UsdPsmError::NotGateway + ); + // Amount mismatch. + assert_err!( + pallet::Pallet::::do_gateway_execute(gateway_h160(), 99, &env), + UsdPsmError::AmountMismatch + ); + // Garbage envelope. + assert_err!( + pallet::Pallet::::do_gateway_execute(gateway_h160(), 0, &[1, 2, 3]), + UsdPsmError::BadEnvelope + ); + }); +} + +#[test] +fn nonces_are_strictly_sequential() { + new_test_ext().execute_with(|| { + setup_psm_and_pool(); + + // Nonce 1 before nonce 0: out of order, delivery reverts. + let early = envelope(GatewayAction::CreditTUsd, 100, 1); + assert_err!( + pallet::Pallet::::do_gateway_execute(gateway_h160(), 100, &early), + UsdPsmError::NonceOutOfOrder + ); + + // Nonce 0 executes and advances the counter. + let first = envelope(GatewayAction::CreditTUsd, 100, 0); + execute(100, &first); + assert_eq!(NextNonce::::get(), 1); + + // Replaying nonce 0 is rejected; nothing further is credited. + assert_err!( + pallet::Pallet::::do_gateway_execute(gateway_h160(), 100, &first), + UsdPsmError::NonceReplayed + ); + assert_eq!(TUsdBalances::::get(account(7)), 100); + + // Now nonce 1 fills the gap and executes. + execute(100, &early); + assert_eq!(NextNonce::::get(), 2); + assert_eq!(TUsdBalances::::get(account(7)), 200); + }); +} + +#[test] +fn gateway_execute_credit_records_receipt() { + new_test_ext().execute_with(|| { + setup_psm_and_pool(); + let env = envelope(GatewayAction::CreditTUsd, 1_000_000_000, 0); + execute(1_000_000_000, &env); + assert_eq!(TUsdBalances::::get(account(7)), 1_000_000_000); + let receipt = ProcessedNonces::::get(0).expect("receipt stored"); + assert_eq!(receipt.fallback, None); + }); +} + +#[test] +fn gateway_execute_stake_action_stakes() { + new_test_ext().execute_with(|| { + setup_psm_and_pool(); + let hotkey = account(9); + let env = envelope( + GatewayAction::Stake { + netuid: NetUid::from(NETUID), + hotkey: AccountId32::new([9u8; 32]), + min_alpha: 0u64.into(), + }, + 1_000_000_000, + 0, + ); + execute(1_000_000_000, &env); + // tUSD fully converted and staked. + assert_eq!(TUsdBalances::::get(account(7)), 0); + assert!(staked_alpha(&account(7), &hotkey, NetUid::from(NETUID)) > 0); + assert_eq!(ProcessedNonces::::get(0).unwrap().fallback, None); + }); +} + +#[test] +fn gateway_execute_falls_back_to_tusd_on_action_failure() { + new_test_ext().execute_with(|| { + setup_psm_and_pool(); + // Staking into the failing netuid: deposit must still land as tUSD. + let env = envelope( + GatewayAction::Stake { + netuid: NetUid::from(FAILING_NETUID), + hotkey: AccountId32::new([9u8; 32]), + min_alpha: 0u64.into(), + }, + 1_000_000_000, + 0, + ); + execute(1_000_000_000, &env); + assert_eq!(TUsdBalances::::get(account(7)), 1_000_000_000); + assert!(ProcessedNonces::::get(0).unwrap().fallback.is_some()); + }); +} + +#[test] +fn gateway_execute_enforces_cap() { + new_test_ext().execute_with(|| { + setup_psm_and_pool(); + let env = envelope(GatewayAction::CreditTUsd, 2_000_000_000_000, 0); + // Cap is 1_000_000_000_000; delivery must revert (relayer retries). + assert_err!( + pallet::Pallet::::do_gateway_execute(gateway_h160(), 2_000_000_000_000, &env), + UsdPsmError::CapExceeded + ); + assert_eq!(TUsdBalances::::get(account(7)), 0); + assert!(ProcessedNonces::::get(0).is_none()); + assert_eq!(NextNonce::::get(), 0); + }); +} + +#[test] +fn buy_shares_stakes_escrow_and_dispatches_mint() { + new_test_ext().execute_with(|| { + setup_psm_and_pool(); + setup_outbound(); + + let usd_in = 100_000_000_000; // 100 USD + execute(usd_in, &buy_envelope(usd_in, 0)); + + // First buy at index 1.0: shares == alpha staked in the escrow. + let escrowed = hub_escrow_alpha(); + assert!(escrowed > 0); + assert_eq!(SharesOutstanding::::get(NetUid::from(NETUID)), escrowed); + assert_eq!( + pallet::Pallet::::share_index_e9(NetUid::from(NETUID)), + 1_000_000_000 + ); + + // No stray tUSD left on the buyer's mirror account. + let mirror = pallet::Pallet::::evm_account(&buyer_h160()); + assert_eq!(TUsdBalances::::get(&mirror), 0); + assert_eq!(ProcessedNonces::::get(0).unwrap().fallback, None); + + // Outbound mint: chutes route, share message with recipient/shares/index. + let dispatches = outbound_dispatches(); + assert_eq!(dispatches.len(), 1); + let (mailbox, sender, domain, recipient, body) = dispatches[0].clone(); + assert_eq!(mailbox, H160::from_low_u64_be(0x1111)); + assert_eq!(sender, pallet::Pallet::::hub_evm_address()); + assert_eq!(domain, BASE_DOMAIN); + assert_eq!(recipient, chutes_recipient()); + // abi.encode(address, uint64, uint64): 3 words. + assert_eq!(body.len(), 96); + assert_eq!(&body[12..32], buyer_h160().as_bytes()); + assert_eq!(body[24 + 32..32 + 32], escrowed.to_be_bytes()); + assert_eq!(body[88..96], 1_000_000_000u64.to_be_bytes()); + }); +} + +#[test] +fn index_rises_with_emissions_and_prices_later_buys() { + new_test_ext().execute_with(|| { + setup_psm_and_pool(); + setup_outbound(); + + let usd_in = 100_000_000_000; + execute(usd_in, &buy_envelope(usd_in, 0)); + let shares_before = SharesOutstanding::::get(NetUid::from(NETUID)); + + // Emissions land on the escrow: +50% alpha. + let hub = pallet::Pallet::::hub_account(); + set_staked_alpha( + &hub, + &escrow_hotkey(), + NetUid::from(NETUID), + hub_escrow_alpha() * 3 / 2, + ); + let index = pallet::Pallet::::share_index_e9(NetUid::from(NETUID)); + assert_eq!(index, 1_500_000_000); + let escrow_before_second_buy = hub_escrow_alpha(); + + // A second identical buy mints alpha / 1.5 shares: the index prices + // in the emissions earned by existing holders. + execute(usd_in, &buy_envelope(usd_in, 1)); + let alpha_gained = hub_escrow_alpha() - escrow_before_second_buy; + let minted = SharesOutstanding::::get(NetUid::from(NETUID)) - shares_before; + assert!(minted > 0 && minted < alpha_gained); + assert_eq!( + minted, + (u128::from(alpha_gained) * 1_000_000_000 / u128::from(index)) as u64 + ); + + // The dispatched mint body carries exactly the minted shares. + let dispatches = outbound_dispatches(); + let (_, _, _, _, body) = dispatches.last().unwrap().clone(); + let mut shares_bytes = [0u8; 8]; + shares_bytes.copy_from_slice(&body[56..64]); + assert_eq!(u64::from_be_bytes(shares_bytes), minted); + }); +} + +#[test] +fn buy_shares_failure_falls_back_to_mirror_credit() { + new_test_ext().execute_with(|| { + setup_psm_and_pool(); + setup_outbound(); + // Point the escrow hotkey at the failing netuid's route by using a + // buy on a netuid with no route: fallback credits the buyer's mirror. + let env = GatewayEnvelope { + asset: AssetId::Usd(USDC), + amount: 50_000_000_000, + dest: AccountId32::new([0u8; 32]), + action: GatewayAction::BuyShares { + netuid: NetUid::from(42), // no route, no escrow hotkey + recipient: buyer_h160().0, + min_alpha: 0u64.into(), + domain: BASE_DOMAIN, + }, + nonce: 0, + } + .to_wire(); + execute(50_000_000_000, &env); + + let mirror = pallet::Pallet::::evm_account(&buyer_h160()); + assert_eq!(TUsdBalances::::get(&mirror), 50_000_000_000); + assert_eq!( + ProcessedNonces::::get(0).unwrap().fallback, + Some(FallbackReason::BuyFailed) + ); + assert!(outbound_dispatches().is_empty()); + }); +} + +#[test] +fn sell_shares_unstakes_and_releases_usd() { + new_test_ext().execute_with(|| { + setup_psm_and_pool(); + setup_outbound(); + + let usd_in = 100_000_000_000; + execute(usd_in, &buy_envelope(usd_in, 0)); + let shares = SharesOutstanding::::get(NetUid::from(NETUID)); + let reserves_before = pallet::Pallet::::psm_asset(USDC).unwrap().reserves; + + execute(shares, &sell_envelope(shares, 1)); + + assert_eq!(SharesOutstanding::::get(NetUid::from(NETUID)), 0); + assert_eq!(hub_escrow_alpha(), 0); + assert_eq!(ProcessedNonces::::get(1).unwrap().fallback, None); + + // Reserves dropped by the released USD. + let asset = pallet::Pallet::::psm_asset(USDC).unwrap(); + let released = reserves_before - asset.reserves; + assert!(released > 0 && released <= usd_in); + + // Outbound release goes to the portal route with (address, uint64). + let dispatches = outbound_dispatches(); + let (_, _, domain, recipient, body) = dispatches.last().unwrap().clone(); + assert_eq!(domain, BASE_DOMAIN); + assert_eq!(recipient, portal_recipient()); + assert_eq!(body.len(), 64); + assert_eq!(&body[12..32], buyer_h160().as_bytes()); + let mut amount_bytes = [0u8; 8]; + amount_bytes.copy_from_slice(&body[56..64]); + assert_eq!(u64::from_be_bytes(amount_bytes), released); + + // The hub holds no residual tUSD. + let hub = pallet::Pallet::::hub_account(); + assert_eq!(TUsdBalances::::get(&hub), 0); + }); +} + +#[test] +fn sell_shares_failure_records_receipt_without_reverting() { + new_test_ext().execute_with(|| { + setup_psm_and_pool(); + setup_outbound(); + // Nothing outstanding: the sell must fail but delivery must succeed. + execute(1_000_000_000, &sell_envelope(1_000_000_000, 0)); + assert_eq!( + ProcessedNonces::::get(0).unwrap().fallback, + Some(FallbackReason::SellFailed) + ); + assert!(outbound_dispatches().is_empty()); + }); +} + +#[test] +fn heartbeat_pushes_index_on_interval() { + new_test_ext().execute_with(|| { + setup_psm_and_pool(); + setup_outbound(); + + let usd_in = 100_000_000_000; + execute(usd_in, &buy_envelope(usd_in, 0)); + let mints = outbound_dispatches().len(); + + // Off-interval block: nothing pushed. + System::set_block_number(11); + UsdPsm::on_idle(11, frame_support::weights::Weight::MAX); + assert_eq!(outbound_dispatches().len(), mints); + + // Emissions land, then an on-interval block pushes the new index. + let hub = pallet::Pallet::::hub_account(); + set_staked_alpha( + &hub, + &escrow_hotkey(), + NetUid::from(NETUID), + hub_escrow_alpha() * 2, + ); + System::set_block_number(20); + UsdPsm::on_idle(20, frame_support::weights::Weight::MAX); + let dispatches = outbound_dispatches(); + assert_eq!(dispatches.len(), mints + 1); + let (_, _, _, recipient, body) = dispatches.last().unwrap().clone(); + assert_eq!(recipient, chutes_recipient()); + assert_eq!(body.len(), 96); + // Zero address, zero shares, doubled index. + assert_eq!(&body[12..32], H160::zero().as_bytes()); + let mut index_bytes = [0u8; 8]; + index_bytes.copy_from_slice(&body[88..96]); + assert_eq!(u64::from_be_bytes(index_bytes), 2_000_000_000); + + // No shares outstanding => no heartbeat. + SharesOutstanding::::remove(NetUid::from(NETUID)); + System::set_block_number(30); + UsdPsm::on_idle(30, frame_support::weights::Weight::MAX); + assert_eq!(outbound_dispatches().len(), mints + 1); + }); +} + +#[test] +fn haircut_applies_on_gateway_deposit() { + new_test_ext().execute_with(|| { + setup_psm_and_pool(); + assert_ok!(UsdPsm::register_usd_asset( + RuntimeOrigin::root(), + 1, + H160::from_low_u64_be(0xdddd), + 1_000_000_000_000, + 0, + 100, // 1% haircut + )); + let env = GatewayEnvelope { + asset: AssetId::Usd(1), + amount: 10_000_000_000, + dest: account(7), + action: GatewayAction::CreditTUsd, + nonce: 0, + } + .to_wire(); + execute(10_000_000_000, &env); + assert_eq!(TUsdBalances::::get(account(7)), 9_900_000_000); + }); +} + +#[test] +fn disabled_asset_rejects_deposits() { + new_test_ext().execute_with(|| { + setup_psm_and_pool(); + assert_ok!(UsdPsm::set_asset_enabled(RuntimeOrigin::root(), USDC, false)); + let env = envelope(GatewayAction::CreditTUsd, 1_000, 0); + assert_err!( + pallet::Pallet::::do_gateway_execute(gateway_h160(), 1_000, &env), + UsdPsmError::AssetDisabled + ); + }); +} diff --git a/precompiles/Cargo.toml b/precompiles/Cargo.toml index 8f2cd1f55f..cb381e0cae 100644 --- a/precompiles/Cargo.toml +++ b/precompiles/Cargo.toml @@ -36,6 +36,7 @@ subtensor-runtime-common.workspace = true substrate-fixed.workspace = true pallet-subtensor.workspace = true pallet-subtensor-swap.workspace = true +pallet-usd-psm.workspace = true pallet-admin-utils.workspace = true subtensor-swap-interface.workspace = true pallet-crowdloan.workspace = true @@ -73,6 +74,7 @@ std = [ "pallet-scheduler/std", "pallet-subtensor-proxy/std", "pallet-subtensor-swap/std", + "pallet-usd-psm/std", "pallet-subtensor/std", "pallet-shield/std", "pallet-timestamp/std", diff --git a/precompiles/src/lib.rs b/precompiles/src/lib.rs index fe098221e0..a5260b32c2 100644 --- a/precompiles/src/lib.rs +++ b/precompiles/src/lib.rs @@ -46,6 +46,7 @@ pub use subnet::SubnetPrecompile; use subtensor_runtime_common::ProxyType; pub use timestamp::TimestampPrecompile; pub use uid_lookup::UidLookupPrecompile; +pub use usd::UsdRailsPrecompile; pub use voting_power::VotingPowerPrecompile; mod address_mapping; @@ -69,6 +70,7 @@ mod storage_query; mod subnet; mod timestamp; mod uid_lookup; +mod usd; mod voting_power; #[cfg(test)] @@ -92,6 +94,7 @@ where + pallet_shield::Config + pallet_subtensor_proxy::Config + pallet_timestamp::Config + + pallet_usd_psm::Config + Send + Sync + scale_info::TypeInfo, @@ -137,6 +140,7 @@ where + pallet_shield::Config + pallet_subtensor_proxy::Config + pallet_timestamp::Config + + pallet_usd_psm::Config + Send + Sync + scale_info::TypeInfo, @@ -165,7 +169,7 @@ where Self(Default::default()) } - pub fn used_addresses() -> [H160; 33] { + pub fn used_addresses() -> [H160; 34] { [ hash(1), hash(2), @@ -200,6 +204,7 @@ where hash(TimestampPrecompile::::INDEX), hash(RuntimeConfigurationPrecompile::::INDEX), hash(PrecompileRegistry::::INDEX), + hash(UsdRailsPrecompile::::INDEX), ] } } @@ -219,6 +224,7 @@ where + pallet_shield::Config + pallet_subtensor_proxy::Config + pallet_timestamp::Config + + pallet_usd_psm::Config + Send + Sync + scale_info::TypeInfo, @@ -340,6 +346,9 @@ where PrecompileEnum::PrecompileRegistry, ) } + a if a == hash(UsdRailsPrecompile::::INDEX) => { + UsdRailsPrecompile::::try_execute::(handle, PrecompileEnum::UsdRails) + } _ => None, } } @@ -394,6 +403,7 @@ mod address_and_selector_tests { assert_eq!(TimestampPrecompile::::INDEX, 2065); assert_eq!(RuntimeConfigurationPrecompile::::INDEX, 2066); assert_eq!(PrecompileRegistry::::INDEX, 2067); + assert_eq!(UsdRailsPrecompile::::INDEX, 2068); } #[test] @@ -417,6 +427,7 @@ mod address_and_selector_tests { (PrecompileEnum::Timestamp, 15), (PrecompileEnum::RuntimeConfiguration, 16), (PrecompileEnum::PrecompileRegistry, 17), + (PrecompileEnum::UsdRails, 18), ]; for (variant, expected_index) in variants { @@ -502,6 +513,21 @@ mod address_and_selector_tests { "getPrecompileStatus(address,bytes4)" )) ); + for signature in [ + "gatewayExecute(uint64,bytes)", + "simSwapUsdForTao(uint64)", + "simSwapTaoForUsd(uint64)", + "tusdBalanceOf(bytes32)", + "poolState()", + "assetErc20(uint32)", + "shareIndexE9(uint16)", + "nextNonce()", + ] { + assert!( + usd::UsdRailsPrecompileCall::::supports_selector(selector_u32(signature)), + "missing UsdRails selector {signature}" + ); + } } #[test] diff --git a/precompiles/src/mock.rs b/precompiles/src/mock.rs index ad207d2484..d807a3ad74 100644 --- a/precompiles/src/mock.rs +++ b/precompiles/src/mock.rs @@ -72,6 +72,7 @@ frame_support::construct_runtime!( Evm: pallet_evm = 12, AdminUtils: pallet_admin_utils = 13, EVMChainId: pallet_evm_chain_id = 14, + UsdPsm: pallet_usd_psm = 16, } ); @@ -385,6 +386,20 @@ mod test_crypto { impl pallet_evm_chain_id::Config for Runtime {} +parameter_types! { + pub const UsdPsmPalletId: PalletId = PalletId(*b"sn/rails"); +} + +impl pallet_usd_psm::Config for Runtime { + type Currency = Balances; + // Staking and outbound dispatch are unavailable in this mock; rails + // pipelines are covered by the pallet's own tests. + type Staking = (); + type Outbound = (); + type AdminOrigin = EnsureRoot; + type PalletId = UsdPsmPalletId; +} + impl pallet_admin_utils::Config for Runtime { type Aura = (); type Grandpa = (); diff --git a/precompiles/src/registry.rs b/precompiles/src/registry.rs index 87681bfb58..f612f00fa4 100644 --- a/precompiles/src/registry.rs +++ b/precompiles/src/registry.rs @@ -142,6 +142,8 @@ where Some(PrecompileEnum::RuntimeConfiguration) } else if at(2067) { Some(PrecompileEnum::PrecompileRegistry) + } else if at(2068) { + Some(PrecompileEnum::UsdRails) } else { None } diff --git a/precompiles/src/solidity/usd.abi b/precompiles/src/solidity/usd.abi new file mode 100644 index 0000000000..f6bb969308 --- /dev/null +++ b/precompiles/src/solidity/usd.abi @@ -0,0 +1,151 @@ +[ + { + "type": "function", + "name": "assetErc20", + "inputs": [ + { + "name": "assetId", + "type": "uint32", + "internalType": "uint32" + } + ], + "outputs": [ + { + "name": "", + "type": "address", + "internalType": "address" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "gatewayExecute", + "inputs": [ + { + "name": "amount", + "type": "uint64", + "internalType": "uint64" + }, + { + "name": "envelope", + "type": "bytes", + "internalType": "bytes" + } + ], + "outputs": [], + "stateMutability": "nonpayable" + }, + { + "type": "function", + "name": "nextNonce", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "uint64", + "internalType": "uint64" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "poolState", + "inputs": [], + "outputs": [ + { + "name": "", + "type": "uint64", + "internalType": "uint64" + }, + { + "name": "", + "type": "uint64", + "internalType": "uint64" + }, + { + "name": "", + "type": "uint16", + "internalType": "uint16" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "shareIndexE9", + "inputs": [ + { + "name": "netuid", + "type": "uint16", + "internalType": "uint16" + } + ], + "outputs": [ + { + "name": "", + "type": "uint64", + "internalType": "uint64" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "simSwapTaoForUsd", + "inputs": [ + { + "name": "amountTao", + "type": "uint64", + "internalType": "uint64" + } + ], + "outputs": [ + { + "name": "", + "type": "uint64", + "internalType": "uint64" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "simSwapUsdForTao", + "inputs": [ + { + "name": "amountUsd", + "type": "uint64", + "internalType": "uint64" + } + ], + "outputs": [ + { + "name": "", + "type": "uint64", + "internalType": "uint64" + } + ], + "stateMutability": "view" + }, + { + "type": "function", + "name": "tusdBalanceOf", + "inputs": [ + { + "name": "account", + "type": "bytes32", + "internalType": "bytes32" + } + ], + "outputs": [ + { + "name": "", + "type": "uint64", + "internalType": "uint64" + } + ], + "stateMutability": "view" + } +] diff --git a/precompiles/src/solidity/usd.sol b/precompiles/src/solidity/usd.sol new file mode 100644 index 0000000000..30952e26d4 --- /dev/null +++ b/precompiles/src/solidity/usd.sol @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +// USD rails precompile: the single EVM door into the canonical rails kernel +// (PSM + internal tUSD/TAO pool + share accounting). The Gateway contract +// delivers bridge envelopes through gatewayExecute; everything else is a +// read-only view. +address constant IUSD_RAILS_ADDRESS = 0x0000000000000000000000000000000000000814; + +interface IUsdRails { + /// Execute an inbound bridge envelope (SCALE-encoded, versioned). + /// Callable only by the registered Gateway contract. + function gatewayExecute(uint64 amount, bytes calldata envelope) external; + + /// Quote tUSD -> TAO through the canonical pool (9 decimals both sides). + function simSwapUsdForTao(uint64 amountUsd) external view returns (uint64); + + /// Quote TAO -> tUSD through the canonical pool (9 decimals both sides). + function simSwapTaoForUsd(uint64 amountTao) external view returns (uint64); + + /// tUSD ledger balance of a substrate account (public key bytes). + function tusdBalanceOf(bytes32 account) external view returns (uint64); + + /// Canonical pool state: (taoReserve, tusdReserve, feeBps). + function poolState() external view returns (uint64, uint64, uint16); + + /// The ERC-20 contract backing a registered PSM asset (zero if unknown). + function assetErc20(uint32 assetId) external view returns (address); + + /// Share index (1e9 fixed point) for a subnet's canonical shares. + function shareIndexE9(uint16 netuid) external view returns (uint64); + + /// Next inbound envelope nonce expected by the sequential guard. + function nextNonce() external view returns (uint64); +} diff --git a/precompiles/src/usd.rs b/precompiles/src/usd.rs new file mode 100644 index 0000000000..53faf4f592 --- /dev/null +++ b/precompiles/src/usd.rs @@ -0,0 +1,124 @@ +//! USD rails precompile (address 2068 / 0x814). +//! +//! The single EVM door into the canonical rails kernel (`pallet-usd-psm`): +//! the Gateway contract delivers bridge envelopes through `gatewayExecute`, +//! plus read-only views (quotes, pool state, share index) for clients. +//! +//! Atomicity: Frontier wraps every EVM frame in a substrate storage +//! transaction, so pallet state changes here revert together with the +//! delivering EVM frame on any failure. + +use core::marker::PhantomData; + +use fp_evm::{ExitError, PrecompileFailure}; +use pallet_evm::PrecompileHandle; +use precompile_utils::EvmResult; +use precompile_utils::prelude::{Address, UnboundedBytes}; +use sp_core::H256; +use sp_runtime::AccountId32; +use subtensor_runtime_common::NetUid; + +use crate::PrecompileExt; +use crate::extensions::PrecompileHandleExt; + +pub struct UsdRailsPrecompile(PhantomData); + +impl PrecompileExt for UsdRailsPrecompile +where + R: frame_system::Config + pallet_evm::Config + pallet_usd_psm::Config, +{ + const INDEX: u64 = 2068; +} + +#[precompile_utils::precompile] +impl UsdRailsPrecompile +where + R: frame_system::Config + pallet_evm::Config + pallet_usd_psm::Config, +{ + /// Execute an inbound gateway envelope. Callable only by the registered + /// Gateway contract; the pallet enforces the caller check. + #[precompile::public("gatewayExecute(uint64,bytes)")] + fn gateway_execute( + handle: &mut impl PrecompileHandle, + amount: u64, + envelope: UnboundedBytes, + ) -> EvmResult<()> { + handle.record_db_reads::(16)?; + let caller = handle.context().caller; + pallet_usd_psm::Pallet::::do_gateway_execute(caller, amount, envelope.as_bytes()) + .map_err(dispatch_error) + } + + /// Quote tUSD -> TAO through the canonical pool. + #[precompile::public("simSwapUsdForTao(uint64)")] + #[precompile::view] + fn sim_swap_usd_for_tao(handle: &mut impl PrecompileHandle, amount_usd: u64) -> EvmResult { + handle.record_db_reads::(3)?; + Ok(pallet_usd_psm::Pallet::::quote_tusd_for_tao(amount_usd).unwrap_or_default()) + } + + /// Quote TAO -> tUSD through the canonical pool. + #[precompile::public("simSwapTaoForUsd(uint64)")] + #[precompile::view] + fn sim_swap_tao_for_usd(handle: &mut impl PrecompileHandle, amount_tao: u64) -> EvmResult { + handle.record_db_reads::(3)?; + Ok(pallet_usd_psm::Pallet::::quote_tao_for_tusd(amount_tao).unwrap_or_default()) + } + + /// tUSD ledger balance of a substrate account. + #[precompile::public("tusdBalanceOf(bytes32)")] + #[precompile::view] + fn tusd_balance_of(handle: &mut impl PrecompileHandle, account: H256) -> EvmResult { + handle.record_db_reads::(1)?; + Ok(pallet_usd_psm::Pallet::::tusd_balance(&AccountId32::new(account.0))) + } + + /// Canonical pool state: (taoReserve, tusdReserve, feeBps). + #[precompile::public("poolState()")] + #[precompile::view] + fn pool_state(handle: &mut impl PrecompileHandle) -> EvmResult<(u64, u64, u16)> { + handle.record_db_reads::(3)?; + Ok(( + pallet_usd_psm::PoolTaoReserve::::get(), + pallet_usd_psm::PoolTUsdReserve::::get(), + pallet_usd_psm::PoolFeeBps::::get(), + )) + } + + /// The ERC-20 contract backing a PSM asset. + #[precompile::public("assetErc20(uint32)")] + #[precompile::view] + fn asset_erc20(handle: &mut impl PrecompileHandle, asset_id: u32) -> EvmResult

{ + handle.record_db_reads::(1)?; + Ok(Address( + pallet_usd_psm::Pallet::::psm_asset(asset_id) + .map(|a| a.erc20) + .unwrap_or_default(), + )) + } + + /// Share index (1e9 fixed point) for a subnet's canonical shares. + #[precompile::public("shareIndexE9(uint16)")] + #[precompile::view] + fn share_index_e9(handle: &mut impl PrecompileHandle, netuid: u16) -> EvmResult { + handle.record_db_reads::(4)?; + Ok(pallet_usd_psm::Pallet::::share_index_e9(NetUid::from( + netuid, + ))) + } + + /// Next inbound envelope nonce expected by the sequential guard. + #[precompile::public("nextNonce()")] + #[precompile::view] + fn next_nonce(handle: &mut impl PrecompileHandle) -> EvmResult { + handle.record_db_reads::(1)?; + Ok(pallet_usd_psm::Pallet::::next_nonce()) + } +} + +fn dispatch_error(err: sp_runtime::DispatchError) -> PrecompileFailure { + log::debug!("usd rails precompile dispatch error: {err:?}"); + PrecompileFailure::Error { + exit_status: ExitError::Other(alloc::format!("rails: {err:?}").into()), + } +} diff --git a/runtime/Cargo.toml b/runtime/Cargo.toml index a94518b140..0c2cd51a26 100644 --- a/runtime/Cargo.toml +++ b/runtime/Cargo.toml @@ -26,6 +26,8 @@ scale-info = { workspace = true, features = ["derive"] } serde_json = { workspace = true, features = ["alloc"] } pallet-aura = { workspace = true } pallet-alpha-assets = { workspace = true } +pallet-usd-psm = { workspace = true } +pallet-usd-psm-runtime-api = { workspace = true } pallet-balances = { workspace = true } pallet-subtensor = { workspace = true } pallet-subtensor-swap = { workspace = true } @@ -163,6 +165,8 @@ frame-metadata.workspace = true sp-tracing.workspace = true sp-keyring.workspace = true precompile-utils = { workspace = true, features = ["testing"] } +libsecp256k1 = { workspace = true, features = ["static-context", "hmac"] } +ethereum = { workspace = true } [build-dependencies] substrate-wasm-builder = { workspace = true, optional = true } @@ -189,6 +193,8 @@ std = [ "frame-try-runtime/std", "pallet-subtensor/std", "pallet-alpha-assets/std", + "pallet-usd-psm/std", + "pallet-usd-psm-runtime-api/std", "pallet-balances/std", "pallet-grandpa/std", "pallet-insecure-randomness-collective-flip/std", diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index d3fb8ccf9c..a05bfc0c56 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -498,6 +498,172 @@ impl pallet_balances::Config for Runtime { impl pallet_alpha_assets::Config for Runtime {} +parameter_types! { + pub const UsdPsmPalletId: PalletId = PalletId(*b"sn/rails"); +} + +/// Bridges the USD PSM pallet to the staking engine in `pallet-subtensor` +/// (loose coupling: neither pallet crate depends on the other). +pub struct SubtensorRailsStaking; + +impl pallet_usd_psm::RailsStaking for SubtensorRailsStaking { + fn stake( + coldkey: &AccountId, + hotkey: &AccountId, + netuid: NetUid, + tao: TaoBalance, + min_alpha: AlphaBalance, + ) -> Result { + let origin: RuntimeOrigin = frame_system::RawOrigin::Signed(coldkey.clone()).into(); + let alpha = + pallet_subtensor::Pallet::::do_add_stake(origin, hotkey.clone(), netuid, tao)?; + frame_support::ensure!( + alpha >= min_alpha, + pallet_usd_psm::Error::::SlippageExceeded + ); + Ok(alpha) + } + + fn unstake( + coldkey: &AccountId, + hotkey: &AccountId, + netuid: NetUid, + alpha: AlphaBalance, + min_tao: TaoBalance, + ) -> Result { + // `do_remove_stake` credits TAO to the coldkey but does not return the + // amount; measure the free-balance delta (refunds included). + let before = Balances::free_balance(coldkey); + let origin: RuntimeOrigin = frame_system::RawOrigin::Signed(coldkey.clone()).into(); + pallet_subtensor::Pallet::::do_remove_stake( + origin, + hotkey.clone(), + netuid, + alpha, + )?; + let after = Balances::free_balance(coldkey); + let tao_out = after.saturating_sub(before); + frame_support::ensure!( + tao_out >= min_tao, + pallet_usd_psm::Error::::SlippageExceeded + ); + Ok(tao_out) + } + + fn stake_of(hotkey: &AccountId, coldkey: &AccountId, netuid: NetUid) -> u64 { + pallet_subtensor::Pallet::::get_stake_for_hotkey_and_coldkey_on_subnet( + hotkey, coldkey, netuid, + ) + .into() + } +} + +/// Outbound bridge leg: the runtime dispatches a Hyperlane message by +/// executing `Mailbox.dispatch()` as a real Ethereum transaction from the +/// keyless hub address. +/// +/// Novelty note: a bare `Runner::call` would mutate EVM state but its logs +/// would never appear in an Ethereum block, so bridge agents (which index +/// via `eth_getLogs`) would miss the dispatch. Instead we build a +/// dummy-signed EIP-1559 transaction and hand it to `pallet_ethereum` with +/// an already-authenticated `EthereumTransaction` origin (the signature is +/// never recovered on this path), which records real receipts and logs. +pub struct SubtensorRailsOutbound; + +impl SubtensorRailsOutbound { + /// ABI-encode `dispatch(uint32,bytes32,bytes)`. + fn encode_dispatch_call(dest_domain: u32, recipient: [u8; 32], body: &[u8]) -> Vec { + let selector = sp_io::hashing::keccak_256(b"dispatch(uint32,bytes32,bytes)"); + let mut input = Vec::with_capacity(4 + 32 * 4 + body.len().div_ceil(32) * 32); + input.extend_from_slice(selector.get(..4).unwrap_or_default()); + // uint32 destination (left-padded). + let mut word = [0u8; 32]; + word[28..].copy_from_slice(&dest_domain.to_be_bytes()); + input.extend_from_slice(&word); + // bytes32 recipient. + input.extend_from_slice(&recipient); + // offset of the dynamic `bytes` argument (3 head words = 0x60). + let mut offset = [0u8; 32]; + offset[31] = 0x60; + input.extend_from_slice(&offset); + // bytes: length word + right-padded payload. + let mut len = [0u8; 32]; + len[24..].copy_from_slice(&(body.len() as u64).to_be_bytes()); + input.extend_from_slice(&len); + input.extend_from_slice(body); + let pad = body.len().div_ceil(32) * 32 - body.len(); + input.extend_from_slice(&vec![0u8; pad]); + input + } +} + +impl pallet_usd_psm::RailsOutbound for SubtensorRailsOutbound { + fn dispatch_mailbox( + mailbox: H160, + sender: H160, + dest_domain: u32, + recipient: [u8; 32], + body: Vec, + ) -> sp_runtime::DispatchResult { + let input = Self::encode_dispatch_call(dest_domain, recipient, &body); + let (who, _) = pallet_evm::Pallet::::account_basic(&sender); + let (base_fee, _) = ::FeeCalculator::min_gas_price(); + + // Dummy signature: this transaction is applied through an + // already-authenticated origin, never signature-recovered. Non-zero + // r/s keep the transaction hash well-defined. + let signature = ethereum::eip2930::TransactionSignature::new( + false, + H256::from_low_u64_be(1), + H256::from_low_u64_be(1), + ) + .ok_or(sp_runtime::DispatchError::Other("rails: bad dummy signature"))?; + + let transaction = pallet_ethereum::Transaction::EIP1559(ethereum::EIP1559Transaction { + chain_id: ::ChainId::get(), + nonce: who.nonce, + max_priority_fee_per_gas: U256::zero(), + max_fee_per_gas: base_fee, + gas_limit: U256::from(1_000_000u64), + action: pallet_ethereum::TransactionAction::Call(mailbox), + value: U256::zero(), + input, + access_list: Vec::new(), + signature, + }); + + let origin: RuntimeOrigin = + pallet_ethereum::RawOrigin::EthereumTransaction(sender).into(); + pallet_ethereum::Pallet::::transact(origin, transaction).map_err(|e| e.error)?; + + // `transact` succeeds even when the inner EVM frame reverted; the + // wrap must not: check the recorded receipt of the transaction we + // just appended to the block under construction. + let last_index = pallet_ethereum::Pending::::count().saturating_sub(1); + if let Some((_, _, receipt)) = pallet_ethereum::Pending::::get(last_index) { + let status_code = match receipt { + pallet_ethereum::Receipt::Legacy(ref d) + | pallet_ethereum::Receipt::EIP2930(ref d) + | pallet_ethereum::Receipt::EIP1559(ref d) + | pallet_ethereum::Receipt::EIP7702(ref d) => d.status_code, + }; + frame_support::ensure!( + status_code == 1, + sp_runtime::DispatchError::Other("rails: mailbox dispatch reverted") + ); + } + Ok(()) + } +} + +impl pallet_usd_psm::Config for Runtime { + type Currency = Balances; + type Staking = SubtensorRailsStaking; + type Outbound = SubtensorRailsOutbound; + type AdminOrigin = EnsureRoot; + type PalletId = UsdPsmPalletId; +} + // Implement AuthorshipInfo trait for Runtime to satisfy pallet transaction // fee OnUnbalanced trait bounds pub struct BlockAuthorFromAura(core::marker::PhantomData); @@ -1488,6 +1654,7 @@ construct_runtime!( MevShield: pallet_shield = 30, AlphaAssets: pallet_alpha_assets = 31, LimitOrders: pallet_limit_orders = 32, + UsdPsm: pallet_usd_psm = 33, } ); @@ -2558,6 +2725,64 @@ impl_runtime_apis! { } } + impl pallet_usd_psm_runtime_api::RailsRuntimeApi for Runtime { + fn rails_quote_usd_to_tao(amount: u64) -> Option { + pallet_usd_psm::Pallet::::quote_tusd_for_tao(amount) + } + + fn rails_quote_tao_to_usd(amount: u64) -> Option { + pallet_usd_psm::Pallet::::quote_tao_for_tusd(amount) + } + + fn rails_pool_state() -> pallet_usd_psm_runtime_api::RailsPoolState { + pallet_usd_psm_runtime_api::RailsPoolState { + tao_reserve: pallet_usd_psm::PoolTaoReserve::::get(), + tusd_reserve: pallet_usd_psm::PoolTUsdReserve::::get(), + fee_bps: pallet_usd_psm::PoolFeeBps::::get(), + } + } + + fn rails_assets() -> Vec { + let now = frame_system::Pallet::::block_number(); + pallet_usd_psm::PsmAssets::::iter() + .map(|(asset_id, asset)| pallet_usd_psm_runtime_api::RailsAssetInfo { + asset_id, + erc20: asset.erc20, + reserves: asset.reserves, + available: asset.window.available(now), + haircut_bps: asset.haircut_bps, + enabled: asset.enabled, + }) + .collect() + } + + fn rails_gateway() -> Option { + pallet_usd_psm::Pallet::::gateway() + } + + fn rails_tusd_balance(account: AccountId) -> u64 { + pallet_usd_psm::Pallet::::tusd_balance(&account) + } + + fn rails_alpha_attestation(netuid: u16) -> pallet_usd_psm_runtime_api::RailsAlphaAttestation { + let (escrowed_alpha, shares_outstanding, index_e9) = + pallet_usd_psm::Pallet::::alpha_attestation(NetUid::from(netuid)); + pallet_usd_psm_runtime_api::RailsAlphaAttestation { + escrowed_alpha, + shares_outstanding, + index_e9, + } + } + + fn rails_hub_info() -> pallet_usd_psm_runtime_api::RailsHubInfo { + pallet_usd_psm_runtime_api::RailsHubInfo { + hub_sender: pallet_usd_psm::Pallet::::hub_evm_address(), + mailbox: pallet_usd_psm::HubMailbox::::get(), + next_nonce: pallet_usd_psm::Pallet::::next_nonce(), + } + } + } + impl stp_shield::ShieldApi for Runtime { fn try_decode_shielded_tx(uxt: ::Extrinsic) -> Option { MevShield::try_decode_shielded_tx::(uxt) diff --git a/runtime/tests/rails_evm_pool_validation.rs b/runtime/tests/rails_evm_pool_validation.rs new file mode 100644 index 0000000000..add6c6565c --- /dev/null +++ b/runtime/tests/rails_evm_pool_validation.rs @@ -0,0 +1,178 @@ +//! Diagnostic: replicate the tx-pool validation of a plain EIP-1559 transfer +//! signed by the well-known anvil deployer key, against the real runtime. + +#![allow(clippy::expect_used, clippy::unwrap_used)] + +use ethereum::eip2930::TransactionSignature as Eip1559Signature; +use ethereum::{EIP1559TransactionMessage, TransactionAction}; +use fp_self_contained::SelfContainedCall; +use frame_support::dispatch::GetDispatchInfo; +use node_subtensor_runtime::{ + BuildStorage, Executive, Runtime, RuntimeCall, RuntimeGenesisConfig, UncheckedExtrinsic, +}; +use sp_runtime::transaction_validity::TransactionSource; +use pallet_evm::AddressMapping; +use sp_core::{H160, H256, U256}; +use subtensor_runtime_common::TaoBalance; + +/// Canonical anvil developer key #0 (public test key), address 0xf39F...2266. +const DEPLOYER_PK: [u8; 32] = [ + 0xac, 0x09, 0x74, 0xbe, 0xc3, 0x9a, 0x17, 0xe3, 0x6b, 0xa4, 0xa6, 0xb4, 0xd2, 0x38, 0xff, + 0x94, 0x4b, 0xac, 0xb4, 0x78, 0xcb, 0xed, 0x5e, 0xfc, 0xae, 0x78, 0x4d, 0x7b, 0xf4, 0xf2, + 0xff, 0x80, +]; + +fn new_test_ext() -> sp_io::TestExternalities { + sp_tracing::try_init_simple(); + let mut ext: sp_io::TestExternalities = RuntimeGenesisConfig { + ..Default::default() + } + .build_storage() + .unwrap() + .into(); + ext.execute_with(|| { + frame_system::Pallet::::set_block_number(1); + // Match the localnet EVM chain id. + pallet_evm_chain_id::ChainId::::put(42); + }); + ext +} + +fn deployer_address() -> H160 { + let secret = libsecp256k1::SecretKey::parse(&DEPLOYER_PK).unwrap(); + let public = libsecp256k1::PublicKey::from_secret_key(&secret); + let hash = sp_io::hashing::keccak_256(&public.serialize()[1..]); + H160::from_slice(&hash[12..]) +} + +fn signed_transfer() -> pallet_ethereum::Transaction { + let msg = EIP1559TransactionMessage { + chain_id: 42, + nonce: U256::zero(), + max_priority_fee_per_gas: U256::zero(), + max_fee_per_gas: U256::from(20_000_000_000u64), + gas_limit: U256::from(21_000u64), + action: TransactionAction::Call(H160::from_low_u64_be(0xbeef)), + value: U256::from(1_000_000_000u64), + input: vec![], + access_list: vec![], + }; + let secret = libsecp256k1::SecretKey::parse(&DEPLOYER_PK).unwrap(); + let signing_message = libsecp256k1::Message::parse_slice(&msg.hash()[..]).unwrap(); + let (signature, recid) = libsecp256k1::sign(&signing_message, &secret); + let rs = signature.serialize(); + let r = H256::from_slice(&rs[0..32]); + let s = H256::from_slice(&rs[32..64]); + pallet_ethereum::Transaction::EIP1559(ethereum::EIP1559Transaction { + chain_id: msg.chain_id, + nonce: msg.nonce, + max_priority_fee_per_gas: msg.max_priority_fee_per_gas, + max_fee_per_gas: msg.max_fee_per_gas, + gas_limit: msg.gas_limit, + action: msg.action, + value: msg.value, + input: msg.input.clone(), + access_list: msg.access_list, + signature: Eip1559Signature::new(recid.serialize() != 0, r, s).unwrap(), + }) +} + +#[test] +fn anvil_deployer_transfer_passes_pool_validation() { + new_test_ext().execute_with(|| { + let deployer = deployer_address(); + let mirror = ::AddressMapping::into_account_id(deployer); + + // Fund like the rig bootstrap: 1M TAO. + let amount = TaoBalance::from(1_000_000_000_000_000u64); + let credit = pallet_subtensor::Pallet::::mint_tao(amount); + let _ = pallet_subtensor::Pallet::::spend_tao(&mirror, credit, amount).unwrap(); + + let call = RuntimeCall::Ethereum(pallet_ethereum::Call::transact { + transaction: signed_transfer(), + }); + + let info = call.check_self_contained().expect("is self contained"); + let recovered = info.expect("signature recovers"); + assert_eq!(recovered, deployer, "recovered sender mismatch"); + + let dispatch_info = call.get_dispatch_info(); + let validity = call + .validate_self_contained(&recovered, &dispatch_info, 0) + .expect("self contained validation ran"); + assert!( + validity.is_ok(), + "pool validation failed: {:?}", + validity.unwrap_err() + ); + }); +} + +/// Raw legacy tx produced by `cast mktx` with the anvil deployer key: +/// to=0x7099..79C8, value=1e9, gasPrice=20 gwei, gasLimit=21000, nonce=0, chain=42. +const CAST_RAW_TX: &str = "f868808504a817c8008252089470997970c51812dc3a010c7d01b50e0d17dc79c8843b9aca008078a0ce7c2757764bafe941e2cb493a74f92a0a9e08147434b339f1d6e158b0f1cae0a02bdb47e97e946f2d31116af519616c988b1c7c3aaa0b77b918b611bece4051d0"; + +#[test] +fn cast_raw_tx_passes_executive_validation() { + use ethereum::EnvelopedDecodable; + + let raw = hex::decode(CAST_RAW_TX).unwrap(); + let tx = ::decode(&raw).unwrap(); + + new_test_ext().execute_with(|| { + let call = RuntimeCall::Ethereum(pallet_ethereum::Call::transact { + transaction: tx.clone(), + }); + let recovered = call + .check_self_contained() + .expect("self contained") + .expect("recovers"); + assert_eq!(recovered, deployer_address(), "recovered sender mismatch"); + + let mirror = ::AddressMapping::into_account_id(recovered); + let amount = TaoBalance::from(1_000_000_000_000_000u64); + let credit = pallet_subtensor::Pallet::::mint_tao(amount); + let _ = pallet_subtensor::Pallet::::spend_tao(&mirror, credit, amount).unwrap(); + + let uxt = UncheckedExtrinsic::new_bare(call); + + let result = Executive::validate_transaction( + TransactionSource::External, + uxt, + frame_system::Pallet::::block_hash(0u32), + ); + assert!( + result.is_ok(), + "executive validation failed: {:?}", + result.unwrap_err() + ); + }); +} + +#[test] +fn anvil_deployer_transfer_passes_executive_validation() { + new_test_ext().execute_with(|| { + let deployer = deployer_address(); + let mirror = ::AddressMapping::into_account_id(deployer); + + let amount = TaoBalance::from(1_000_000_000_000_000u64); + let credit = pallet_subtensor::Pallet::::mint_tao(amount); + let _ = pallet_subtensor::Pallet::::spend_tao(&mirror, credit, amount).unwrap(); + + let call = RuntimeCall::Ethereum(pallet_ethereum::Call::transact { + transaction: signed_transfer(), + }); + let uxt = UncheckedExtrinsic::new_bare(call); + + let result = Executive::validate_transaction( + TransactionSource::External, + uxt, + frame_system::Pallet::::block_hash(0u32), + ); + assert!( + result.is_ok(), + "executive validation failed: {:?}", + result.unwrap_err() + ); + }); +} diff --git a/scripts/localnet.sh b/scripts/localnet.sh index ab34221d8e..924fdb7327 100755 --- a/scripts/localnet.sh +++ b/scripts/localnet.sh @@ -214,6 +214,10 @@ if [ $BUILD_ONLY -eq 0 ]; then done } + # Archive mode keeps historical state queryable. Frontier's eth_getLogs / + # eth_getTransactionReceipt read receipts from per-block state, so with the + # default 256-block state pruning EVM logs silently disappear after ~4 min, + # which breaks anything indexing history (e.g. Hyperlane agents). one_start=( "$NODE_BINARY" --base-path /tmp/one @@ -226,6 +230,8 @@ if [ $BUILD_ONLY -eq 0 ]; then --allow-private-ipv4 --discover-local --unsafe-force-node-key-generation + --state-pruning archive + --blocks-pruning archive ) two_start=( @@ -240,6 +246,8 @@ if [ $BUILD_ONLY -eq 0 ]; then --allow-private-ipv4 --discover-local --unsafe-force-node-key-generation + --state-pruning archive + --blocks-pruning archive ) # Insert //Three keys manually (no --three shorthand exists in Substrate) @@ -268,6 +276,8 @@ if [ $BUILD_ONLY -eq 0 ]; then --allow-private-ipv4 --discover-local --unsafe-force-node-key-generation + --state-pruning archive + --blocks-pruning archive ) # Provide RUN_IN_DOCKER local environment variable if run script in the docker image diff --git a/scripts/rails/agents.sh b/scripts/rails/agents.sh new file mode 100755 index 0000000000..f4b0bf23aa --- /dev/null +++ b/scripts/rails/agents.sh @@ -0,0 +1,88 @@ +#!/usr/bin/env bash +# Run the self-hosted Hyperlane agents in docker: one validator per chain +# (in production these are sidecars on subtensor validators) plus one relayer. +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)" +# shellcheck source=env.sh +source "$SCRIPT_DIR/env.sh" + +CMD="${1:-start}" + +CONTAINERS=(rails-validator-btlocal rails-validator-baselocal rails-relayer) + +stop_all() { + for c in "${CONTAINERS[@]}"; do + docker rm -f "$c" >/dev/null 2>&1 || true + done +} + +start_validator() { + local chain="$1" + local name="rails-validator-$chain" + mkdir -p "$RAILS_CHECKPOINT_DIR/$chain" "$RAILS_STATE_DIR/validator-db-$chain" + # The agent image runs as uid 1000; state dirs must be writable. + chmod -R a+rwX "$RAILS_CHECKPOINT_DIR/$chain" "$RAILS_STATE_DIR/validator-db-$chain" + # The announced checkpoint location (file:///checkpoints/) must + # resolve identically inside the relayer container, so validators and the + # relayer all mount the whole checkpoint dir at /checkpoints. + docker run -d --name "$name" \ + --add-host host.docker.internal:host-gateway \ + -v "$RAILS_AGENT_DIR/agent-config.docker.json:/config/agent-config.json:ro" \ + -v "$RAILS_CHECKPOINT_DIR:/checkpoints" \ + -v "$RAILS_STATE_DIR/validator-db-$chain:/db" \ + -e CONFIG_FILES=/config/agent-config.json \ + "$HYPERLANE_AGENT_IMAGE" \ + ./validator \ + --db /db \ + --originChainName "$chain" \ + --checkpointSyncer.type localStorage \ + --checkpointSyncer.path "/checkpoints/$chain" \ + --validator.key "$VALIDATOR_PK" \ + --chains."$chain".signer.key "$VALIDATOR_PK" \ + >/dev/null + echo "[rails] started $name" +} + +start_relayer() { + mkdir -p "$RAILS_STATE_DIR/relayer-db" + chmod -R a+rwX "$RAILS_STATE_DIR/relayer-db" "$RAILS_CHECKPOINT_DIR" + docker run -d --name rails-relayer \ + --add-host host.docker.internal:host-gateway \ + -v "$RAILS_AGENT_DIR/agent-config.docker.json:/config/agent-config.json:ro" \ + -v "$RAILS_CHECKPOINT_DIR:/checkpoints:ro" \ + -v "$RAILS_STATE_DIR/relayer-db:/db" \ + -e CONFIG_FILES=/config/agent-config.json \ + "$HYPERLANE_AGENT_IMAGE" \ + ./relayer \ + --db /db \ + --relayChains "$BT_CHAIN_NAME,$BASE_CHAIN_NAME" \ + --allowLocalCheckpointSyncers true \ + --defaultSigner.key "$RELAYER_PK" \ + --gasPaymentEnforcement '[{"type": "none"}]' \ + >/dev/null + echo "[rails] started rails-relayer" +} + +case "$CMD" in + start) + stop_all + start_validator "$BT_CHAIN_NAME" + start_validator "$BASE_CHAIN_NAME" + start_relayer + ;; + stop) + stop_all + echo "[rails] agents stopped" + ;; + logs) + for c in "${CONTAINERS[@]}"; do + echo "===== $c =====" + docker logs --tail 20 "$c" 2>&1 || true + done + ;; + *) + echo "usage: agents.sh start|stop|logs" >&2 + exit 1 + ;; +esac diff --git a/scripts/rails/demo.sh b/scripts/rails/demo.sh new file mode 100755 index 0000000000..93c87b3b86 --- /dev/null +++ b/scripts/rails/demo.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# Serve the CHUTES demo page against the live rig. MetaMask requires an +# http(s) origin, so we serve the repo root (page fetches ../.rails/manifest.json). +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)" +# shellcheck source=env.sh +source "$SCRIPT_DIR/env.sh" + +[ -f "$RAILS_MANIFEST" ] || { echo "[rails] no manifest; run up.sh first" >&2; exit 1; } + +PORT="${DEMO_PORT:-8666}" +URL="http://127.0.0.1:${PORT}/demo/" + +echo "[rails] serving demo at $URL" +command -v open >/dev/null && open "$URL" & +exec python3 -m http.server "$PORT" --bind 127.0.0.1 --directory "$RAILS_BASE_DIR" diff --git a/scripts/rails/deploy-contracts.sh b/scripts/rails/deploy-contracts.sh new file mode 100755 index 0000000000..1fee24a3ce --- /dev/null +++ b/scripts/rails/deploy-contracts.sh @@ -0,0 +1,194 @@ +#!/usr/bin/env bash +# Deploy the chain-owned rails contracts to both local chains and wire the +# trust relationships (minter windows, trusted senders). Idempotent via +# CREATE2: re-running against live chains is a no-op re-wire. +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)" +# shellcheck source=env.sh +source "$SCRIPT_DIR/env.sh" + +CONTRACTS_DIR="$RAILS_BASE_DIR/contracts/evm" + +yaml_value() { # file key + awk -v k="$2:" '$1 == k { print $2; exit }' "$1" | tr -d '"' +} + +bt_mailbox="$(yaml_value "$RAILS_REGISTRY_DIR/chains/$BT_CHAIN_NAME/addresses.yaml" mailbox)" +base_mailbox="$(yaml_value "$RAILS_REGISTRY_DIR/chains/$BASE_CHAIN_NAME/addresses.yaml" mailbox)" +[ -n "$bt_mailbox" ] && [ -n "$base_mailbox" ] || { + echo "[rails] ERROR: mailbox addresses missing; run hyperlane-deploy.sh first" >&2 + exit 1 +} + +extract_addr() { # log-file label + awk -v k="$2" '$1 == k { print $2 }' "$1" | tail -1 +} + +# The canonical CREATE2 deployer (0x4e59b4...956C) is pre-installed on anvil +# but not on the Bittensor localnet EVM. Install it via Nick's method: fund +# the one-time deployer EOA, then broadcast the well-known presigned tx. +CREATE2_DEPLOYER="0x4e59b44847b379578588920cA78FbF26c0B4956C" +CREATE2_SIGNER="0x3fAB184622Dc19b6109349B94811493BF2a45362" +CREATE2_RAW_TX="0xf8a58085174876e800830186a08080b853604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222" +wait_for_code() { # addr + for _ in $(seq 1 30); do + [ "$(cast code "$1" --rpc-url "$BT_RPC_HTTP")" != "0x" ] && return 0 + sleep 1 + done + return 1 +} +if [ "$(cast code "$CREATE2_DEPLOYER" --rpc-url "$BT_RPC_HTTP")" = "0x" ]; then + echo "[rails] installing CREATE2 deployer on $BT_CHAIN_NAME ..." + # --async: cast's receipt watcher cannot parse this node's block JSON. + cast send "$CREATE2_SIGNER" --value 100000000000000000 \ + --rpc-url "$BT_RPC_HTTP" --private-key "$DEPLOYER_PK" --legacy --async >/dev/null + for _ in $(seq 1 30); do + [ "$(cast balance "$CREATE2_SIGNER" --rpc-url "$BT_RPC_HTTP")" != "0" ] && break + sleep 1 + done + cast publish "$CREATE2_RAW_TX" --rpc-url "$BT_RPC_HTTP" --async >/dev/null + wait_for_code "$CREATE2_DEPLOYER" || { + echo "[rails] ERROR: CREATE2 deployer install failed" >&2 + exit 1 + } +fi + +echo "[rails] deploying Bittensor-EVM contracts (canonical USD + Gateway) ..." +RAILS_OWNER="$DEPLOYER_ADDR" RAILS_MAILBOX="$bt_mailbox" RAILS_PSM_ESCROW="$RAILS_PSM_ESCROW" \ + forge script "$CONTRACTS_DIR/script/DeployBittensor.s.sol:DeployBittensor" \ + --root "$CONTRACTS_DIR" \ + --rpc-url "$BT_RPC_HTTP" \ + --private-key "$DEPLOYER_PK" \ + --broadcast --slow --legacy \ + >"$RAILS_LOG_DIR/deploy-bittensor.log" 2>&1 +canonical_usd="$(extract_addr "$RAILS_LOG_DIR/deploy-bittensor.log" CANONICAL_USD)" +gateway="$(extract_addr "$RAILS_LOG_DIR/deploy-bittensor.log" GATEWAY)" +[ -n "$canonical_usd" ] && [ -n "$gateway" ] || { + echo "[rails] ERROR: Bittensor deploy failed, see $RAILS_LOG_DIR/deploy-bittensor.log" >&2 + exit 1 +} + +# The subnet token catalog: real mainnet identities (name, description, +# logo) that the configure step replicates onto localnet subnets. +CATALOG="$SCRIPT_DIR/subnets.json" +tokens_env="$(jq -r 'map(.name + "|" + .symbol) | join(",")' "$CATALOG")" +token_count="$(jq 'length' "$CATALOG")" + +echo "[rails] deploying fake-Base contracts (USDC, portal, $token_count subnet tokens) ..." +RAILS_OWNER="$DEPLOYER_ADDR" RAILS_MAILBOX="$base_mailbox" RAILS_HUB_DOMAIN="$BT_DOMAIN" \ + RAILS_GATEWAY="$gateway" RAILS_USD_ASSET_ID=0 RAILS_TOKENS="$tokens_env" \ + forge script "$CONTRACTS_DIR/script/DeployBase.s.sol:DeployBase" \ + --root "$CONTRACTS_DIR" \ + --rpc-url "$BASE_RPC_HTTP" \ + --private-key "$DEPLOYER_PK" \ + --broadcast --slow \ + >"$RAILS_LOG_DIR/deploy-base.log" 2>&1 +mock_usdc="$(extract_addr "$RAILS_LOG_DIR/deploy-base.log" MOCK_USDC)" +portal="$(extract_addr "$RAILS_LOG_DIR/deploy-base.log" PORTAL)" +[ -n "$mock_usdc" ] && [ -n "$portal" ] || { + echo "[rails] ERROR: Base deploy failed, see $RAILS_LOG_DIR/deploy-base.log" >&2 + exit 1 +} +# Collect the per-catalog-entry token addresses (TOKEN_0, TOKEN_1, ...). +token_addrs=() +for i in $(seq 0 $((token_count - 1))); do + addr="$(extract_addr "$RAILS_LOG_DIR/deploy-base.log" "TOKEN_$i")" + [ -n "$addr" ] || { + echo "[rails] ERROR: token $i missing from deploy log" >&2 + exit 1 + } + token_addrs+=("$addr") +done +# Merge deployed addresses into the catalog for the configure step. +tokens_json="$(jq -cn --slurpfile cat "$CATALOG" --args \ + '$cat[0] | to_entries | map(.value + {address: $ARGS.positional[.key]})' \ + "${token_addrs[@]}")" + +addr32() { # 0x-address -> bytes32 + printf '0x%024x%s' 0 "${1#0x}" +} + +echo "[rails] wiring trust relationships ..." +# Gateway may mint canonical USD backing: 1M USD window, 100/s refill. +cast send --rpc-url "$BT_RPC_HTTP" --private-key "$DEPLOYER_PK" --legacy \ + "$canonical_usd" "setMinterLimits(address,uint64,uint64)" \ + "$gateway" 1000000000000000 100000000000 >/dev/null +# Portal (on Base) is a trusted UsdPortal sender: buys lock USDC at origin, +# so the Gateway mints canonical USD backing on arrival. +cast send --rpc-url "$BT_RPC_HTTP" --private-key "$DEPLOYER_PK" --legacy \ + "$gateway" "setTrustedSender(uint32,bytes32,uint8)" \ + "$BASE_DOMAIN" "$(addr32 "$portal")" 1 >/dev/null +# The deployer EOA is also trusted (walking-skeleton ping dispatches directly). +cast send --rpc-url "$BT_RPC_HTTP" --private-key "$DEPLOYER_PK" --legacy \ + "$gateway" "setTrustedSender(uint32,bytes32,uint8)" \ + "$BASE_DOMAIN" "$(addr32 "$DEPLOYER_ADDR")" 1 >/dev/null +# Token sells burn shares at origin: trusted RemoteToken senders (kind 2, no +# USD mint on arrival; the runtime unstakes escrow instead). +for addr in "${token_addrs[@]}"; do + cast send --rpc-url "$BT_RPC_HTTP" --private-key "$DEPLOYER_PK" --legacy \ + "$gateway" "setTrustedSender(uint32,bytes32,uint8)" \ + "$BASE_DOMAIN" "$(addr32 "$addr")" 2 >/dev/null +done + +echo "[rails] configuring pallet-usd-psm (gateway, PSM asset, pool, $token_count demo subnets) ..." +configure_log="$RAILS_LOG_DIR/configure-pallet.log" +resolved_json="$RAILS_STATE_DIR/subnets-resolved.json" +(cd "$RAILS_BASE_DIR/ts-tests" && BT_RPC_WS="$BT_RPC_WS" \ + GATEWAY_ADDR="$gateway" CANONICAL_USD_ADDR="$canonical_usd" \ + BT_MAILBOX_ADDR="$bt_mailbox" PORTAL_ADDR="$portal" \ + BASE_DOMAIN="$BASE_DOMAIN" TOKENS_JSON="$tokens_json" \ + RESOLVED_OUT="$resolved_json" \ + pnpm exec tsx scripts/rails-configure-pallet.ts) | tee "$configure_log" +hub_sender="$(extract_addr "$configure_log" HUB_SENDER)" +netuid="$(extract_addr "$configure_log" NETUID)" +[ -n "$hub_sender" ] && [ -n "$netuid" ] && [ -f "$resolved_json" ] || { + echo "[rails] ERROR: configure step did not report HUB_SENDER/NETUID/catalog" >&2 + exit 1 +} + +echo "[rails] wiring $token_count share tokens + portal hub path on $BASE_CHAIN_NAME ..." +# Each token trusts the runtime's keyless identity for mints/index pushes and +# dispatches sell envelopes to the Gateway on the hub. +while IFS=$'\t' read -r token_addr token_netuid; do + cast send --rpc-url "$BASE_RPC_HTTP" --private-key "$DEPLOYER_PK" \ + "$token_addr" "configureHub(address,uint32,bytes32,bytes32,address,uint16,uint32)" \ + "$base_mailbox" "$BT_DOMAIN" "$(addr32 "$hub_sender")" "$(addr32 "$gateway")" \ + "$portal" "$token_netuid" 0 >/dev/null + # Portal: the token may draw sequential nonces for sell envelopes. + cast send --rpc-url "$BASE_RPC_HTTP" --private-key "$DEPLOYER_PK" \ + "$portal" "setToken(address,bool)" "$token_addr" true >/dev/null +done < <(jq -r '.[] | [.address, (.netuid | tostring)] | @tsv' "$resolved_json") +# Hub releases sell proceeds through the portal. +cast send --rpc-url "$BASE_RPC_HTTP" --private-key "$DEPLOYER_PK" \ + "$portal" "setHubReleaser(bytes32)" "$(addr32 "$hub_sender")" >/dev/null + +# Persist for the manifest step. `chutes` stays as an alias for the first +# catalog token (existing tooling reads it). +jq -n \ + --slurpfile tokens "$resolved_json" \ + --arg btMailbox "$bt_mailbox" \ + --arg canonicalUsd "$canonical_usd" \ + --arg gateway "$gateway" \ + --arg hubSender "$hub_sender" \ + --argjson netuid "$netuid" \ + --arg baseMailbox "$base_mailbox" \ + --arg mockUsdc "$mock_usdc" \ + --arg portal "$portal" \ + '{ + btlocal: { + mailbox: $btMailbox, + canonicalUsd: $canonicalUsd, + gateway: $gateway, + hubSender: $hubSender, + netuid: $netuid + }, + baselocal: { + mailbox: $baseMailbox, + mockUsdc: $mockUsdc, + portal: $portal, + chutes: $tokens[0][0].address, + tokens: $tokens[0] + } + }' >"$RAILS_STATE_DIR/contracts.json" +echo "[rails] contracts deployed and wired ($token_count subnets, first netuid $netuid)" diff --git a/scripts/rails/down.sh b/scripts/rails/down.sh new file mode 100755 index 0000000000..cb3d1074da --- /dev/null +++ b/scripts/rails/down.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash +# Tear down the local rails rig: agents, anvil, localnet. Keeps .rails state +# (registry, manifest) unless --purge is passed. +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)" +# shellcheck source=env.sh +source "$SCRIPT_DIR/env.sh" + +"$SCRIPT_DIR/agents.sh" stop + +if [ -f "$RAILS_STATE_DIR/anvil.pid" ]; then + kill "$(cat "$RAILS_STATE_DIR/anvil.pid")" 2>/dev/null || true + rm -f "$RAILS_STATE_DIR/anvil.pid" +fi +# Belt and braces: the pid file can be stale (e.g. after --purge), but a +# surviving anvil keeps old CREATE2 deployments and breaks the next rig. +for pid in $(lsof -ti tcp:"$ANVIL_PORT" 2>/dev/null); do + kill "$pid" 2>/dev/null || true +done +echo "[rails] anvil stopped" + +# localnet.sh traps TERM and shuts down its three nodes cleanly. +if [ -f "$RAILS_STATE_DIR/localnet-runner.pid" ]; then + kill "$(cat "$RAILS_STATE_DIR/localnet-runner.pid")" 2>/dev/null || true + rm -f "$RAILS_STATE_DIR/localnet-runner.pid" + echo "[rails] localnet stopped" +fi +# Belt and braces: any nodes recorded by localnet.sh itself. +if [ -f /tmp/subtensor-localnet.pids ]; then + while IFS= read -r pid; do + case "$pid" in + ''|*[!0-9]*) continue ;; + esac + kill "$pid" 2>/dev/null || true + done /dev/null && pwd)" +RAILS_BASE_DIR="$(cd "$RAILS_SCRIPT_DIR/../.." &>/dev/null && pwd)" +RAILS_STATE_DIR="$RAILS_BASE_DIR/.rails" +RAILS_LOG_DIR="$RAILS_STATE_DIR/logs" +RAILS_MANIFEST="$RAILS_STATE_DIR/manifest.json" +RAILS_REGISTRY_DIR="$RAILS_STATE_DIR/registry" +RAILS_CHECKPOINT_DIR="$RAILS_STATE_DIR/checkpoints" +RAILS_AGENT_DIR="$RAILS_STATE_DIR/agents" + +# Chains +BT_CHAIN_NAME="btlocal" +BT_CHAIN_ID=42 +# Hyperlane domain id. Distinct from the EVM chain id: 42 collides with a +# known Hyperlane domain (lukso), which the agents reject for unknown names. +BT_DOMAIN=10042 +BT_RPC_HTTP="http://127.0.0.1:9944" +BT_RPC_WS="ws://127.0.0.1:9944" +# RPC URL as seen from inside docker containers (agents). +BT_RPC_DOCKER="http://host.docker.internal:9944" + +BASE_CHAIN_NAME="baselocal" +# Deliberately NOT real Base's 8453: wallets that already know mainnet Base +# would silently keep using its public RPC. The Hyperlane domain keeps 8453 +# (it is baked into envelopes, routes, and contract constructor args). +BASE_CHAIN_ID=84530 +BASE_DOMAIN=8453 +ANVIL_PORT=8545 +BASE_RPC_HTTP="http://127.0.0.1:${ANVIL_PORT}" +BASE_RPC_DOCKER="http://host.docker.internal:${ANVIL_PORT}" + +# Well-known anvil developer keys (public test keys, never real funds). +DEPLOYER_PK="0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" +DEPLOYER_ADDR="0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266" +VALIDATOR_PK="0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d" +VALIDATOR_ADDR="0x70997970C51812dc3A010C7d01b50e0d17dc79C8" +RELAYER_PK="0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a" +RELAYER_ADDR="0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC" + +# The USD rails precompile address (2068 = 0x814). The precompile itself is +# the PSM escrow: it holds the canonical USD ERC-20 reserves and moves them +# via EVM subcalls (msg.sender = 0x814). +RAILS_PRECOMPILE="0x0000000000000000000000000000000000000814" +RAILS_PSM_ESCROW="$RAILS_PRECOMPILE" + +# Hyperlane agent docker image. +HYPERLANE_AGENT_IMAGE="gcr.io/abacus-labs-dev/hyperlane-agent:agents-v1.4.0" + +# Node binary produced by scripts/localnet.sh (fast runtime). +NODE_BINARY="$RAILS_BASE_DIR/target/fast-runtime/release/node-subtensor" + +mkdir -p "$RAILS_STATE_DIR" "$RAILS_LOG_DIR" "$RAILS_REGISTRY_DIR" \ + "$RAILS_CHECKPOINT_DIR" "$RAILS_AGENT_DIR" + +# Wait until an HTTP JSON-RPC endpoint answers eth_chainId. +wait_for_rpc() { + local url="$1" name="$2" tries="${3:-120}" + for _ in $(seq 1 "$tries"); do + if curl -sf -X POST -H 'Content-Type: application/json' \ + --data '{"jsonrpc":"2.0","id":1,"method":"eth_chainId","params":[]}' \ + "$url" | grep -q result; then + echo "[rails] $name RPC ready at $url" + return 0 + fi + sleep 1 + done + echo "[rails] ERROR: $name RPC at $url not ready" >&2 + return 1 +} diff --git a/scripts/rails/hyperlane-deploy.sh b/scripts/rails/hyperlane-deploy.sh new file mode 100755 index 0000000000..22c551e055 --- /dev/null +++ b/scripts/rails/hyperlane-deploy.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash +# Deploy Hyperlane core (mailbox, ISM, hooks) to both local chains using a +# file-based local registry. Idempotent: skips chains that already have +# deployed core addresses in the registry. +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)" +# shellcheck source=env.sh +source "$SCRIPT_DIR/env.sh" + +HL="npx --yes @hyperlane-xyz/cli" + +# Seed the local registry with chain metadata. +for chain in "$BT_CHAIN_NAME" "$BASE_CHAIN_NAME"; do + mkdir -p "$RAILS_REGISTRY_DIR/chains/$chain" + cp "$SCRIPT_DIR/hyperlane/$chain.metadata.yaml" \ + "$RAILS_REGISTRY_DIR/chains/$chain/metadata.yaml" +done + +for chain in "$BT_CHAIN_NAME" "$BASE_CHAIN_NAME"; do + addresses="$RAILS_REGISTRY_DIR/chains/$chain/addresses.yaml" + if [ -f "$addresses" ] && grep -q mailbox "$addresses"; then + echo "[rails] hyperlane core already deployed on $chain" + continue + fi + echo "[rails] deploying hyperlane core to $chain ..." + $HL core deploy \ + --registry "$RAILS_REGISTRY_DIR" \ + --overrides " " \ + --chain "$chain" \ + --config "$SCRIPT_DIR/hyperlane/core-config.yaml" \ + --key "$DEPLOYER_PK" \ + --yes 2>&1 | tee "$RAILS_LOG_DIR/hyperlane-core-$chain.log" | tail -5 + [ -f "$addresses" ] || { echo "[rails] ERROR: core deploy on $chain produced no addresses" >&2; exit 1; } +done + +# Generate the agent config consumed by validator/relayer containers. +echo "[rails] generating agent config ..." +$HL registry agent-config \ + --registry "$RAILS_REGISTRY_DIR" \ + --overrides " " \ + --chains "$BT_CHAIN_NAME" "$BASE_CHAIN_NAME" \ + --yes \ + --out "$RAILS_AGENT_DIR/agent-config.json" 2>&1 | tail -2 + +# Containers reach host RPCs via host.docker.internal. +jq \ + --arg bt "$BT_RPC_DOCKER" \ + --arg base "$BASE_RPC_DOCKER" \ + '.chains.btlocal.rpcUrls = [{http: $bt}] + | .chains.baselocal.rpcUrls = [{http: $base}]' \ + "$RAILS_AGENT_DIR/agent-config.json" >"$RAILS_AGENT_DIR/agent-config.docker.json" + +echo "[rails] hyperlane core ready" diff --git a/scripts/rails/hyperlane/baselocal.metadata.yaml b/scripts/rails/hyperlane/baselocal.metadata.yaml new file mode 100644 index 0000000000..d552eaf2ce --- /dev/null +++ b/scripts/rails/hyperlane/baselocal.metadata.yaml @@ -0,0 +1,18 @@ +# Hyperlane chain metadata for the fake Base chain (anvil). +name: baselocal +protocol: ethereum +chainId: 84530 +domainId: 8453 +displayName: Base Localnet +nativeToken: + name: Ether + symbol: ETH + decimals: 18 +rpcUrls: + - http: http://127.0.0.1:8545 +blocks: + confirmations: 1 + reorgPeriod: 0 + estimateBlockTime: 1 +technicalStack: other +isTestnet: true diff --git a/scripts/rails/hyperlane/btlocal.metadata.yaml b/scripts/rails/hyperlane/btlocal.metadata.yaml new file mode 100644 index 0000000000..97691608f6 --- /dev/null +++ b/scripts/rails/hyperlane/btlocal.metadata.yaml @@ -0,0 +1,18 @@ +# Hyperlane chain metadata for the subtensor localnet EVM. +name: btlocal +protocol: ethereum +chainId: 42 +domainId: 10042 +displayName: Bittensor Localnet +nativeToken: + name: TAO + symbol: TAO + decimals: 18 +rpcUrls: + - http: http://127.0.0.1:9944 +blocks: + confirmations: 1 + reorgPeriod: 1 + estimateBlockTime: 1 +technicalStack: other +isTestnet: true diff --git a/scripts/rails/hyperlane/core-config.yaml b/scripts/rails/hyperlane/core-config.yaml new file mode 100644 index 0000000000..ece28ab208 --- /dev/null +++ b/scripts/rails/hyperlane/core-config.yaml @@ -0,0 +1,17 @@ +# Hyperlane core deployment config for both local chains. +# ISM: 1-of-1 message-id multisig over our own validator (self-run sidecar). +# Roster ISM / slashing integration is a later, out-of-scope hardening step. +owner: "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266" +defaultIsm: + type: messageIdMultisigIsm + validators: + - "0x70997970C51812dc3A010C7d01b50e0d17dc79C8" + threshold: 1 +defaultHook: + type: merkleTreeHook +requiredHook: + type: protocolFee + owner: "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266" + beneficiary: "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266" + maxProtocolFee: "1000000000000000000" + protocolFee: "0" diff --git a/scripts/rails/manifest.sh b/scripts/rails/manifest.sh new file mode 100755 index 0000000000..bfe94f5ffa --- /dev/null +++ b/scripts/rails/manifest.sh @@ -0,0 +1,64 @@ +#!/usr/bin/env bash +# Write the rig manifest: the single JSON file that ts-tests and btcli read +# to find every endpoint and address in the local rig. +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)" +# shellcheck source=env.sh +source "$SCRIPT_DIR/env.sh" + +[ -f "$RAILS_STATE_DIR/contracts.json" ] || { + echo "[rails] ERROR: contracts.json missing; run deploy-contracts.sh first" >&2 + exit 1 +} + +jq -n \ + --slurpfile contracts "$RAILS_STATE_DIR/contracts.json" \ + --arg btRpcHttp "$BT_RPC_HTTP" \ + --arg btRpcWs "$BT_RPC_WS" \ + --arg baseRpcHttp "$BASE_RPC_HTTP" \ + --argjson btChainId "$BT_CHAIN_ID" \ + --argjson btDomain "$BT_DOMAIN" \ + --argjson baseChainId "$BASE_CHAIN_ID" \ + --argjson baseDomain "$BASE_DOMAIN" \ + --arg psmEscrow "$RAILS_PSM_ESCROW" \ + --arg precompile "$RAILS_PRECOMPILE" \ + --arg deployer "$DEPLOYER_ADDR" \ + --arg validator "$VALIDATOR_ADDR" \ + --arg relayer "$RELAYER_ADDR" \ + '{ + version: 1, + chains: { + btlocal: { + chainId: $btChainId, + domain: $btDomain, + rpcHttp: $btRpcHttp, + rpcWs: $btRpcWs, + mailbox: $contracts[0].btlocal.mailbox, + canonicalUsd: $contracts[0].btlocal.canonicalUsd, + gateway: $contracts[0].btlocal.gateway, + hubSender: $contracts[0].btlocal.hubSender, + netuid: $contracts[0].btlocal.netuid, + usdRailsPrecompile: $precompile, + psmEscrow: $psmEscrow + }, + baselocal: { + chainId: $baseChainId, + domain: $baseDomain, + rpcHttp: $baseRpcHttp, + mailbox: $contracts[0].baselocal.mailbox, + mockUsdc: $contracts[0].baselocal.mockUsdc, + portal: $contracts[0].baselocal.portal, + chutes: $contracts[0].baselocal.chutes, + tokens: $contracts[0].baselocal.tokens + } + }, + accounts: { + deployer: $deployer, + hyperlaneValidator: $validator, + relayer: $relayer + } + }' >"$RAILS_MANIFEST" + +echo "[rails] wrote $RAILS_MANIFEST" +jq . "$RAILS_MANIFEST" diff --git a/scripts/rails/ping.sh b/scripts/rails/ping.sh new file mode 100755 index 0000000000..d84ecd310b --- /dev/null +++ b/scripts/rails/ping.sh @@ -0,0 +1,64 @@ +#!/usr/bin/env bash +# Walking-skeleton ping (gate G1): lock 1 test USDC through the portal with a +# CreditTUsd envelope and watch it traverse +# anvil -> validator/relayer agents -> Bittensor mailbox -> Gateway -> runtime. +# Routes through portal.deposit() so the portal's sequential nonce counter +# stays in sync with the hub's NextNonce (a direct mailbox dispatch would +# desync them and wedge the rig). +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)" +# shellcheck source=env.sh +source "$SCRIPT_DIR/env.sh" + +[ -f "$RAILS_MANIFEST" ] || { echo "[rails] no manifest; run up.sh first" >&2; exit 1; } + +portal="$(jq -r '.chains.baselocal.portal' "$RAILS_MANIFEST")" +usdc="$(jq -r '.chains.baselocal.mockUsdc' "$RAILS_MANIFEST")" + +# Alice's well-known sr25519 public key as the destination account. +ALICE_PUB="0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d" +AMOUNT=1000000000 # 1 USDC (9 decimals) + +envelope_prefix="$(cd "$RAILS_BASE_DIR/ts-tests" \ + && pnpm exec tsx scripts/rails-envelope.ts credit 0 "$AMOUNT" "$ALICE_PUB")" +echo "[rails] envelope prefix: $envelope_prefix" + +echo "[rails] minting + approving 1 test USDC ..." +cast send --rpc-url "$BASE_RPC_HTTP" --private-key "$DEPLOYER_PK" \ + "$usdc" "mint(address,uint256)" "$DEPLOYER_ADDR" "$AMOUNT" >/dev/null +cast send --rpc-url "$BASE_RPC_HTTP" --private-key "$DEPLOYER_PK" \ + "$usdc" "approve(address,uint256)" "$portal" "$AMOUNT" >/dev/null + +echo "[rails] dispatching ping deposit through the portal ..." +tx_out="$(cast send --rpc-url "$BASE_RPC_HTTP" --private-key "$DEPLOYER_PK" --json \ + "$portal" "deposit(uint64,bytes)" "$AMOUNT" "$envelope_prefix")" +echo "$tx_out" | jq -r '"[rails] origin tx: " + .transactionHash' + +# Deposited(address indexed from, uint64 amount, uint64 indexed nonce, +# bytes32 messageId): the portal-assigned nonce is the second indexed topic. +deposited_topic="$(cast keccak "Deposited(address,uint64,uint64,bytes32)")" +nonce_hex="$(echo "$tx_out" \ + | jq -r --arg t "$deposited_topic" \ + '[.logs[] | select(.topics[0] == $t)][0].topics[2]')" +nonce="$((nonce_hex))" +echo "[rails] portal-assigned nonce: $nonce" + +echo "[rails] waiting for runtime execution ..." +for i in $(seq 1 90); do + processed="$(cd "$RAILS_BASE_DIR/ts-tests" \ + && pnpm exec tsx scripts/rails-check-nonce.ts "$nonce")" + case "$processed" in + *block*) + echo "[rails] $processed" + echo "[rails] G1 PASS: envelope processed by runtime in ~${i} polls" + exit 0 + ;; + esac + sleep 2 +done + +echo "[rails] G1 FAIL: nonce $nonce not processed within 180s" >&2 +echo "[rails] agent logs:" >&2 +"$SCRIPT_DIR/agents.sh" logs >&2 +exit 1 diff --git a/scripts/rails/subnets.json b/scripts/rails/subnets.json new file mode 100644 index 0000000000..43cdcaf9f4 --- /dev/null +++ b/scripts/rails/subnets.json @@ -0,0 +1,66 @@ +[ + { + "mainnetNetuid": 1, + "name": "Apex", + "symbol": "APEX", + "description": "Open competitions for algorithmic and agentic optimization", + "logo": "https://www.macrocosmos.ai/images/mc_logo_black.png", + "url": "https://apex.macrocosmos.ai" + }, + { + "mainnetNetuid": 4, + "name": "Targon", + "symbol": "TARGON", + "description": "Incentivized Compute Marketplace powered by the Targon Virtual Machine (TVM).", + "logo": "https://www.manifold.inc/favicon.svg", + "url": "https://targon.com" + }, + { + "mainnetNetuid": 8, + "name": "Vanta", + "symbol": "VANTA", + "description": "The first decentralized & trustless liquidity and execution engine for prop firms and traders", + "logo": "https://website-git-ken-vanta-taoshi.vercel.app/black-white.png", + "url": "https://www.vantanetwork.io/" + }, + { + "mainnetNetuid": 19, + "name": "blockmachine", + "symbol": "BLOCK", + "description": "Harnessing Bittensor's incentive layer to forge self-optimizing infrastructure.", + "logo": "https://blockmachine.io/logo.svg", + "url": "blockmachine.io" + }, + { + "mainnetNetuid": 51, + "name": "lium.io", + "symbol": "LIUM", + "description": "revolutionizing the democratization of compute", + "logo": "https://raw.githubusercontent.com/Datura-ai/lium-logos/refs/heads/main/Celium_Icon_FullColor.png", + "url": "lium.io" + }, + { + "mainnetNetuid": 56, + "name": "Gradients", + "symbol": "GRAD", + "description": "Best AutoML plaftorm in the world", + "logo": "https://gradients-public.s3.eu-central-003.backblazeb2.com/gradientslogo.png", + "url": "https://www.gradients.io/" + }, + { + "mainnetNetuid": 62, + "name": "Ridges", + "symbol": "RIDGES", + "description": "Software Engineering Agents", + "logo": "https://www.ridges.ai/logo.png", + "url": "https://www.ridges.ai/" + }, + { + "mainnetNetuid": 64, + "name": "Chutes", + "symbol": "CHUTES", + "description": "Breakthrough Serverless Compute for AI, At Scale.", + "logo": "https://storage.googleapis.com/chutes-random/logo-chutes.png", + "url": "https://chutes.ai" + } +] \ No newline at end of file diff --git a/scripts/rails/up.sh b/scripts/rails/up.sh new file mode 100755 index 0000000000..284677b2f6 --- /dev/null +++ b/scripts/rails/up.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# Bring up the full local rails rig: +# subtensor localnet + anvil (fake Base) + Hyperlane core + self-run agents +# + rails contracts, then write the rig manifest consumed by ts-tests/btcli. +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)" +# shellcheck source=env.sh +source "$SCRIPT_DIR/env.sh" + +cd "$RAILS_BASE_DIR" + +echo "[rails] === 1/7 localnet ===" +if curl -sf -X POST -H 'Content-Type: application/json' \ + --data '{"jsonrpc":"2.0","id":1,"method":"eth_chainId","params":[]}' \ + "$BT_RPC_HTTP" >/dev/null 2>&1; then + echo "[rails] localnet already running" +else + if [ ! -x "$NODE_BINARY" ]; then + echo "[rails] node binary missing; building (this takes a while)..." + BUILD_BINARY=1 "$RAILS_BASE_DIR/scripts/localnet.sh" --build-only + fi + BUILD_BINARY=0 nohup "$RAILS_BASE_DIR/scripts/localnet.sh" \ + >"$RAILS_LOG_DIR/localnet.log" 2>&1 & + echo $! >"$RAILS_STATE_DIR/localnet-runner.pid" + wait_for_rpc "$BT_RPC_HTTP" "localnet" 180 +fi + +echo "[rails] === 2/7 anvil (fake Base) ===" +if curl -sf -X POST -H 'Content-Type: application/json' \ + --data '{"jsonrpc":"2.0","id":1,"method":"eth_chainId","params":[]}' \ + "$BASE_RPC_HTTP" >/dev/null 2>&1; then + echo "[rails] anvil already running" +else + nohup anvil --chain-id "$BASE_CHAIN_ID" --port "$ANVIL_PORT" --block-time 1 \ + --silent >"$RAILS_LOG_DIR/anvil.log" 2>&1 & + echo $! >"$RAILS_STATE_DIR/anvil.pid" + wait_for_rpc "$BASE_RPC_HTTP" "anvil" 30 +fi + +echo "[rails] === 3/7 substrate bootstrap (whitelist + funding) ===" +(cd "$RAILS_BASE_DIR/ts-tests" && BT_RPC_WS="$BT_RPC_WS" pnpm exec tsx scripts/rails-bootstrap.ts) + +echo "[rails] === 4/7 hyperlane core ===" +"$SCRIPT_DIR/hyperlane-deploy.sh" + +echo "[rails] === 5/7 hyperlane agents ===" +"$SCRIPT_DIR/agents.sh" start + +echo "[rails] === 6/7 rails contracts ===" +"$SCRIPT_DIR/deploy-contracts.sh" + +echo "[rails] === 7/7 manifest ===" +"$SCRIPT_DIR/manifest.sh" + +echo "[rails] rig is up. Manifest: $RAILS_MANIFEST" diff --git a/swapdemo.md b/swapdemo.md new file mode 100644 index 0000000000..42d180547b --- /dev/null +++ b/swapdemo.md @@ -0,0 +1,82 @@ +# Subnet tokens swap demo + +Buy and sell subnet tokens from MetaMask with USDC. Each token is an ERC-20 +on a local fake-Base chain, backed 1:1 by real staked alpha in an on-chain +escrow on a local Bittensor chain. Balances rebase upward as the escrow +earns emissions. + +## What you need + +- **Rust toolchain** — builds the `node-subtensor` binary (first run only, + slow). +- **Foundry** (`anvil`, `forge`, `cast`) — runs the fake Base chain and + deploys contracts. +- **Node.js + pnpm** — runs the rig scripts (`cd ts-tests && pnpm install` + once). +- **Docker** — runs the Hyperlane agents (two validators, one relayer) that + carry messages between the two chains. +- **jq**, **just** — script plumbing. +- **MetaMask** in your browser. + +## Start the rig + +```bash +just rails-up +``` + +This starts, in order: the Bittensor localnet (3 nodes), anvil (fake Base, +chain id 84530), the Hyperlane message layer, and the rails contracts. It +then creates 8 demo subnets (Apex, Targon, Vanta, blockmachine, lium.io, +Gradients, Ridges, Chutes), sets their real mainnet identities on-chain +(name, description, logo), and deploys one ERC-20 per subnet on fake Base. + +Takes ~5 minutes. It is done when it prints `rig is up` and the manifest +path. Keep the terminal open: closing it stops the chains. + +## Open the demo + +```bash +just rails-demo +``` + +This serves the page at and opens it. + +1. Click **Connect MetaMask**. The page adds the "Base rails localnet" + network for you and tops your account up with gas ETH automatically. +2. Pick a subnet in the dropdown. Name, logo, description, live pool price + and hub escrow all come from the chain. +3. Click **Faucet USDC** for test money (no signature needed). +4. Enter an amount and click **Buy**. One approve + one buy transaction. + The hub mints tUSD against your USDC, swaps to TAO, and stakes into the + subnet's escrow. The token lands in ~20–60 seconds. +5. Click **Watch in MetaMask** to see the token in your wallet. The balance + ticks upward by itself as emissions accrue (the index heartbeat pushes + every ~20 blocks). +6. **Sell** any amount (blank = all). The hub unstakes, swaps back, and + USDC returns to your address. + +The log at the bottom of the page narrates every step and prints wallet +errors verbatim. + +## Check it from the terminal + +```bash +just rails-ping # end-to-end message round trip +cd ts-tests && pnpm exec moonwall test rails # full e2e suite (12 tests) +``` + +## Stop it + +```bash +just rails-down # stop chains + agents, keep state +just rails-down --purge # also wipe state (next up is a fresh rig) +``` + +## Known localnet quirks + +- MetaMask cannot show fiat prices or charts for a custom chain; the page's + "Price (pool quote)" row is the real execution price. +- After a `--purge` restart, MetaMask's cached nonce can go stale. The page + detects the stuck transaction and heals it automatically (watch the log). +- If MetaMask refuses the network add, add it manually: RPC + `http://localhost:8545`, chain id `84530`, currency ETH. diff --git a/ts-tests/moonwall.config.json b/ts-tests/moonwall.config.json index e3c23933e6..2890690d3f 100644 --- a/ts-tests/moonwall.config.json +++ b/ts-tests/moonwall.config.json @@ -1,6 +1,6 @@ { "$schema": "https://raw.githubusercontent.com/Moonsong-Labs/moonwall/main/packages/types/config_schema.json", - "label": "💃 MasterConfig", + "label": "\ud83d\udc83 MasterConfig", "defaultTestTimeout": 120000, "scriptsDir": "scripts/", "environments": [ @@ -282,6 +282,30 @@ ] } ] + }, + { + "name": "rails", + "timeout": 600000, + "defaultTestTimeout": 600000, + "testFileDir": [ + "suites/rails" + ], + "multiThreads": false, + "reporters": [ + "basic" + ], + "foundation": { + "type": "read_only" + }, + "connections": [ + { + "name": "node", + "type": "polkadotJs", + "endpoints": [ + "ws://127.0.0.1:9944" + ] + } + ] } ] -} +} \ No newline at end of file diff --git a/ts-tests/scripts/rails-bootstrap.ts b/ts-tests/scripts/rails-bootstrap.ts new file mode 100644 index 0000000000..299038f49b --- /dev/null +++ b/ts-tests/scripts/rails-bootstrap.ts @@ -0,0 +1,89 @@ +/** + * Substrate-side bootstrap for the rails rig, run with tsx from ts-tests + * (which provides @polkadot/api): disables the EVM deploy whitelist and + * funds the rig's EVM accounts with TAO via their SS58 mirrors. + * + * Usage: pnpm exec tsx ../scripts/rails/bootstrap.ts + */ +import { ApiPromise, WsProvider } from "@polkadot/api"; +import { Keyring } from "@polkadot/keyring"; +import { blake2AsU8a, encodeAddress } from "@polkadot/util-crypto"; +import { hexToU8a, stringToU8a, u8aConcat } from "@polkadot/util"; + +const WS_URL = process.env.BT_RPC_WS ?? "ws://127.0.0.1:9944"; +const SS58_PREFIX = 42; +// 1M TAO per rig account: ample for gas, far below u64 issuance limits. +const FUND_RAO = 1_000_000n * 10n ** 9n; + +const EVM_ACCOUNTS: Record = { + deployer: process.env.DEPLOYER_ADDR ?? "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", + relayer: process.env.RELAYER_ADDR ?? "0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC", + // The btlocal Hyperlane validator must self-announce its checkpoint + // location on-chain; without gas here, outbound messages never relay. + hyperlaneValidator: process.env.VALIDATOR_ADDR ?? "0x70997970C51812dc3A010C7d01b50e0d17dc79C8", +}; + +/** SS58 mirror of an H160: blake2_256("evm:" ++ h160) — Frontier's HashedAddressMapping. */ +function h160ToSS58(ethAddress: string): string { + const prefixed = u8aConcat(stringToU8a("evm:"), hexToU8a(ethAddress)); + return encodeAddress(blake2AsU8a(prefixed, 256), SS58_PREFIX); +} + +async function signAndWait(api: ApiPromise, tx: any, signer: any, label: string): Promise { + await new Promise((resolve, reject) => { + tx.signAndSend(signer, ({ status, dispatchError }: any) => { + if (dispatchError) { + reject(new Error(`${label}: ${dispatchError.toString()}`)); + } else if (status.isInBlock || status.isFinalized) { + resolve(); + } + }).catch(reject); + }); + console.log(`[bootstrap] ${label}: ok`); +} + +async function main() { + const api = await ApiPromise.create({ + provider: new WsProvider(WS_URL), + noInitWarn: true, + }); + const alice = new Keyring({ type: "sr25519" }).addFromUri("//Alice"); + + // 1. Disable the EVM deploy whitelist so the rig deployer can create + // contracts (localnet-only setting). + const whitelistDisabled = (await api.query.evm.disableWhitelistCheck()).toPrimitive(); + if (whitelistDisabled !== true) { + await signAndWait( + api, + api.tx.sudo.sudo(api.tx.evm.disableWhitelist(true)), + alice, + "disable EVM whitelist" + ); + } else { + console.log("[bootstrap] EVM whitelist already disabled"); + } + + // 2. Fund the rig EVM accounts through their SS58 mirrors. + for (const [label, h160] of Object.entries(EVM_ACCOUNTS)) { + const mirror = h160ToSS58(h160); + const account: any = (await api.query.system.account(mirror)).toPrimitive(); + const free = BigInt(account?.data?.free ?? 0); + if (free >= FUND_RAO) { + console.log(`[bootstrap] ${label} (${h160}) already funded`); + continue; + } + await signAndWait( + api, + api.tx.sudo.sudo(api.tx.balances.forceSetBalance(mirror, FUND_RAO)), + alice, + `fund ${label} ${h160}` + ); + } + + await api.disconnect(); +} + +main().catch((err) => { + console.error("[bootstrap] FAILED:", err); + process.exit(1); +}); diff --git a/ts-tests/scripts/rails-check-emissions.ts b/ts-tests/scripts/rails-check-emissions.ts new file mode 100644 index 0000000000..f3b656dcbc --- /dev/null +++ b/ts-tests/scripts/rails-check-emissions.ts @@ -0,0 +1,23 @@ +import { ApiPromise, WsProvider } from "@polkadot/api"; + +async function main() { + const api = await ApiPromise.create({ + provider: new WsProvider("ws://127.0.0.1:9944"), + noInitWarn: true, + }); + const alice = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"; + const read = async () => + BigInt((await api.query.subtensorModule.totalHotkeyAlpha(alice, 7)).toString()); + const a = await read(); + await new Promise((r) => setTimeout(r, 20000)); + const b = await read(); + console.log("t0:", a.toString()); + console.log("t+20s:", b.toString()); + console.log("delta:", (b - a).toString()); + await api.disconnect(); +} + +main().catch((e) => { + console.error(e); + process.exit(1); +}); diff --git a/ts-tests/scripts/rails-check-nonce.ts b/ts-tests/scripts/rails-check-nonce.ts new file mode 100644 index 0000000000..1b94339f3c --- /dev/null +++ b/ts-tests/scripts/rails-check-nonce.ts @@ -0,0 +1,18 @@ +// Quick check: was a gateway envelope nonce processed by pallet-usd-psm? +import { ApiPromise, WsProvider } from "@polkadot/api"; + +async function main() { + const api = await ApiPromise.create({ + provider: new WsProvider(process.env.BT_RPC_WS ?? "ws://127.0.0.1:9944"), + noInitWarn: true, + }); + const nonce = process.argv[2]; + const processed = await api.query.usdPsm.processedNonces(nonce); + console.log(`processedNonces(${nonce}):`, processed.toHuman()); + process.exit(0); +} + +main().catch((e) => { + console.error(e); + process.exit(1); +}); diff --git a/ts-tests/scripts/rails-configure-pallet.ts b/ts-tests/scripts/rails-configure-pallet.ts new file mode 100644 index 0000000000..72aa4326cc --- /dev/null +++ b/ts-tests/scripts/rails-configure-pallet.ts @@ -0,0 +1,305 @@ +/** + * Configure pallet-usd-psm on the localnet after the rails contracts are + * deployed (run with tsx from ts-tests, like bootstrap.ts): + * - register the deployed Gateway contract as the pallet's gateway, + * - register the canonical USD ERC-20 as PSM asset 0, + * - initialize the protocol-owned tUSD/TAO pool from Alice's balance, + * - wire the outbound leg: hub mailbox + hub sender gas, + * - for every catalog token: create a started subnet (emissions running), + * set its on-chain identity (name/description/logo mirrored from the + * mainnet subnet), and wire the escrow hotkey + share-mint route, + * - wire the USDC release route back to the portal. + * + * Env: GATEWAY_ADDR, CANONICAL_USD_ADDR, BT_MAILBOX_ADDR, PORTAL_ADDR (H160 + * hex), BASE_DOMAIN, BT_RPC_WS, TOKENS_JSON (catalog entries with deployed + * `address` fields), RESOLVED_OUT (path for the resolved catalog). + * Idempotent: every step checks current state first; a subnet is reused when + * an outbound route already points at its token. + * + * Prints on stdout for deploy-contracts.sh: `HUB_SENDER 0x..`, `NETUID n` + * (first catalog subnet), and writes RESOLVED_OUT with one entry per token: + * netuid, address, symbol, plus name/description/logo/url read back from the + * chain's SubnetIdentitiesV3 (the chain is the source of truth the demo page + * displays). + */ +import { writeFileSync } from "node:fs"; +import { ApiPromise, WsProvider } from "@polkadot/api"; +import { blake2AsU8a } from "@polkadot/util-crypto"; +import { stringToU8a, u8aToHex } from "@polkadot/util"; +import { + addr32, + alicePair, + createStartedSubnet, + h160ToSS58, + signAndWait, +} from "../utils/rails"; + +const WS_URL = process.env.BT_RPC_WS ?? "ws://127.0.0.1:9944"; +const GATEWAY = required("GATEWAY_ADDR"); +const CANONICAL_USD = required("CANONICAL_USD_ADDR"); +const BT_MAILBOX = required("BT_MAILBOX_ADDR"); +const PORTAL = required("PORTAL_ADDR"); +const BASE_DOMAIN = Number(process.env.BASE_DOMAIN ?? "8453"); +const RESOLVED_OUT = process.env.RESOLVED_OUT ?? ""; + +interface CatalogToken { + address: string; + name: string; + symbol: string; + description: string; + logo: string; + url: string; +} +const TOKENS: CatalogToken[] = JSON.parse(required("TOKENS_JSON")); + +const USD_ASSET_ID = 0; +// PSM inflow window: 1M USD cap, ~100 USD/block refill (9 decimals). +const CAP_LIMIT = 1_000_000n * 10n ** 9n; +const REFILL_PER_BLOCK = 100n * 10n ** 9n; +const HAIRCUT_BPS = 0; +// Protocol-owned pool seed: 10k TAO against 40k tUSD (1 TAO = 4 USD locally). +const POOL_TAO = 10_000n * 10n ** 9n; +const POOL_TUSD = 40_000n * 10n ** 9n; +const POOL_FEE_BPS = 30; +// Index heartbeat: push the share index to the spoke every ~20 blocks so the +// MetaMask balance visibly ticks without any buy/sell traffic. +const HEARTBEAT_BLOCKS = 20; + +function required(name: string): string { + const value = process.env[name]; + if (!value) { + throw new Error(`missing env ${name}`); + } + return name === "TOKENS_JSON" ? value : value.toLowerCase(); +} + +/** The runtime's keyless outbound identity: blake2_256("rails/hub-evm")[..20]. */ +function hubEvmAddress(): string { + return u8aToHex(blake2AsU8a(stringToU8a("rails/hub-evm"), 256).slice(0, 20)); +} + +async function sudoAndWait(api: ApiPromise, call: any, signer: any, label: string): Promise { + await signAndWait(api, api.tx.sudo.sudo(call), signer, label); + console.log(`[configure] ${label}: ok`); +} + +/** Map token address (as bytes32 route) -> netuid for already-wired routes. */ +async function existingRoutes(api: ApiPromise): Promise> { + const routes = new Map(); + const entries = await api.query.usdPsm.remoteRoutes.entries(BASE_DOMAIN); + for (const [key, value] of entries) { + const route = (value.toPrimitive() as string | null)?.toLowerCase(); + if (route) { + routes.set(route, Number(key.args[1].toPrimitive())); + } + } + return routes; +} + +async function main() { + const api = await ApiPromise.create({ + provider: new WsProvider(WS_URL), + noInitWarn: true, + }); + const alice = alicePair(); + + const gateway = (await api.query.usdPsm.gateway()).toPrimitive() as string | null; + if (gateway?.toLowerCase() === GATEWAY) { + console.log("[configure] gateway already set"); + } else { + await sudoAndWait(api, api.tx.usdPsm.setGateway(GATEWAY), alice, `set gateway ${GATEWAY}`); + } + + const asset: any = (await api.query.usdPsm.psmAssets(USD_ASSET_ID)).toPrimitive(); + if (asset && asset.erc20?.toLowerCase() === CANONICAL_USD) { + console.log("[configure] canonical USD asset already registered"); + } else { + await sudoAndWait( + api, + api.tx.usdPsm.registerUsdAsset( + USD_ASSET_ID, + CANONICAL_USD, + CAP_LIMIT, + REFILL_PER_BLOCK, + HAIRCUT_BPS + ), + alice, + `register USD asset 0 -> ${CANONICAL_USD}` + ); + } + + const taoReserve = BigInt( + ((await api.query.usdPsm.poolTaoReserve()).toPrimitive() as number | string) ?? 0 + ); + if (taoReserve > 0n) { + console.log("[configure] pool already initialized"); + } else { + await sudoAndWait( + api, + api.tx.usdPsm.initPool(alice.address, POOL_TAO, POOL_TUSD, POOL_FEE_BPS), + alice, + `init pool ${POOL_TAO} rao / ${POOL_TUSD} tUSD` + ); + } + + // Outbound leg: the runtime dispatches share mints, index heartbeats and + // USDC releases through this mailbox. + const hubMailbox = (await api.query.usdPsm.hubMailbox()).toPrimitive() as string | null; + if (hubMailbox?.toLowerCase() === BT_MAILBOX) { + console.log("[configure] hub mailbox already set"); + } else { + await sudoAndWait( + api, + api.tx.usdPsm.setHubMailbox(BT_MAILBOX), + alice, + `set hub mailbox ${BT_MAILBOX}` + ); + } + + // One started subnet per catalog token, owned by Alice, with Alice's + // hotkey as the escrow validator. Identities mirror the real mainnet + // subnets so the demo page can pull names/descriptions/logos from the + // chain. Reused across re-runs via the outbound-route mapping. + const routes = await existingRoutes(api); + const resolved: Array<{ + netuid: number; + address: string; + symbol: string; + name: string; + description: string; + logo: string; + url: string; + }> = []; + for (const token of TOKENS) { + const token32 = addr32(token.address.toLowerCase()); + let netuid = routes.get(token32); + if (netuid !== undefined) { + console.log(`[configure] ${token.symbol} already wired (netuid ${netuid})`); + } else { + netuid = await createStartedSubnet(api, alice); + console.log(`[configure] created started subnet netuid ${netuid} for ${token.symbol}`); + await sudoAndWait( + api, + api.tx.usdPsm.setOutboundRoute(BASE_DOMAIN, netuid, token32), + alice, + `route netuid ${netuid} shares -> domain ${BASE_DOMAIN} ${token.symbol} ${token.address}` + ); + } + + // On-chain identity: Alice owns the subnet, so she signs directly. + const identity: any = ( + await api.query.subtensorModule.subnetIdentitiesV3(netuid) + ).toHuman(); + if (identity?.subnetName === token.name) { + console.log(`[configure] identity for netuid ${netuid} already set`); + } else { + await signAndWait( + api, + api.tx.subtensorModule.setSubnetIdentity( + netuid, + token.name, + "", // github_repo + "", // subnet_contact + token.url, + "", // discord + token.description, + token.logo, + "" // additional + ), + alice, + `identity netuid ${netuid} = ${token.name}` + ); + console.log(`[configure] identity netuid ${netuid} = ${token.name}: ok`); + } + + // Escrow hotkey: buys stake into (hotkey=Alice, coldkey=hub escrow) + // so the escrow earns emissions like any nominator. + const escrowHotkey = (await api.query.usdPsm.escrowHotkeys(netuid)).toPrimitive() as + | string + | null; + if (escrowHotkey === alice.address) { + console.log(`[configure] escrow hotkey netuid ${netuid} already set`); + } else { + await sudoAndWait( + api, + api.tx.usdPsm.setEscrowHotkey(netuid, alice.address), + alice, + `escrow hotkey netuid ${netuid} -> Alice` + ); + } + + // Read the identity back: what the chain stores is what ships. + const onChain: any = ( + await api.query.subtensorModule.subnetIdentitiesV3(netuid) + ).toHuman(); + resolved.push({ + netuid, + address: token.address, + symbol: token.symbol, + name: onChain?.subnetName ?? token.name, + description: onChain?.description ?? token.description, + logo: onChain?.logoUrl ?? token.logo, + url: onChain?.subnetUrl ?? token.url, + }); + } + + // USDC release route: sells pay out through the portal on fake Base. + const portal32 = addr32(PORTAL); + const usdRoute = (await api.query.usdPsm.usdReleaseRoutes(BASE_DOMAIN)).toPrimitive() as + | string + | null; + if (usdRoute?.toLowerCase() === portal32) { + console.log("[configure] USD release route already set"); + } else { + await sudoAndWait( + api, + api.tx.usdPsm.setUsdRoute(BASE_DOMAIN, portal32), + alice, + `USD release route domain ${BASE_DOMAIN} -> portal ${PORTAL}` + ); + } + + const heartbeat = Number((await api.query.usdPsm.heartbeatInterval()).toPrimitive()); + if (heartbeat === HEARTBEAT_BLOCKS) { + console.log("[configure] heartbeat interval already set"); + } else { + await sudoAndWait( + api, + api.tx.usdPsm.setHeartbeatInterval(HEARTBEAT_BLOCKS), + alice, + `heartbeat every ${HEARTBEAT_BLOCKS} blocks` + ); + } + + // Gas for the hub's keyless EVM identity: outbound dispatches are real + // EVM transactions and pay fees from this account. + const hubSender = hubEvmAddress(); + const hubMirror = h160ToSS58(hubSender); + const HUB_GAS_RAO = 1_000_000n * 10n ** 9n; + const hubAccount: any = (await api.query.system.account(hubMirror)).toPrimitive(); + if (BigInt(hubAccount?.data?.free ?? 0) >= HUB_GAS_RAO) { + console.log(`[configure] hub sender ${hubSender} already funded`); + } else { + await sudoAndWait( + api, + api.tx.balances.forceSetBalance(hubMirror, HUB_GAS_RAO), + alice, + `fund hub sender ${hubSender}` + ); + } + + if (RESOLVED_OUT) { + writeFileSync(RESOLVED_OUT, JSON.stringify(resolved, null, 2)); + console.log(`[configure] wrote resolved catalog -> ${RESOLVED_OUT}`); + } + // Consumed by deploy-contracts.sh to wire the Base side. + console.log(`HUB_SENDER ${hubSender}`); + console.log(`NETUID ${resolved[0].netuid}`); + + await api.disconnect(); +} + +main().catch((err) => { + console.error("[configure] FAILED:", err); + process.exit(1); +}); diff --git a/ts-tests/scripts/rails-debug-alpha.ts b/ts-tests/scripts/rails-debug-alpha.ts new file mode 100644 index 0000000000..6011e3cbff --- /dev/null +++ b/ts-tests/scripts/rails-debug-alpha.ts @@ -0,0 +1,35 @@ +// Debug: how does the Alpha NMap decode for a live stake? +import { ApiPromise, WsProvider } from "@polkadot/api"; +import { Keyring } from "@polkadot/keyring"; +import { alicePair, createStartedSubnet, signAndWait } from "../utils/rails.js"; + +async function main() { + const api = await ApiPromise.create({ + provider: new WsProvider("ws://127.0.0.1:9944"), + noInitWarn: true, + }); + const alice = alicePair(); + const hot = new Keyring({ type: "sr25519" }).addFromUri(`//DebugHot/${Date.now()}`); + + const netuid = await createStartedSubnet(api, hot); + console.log("netuid:", netuid); + await signAndWait(api, api.tx.subtensorModule.addStake(hot.address, netuid, 10_000_000_000n), alice, "add_stake"); + console.log("staked 10 TAO"); + + const entry = await api.query.subtensorModule.alpha(hot.address, alice.address, netuid); + console.log("alpha(hot, cold, netuid) json:", JSON.stringify(entry.toJSON())); + console.log("alpha(hot, cold, netuid) str:", entry.toString()); + const th = await api.query.subtensorModule.totalHotkeyAlpha(hot.address, netuid); + console.log("totalHotkeyAlpha:", th.toString()); + const entries = await api.query.subtensorModule.alpha.entries(); + console.log("total Alpha entries:", entries.length); + for (const [k, v] of entries.slice(-3)) { + console.log(" key:", k.args.map(String).join(", "), "value:", JSON.stringify(v.toJSON())); + } + process.exit(0); +} + +main().catch((e) => { + console.error(e); + process.exit(1); +}); diff --git a/ts-tests/scripts/rails-debug-balance.ts b/ts-tests/scripts/rails-debug-balance.ts new file mode 100644 index 0000000000..15e9f0d699 --- /dev/null +++ b/ts-tests/scripts/rails-debug-balance.ts @@ -0,0 +1,23 @@ +import { ApiPromise, WsProvider } from "@polkadot/api"; +import { blake2AsU8a, encodeAddress } from "@polkadot/util-crypto"; +import { hexToU8a, stringToU8a, u8aConcat } from "@polkadot/util"; + +async function main() { + const api = await ApiPromise.create({ + provider: new WsProvider("ws://127.0.0.1:9944"), + noInitWarn: true, + }); + const mirror = encodeAddress( + blake2AsU8a( + u8aConcat(stringToU8a("evm:"), hexToU8a("0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266")), + 256 + ), + 42 + ); + console.log("mirror", mirror); + console.log(JSON.stringify((await api.query.system.account(mirror)).toJSON())); + console.log("totalIssuance", (await api.query.balances.totalIssuance()).toString()); + await api.disconnect(); +} + +main(); diff --git a/ts-tests/scripts/rails-envelope.ts b/ts-tests/scripts/rails-envelope.ts new file mode 100644 index 0000000000..a7292888fe --- /dev/null +++ b/ts-tests/scripts/rails-envelope.ts @@ -0,0 +1,90 @@ +/** + * Encode a v1 GatewayEnvelope *prefix* to wire hex (mirror of + * subtensor_runtime_common::rails::GatewayEnvelope::to_wire, minus the + * trailing u64 nonce — the RailsPortal appends its own sequential nonce on + * dispatch). + * + * Usage (run with tsx from ts-tests): + * tsx scripts/rails-envelope.ts credit + * tsx scripts/rails-envelope.ts stake [minAlpha] + * + * Prints the 0x-prefixed envelope prefix hex on stdout. + */ +import { decodeAddress } from "@polkadot/util-crypto"; +import { hexToU8a, isHex, u8aConcat, u8aToHex } from "@polkadot/util"; + +const VERSION_V1 = 1; + +function u32le(n: number): Uint8Array { + const b = new Uint8Array(4); + new DataView(b.buffer).setUint32(0, n, true); + return b; +} + +function u64le(n: bigint): Uint8Array { + const b = new Uint8Array(8); + new DataView(b.buffer).setBigUint64(0, n, true); + return b; +} + +function u16le(n: number): Uint8Array { + const b = new Uint8Array(2); + new DataView(b.buffer).setUint16(0, n, true); + return b; +} + +function accountId(dest: string): Uint8Array { + if (isHex(dest) && dest.length === 66) { + return hexToU8a(dest); + } + return decodeAddress(dest); +} + +function main() { + const [mode, usdAssetId, amount, dest, ...rest] = process.argv.slice(2); + if (!mode || !usdAssetId || !amount || !dest) { + console.error("usage: rails-envelope.ts credit|stake [...]"); + process.exit(1); + } + + // AssetId::Usd(u32) = variant index 3 + u32 LE. + const asset = u8aConcat(new Uint8Array([3]), u32le(Number(usdAssetId))); + + let action: Uint8Array; + switch (mode) { + case "credit": + // GatewayAction::CreditTUsd = variant 0. + action = new Uint8Array([0]); + break; + case "stake": { + // GatewayAction::Stake { netuid, hotkey, min_alpha } + // = variant 2 + u16 LE + AccountId32 + u64 LE. + const [netuid, hotkey, minAlpha] = rest; + if (!netuid || !hotkey) { + console.error("stake mode needs [minAlpha]"); + process.exit(1); + } + action = u8aConcat( + new Uint8Array([2]), + u16le(Number(netuid)), + accountId(hotkey), + u64le(BigInt(minAlpha ?? "0")) + ); + break; + } + default: + console.error(`unknown mode ${mode}`); + process.exit(1); + } + + const prefix = u8aConcat( + new Uint8Array([VERSION_V1]), + asset, + u64le(BigInt(amount)), + accountId(dest), + action + ); + console.log(u8aToHex(prefix)); +} + +main(); diff --git a/ts-tests/suites/rails/fixtures/golden-envelopes.json b/ts-tests/suites/rails/fixtures/golden-envelopes.json new file mode 100644 index 0000000000..cf86f5c290 --- /dev/null +++ b/ts-tests/suites/rails/fixtures/golden-envelopes.json @@ -0,0 +1,66 @@ +{ + "comment": "Golden GatewayEnvelope wire vectors. The same bytes are pinned on the Rust side in common/src/rails.rs (envelope_golden_vectors) and on the Solidity side in contracts/evm/test/Chutes.t.sol (testGoldenEnvelopes). Any change to the wire format must update all three files consciously — this is the cross-chain compatibility contract.", + "cases": [ + { + "name": "credit", + "input": { + "usdAssetId": 0, + "amount": "250000000000", + "dest": "0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d", + "action": { "kind": "credit" }, + "nonce": "7" + }, + "wire": "0x010300000000004429353a000000d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d000700000000000000" + }, + { + "name": "stake", + "input": { + "usdAssetId": 0, + "amount": "1000000000000", + "dest": "0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d", + "action": { + "kind": "stake", + "netuid": 64, + "hotkey": "0x9090909090909090909090909090909090909090909090909090909090909090", + "minAlpha": "1" + }, + "nonce": "42" + }, + "wire": "0x0103000000000010a5d4e8000000d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d024000909090909090909090909090909090909090909090909090909090909090909001000000000000002a00000000000000" + }, + { + "name": "buy_shares", + "input": { + "usdAssetId": 0, + "amount": "500000000000", + "dest": "0x0000000000000000000000000000000000000000000000000000000000000000", + "action": { + "kind": "buyShares", + "netuid": 64, + "recipient": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266", + "minAlpha": "1", + "domain": 8453 + }, + "nonce": "0" + }, + "wire": "0x0103000000000088526a740000000000000000000000000000000000000000000000000000000000000000000000044000f39fd6e51aad88f6f4ce6ab8827279cfffb922660100000000000000052100000000000000000000" + }, + { + "name": "sell_shares", + "input": { + "amount": "2000000000", + "dest": "0x0000000000000000000000000000000000000000000000000000000000000000", + "action": { + "kind": "sellShares", + "netuid": 64, + "recipient": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266", + "usdAssetId": 0, + "minUsd": "1000000000", + "domain": 8453 + }, + "nonce": "1" + }, + "wire": "0x0102400000943577000000000000000000000000000000000000000000000000000000000000000000000000054000f39fd6e51aad88f6f4ce6ab8827279cfffb922660000000000ca9a3b00000000052100000100000000000000" + } + ] +} diff --git a/ts-tests/suites/rails/test-rails-buy-sell.ts b/ts-tests/suites/rails/test-rails-buy-sell.ts new file mode 100644 index 0000000000..148ba4ff21 --- /dev/null +++ b/ts-tests/suites/rails/test-rails-buy-sell.ts @@ -0,0 +1,195 @@ +/** + * R01 — the product, end to end against the live rig (`just rails-up` + * first): buy CHUTES with USDC on fake Base, watch the rebasing balance + * grow as the hub escrow earns emissions, and sell back to USDC. This is + * exactly what the demo page does, minus MetaMask. + */ +import { beforeAll, describeSuite, expect } from "@moonwall/cli"; +import type { ApiPromise } from "@polkadot/api"; +import { type RailsRig, connectRig, waitForReceipt, waitUntil } from "../../utils/rails.js"; + +describeSuite({ + id: "R01", + title: "Rails buy/sell: USDC to CHUTES and back, index accrues", + foundationMethods: "read_only", + testCases: ({ it, context, log }) => { + let api: ApiPromise; + let rig: RailsRig; + let netuid: number; + let buyer: string; + + async function attestation(): Promise<{ + escrowed_alpha: number; + shares_outstanding: number; + index_e9: number; + }> { + const response = await fetch(rig.manifest.chains.btlocal.rpcHttp, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + jsonrpc: "2.0", + id: 1, + method: "rails_alphaAttestation", + params: [netuid], + }), + }); + const json = (await response.json()) as { + result?: { escrowed_alpha: number; shares_outstanding: number; index_e9: number }; + error?: { message: string }; + }; + if (!json.result) { + throw new Error(`rails_alphaAttestation failed: ${JSON.stringify(json.error)}`); + } + return json.result; + } + + /** Pull the assigned envelope nonce out of a portal/chutes event. */ + function eventArg(receipt: any, contract: any, eventName: string, arg: string): bigint { + for (const logEntry of receipt.logs) { + try { + const parsed = contract.interface.parseLog(logEntry); + if (parsed?.name === eventName) { + return BigInt(parsed.args[arg]); + } + } catch { + // Not this contract's event. + } + } + throw new Error(`no ${eventName} event in receipt`); + } + + beforeAll(() => { + api = context.polkadotJs(); + rig = connectRig(); + netuid = rig.manifest.chains.btlocal.netuid; + buyer = rig.baseDeployer.address; + log(`demo netuid=${netuid}, buyer=${buyer}`); + }); + + it({ + id: "C01", + title: "buy: one approve + one buy() mints CHUTES backed by staked alpha", + test: async () => { + const amount = 100n * 10n ** 9n; // 100 USDC + const sharesBefore = BigInt(await rig.chutes.sharesOf(buyer)); + const escrowBefore = BigInt((await attestation()).escrowed_alpha); + + await (await rig.mockUsdc.mint(buyer, amount)).wait(); + await (await rig.mockUsdc.approve(await rig.portal.getAddress(), amount)).wait(); + const receipt = await (await rig.portal.buy(amount, netuid, 1n)).wait(); + const nonce = eventArg(receipt, rig.portal, "Bought", "nonce"); + log(`buy dispatched (nonce ${nonce}), waiting for hub execution...`); + + const hubReceipt = await waitForReceipt(api, nonce, 180_000); + expect(hubReceipt.fallback).toBeNull(); + + // Real staked alpha now backs the position. + const view = await attestation(); + expect(BigInt(view.escrowed_alpha)).toBeGreaterThan(escrowBefore); + + // The share mint flows back to Base and lands in the wallet. + const sharesAfter = await waitUntil( + async () => { + const shares = BigInt(await rig.chutes.sharesOf(buyer)); + return shares > sharesBefore ? shares : undefined; + }, + "CHUTES mint on Base", + 180_000 + ); + const balance = BigInt(await rig.chutes.balanceOf(buyer)); + log(`shares ${sharesBefore} -> ${sharesAfter}, display balance ${balance}`); + expect(balance).toBeGreaterThan(0n); + }, + }); + + it({ + id: "C02", + title: "accrue: the heartbeat pushes a rising index and the balance ticks up", + test: async () => { + const indexBefore = BigInt(await rig.chutes.indexE9()); + const balanceBefore = BigInt(await rig.chutes.balanceOf(buyer)); + const sharesBefore = BigInt(await rig.chutes.sharesOf(buyer)); + + // No transaction from the user: emissions on the hub raise + // alpha-per-share, the heartbeat pushes it, balanceOf grows. + const indexAfter = await waitUntil( + async () => { + const index = BigInt(await rig.chutes.indexE9()); + return index > indexBefore ? index : undefined; + }, + "index heartbeat on Base", + 240_000, + 2_000 + ); + const balanceAfter = BigInt(await rig.chutes.balanceOf(buyer)); + log(`index ${indexBefore} -> ${indexAfter}, balance ${balanceBefore} -> ${balanceAfter}`); + expect(balanceAfter).toBeGreaterThan(balanceBefore); + // Shares never moved; only the index did. + expect(BigInt(await rig.chutes.sharesOf(buyer))).toBe(sharesBefore); + }, + }); + + it({ + id: "C03", + title: "attestation: hub escrow covers remote share supply at the index", + test: async () => { + const view = await attestation(); + log(`attestation: ${JSON.stringify(view)}`); + expect(BigInt(view.shares_outstanding)).toBe(BigInt(await rig.chutes.totalShares())); + // Escrow backs shares at the index: escrow >= shares * index. + const backed = + (BigInt(view.shares_outstanding) * BigInt(view.index_e9)) / 10n ** 9n; + expect(BigInt(view.escrowed_alpha)).toBeGreaterThanOrEqual(backed); + }, + }); + + it({ + id: "C04", + title: "sell: burning CHUTES unstakes escrow and releases USDC on Base", + test: async () => { + const shares = BigInt(await rig.chutes.sharesOf(buyer)) / 2n; + expect(shares).toBeGreaterThan(0n); + const usdcBefore = BigInt(await rig.mockUsdc.balanceOf(buyer)); + const escrowBefore = BigInt((await attestation()).escrowed_alpha); + + const receipt = await (await rig.chutes.sell(shares, 1n)).wait(); + const nonce = eventArg(receipt, rig.chutes, "SoldToHub", "nonce"); + log(`sell dispatched (nonce ${nonce}), waiting for hub execution...`); + + const hubReceipt = await waitForReceipt(api, nonce, 180_000); + expect(hubReceipt.fallback).toBeNull(); + + const view = await attestation(); + expect(BigInt(view.escrowed_alpha)).toBeLessThan(escrowBefore); + expect(BigInt(view.shares_outstanding)).toBe(BigInt(await rig.chutes.totalShares())); + + const usdcAfter = await waitUntil( + async () => { + const balance = BigInt(await rig.mockUsdc.balanceOf(buyer)); + return balance > usdcBefore ? balance : undefined; + }, + "USDC release on Base", + 180_000 + ); + log(`USDC ${usdcBefore} -> ${usdcAfter}`); + }, + }); + + it({ + id: "C05", + title: "nonce sync: the portal counter matches the hub's NextNonce", + test: async () => { + const response = await fetch(rig.manifest.chains.btlocal.rpcHttp, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "rails_hubInfo", params: [] }), + }); + const json = (await response.json()) as { result?: { next_nonce: number } }; + expect(json.result).toBeDefined(); + const portalNext = BigInt(await rig.portal.nextNonce()); + log(`portal nextNonce=${portalNext}, hub next_nonce=${json.result?.next_nonce}`); + expect(BigInt(json.result?.next_nonce ?? -1)).toBe(portalNext); + }, + }); + }, +}); diff --git a/ts-tests/suites/rails/test-rails-failures.ts b/ts-tests/suites/rails/test-rails-failures.ts new file mode 100644 index 0000000000..71dde9fbc3 --- /dev/null +++ b/ts-tests/suites/rails/test-rails-failures.ts @@ -0,0 +1,194 @@ +/** + * Failure drills against the live rig: buy fallback to tUSD when the action + * cannot run, revoked minter bounce + recovery, and relayer outage + * (InTransit) + recovery. Nonces are portal-assigned and sequential; each + * drill reads its assigned nonce from the portal's Deposited/Bought event. + */ +import { execSync } from "node:child_process"; +import { beforeAll, describeSuite, expect } from "@moonwall/cli"; +import type { ApiPromise } from "@polkadot/api"; +import { Keyring } from "@polkadot/keyring"; +import type { KeyringPair } from "@polkadot/keyring/types"; +import { + type EnvelopeInput, + type RailsRig, + connectRig, + encodeEnvelope, + h160ToSS58, + waitForReceipt, +} from "../../utils/rails.js"; + +describeSuite({ + id: "R03", + title: "Rails failure drills: fallback, revocation, outage", + foundationMethods: "read_only", + testCases: ({ it, context, log }) => { + let api: ApiPromise; + let rig: RailsRig; + + async function tusdOf(address: string): Promise { + return BigInt((await api.query.usdPsm.tUsdBalances(address)).toPrimitive() as number | string); + } + + /** + * Lock USD on Base through the generic deposit door. The portal + * appends its own sequential nonce, so we encode with nonce 0, strip + * the trailing 8 nonce bytes, and read the assigned nonce back from + * the Deposited event. + */ + async function depositFromBase(input: Omit): Promise { + const wire = encodeEnvelope({ ...input, nonce: 0n }); + const prefix = wire.slice(0, wire.length - 16); + await (await rig.mockUsdc.mint(rig.baseDeployer.address, input.amount)).wait(); + await (await rig.mockUsdc.approve(await rig.portal.getAddress(), input.amount)).wait(); + const receipt = await (await rig.portal.deposit(input.amount, prefix)).wait(); + for (const logEntry of receipt.logs) { + try { + const parsed = rig.portal.interface.parseLog(logEntry); + if (parsed?.name === "Deposited") { + return BigInt(parsed.args.nonce); + } + } catch { + // Not a portal event. + } + } + throw new Error("no Deposited event"); + } + + function freshUser(label: string): KeyringPair { + return new Keyring({ type: "sr25519" }).addFromUri(`//RailsFail/${label}/${Date.now()}`); + } + + beforeAll(() => { + api = context.polkadotJs(); + rig = connectRig(); + }); + + it({ + id: "C01", + title: "failed stake action falls back to a tUSD credit", + test: async () => { + const user = freshUser("fallback"); + const amount = 50n * 10n ** 9n; + const bogusHotkey = new Keyring({ type: "sr25519" }).addFromUri("//RailsNobody"); + + const nonce = await depositFromBase({ + amount, + dest: user.address, + // Netuid 20000 does not exist: the stake leg must fail. + action: { kind: "stake", netuid: 20000, hotkey: bogusHotkey.address, minAlpha: 1n }, + }); + + const receipt = await waitForReceipt(api, nonce); + expect(receipt.fallback).toBe("StakeFailed"); + // Funds are not lost: the deposit stayed as tUSD. + expect(await tusdOf(user.address)).toBe(amount); + }, + }); + + it({ + id: "C02", + title: "failed buy falls back to a mirror tUSD credit, never a share mint", + test: async () => { + const amount = 20n * 10n ** 9n; + const buyer = rig.baseDeployer.address; + const sharesBefore = BigInt(await rig.chutes.sharesOf(buyer)); + const mirror = h160ToSS58(buyer); + const mirrorTusdBefore = await tusdOf(mirror); + + // Netuid 20001 has no escrow hotkey or route: BuyShares must + // fail on the hub and credit the buyer's EVM mirror instead. + await (await rig.mockUsdc.mint(buyer, amount)).wait(); + await (await rig.mockUsdc.approve(await rig.portal.getAddress(), amount)).wait(); + const receipt = await (await rig.portal.buy(amount, 20001, 1n)).wait(); + let nonce = -1n; + for (const logEntry of receipt.logs) { + try { + const parsed = rig.portal.interface.parseLog(logEntry); + if (parsed?.name === "Bought") { + nonce = BigInt(parsed.args.nonce); + } + } catch { + // Not a portal event. + } + } + expect(nonce).toBeGreaterThanOrEqual(0n); + + const hubReceipt = await waitForReceipt(api, nonce); + expect(hubReceipt.fallback).toBe("BuyFailed"); + // No shares were minted; the funds landed as tUSD on the + // buyer's EVM-mirror account instead. + expect(BigInt(await rig.chutes.sharesOf(buyer))).toBe(sharesBefore); + expect(await tusdOf(mirror)).toBe(mirrorTusdBefore + amount); + }, + }); + + it({ + id: "C03", + title: "revoked minter bounces the deposit; re-granting recovers it", + test: async () => { + const user = freshUser("revoked"); + const amount = 25n * 10n ** 9n; + const gatewayAddr = rig.manifest.chains.btlocal.gateway; + + await (await rig.canonicalUsd.removeMinter(gatewayAddr)).wait(); + let nonce: bigint; + try { + nonce = await depositFromBase({ + amount, + dest: user.address, + action: { kind: "credit" }, + }); + + // The backing mint reverts, so delivery cannot complete. + await new Promise((resolve) => setTimeout(resolve, 20_000)); + const processed = (await api.query.usdPsm.processedNonces(nonce)).toJSON(); + expect(processed).toBeNull(); + expect(await tusdOf(user.address)).toBe(0n); + } finally { + // Restore mint rights: 1M USD window, 100/s refill. + await ( + await rig.canonicalUsd.setMinterLimits(gatewayAddr, 1_000_000n * 10n ** 9n, 100n * 10n ** 9n) + ).wait(); + } + + // The relayer retries the stuck message and it lands. + log("minter restored; waiting for relayer retry..."); + const receipt = await waitForReceipt(api, nonce, 420_000); + expect(receipt.fallback).toBeNull(); + expect(await tusdOf(user.address)).toBe(amount); + }, + }); + + it({ + id: "C04", + title: "relayer outage leaves the transfer in transit; restart recovers it", + test: async () => { + const user = freshUser("outage"); + const amount = 15n * 10n ** 9n; + + execSync("docker stop rails-relayer", { stdio: "pipe" }); + let nonce: bigint; + try { + nonce = await depositFromBase({ + amount, + dest: user.address, + action: { kind: "credit" }, + }); + + // In transit: locked at origin, not processed on the hub. + await new Promise((resolve) => setTimeout(resolve, 15_000)); + const processed = (await api.query.usdPsm.processedNonces(nonce)).toJSON(); + expect(processed).toBeNull(); + } finally { + execSync("docker start rails-relayer", { stdio: "pipe" }); + } + + log("relayer restarted; waiting for recovery..."); + const receipt = await waitForReceipt(api, nonce, 300_000); + expect(receipt.fallback).toBeNull(); + expect(await tusdOf(user.address)).toBe(amount); + }, + }); + }, +}); diff --git a/ts-tests/suites/rails/test-rails-golden.ts b/ts-tests/suites/rails/test-rails-golden.ts new file mode 100644 index 0000000000..9d7c7d1f0e --- /dev/null +++ b/ts-tests/suites/rails/test-rails-golden.ts @@ -0,0 +1,118 @@ +/** + * Golden transcript replay: the envelope wire vectors pinned in + * fixtures/golden-envelopes.json (and mirrored byte-for-byte in the Rust + * test `envelope_golden_vectors`) must be reproduced exactly by the TS + * encoder, and the rig quote surface must satisfy the constant-product + * pool invariants the CLI transcripts rely on. + */ +import { beforeAll, describeSuite, expect } from "@moonwall/cli"; +import { type EnvelopeAction, type RailsRig, connectRig, encodeEnvelope } from "../../utils/rails.js"; +import golden from "./fixtures/golden-envelopes.json"; + +describeSuite({ + id: "R04", + title: "Rails golden fixtures: wire format and quote surface", + foundationMethods: "read_only", + testCases: ({ it, log }) => { + let rig: RailsRig; + + async function rpc(method: string, params: unknown[]): Promise { + const response = await fetch(rig.manifest.chains.btlocal.rpcHttp, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }), + }); + const json = (await response.json()) as { result?: T; error?: { message: string } }; + if (json.result === undefined) { + throw new Error(`${method} failed: ${JSON.stringify(json.error)}`); + } + return json.result; + } + + beforeAll(() => { + rig = connectRig(); + }); + + it({ + id: "C01", + title: "encoder reproduces every golden envelope byte-for-byte", + test: () => { + for (const testCase of golden.cases) { + const input = testCase.input as { + usdAssetId?: number; + amount: string; + dest: string; + action: Record & { kind: string }; + nonce: string; + }; + const action = { + ...input.action, + ...(input.action.minAlpha !== undefined + ? { minAlpha: BigInt(input.action.minAlpha as string) } + : {}), + ...(input.action.minUsd !== undefined + ? { minUsd: BigInt(input.action.minUsd as string) } + : {}), + } as EnvelopeAction; + const wire = encodeEnvelope({ + usdAssetId: input.usdAssetId, + amount: BigInt(input.amount), + dest: input.dest, + action, + nonce: BigInt(input.nonce), + }); + log(`${testCase.name}: ${wire.length / 2 - 1} bytes`); + expect(wire).toBe(testCase.wire); + } + }, + }); + + it({ + id: "C02", + title: "quote surface is consistent with pool state (constant product)", + test: async () => { + const pool = await rpc<{ tao_reserve: number; tusd_reserve: number; fee_bps: number }>( + "rails_poolState", + [] + ); + expect(pool.tao_reserve).toBeGreaterThan(0); + expect(pool.tusd_reserve).toBeGreaterThan(0); + + const usdIn = 1_000_000_000; // 1 USD + const quoted = await rpc("rails_quoteUsdToTao", [usdIn]); + expect(quoted).not.toBeNull(); + + // Expected constant-product output with the pool fee applied. + const inAfterFee = (BigInt(usdIn) * BigInt(10_000 - pool.fee_bps)) / 10_000n; + const expected = (BigInt(pool.tao_reserve) * inAfterFee) / (BigInt(pool.tusd_reserve) + inAfterFee); + log(`1 USD -> ${quoted} rao (expected ${expected})`); + expect(BigInt(quoted as number)).toBe(expected); + + // Round-trip quotes never create value: 1 USD -> TAO -> USD < 1 USD. + const back = await rpc("rails_quoteTaoToUsd", [quoted]); + expect(back).not.toBeNull(); + expect(BigInt(back as number)).toBeLessThan(BigInt(usdIn)); + }, + }); + + it({ + id: "C03", + title: "registry views resolve the rig's canonical facts", + test: async () => { + const gateway = await rpc("rails_gateway", []); + expect(gateway?.toLowerCase()).toBe(rig.manifest.chains.btlocal.gateway.toLowerCase()); + + const assets = await rpc<{ asset_id: number; erc20: string; enabled: boolean }[]>("rails_assets", []); + const canonical = assets.find( + (a) => a.erc20.toLowerCase() === rig.manifest.chains.btlocal.canonicalUsd.toLowerCase() + ); + expect(canonical).toBeDefined(); + expect(canonical?.enabled).toBe(true); + + const hub = await rpc<{ hub_sender: string; mailbox: string | null }>("rails_hubInfo", []); + expect(hub.hub_sender.toLowerCase()).toBe(rig.manifest.chains.btlocal.hubSender.toLowerCase()); + expect(hub.mailbox?.toLowerCase()).toBe(rig.manifest.chains.btlocal.mailbox.toLowerCase()); + }, + }); + }, +}); diff --git a/ts-tests/utils/rails-artifacts.json b/ts-tests/utils/rails-artifacts.json new file mode 100644 index 0000000000..7650220eaa --- /dev/null +++ b/ts-tests/utils/rails-artifacts.json @@ -0,0 +1,12 @@ +{ + "MockUSDC": {"abi":[{"type":"constructor","inputs":[],"stateMutability":"nonpayable"},{"type":"function","name":"allowance","inputs":[{"name":"","type":"address","internalType":"address"},{"name":"","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"type":"function","name":"approve","inputs":[{"name":"spender","type":"address","internalType":"address"},{"name":"value","type":"uint256","internalType":"uint256"}],"outputs":[{"name":"","type":"bool","internalType":"bool"}],"stateMutability":"nonpayable"},{"type":"function","name":"balanceOf","inputs":[{"name":"","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"type":"function","name":"decimals","inputs":[],"outputs":[{"name":"","type":"uint8","internalType":"uint8"}],"stateMutability":"view"},{"type":"function","name":"mint","inputs":[{"name":"to","type":"address","internalType":"address"},{"name":"amount","type":"uint256","internalType":"uint256"}],"outputs":[],"stateMutability":"nonpayable"},{"type":"function","name":"name","inputs":[],"outputs":[{"name":"","type":"string","internalType":"string"}],"stateMutability":"view"},{"type":"function","name":"symbol","inputs":[],"outputs":[{"name":"","type":"string","internalType":"string"}],"stateMutability":"view"},{"type":"function","name":"totalSupply","inputs":[],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"type":"function","name":"transfer","inputs":[{"name":"to","type":"address","internalType":"address"},{"name":"value","type":"uint256","internalType":"uint256"}],"outputs":[{"name":"","type":"bool","internalType":"bool"}],"stateMutability":"nonpayable"},{"type":"function","name":"transferFrom","inputs":[{"name":"from","type":"address","internalType":"address"},{"name":"to","type":"address","internalType":"address"},{"name":"value","type":"uint256","internalType":"uint256"}],"outputs":[{"name":"","type":"bool","internalType":"bool"}],"stateMutability":"nonpayable"},{"type":"event","name":"Approval","inputs":[{"name":"owner","type":"address","indexed":true,"internalType":"address"},{"name":"spender","type":"address","indexed":true,"internalType":"address"},{"name":"value","type":"uint256","indexed":false,"internalType":"uint256"}],"anonymous":false},{"type":"event","name":"Transfer","inputs":[{"name":"from","type":"address","indexed":true,"internalType":"address"},{"name":"to","type":"address","indexed":true,"internalType":"address"},{"name":"value","type":"uint256","indexed":false,"internalType":"uint256"}],"anonymous":false}],"bytecode":"0x608060405234801561001057600080fd5b50604051806040016040528060098152602001684d6f636b205553444360b81b815250604051806040016040528060048152602001635553444360e01b815250816000908161005f9190610115565b50600161006c8282610115565b5050506101d4565b634e487b7160e01b600052604160045260246000fd5b600181811c9082168061009e57607f821691505b6020821081036100be57634e487b7160e01b600052602260045260246000fd5b50919050565b601f821115610110576000816000526020600020601f850160051c810160208610156100ed5750805b601f850160051c820191505b8181101561010c578281556001016100f9565b5050505b505050565b81516001600160401b0381111561012e5761012e610074565b6101428161013c845461008a565b846100c4565b602080601f831160018114610177576000841561015f5750858301515b600019600386901b1c1916600185901b17855561010c565b600085815260208120601f198616915b828110156101a657888601518255948401946001909101908401610187565b50858210156101c45787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b61074c806101e36000396000f3fe608060405234801561001057600080fd5b506004361061009e5760003560e01c806340c10f191161006657806340c10f191461012857806370a082311461013d57806395d89b411461015d578063a9059cbb14610165578063dd62ed3e1461017857600080fd5b806306fdde03146100a3578063095ea7b3146100c157806318160ddd146100e457806323b872dd146100fb578063313ce5671461010e575b600080fd5b6100ab6101a3565b6040516100b8919061057a565b60405180910390f35b6100d46100cf3660046105e5565b610231565b60405190151581526020016100b8565b6100ed60025481565b6040519081526020016100b8565b6100d461010936600461060f565b61029e565b610116600981565b60405160ff90911681526020016100b8565b61013b6101363660046105e5565b610365565b005b6100ed61014b36600461064b565b60036020526000908152604090205481565b6100ab610373565b6100d46101733660046105e5565b610380565b6100ed61018636600461066d565b600460209081526000928352604080842090915290825290205481565b600080546101b0906106a0565b80601f01602080910402602001604051908101604052809291908181526020018280546101dc906106a0565b80156102295780601f106101fe57610100808354040283529160200191610229565b820191906000526020600020905b81548152906001019060200180831161020c57829003601f168201915b505050505081565b3360008181526004602090815260408083206001600160a01b038716808552925280832085905551919290917f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259061028c9086815260200190565b60405180910390a35060015b92915050565b6001600160a01b0383166000908152600460209081526040808320338452909152812054600019811461034f57828110156103205760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e636500000060448201526064015b60405180910390fd5b61032a83826106f0565b6001600160a01b03861660009081526004602090815260408083203384529091529020555b61035a858585610396565b506001949350505050565b61036f82826104c3565b5050565b600180546101b0906106a0565b600061038d338484610396565b50600192915050565b6001600160a01b0382166103ec5760405162461bcd60e51b815260206004820152601760248201527f45524332303a207472616e7366657220746f207a65726f0000000000000000006044820152606401610317565b6001600160a01b038316600090815260036020526040902054818110156104555760405162461bcd60e51b815260206004820152601b60248201527f45524332303a20696e73756666696369656e742062616c616e636500000000006044820152606401610317565b6001600160a01b0380851660008181526003602052604080822086860390559286168082529083902080548601905591517fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef906104b59086815260200190565b60405180910390a350505050565b6001600160a01b03821661050f5760405162461bcd60e51b815260206004820152601360248201527245524332303a206d696e7420746f207a65726f60681b6044820152606401610317565b80600260008282546105219190610703565b90915550506001600160a01b0382166000818152600360209081526040808320805486019055518481527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a35050565b60006020808352835180602085015260005b818110156105a85785810183015185820160400152820161058c565b506000604082860101526040601f19601f8301168501019250505092915050565b80356001600160a01b03811681146105e057600080fd5b919050565b600080604083850312156105f857600080fd5b610601836105c9565b946020939093013593505050565b60008060006060848603121561062457600080fd5b61062d846105c9565b925061063b602085016105c9565b9150604084013590509250925092565b60006020828403121561065d57600080fd5b610666826105c9565b9392505050565b6000806040838503121561068057600080fd5b610689836105c9565b9150610697602084016105c9565b90509250929050565b600181811c908216806106b457607f821691505b6020821081036106d457634e487b7160e01b600052602260045260246000fd5b50919050565b634e487b7160e01b600052601160045260246000fd5b81810381811115610298576102986106da565b80820180821115610298576102986106da56fea2646970667358221220965041dcd48e8bafef42cfc83ddaeebfccc472a300fae60e5f8649941442780564736f6c63430008180033"} +, + "CanonicalShareToken": {"abi":[{"type":"constructor","inputs":[{"name":"name_","type":"string","internalType":"string"},{"name":"symbol_","type":"string","internalType":"string"},{"name":"owner_","type":"address","internalType":"address"}],"stateMutability":"nonpayable"},{"type":"function","name":"allowance","inputs":[{"name":"","type":"address","internalType":"address"},{"name":"","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"type":"function","name":"approve","inputs":[{"name":"spender","type":"address","internalType":"address"},{"name":"value","type":"uint256","internalType":"uint256"}],"outputs":[{"name":"","type":"bool","internalType":"bool"}],"stateMutability":"nonpayable"},{"type":"function","name":"balanceOf","inputs":[{"name":"","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"type":"function","name":"burnFrom","inputs":[{"name":"from","type":"address","internalType":"address"},{"name":"amount","type":"uint64","internalType":"uint64"}],"outputs":[],"stateMutability":"nonpayable"},{"type":"function","name":"decimals","inputs":[],"outputs":[{"name":"","type":"uint8","internalType":"uint8"}],"stateMutability":"view"},{"type":"function","name":"isMinter","inputs":[{"name":"","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"bool","internalType":"bool"}],"stateMutability":"view"},{"type":"function","name":"mint","inputs":[{"name":"to","type":"address","internalType":"address"},{"name":"amount","type":"uint64","internalType":"uint64"}],"outputs":[],"stateMutability":"nonpayable"},{"type":"function","name":"minterWindows","inputs":[{"name":"","type":"address","internalType":"address"}],"outputs":[{"name":"limit","type":"uint64","internalType":"uint64"},{"name":"used","type":"uint64","internalType":"uint64"},{"name":"refillPerTick","type":"uint64","internalType":"uint64"},{"name":"lastTick","type":"uint64","internalType":"uint64"}],"stateMutability":"view"},{"type":"function","name":"name","inputs":[],"outputs":[{"name":"","type":"string","internalType":"string"}],"stateMutability":"view"},{"type":"function","name":"owner","inputs":[],"outputs":[{"name":"","type":"address","internalType":"address"}],"stateMutability":"view"},{"type":"function","name":"removeMinter","inputs":[{"name":"minter","type":"address","internalType":"address"}],"outputs":[],"stateMutability":"nonpayable"},{"type":"function","name":"setMinterLimits","inputs":[{"name":"minter","type":"address","internalType":"address"},{"name":"limit","type":"uint64","internalType":"uint64"},{"name":"refillPerSecond","type":"uint64","internalType":"uint64"}],"outputs":[],"stateMutability":"nonpayable"},{"type":"function","name":"symbol","inputs":[],"outputs":[{"name":"","type":"string","internalType":"string"}],"stateMutability":"view"},{"type":"function","name":"totalSupply","inputs":[],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"type":"function","name":"transfer","inputs":[{"name":"to","type":"address","internalType":"address"},{"name":"value","type":"uint256","internalType":"uint256"}],"outputs":[{"name":"","type":"bool","internalType":"bool"}],"stateMutability":"nonpayable"},{"type":"function","name":"transferFrom","inputs":[{"name":"from","type":"address","internalType":"address"},{"name":"to","type":"address","internalType":"address"},{"name":"value","type":"uint256","internalType":"uint256"}],"outputs":[{"name":"","type":"bool","internalType":"bool"}],"stateMutability":"nonpayable"},{"type":"function","name":"transferOwnership","inputs":[{"name":"next","type":"address","internalType":"address"}],"outputs":[],"stateMutability":"nonpayable"},{"type":"event","name":"Approval","inputs":[{"name":"owner","type":"address","indexed":true,"internalType":"address"},{"name":"spender","type":"address","indexed":true,"internalType":"address"},{"name":"value","type":"uint256","indexed":false,"internalType":"uint256"}],"anonymous":false},{"type":"event","name":"MinterLimitsSet","inputs":[{"name":"minter","type":"address","indexed":true,"internalType":"address"},{"name":"limit","type":"uint64","indexed":false,"internalType":"uint64"},{"name":"refillPerSecond","type":"uint64","indexed":false,"internalType":"uint64"}],"anonymous":false},{"type":"event","name":"MinterRemoved","inputs":[{"name":"minter","type":"address","indexed":true,"internalType":"address"}],"anonymous":false},{"type":"event","name":"Transfer","inputs":[{"name":"from","type":"address","indexed":true,"internalType":"address"},{"name":"to","type":"address","indexed":true,"internalType":"address"},{"name":"value","type":"uint256","indexed":false,"internalType":"uint256"}],"anonymous":false}],"bytecode":"0x60806040523480156200001157600080fd5b50604051620013983803806200139883398101604081905262000034916200018f565b82826000620000448382620002ad565b506001620000538282620002ad565b5050506001600160a01b0381166200009e5760405162461bcd60e51b815260206004820152600a6024820152696f776e6572207a65726f60b01b604482015260640160405180910390fd5b600580546001600160a01b0319166001600160a01b039290921691909117905550620003799050565b634e487b7160e01b600052604160045260246000fd5b600082601f830112620000ef57600080fd5b81516001600160401b03808211156200010c576200010c620000c7565b604051601f8301601f19908116603f01168101908282118183101715620001375762000137620000c7565b81604052838152602092508660208588010111156200015557600080fd5b600091505b838210156200017957858201830151818301840152908201906200015a565b6000602085830101528094505050505092915050565b600080600060608486031215620001a557600080fd5b83516001600160401b0380821115620001bd57600080fd5b620001cb87838801620000dd565b94506020860151915080821115620001e257600080fd5b50620001f186828701620000dd565b604086015190935090506001600160a01b03811681146200021157600080fd5b809150509250925092565b600181811c908216806200023157607f821691505b6020821081036200025257634e487b7160e01b600052602260045260246000fd5b50919050565b601f821115620002a8576000816000526020600020601f850160051c81016020861015620002835750805b601f850160051c820191505b81811015620002a4578281556001016200028f565b5050505b505050565b81516001600160401b03811115620002c957620002c9620000c7565b620002e181620002da84546200021c565b8462000258565b602080601f831160018114620003195760008415620003005750858301515b600019600386901b1c1916600185901b178555620002a4565b600085815260208120601f198616915b828110156200034a5788860151825594840194600190910190840162000329565b5085821015620003695787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b61100f80620003896000396000f3fe608060405234801561001057600080fd5b506004361061010b5760003560e01c80638da5cb5b116100a2578063b565c1f511610071578063b565c1f514610246578063c1eccbe014610259578063c2db74f61461026c578063dd62ed3e146102e7578063f2fde38b1461031257600080fd5b80638da5cb5b146101dd57806395d89b4114610208578063a9059cbb14610210578063aa271e1a1461022357600080fd5b80632893c5b0116100de5780632893c5b01461017b5780633092afd514610190578063313ce567146101a357806370a08231146101bd57600080fd5b806306fdde0314610110578063095ea7b31461012e57806318160ddd1461015157806323b872dd14610168575b600080fd5b610118610325565b6040516101259190610d5f565b60405180910390f35b61014161013c366004610dca565b6103b3565b6040519015158152602001610125565b61015a60025481565b604051908152602001610125565b610141610176366004610df4565b610420565b61018e610189366004610e47565b6104e9565b005b61018e61019e366004610e7a565b6105a6565b6101ab600981565b60405160ff9091168152602001610125565b61015a6101cb366004610e7a565b60036020526000908152604090205481565b6005546101f0906001600160a01b031681565b6040516001600160a01b039091168152602001610125565b610118610626565b61014161021e366004610dca565b610633565b610141610231366004610e7a565b60076020526000908152604090205460ff1681565b61018e610254366004610e95565b610649565b61018e610267366004610e47565b61072e565b6102b461027a366004610e7a565b6006602052600090815260409020546001600160401b0380821691600160401b8104821691600160801b8204811691600160c01b90041684565b604080516001600160401b0395861681529385166020850152918416918301919091529091166060820152608001610125565b61015a6102f5366004610ed8565b600460209081526000928352604080842090915290825290205481565b61018e610320366004610e7a565b610868565b6000805461033290610f02565b80601f016020809104026020016040519081016040528092919081815260200182805461035e90610f02565b80156103ab5780601f10610380576101008083540402835291602001916103ab565b820191906000526020600020905b81548152906001019060200180831161038e57829003601f168201915b505050505081565b3360008181526004602090815260408083206001600160a01b038716808552925280832085905551919290917f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259061040e9086815260200190565b60405180910390a35060015b92915050565b6001600160a01b038316600090815260046020908152604080832033845290915281205460001981146104d157828110156104a25760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e636500000060448201526064015b60405180910390fd5b6104ac8382610f52565b6001600160a01b03861660009081526004602090815260408083203384529091529020555b6104dc8585856108f7565b60019150505b9392505050565b3360009081526007602052604090205460ff166105355760405162461bcd60e51b815260206004820152600a6024820152693737ba1036b4b73a32b960b11b6044820152606401610499565b33600090815260066020526040902061054f904283610a24565b61058f5760405162461bcd60e51b81526020600482015260116024820152701b5a5b9d081c985d19481b1a5b5a5d1959607a1b6044820152606401610499565b6105a282826001600160401b0316610aa1565b5050565b6005546001600160a01b031633146105d05760405162461bcd60e51b815260040161049990610f65565b6001600160a01b0381166000818152600760209081526040808320805460ff191690556006909152808220829055517fe94479a9f7e1952cc78f2d6baab678adc1b772d936c6583def489e524cb666929190a250565b6001805461033290610f02565b60006106403384846108f7565b50600192915050565b6005546001600160a01b031633146106735760405162461bcd60e51b815260040161049990610f65565b6001600160a01b0383166000818152600760209081526040808320805460ff1916600117905560068252918290208054426001600160401b03908116600160c01b026001600160c01b03888316600160801b810277ffffffffffffffff0000000000000000ffffffffffffffff19909516938b16938417949094171617835584519081529283015292917f9c7261e43260f03c18297287b76105a4b849fb2b7e0ae5c9c4ed2e5cabefb2f2910160405180910390a250505050565b3360009081526007602052604090205460ff1661077a5760405162461bcd60e51b815260206004820152600a6024820152693737ba1036b4b73a32b960b11b6044820152606401610499565b6001600160a01b038216331461083b576001600160a01b03821660009081526004602090815260408083203384529091529020546001600160401b0382168110156107f85760405162461bcd60e51b815260206004820152600e60248201526d6275726e20616c6c6f77616e636560901b6044820152606401610499565b6000198114610839576108146001600160401b03831682610f52565b6001600160a01b03841660009081526004602090815260408083203384529091529020555b505b61084e82826001600160401b0316610b58565b3360009081526006602052604090206105a2904283610c21565b6005546001600160a01b031633146108925760405162461bcd60e51b815260040161049990610f65565b6001600160a01b0381166108d55760405162461bcd60e51b815260206004820152600a6024820152696f776e6572207a65726f60b01b6044820152606401610499565b600580546001600160a01b0319166001600160a01b0392909216919091179055565b6001600160a01b03821661094d5760405162461bcd60e51b815260206004820152601760248201527f45524332303a207472616e7366657220746f207a65726f0000000000000000006044820152606401610499565b6001600160a01b038316600090815260036020526040902054818110156109b65760405162461bcd60e51b815260206004820152601b60248201527f45524332303a20696e73756666696369656e742062616c616e636500000000006044820152606401610499565b6001600160a01b0380851660008181526003602052604080822086860390559286168082529083902080548601905591517fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef90610a169086815260200190565b60405180910390a350505050565b6000610a308484610c88565b8354600090610a52906001600160401b0380861691600160401b900416610f88565b85549091506001600160401b0316811115610a715760009150506104e2565b84546001600160401b03909116600160401b0267ffffffffffffffff60401b199091161784555060019392505050565b6001600160a01b038216610aed5760405162461bcd60e51b815260206004820152601360248201527245524332303a206d696e7420746f207a65726f60681b6044820152606401610499565b8060026000828254610aff9190610f88565b90915550506001600160a01b0382166000818152600360209081526040808320805486019055518481527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a35050565b6001600160a01b03821660009081526003602052604090205481811015610bc15760405162461bcd60e51b815260206004820152601b60248201527f45524332303a206275726e20657863656564732062616c616e636500000000006044820152606401610499565b6001600160a01b03831660008181526003602090815260408083208686039055600280548790039055518581529192917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a3505050565b610c2b8383610c88565b82546001600160401b03600160401b9091048116908216811115610c5857610c538282610f9b565b610c5b565b60005b84546001600160401b0391909116600160401b0267ffffffffffffffff60401b1990911617909355505050565b81546001600160401b03600160c01b90910481169060009083168210610caf576000610cb9565b610cb98284610f9b565b8454909150600090610cdf906001600160401b03600160801b9091048116908416610fc2565b8554909150600160401b90046001600160401b031680821015610d0b57610d068282610f9b565b610d0e565b60005b865477ffffffffffffffff0000000000000000ffffffffffffffff16600160401b6001600160401b03928316026001600160c01b031617600160c01b96909116959095029490941790945550505050565b60006020808352835180602085015260005b81811015610d8d57858101830151858201604001528201610d71565b506000604082860101526040601f19601f8301168501019250505092915050565b80356001600160a01b0381168114610dc557600080fd5b919050565b60008060408385031215610ddd57600080fd5b610de683610dae565b946020939093013593505050565b600080600060608486031215610e0957600080fd5b610e1284610dae565b9250610e2060208501610dae565b9150604084013590509250925092565b80356001600160401b0381168114610dc557600080fd5b60008060408385031215610e5a57600080fd5b610e6383610dae565b9150610e7160208401610e30565b90509250929050565b600060208284031215610e8c57600080fd5b6104e282610dae565b600080600060608486031215610eaa57600080fd5b610eb384610dae565b9250610ec160208501610e30565b9150610ecf60408501610e30565b90509250925092565b60008060408385031215610eeb57600080fd5b610ef483610dae565b9150610e7160208401610dae565b600181811c90821680610f1657607f821691505b602082108103610f3657634e487b7160e01b600052602260045260246000fd5b50919050565b634e487b7160e01b600052601160045260246000fd5b8181038181111561041a5761041a610f3c565b6020808252600990820152683737ba1037bbb732b960b91b604082015260600190565b8082018082111561041a5761041a610f3c565b6001600160401b03828116828216039080821115610fbb57610fbb610f3c565b5092915050565b808202811582820484141761041a5761041a610f3c56fea26469706673582212207ff931ee7b1e6935b4c5ae19d2eb11cd040213b2ae8130a86e284992fe4164a564736f6c63430008180033"} +, + "Gateway": {"abi":[{"type":"constructor","inputs":[{"name":"owner_","type":"address","internalType":"address"},{"name":"mailbox_","type":"address","internalType":"address"},{"name":"canonicalUsd_","type":"address","internalType":"address"},{"name":"psmEscrow_","type":"address","internalType":"address"}],"stateMutability":"nonpayable"},{"type":"function","name":"canonicalUsd","inputs":[],"outputs":[{"name":"","type":"address","internalType":"contract CanonicalShareToken"}],"stateMutability":"view"},{"type":"function","name":"handle","inputs":[{"name":"origin","type":"uint32","internalType":"uint32"},{"name":"sender","type":"bytes32","internalType":"bytes32"},{"name":"body","type":"bytes","internalType":"bytes"}],"outputs":[],"stateMutability":"payable"},{"type":"function","name":"mailbox","inputs":[],"outputs":[{"name":"","type":"address","internalType":"address"}],"stateMutability":"view"},{"type":"function","name":"owner","inputs":[],"outputs":[{"name":"","type":"address","internalType":"address"}],"stateMutability":"view"},{"type":"function","name":"psmEscrow","inputs":[],"outputs":[{"name":"","type":"address","internalType":"address"}],"stateMutability":"view"},{"type":"function","name":"setTrustedSender","inputs":[{"name":"origin","type":"uint32","internalType":"uint32"},{"name":"sender","type":"bytes32","internalType":"bytes32"},{"name":"kind","type":"uint8","internalType":"enum Gateway.SenderKind"}],"outputs":[],"stateMutability":"nonpayable"},{"type":"function","name":"trustedSenders","inputs":[{"name":"","type":"uint32","internalType":"uint32"},{"name":"","type":"bytes32","internalType":"bytes32"}],"outputs":[{"name":"","type":"uint8","internalType":"enum Gateway.SenderKind"}],"stateMutability":"view"},{"type":"event","name":"InboundExecuted","inputs":[{"name":"origin","type":"uint32","indexed":true,"internalType":"uint32"},{"name":"sender","type":"bytes32","indexed":true,"internalType":"bytes32"},{"name":"amount","type":"uint64","indexed":false,"internalType":"uint64"}],"anonymous":false},{"type":"event","name":"TrustedSenderSet","inputs":[{"name":"origin","type":"uint32","indexed":true,"internalType":"uint32"},{"name":"sender","type":"bytes32","indexed":true,"internalType":"bytes32"},{"name":"kind","type":"uint8","indexed":false,"internalType":"enum Gateway.SenderKind"}],"anonymous":false}],"bytecode":"0x608060405234801561001057600080fd5b5060405161088a38038061088a83398101604081905261002f916100e5565b6001600160a01b0384166100765760405162461bcd60e51b815260206004820152600a6024820152696f776e6572207a65726f60b01b604482015260640160405180910390fd5b600080546001600160a01b039586166001600160a01b0319918216179091556001805494861694821694909417909355600280549285169284169290921790915560038054919093169116179055610139565b80516001600160a01b03811681146100e057600080fd5b919050565b600080600080608085870312156100fb57600080fd5b610104856100c9565b9350610112602086016100c9565b9250610120604086016100c9565b915061012e606086016100c9565b905092959194509250565b610742806101486000396000f3fe6080604052600436106100705760003560e01c80637d354ec81161004e5780637d354ec81461010f5780638da5cb5b1461012f57806394df9ea41461014f578063d5438eae1461016f57600080fd5b80630c4da705146100755780633ff0c047146100b257806356d5d475146100fa575b600080fd5b34801561008157600080fd5b50600354610095906001600160a01b031681565b6040516001600160a01b0390911681526020015b60405180910390f35b3480156100be57600080fd5b506100ed6100cd366004610497565b600460209081526000928352604080842090915290825290205460ff1681565b6040516100a991906104d7565b61010d6101083660046104ff565b61018f565b005b34801561011b57600080fd5b50600254610095906001600160a01b031681565b34801561013b57600080fd5b50600054610095906001600160a01b031681565b34801561015b57600080fd5b5061010d61016a366004610586565b6103b2565b34801561017b57600080fd5b50600154610095906001600160a01b031681565b6001546001600160a01b031633146101dc5760405162461bcd60e51b815260206004820152600b60248201526a0dcdee840dac2d2d8c4def60ab1b60448201526064015b60405180910390fd5b63ffffffff8416600090815260046020908152604080832086845290915281205460ff1690816002811115610213576102136104c1565b036102535760405162461bcd60e51b815260206004820152601060248201526f3ab73a393ab9ba32b21039b2b73232b960811b60448201526064016101d3565b600080610262848601866105e0565b9092509050600183600281111561027b5761027b6104c1565b148015610292575060008267ffffffffffffffff16115b15610309576002546003546040516302893c5b60e41b81526001600160a01b03918216600482015267ffffffffffffffff85166024820152911690632893c5b090604401600060405180830381600087803b1580156102f057600080fd5b505af1158015610304573d6000803e3d6000fd5b505050505b604051632f54443960e21b81526108149063bd5110e49061033090859085906004016106ab565b600060405180830381600087803b15801561034a57600080fd5b505af115801561035e573d6000803e3d6000fd5b505060405167ffffffffffffffff8516815288925063ffffffff8a1691507f8b792a4b1369f820cce135ba461249fb2265e63f7de5b98b1f873a4c37bfe3e69060200160405180910390a350505050505050565b6000546001600160a01b031633146103f85760405162461bcd60e51b81526020600482015260096024820152683737ba1037bbb732b960b91b60448201526064016101d3565b63ffffffff831660009081526004602090815260408083208584529091529020805482919060ff19166001836002811115610435576104356104c1565b0217905550818363ffffffff167f57ae287204bfd27f7c8ad064425b8530d92bd70e9c8302a44150ea8fbe6611048360405161047191906104d7565b60405180910390a3505050565b803563ffffffff8116811461049257600080fd5b919050565b600080604083850312156104aa57600080fd5b6104b38361047e565b946020939093013593505050565b634e487b7160e01b600052602160045260246000fd5b60208101600383106104f957634e487b7160e01b600052602160045260246000fd5b91905290565b6000806000806060858703121561051557600080fd5b61051e8561047e565b935060208501359250604085013567ffffffffffffffff8082111561054257600080fd5b818701915087601f83011261055657600080fd5b81358181111561056557600080fd5b88602082850101111561057757600080fd5b95989497505060200194505050565b60008060006060848603121561059b57600080fd5b6105a48461047e565b9250602084013591506040840135600381106105bf57600080fd5b809150509250925092565b634e487b7160e01b600052604160045260246000fd5b600080604083850312156105f357600080fd5b823567ffffffffffffffff808216821461060c57600080fd5b9092506020840135908082111561062257600080fd5b818501915085601f83011261063657600080fd5b813581811115610648576106486105ca565b604051601f8201601f19908116603f01168101908382118183101715610670576106706105ca565b8160405282815288602084870101111561068957600080fd5b8260208601602083013760006020848301015280955050505050509250929050565b67ffffffffffffffff831681526000602060406020840152835180604085015260005b818110156106ea578581018301518582016060015282016106ce565b506000606082860101526060601f19601f83011685010192505050939250505056fea26469706673582212203af1c5624a5bb59337613a597db001c7c4185f5be434611db937c8dc6fc0ea2f64736f6c63430008180033"} +, + "RailsPortal": {"abi":[{"type":"constructor","inputs":[{"name":"owner_","type":"address","internalType":"address"},{"name":"usd_","type":"address","internalType":"address"},{"name":"mailbox_","type":"address","internalType":"address"},{"name":"hubDomain_","type":"uint32","internalType":"uint32"},{"name":"usdAssetId_","type":"uint32","internalType":"uint32"},{"name":"gateway_","type":"bytes32","internalType":"bytes32"}],"stateMutability":"nonpayable"},{"type":"function","name":"assignNonce","inputs":[],"outputs":[{"name":"nonce","type":"uint64","internalType":"uint64"}],"stateMutability":"nonpayable"},{"type":"function","name":"buy","inputs":[{"name":"amountUsd","type":"uint64","internalType":"uint64"},{"name":"netuid","type":"uint16","internalType":"uint16"},{"name":"minAlpha","type":"uint64","internalType":"uint64"}],"outputs":[{"name":"messageId","type":"bytes32","internalType":"bytes32"},{"name":"nonce","type":"uint64","internalType":"uint64"}],"stateMutability":"payable"},{"type":"function","name":"chutes","inputs":[],"outputs":[{"name":"","type":"address","internalType":"address"}],"stateMutability":"view"},{"type":"function","name":"deposit","inputs":[{"name":"amount","type":"uint64","internalType":"uint64"},{"name":"envelopePrefix","type":"bytes","internalType":"bytes"}],"outputs":[{"name":"messageId","type":"bytes32","internalType":"bytes32"},{"name":"nonce","type":"uint64","internalType":"uint64"}],"stateMutability":"payable"},{"type":"function","name":"gateway","inputs":[],"outputs":[{"name":"","type":"bytes32","internalType":"bytes32"}],"stateMutability":"view"},{"type":"function","name":"handle","inputs":[{"name":"origin","type":"uint32","internalType":"uint32"},{"name":"sender","type":"bytes32","internalType":"bytes32"},{"name":"body","type":"bytes","internalType":"bytes"}],"outputs":[],"stateMutability":"payable"},{"type":"function","name":"hubDomain","inputs":[],"outputs":[{"name":"","type":"uint32","internalType":"uint32"}],"stateMutability":"view"},{"type":"function","name":"hubReleaser","inputs":[],"outputs":[{"name":"","type":"bytes32","internalType":"bytes32"}],"stateMutability":"view"},{"type":"function","name":"mailbox","inputs":[],"outputs":[{"name":"","type":"address","internalType":"contract IMailbox"}],"stateMutability":"view"},{"type":"function","name":"nextNonce","inputs":[],"outputs":[{"name":"","type":"uint64","internalType":"uint64"}],"stateMutability":"view"},{"type":"function","name":"owner","inputs":[],"outputs":[{"name":"","type":"address","internalType":"address"}],"stateMutability":"view"},{"type":"function","name":"setChutes","inputs":[{"name":"chutes_","type":"address","internalType":"address"}],"outputs":[],"stateMutability":"nonpayable"},{"type":"function","name":"setGateway","inputs":[{"name":"gateway_","type":"bytes32","internalType":"bytes32"}],"outputs":[],"stateMutability":"nonpayable"},{"type":"function","name":"setHubReleaser","inputs":[{"name":"releaser","type":"bytes32","internalType":"bytes32"}],"outputs":[],"stateMutability":"nonpayable"},{"type":"function","name":"usd","inputs":[],"outputs":[{"name":"","type":"address","internalType":"contract BaseERC20"}],"stateMutability":"view"},{"type":"function","name":"usdAssetId","inputs":[],"outputs":[{"name":"","type":"uint32","internalType":"uint32"}],"stateMutability":"view"},{"type":"event","name":"Bought","inputs":[{"name":"from","type":"address","indexed":true,"internalType":"address"},{"name":"amountUsd","type":"uint64","indexed":false,"internalType":"uint64"},{"name":"netuid","type":"uint16","indexed":false,"internalType":"uint16"},{"name":"nonce","type":"uint64","indexed":true,"internalType":"uint64"},{"name":"messageId","type":"bytes32","indexed":false,"internalType":"bytes32"}],"anonymous":false},{"type":"event","name":"Deposited","inputs":[{"name":"from","type":"address","indexed":true,"internalType":"address"},{"name":"amount","type":"uint64","indexed":false,"internalType":"uint64"},{"name":"nonce","type":"uint64","indexed":true,"internalType":"uint64"},{"name":"messageId","type":"bytes32","indexed":false,"internalType":"bytes32"}],"anonymous":false},{"type":"event","name":"Released","inputs":[{"name":"to","type":"address","indexed":true,"internalType":"address"},{"name":"amount","type":"uint64","indexed":false,"internalType":"uint64"}],"anonymous":false}],"bytecode":"0x6101006040523480156200001257600080fd5b506040516200141d3803806200141d8339810160408190526200003591620000f3565b6001600160a01b0386166200007d5760405162461bcd60e51b815260206004820152600a6024820152696f776e6572207a65726f60b01b604482015260640160405180910390fd5b600080546001600160a01b0319166001600160a01b039788161790559385166080529190931660a05263ffffffff92831660c0529190911660e0526001556200016b565b80516001600160a01b0381168114620000d957600080fd5b919050565b805163ffffffff81168114620000d957600080fd5b60008060008060008060c087890312156200010d57600080fd5b6200011887620000c1565b95506200012860208801620000c1565b94506200013860408801620000c1565b93506200014860608801620000de565b92506200015860808801620000de565b915060a087015190509295509295509295565b60805160a05160c05160e05161122b620001f2600039600081816101ee01526105a301526000818161028f01528181610682015281816107ef0152610b73015260008181610303015281816105c801528181610652015281816107920152610b43015260008181610337015281816104a7015281816108ad0152610a1c015261122b6000f3fe6080604052600436106100f35760003560e01c80636b615a271161008a578063bd81232811610059578063bd812328146102c4578063d5438eae146102f1578063d63a6ccd14610325578063d69c3d301461035957600080fd5b80636b615a27146102255780638da5cb5b1461025d578063a226b2cb1461027d578063bba84ffb146102b157600080fd5b80633745197f116100c65780633745197f146101835780634a228a74146101b357806356d5d475146101c957806364ba23ea146101dc57600080fd5b8063116191b6146100f85780631f1422b9146101215780632b8108c91461014357806330fece0314610163575b600080fd5b34801561010457600080fd5b5061010e60015481565b6040519081526020015b60405180910390f35b34801561012d57600080fd5b5061014161013c366004610e91565b610380565b005b34801561014f57600080fd5b5061014161015e366004610e91565b6103b8565b34801561016f57600080fd5b5061014161017e366004610ec2565b6103e7565b610196610191366004610f02565b610433565b604080519283526001600160401b03909116602083015201610118565b3480156101bf57600080fd5b5061010e60025481565b6101416101d7366004610fa8565b610787565b3480156101e857600080fd5b506102107f000000000000000000000000000000000000000000000000000000000000000081565b60405163ffffffff9091168152602001610118565b34801561023157600080fd5b50600354610245906001600160a01b031681565b6040516001600160a01b039091168152602001610118565b34801561026957600080fd5b50600054610245906001600160a01b031681565b34801561028957600080fd5b506102107f000000000000000000000000000000000000000000000000000000000000000081565b6101966102bf366004611003565b6109a8565b3480156102d057600080fd5b506102d9610c61565b6040516001600160401b039091168152602001610118565b3480156102fd57600080fd5b506102457f000000000000000000000000000000000000000000000000000000000000000081565b34801561033157600080fd5b506102457f000000000000000000000000000000000000000000000000000000000000000081565b34801561036557600080fd5b506003546102d990600160a01b90046001600160401b031681565b6000546001600160a01b031633146103b35760405162461bcd60e51b81526004016103aa90611055565b60405180910390fd5b600155565b6000546001600160a01b031633146103e25760405162461bcd60e51b81526004016103aa90611055565b600255565b6000546001600160a01b031633146104115760405162461bcd60e51b81526004016103aa90611055565b600380546001600160a01b0319166001600160a01b0392909216919091179055565b6000806000856001600160401b03161161047d5760405162461bcd60e51b815260206004820152600b60248201526a616d6f756e74207a65726f60a81b60448201526064016103aa565b6040516323b872dd60e01b81523360048201523060248201526001600160401b03861660448201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906323b872dd906064016020604051808303816000875af11580156104f8573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061051c9190611078565b6105565760405162461bcd60e51b815260206004820152600b60248201526a1b1bd8dac819985a5b195960aa1b60448201526064016103aa565b60038054600160a01b90046001600160401b03169060146105768361109a565b91906101000a8154816001600160401b0302191690836001600160401b031602179055509050600061064e7f0000000000000000000000000000000000000000000000000000000000000000878733887f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316638d3638f46040518163ffffffff1660e01b8152600401602060405180830381865afa158015610624573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061064891906110ce565b88610cf4565b90507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663fa31de01347f00000000000000000000000000000000000000000000000000000000000000006001548a866040516020016106b7929190611131565b6040516020818303038152906040526040518563ffffffff1660e01b81526004016106e49392919061115b565b60206040518083038185885af1158015610702573d6000803e3d6000fd5b50505050506040513d601f19601f820116820180604052508101906107279190611189565b604080516001600160401b03898116825261ffff8916602083015291810183905291945083169033907f5018328fc2d13e6eb1f7df665c70d5136b295a972a11e78efbe4abf9c5ef8217906060015b60405180910390a350935093915050565b336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146107ed5760405162461bcd60e51b815260206004820152600b60248201526a0dcdee840dac2d2d8c4def60ab1b60448201526064016103aa565b7f000000000000000000000000000000000000000000000000000000000000000063ffffffff168463ffffffff16148015610829575060025483145b61086a5760405162461bcd60e51b81526020600482015260126024820152713ab73a393ab9ba32b2103932b632b0b9b2b960711b60448201526064016103aa565b600080610879838501856111a2565b60405163a9059cbb60e01b81526001600160a01b0380841660048301526001600160401b03831660248301529294509092507f00000000000000000000000000000000000000000000000000000000000000009091169063a9059cbb906044016020604051808303816000875af11580156108f8573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061091c9190611078565b6109595760405162461bcd60e51b815260206004820152600e60248201526d1c995b19585cd94819985a5b195960921b60448201526064016103aa565b6040516001600160401b03821681526001600160a01b038316907fd8b7dff13b7b7971dc4f979e45e17ffb6032f0e53299c49108e2ebe8bebd9b719060200160405180910390a2505050505050565b6000806000856001600160401b0316116109f25760405162461bcd60e51b815260206004820152600b60248201526a616d6f756e74207a65726f60a81b60448201526064016103aa565b6040516323b872dd60e01b81523360048201523060248201526001600160401b03861660448201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906323b872dd906064016020604051808303816000875af1158015610a6d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a919190611078565b610acb5760405162461bcd60e51b815260206004820152600b60248201526a1b1bd8dac819985a5b195960aa1b60448201526064016103aa565b60038054600160a01b90046001600160401b0316906014610aeb8361109a565b91906101000a8154816001600160401b0302191690836001600160401b03160217905550905060008484610b1e84610e2f565b604051602001610b30939291906111d7565b60405160208183030381529060405290507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663fa31de01347f00000000000000000000000000000000000000000000000000000000000000006001548a86604051602001610ba8929190611131565b6040516020818303038152906040526040518563ffffffff1660e01b8152600401610bd59392919061115b565b60206040518083038185885af1158015610bf3573d6000803e3d6000fd5b50505050506040513d601f19601f82011682018060405250810190610c189190611189565b604080516001600160401b038981168252602082018490529295509184169133917fe1fbf91ca06aef2d373f932e438fdc430b4876957137a7958485f221ca9bab5d9101610776565b6003546000906001600160a01b03163314610cab5760405162461bcd60e51b815260206004820152600a6024820152696e6f742063687574657360b01b60448201526064016103aa565b60038054600160a01b90046001600160401b0316906014610ccb8361109a565b91906101000a8154816001600160401b0302191690836001600160401b03160217905550905090565b60606001600360088a811b63ff00ff001662ff00ff918c901c9190911617601081811b91901c1760e01b610d278a610e2f565b6000600460088c811b62ffff0016908d901c60ff161760f01b8b610d4a8c610e2f565b60088c811b63ff00ff001662ff00ff918e901c9190911617601081811b91901c1760e01b610d778c610e2f565b60405160f89b8c1b6001600160f81b031990811660208301529a8c1b8b1660218201526001600160e01b0319998a1660228201526001600160c01b03199889166026820152602e8101979097529490991b909716604e8501526001600160f01b031991909116604f84015260601b6bffffffffffffffffffffffff19166051830152938216606582015293909116606d8401521660718201526079016040516020818303038152906040529050979650505050505050565b64ff000000ff600882811c91821665ff000000ff009390911b92831617601090811b6001600160401b031666ff00ff00ff00ff9290921667ff00ff00ff00ff009093169290921790911c65ffff0000ffff1617602081811c91901b1760c01b90565b600060208284031215610ea357600080fd5b5035919050565b6001600160a01b0381168114610ebf57600080fd5b50565b600060208284031215610ed457600080fd5b8135610edf81610eaa565b9392505050565b80356001600160401b0381168114610efd57600080fd5b919050565b600080600060608486031215610f1757600080fd5b610f2084610ee6565b9250602084013561ffff81168114610f3757600080fd5b9150610f4560408501610ee6565b90509250925092565b63ffffffff81168114610ebf57600080fd5b60008083601f840112610f7257600080fd5b5081356001600160401b03811115610f8957600080fd5b602083019150836020828501011115610fa157600080fd5b9250929050565b60008060008060608587031215610fbe57600080fd5b8435610fc981610f4e565b93506020850135925060408501356001600160401b03811115610feb57600080fd5b610ff787828801610f60565b95989497509550505050565b60008060006040848603121561101857600080fd5b61102184610ee6565b925060208401356001600160401b0381111561103c57600080fd5b61104886828701610f60565b9497909650939450505050565b6020808252600990820152683737ba1037bbb732b960b91b604082015260600190565b60006020828403121561108a57600080fd5b81518015158114610edf57600080fd5b60006001600160401b038083168181036110c457634e487b7160e01b600052601160045260246000fd5b6001019392505050565b6000602082840312156110e057600080fd5b8151610edf81610f4e565b6000815180845260005b81811015611111576020818501810151868301820152016110f5565b506000602082860101526020601f19601f83011685010191505092915050565b6001600160401b038316815260406020820152600061115360408301846110eb565b949350505050565b63ffffffff8416815282602082015260606040820152600061118060608301846110eb565b95945050505050565b60006020828403121561119b57600080fd5b5051919050565b600080604083850312156111b557600080fd5b82356111c081610eaa565b91506111ce60208401610ee6565b90509250929050565b828482376001600160c01b031991909116910190815260080191905056fea2646970667358221220a0ab88ac6696435ee87eb936e0cea790a5159b236ae7d1131db09dadd7f5d17b64736f6c63430008180033"} +, + "Chutes": {"abi":[{"type":"constructor","inputs":[{"name":"owner_","type":"address","internalType":"address"}],"stateMutability":"nonpayable"},{"type":"function","name":"allowance","inputs":[{"name":"","type":"address","internalType":"address"},{"name":"","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"type":"function","name":"approve","inputs":[{"name":"spender","type":"address","internalType":"address"},{"name":"amount","type":"uint256","internalType":"uint256"}],"outputs":[{"name":"","type":"bool","internalType":"bool"}],"stateMutability":"nonpayable"},{"type":"function","name":"balanceOf","inputs":[{"name":"account","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"type":"function","name":"configureHub","inputs":[{"name":"mailbox_","type":"address","internalType":"address"},{"name":"hubDomain_","type":"uint32","internalType":"uint32"},{"name":"hubSender_","type":"bytes32","internalType":"bytes32"},{"name":"hubRecipient_","type":"bytes32","internalType":"bytes32"},{"name":"portal_","type":"address","internalType":"address"},{"name":"netuid_","type":"uint16","internalType":"uint16"},{"name":"usdAssetId_","type":"uint32","internalType":"uint32"}],"outputs":[],"stateMutability":"nonpayable"},{"type":"function","name":"decimals","inputs":[],"outputs":[{"name":"","type":"uint8","internalType":"uint8"}],"stateMutability":"view"},{"type":"function","name":"handle","inputs":[{"name":"origin","type":"uint32","internalType":"uint32"},{"name":"sender","type":"bytes32","internalType":"bytes32"},{"name":"body","type":"bytes","internalType":"bytes"}],"outputs":[],"stateMutability":"payable"},{"type":"function","name":"hubDomain","inputs":[],"outputs":[{"name":"","type":"uint32","internalType":"uint32"}],"stateMutability":"view"},{"type":"function","name":"hubRecipient","inputs":[],"outputs":[{"name":"","type":"bytes32","internalType":"bytes32"}],"stateMutability":"view"},{"type":"function","name":"hubSender","inputs":[],"outputs":[{"name":"","type":"bytes32","internalType":"bytes32"}],"stateMutability":"view"},{"type":"function","name":"indexE9","inputs":[],"outputs":[{"name":"","type":"uint64","internalType":"uint64"}],"stateMutability":"view"},{"type":"function","name":"mailbox","inputs":[],"outputs":[{"name":"","type":"address","internalType":"contract IMailbox"}],"stateMutability":"view"},{"type":"function","name":"name","inputs":[],"outputs":[{"name":"","type":"string","internalType":"string"}],"stateMutability":"view"},{"type":"function","name":"netuid","inputs":[],"outputs":[{"name":"","type":"uint16","internalType":"uint16"}],"stateMutability":"view"},{"type":"function","name":"owner","inputs":[],"outputs":[{"name":"","type":"address","internalType":"address"}],"stateMutability":"view"},{"type":"function","name":"portal","inputs":[],"outputs":[{"name":"","type":"address","internalType":"contract RailsPortal"}],"stateMutability":"view"},{"type":"function","name":"sell","inputs":[{"name":"shares","type":"uint64","internalType":"uint64"},{"name":"minUsd","type":"uint64","internalType":"uint64"}],"outputs":[{"name":"messageId","type":"bytes32","internalType":"bytes32"}],"stateMutability":"payable"},{"type":"function","name":"sharesForAmount","inputs":[{"name":"amount","type":"uint256","internalType":"uint256"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"type":"function","name":"sharesOf","inputs":[{"name":"","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"type":"function","name":"symbol","inputs":[],"outputs":[{"name":"","type":"string","internalType":"string"}],"stateMutability":"view"},{"type":"function","name":"totalShares","inputs":[],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"type":"function","name":"totalSupply","inputs":[],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"type":"function","name":"transfer","inputs":[{"name":"to","type":"address","internalType":"address"},{"name":"amount","type":"uint256","internalType":"uint256"}],"outputs":[{"name":"","type":"bool","internalType":"bool"}],"stateMutability":"nonpayable"},{"type":"function","name":"transferFrom","inputs":[{"name":"from","type":"address","internalType":"address"},{"name":"to","type":"address","internalType":"address"},{"name":"amount","type":"uint256","internalType":"uint256"}],"outputs":[{"name":"","type":"bool","internalType":"bool"}],"stateMutability":"nonpayable"},{"type":"function","name":"transferOwnership","inputs":[{"name":"next","type":"address","internalType":"address"}],"outputs":[],"stateMutability":"nonpayable"},{"type":"function","name":"usdAssetId","inputs":[],"outputs":[{"name":"","type":"uint32","internalType":"uint32"}],"stateMutability":"view"},{"type":"event","name":"Approval","inputs":[{"name":"owner","type":"address","indexed":true,"internalType":"address"},{"name":"spender","type":"address","indexed":true,"internalType":"address"},{"name":"value","type":"uint256","indexed":false,"internalType":"uint256"}],"anonymous":false},{"type":"event","name":"HubConfigured","inputs":[{"name":"mailbox","type":"address","indexed":false,"internalType":"address"},{"name":"hubDomain","type":"uint32","indexed":false,"internalType":"uint32"},{"name":"hubSender","type":"bytes32","indexed":false,"internalType":"bytes32"},{"name":"hubRecipient","type":"bytes32","indexed":false,"internalType":"bytes32"},{"name":"portal","type":"address","indexed":false,"internalType":"address"},{"name":"netuid","type":"uint16","indexed":false,"internalType":"uint16"},{"name":"usdAssetId","type":"uint32","indexed":false,"internalType":"uint32"}],"anonymous":false},{"type":"event","name":"HubMint","inputs":[{"name":"to","type":"address","indexed":true,"internalType":"address"},{"name":"shares","type":"uint64","indexed":false,"internalType":"uint64"},{"name":"indexE9","type":"uint64","indexed":false,"internalType":"uint64"}],"anonymous":false},{"type":"event","name":"IndexUpdated","inputs":[{"name":"indexE9","type":"uint64","indexed":false,"internalType":"uint64"}],"anonymous":false},{"type":"event","name":"SoldToHub","inputs":[{"name":"from","type":"address","indexed":true,"internalType":"address"},{"name":"shares","type":"uint64","indexed":false,"internalType":"uint64"},{"name":"minUsd","type":"uint64","indexed":false,"internalType":"uint64"},{"name":"nonce","type":"uint64","indexed":true,"internalType":"uint64"},{"name":"messageId","type":"bytes32","indexed":false,"internalType":"bytes32"}],"anonymous":false},{"type":"event","name":"Transfer","inputs":[{"name":"from","type":"address","indexed":true,"internalType":"address"},{"name":"to","type":"address","indexed":true,"internalType":"address"},{"name":"value","type":"uint256","indexed":false,"internalType":"uint256"}],"anonymous":false}],"bytecode":"0x6080604052600580546001600160401b031916633b9aca0017905534801561002657600080fd5b50604051611773380380611773833981016040819052610045916100b1565b6001600160a01b03811661008c5760405162461bcd60e51b815260206004820152600a6024820152696f776e6572207a65726f60b01b604482015260640160405180910390fd5b600080546001600160a01b0319166001600160a01b03929092169190911790556100e1565b6000602082840312156100c357600080fd5b81516001600160a01b03811681146100da57600080fd5b9392505050565b611683806100f06000396000f3fe6080604052600436106101665760003560e01c806370a08231116100d1578063a9059cbb1161008a578063e78015b111610064578063e78015b11461049b578063f2fde38b146104d0578063f5eb42dc146104f0578063ff58766d1461051d57600080fd5b8063a9059cbb14610423578063d5438eae14610443578063dd62ed3e1461046357600080fd5b806370a082311461033f57806377038a3f1461035f5780638b42e1ca146103755780638da5cb5b146103ad57806395d89b41146103cd578063a226b2cb146103ff57600080fd5b806335b370551161012357806335b370551461026f5780633a53acb0146102855780633a98ef39146102a557806356d5d475146102bb5780636425666b146102ce57806364ba23ea1461030657600080fd5b806305ae785c1461016b57806306fdde031461018d578063095ea7b3146101d557806318160ddd1461020557806323b872dd14610228578063313ce56714610248575b600080fd5b34801561017757600080fd5b5061018b610186366004611192565b610530565b005b34801561019957600080fd5b506101bf6040518060400160405280600681526020016543687574657360d01b81525081565b6040516101cc9190611263565b60405180910390f35b3480156101e157600080fd5b506101f56101f036600461127d565b610656565b60405190151581526020016101cc565b34801561021157600080fd5b5061021a6106c3565b6040519081526020016101cc565b34801561023457600080fd5b506101f56102433660046112a9565b6106f4565b34801561025457600080fd5b5061025d600981565b60405160ff90911681526020016101cc565b34801561027b57600080fd5b5061021a60035481565b34801561029157600080fd5b5061021a6102a03660046112ea565b6107b6565b3480156102b157600080fd5b5061021a60075481565b61018b6102c9366004611303565b6107dd565b3480156102da57600080fd5b506004546102ee906001600160a01b031681565b6040516001600160a01b0390911681526020016101cc565b34801561031257600080fd5b5060045461032a90600160b01b900463ffffffff1681565b60405163ffffffff90911681526020016101cc565b34801561034b57600080fd5b5061021a61035a36600461138b565b610a41565b34801561036b57600080fd5b5061021a60025481565b34801561038157600080fd5b50600554610395906001600160401b031681565b6040516001600160401b0390911681526020016101cc565b3480156103b957600080fd5b506000546102ee906001600160a01b031681565b3480156103d957600080fd5b506101bf6040518060400160405280600681526020016543485554455360d01b81525081565b34801561040b57600080fd5b5060015461032a90600160a01b900463ffffffff1681565b34801561042f57600080fd5b506101f561043e36600461127d565b610a78565b34801561044f57600080fd5b506001546102ee906001600160a01b031681565b34801561046f57600080fd5b5061021a61047e3660046113a8565b600860209081526000928352604080842090915290825290205481565b3480156104a757600080fd5b506004546104bd90600160a01b900461ffff1681565b60405161ffff90911681526020016101cc565b3480156104dc57600080fd5b5061018b6104eb36600461138b565b610a8e565b3480156104fc57600080fd5b5061021a61050b36600461138b565b60066020526000908152604090205481565b61021a61052b3660046113f6565b610b39565b6000546001600160a01b0316331461057b5760405162461bcd60e51b81526020600482015260096024820152683737ba1037bbb732b960b91b60448201526064015b60405180910390fd5b600180546001600160a01b038981166001600160c01b03199092168217600160a01b63ffffffff8b81168281029390931790955560028a90556003899055600480549389166001600160b01b0319909416841761ffff89169283021763ffffffff60b01b1916600160b01b96881696870217905560408051948552602085019290925290830189905260608301889052608083019190915260a082015260c08101919091527f12edea4d0393ec0bf54490e5eb3270cee0dfcbc04d3d0a329b1f1369c6ce55279060e00160405180910390a150505050505050565b3360008181526008602090815260408083206001600160a01b038716808552925280832085905551919290917f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925906106b19086815260200190565b60405180910390a35060015b92915050565b600554600754600091633b9aca00916106e5916001600160401b03169061143a565b6106ef9190611451565b905090565b6001600160a01b038316600090815260086020908152604080832033845290915281205460001981146107a057828110156107715760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606401610572565b61077b8382611473565b6001600160a01b03861660009081526008602090815260408083203384529091529020555b6107ab858585610eed565b506001949350505050565b6005546000906001600160401b03166107d383633b9aca0061143a565b6106bd9190611451565b6001546001600160a01b031633146108255760405162461bcd60e51b815260206004820152600b60248201526a0dcdee840dac2d2d8c4def60ab1b6044820152606401610572565b60015463ffffffff858116600160a01b90920416148015610847575060025483145b6108835760405162461bcd60e51b815260206004820152600d60248201526c3ab73a393ab9ba32b210343ab160991b6044820152606401610572565b6000808061089384860186611486565b919450925090506001600160401b038116156108fc576005805467ffffffffffffffff19166001600160401b0383169081179091556040519081527f74bc1027c6dd1ebe6f5886dc387d0e1c72dffafb06ade715395484225d44e7d39060200160405180910390a15b6000826001600160401b031611801561091d57506001600160a01b03831615155b15610a38576001600160a01b038316600090815260066020526040812080546001600160401b03851692906109539084906114d1565b92505081905550816001600160401b03166007600082825461097591906114d1565b9091555050600554604080516001600160401b03808616825290921660208301526001600160a01b038516917f21684c01102a98fbc58b41de1cb466404d998ad704eebc6694df525d141865f0910160405180910390a26005546001600160a01b038416906000907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef90633b9aca0090610a1c906001600160401b0390811690881661143a565b610a269190611451565b60405190815260200160405180910390a35b50505050505050565b6005546001600160a01b0382166000908152600660205260408120549091633b9aca00916107d3916001600160401b03169061143a565b6000610a85338484610eed565b50600192915050565b6000546001600160a01b03163314610ad45760405162461bcd60e51b81526020600482015260096024820152683737ba1037bbb732b960b91b6044820152606401610572565b6001600160a01b038116610b175760405162461bcd60e51b815260206004820152600a6024820152696f776e6572207a65726f60b01b6044820152606401610572565b600080546001600160a01b0319166001600160a01b0392909216919091179055565b6001546000906001600160a01b031615801590610b57575060035415155b610b985760405162461bcd60e51b81526020600482015260126024820152711a1d58881b9bdd0818dbdb999a59dd5c995960721b6044820152606401610572565b6000836001600160401b031611610bdf5760405162461bcd60e51b815260206004820152600b60248201526a736861726573207a65726f60a81b6044820152606401610572565b336000908152600660205260409020546001600160401b038416811015610c3f5760405162461bcd60e51b815260206004820152601460248201527373656c6c20657863656564732062616c616e636560601b6044820152606401610572565b3360008181526006602052604081206001600160401b038088168086039092556007805483900390556005549293927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92633b9aca0092610ca192169061143a565b610cab9190611451565b60405190815260200160405180910390a36000600460009054906101000a90046001600160a01b03166001600160a01b031663bd8123286040518163ffffffff1660e01b81526004016020604051808303816000875af1158015610d13573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d3791906114e4565b90506000610de2600460149054906101000a900461ffff168733600460169054906101000a900463ffffffff1689600160009054906101000a90046001600160a01b03166001600160a01b0316638d3638f46040518163ffffffff1660e01b8152600401602060405180830381865afa158015610db8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ddc9190611501565b88611029565b6001546003546040519293506001600160a01b0382169263fa31de01923492600160a01b90910463ffffffff1691610e20908c90889060200161151e565b6040516020818303038152906040526040518563ffffffff1660e01b8152600401610e4d93929190611548565b60206040518083038185885af1158015610e6b573d6000803e3d6000fd5b50505050506040513d601f19601f82011682018060405250810190610e909190611576565b604080516001600160401b038981168252888116602083015291810183905291955083169033907f42f63edb4e4f9ec89364498fd0e2b753ee0d05cb5aa0d2d3d14346ce3224d85e9060600160405180910390a350505092915050565b6001600160a01b038216610f435760405162461bcd60e51b815260206004820152601760248201527f45524332303a207472616e7366657220746f207a65726f0000000000000000006044820152606401610572565b6000610f4e826107b6565b6001600160a01b03851660009081526006602052604090205490915081811015610fba5760405162461bcd60e51b815260206004820152601b60248201527f45524332303a20696e73756666696369656e742062616c616e636500000000006044820152606401610572565b6001600160a01b0380861660008181526006602052604080822086860390559287168082529083902080548601905591517fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9061101a9087815260200190565b60405180910390a35050505050565b60606001600260088a811b62ffff0016908b901c60ff161760f01b61104d8a611106565b600060056110748e600060088261ffff16901b60088361ffff16901c1760f01b9050919050565b8c60088d811b63ff00ff001662ff00ff918f901c9190911617601081811b91901c1760e01b6110a28d611106565b60088d811b63ff00ff001662ff00ff918f901c9190911617601081811b91901c1760e01b6110cf8d611106565b6040516020016110ea9c9b9a9998979695949392919061158f565b6040516020818303038152906040529050979650505050505050565b64ff000000ff600882811c91821665ff000000ff009390911b92831617601090811b6001600160401b031666ff00ff00ff00ff9290921667ff00ff00ff00ff009093169290921790911c65ffff0000ffff1617602081811c91901b1760c01b90565b6001600160a01b038116811461117d57600080fd5b50565b63ffffffff8116811461117d57600080fd5b600080600080600080600060e0888a0312156111ad57600080fd5b87356111b881611168565b965060208801356111c881611180565b9550604088013594506060880135935060808801356111e681611168565b925060a088013561ffff811681146111fd57600080fd5b915060c088013561120d81611180565b8091505092959891949750929550565b6000815180845260005b8181101561124357602081850181015186830182015201611227565b506000602082860101526020601f19601f83011685010191505092915050565b602081526000611276602083018461121d565b9392505050565b6000806040838503121561129057600080fd5b823561129b81611168565b946020939093013593505050565b6000806000606084860312156112be57600080fd5b83356112c981611168565b925060208401356112d981611168565b929592945050506040919091013590565b6000602082840312156112fc57600080fd5b5035919050565b6000806000806060858703121561131957600080fd5b843561132481611180565b93506020850135925060408501356001600160401b038082111561134757600080fd5b818701915087601f83011261135b57600080fd5b81358181111561136a57600080fd5b88602082850101111561137c57600080fd5b95989497505060200194505050565b60006020828403121561139d57600080fd5b813561127681611168565b600080604083850312156113bb57600080fd5b82356113c681611168565b915060208301356113d681611168565b809150509250929050565b6001600160401b038116811461117d57600080fd5b6000806040838503121561140957600080fd5b8235611414816113e1565b915060208301356113d6816113e1565b634e487b7160e01b600052601160045260246000fd5b80820281158282048414176106bd576106bd611424565b60008261146e57634e487b7160e01b600052601260045260246000fd5b500490565b818103818111156106bd576106bd611424565b60008060006060848603121561149b57600080fd5b83356114a681611168565b925060208401356114b6816113e1565b915060408401356114c6816113e1565b809150509250925092565b808201808211156106bd576106bd611424565b6000602082840312156114f657600080fd5b8151611276816113e1565b60006020828403121561151357600080fd5b815161127681611180565b6001600160401b0383168152604060208201526000611540604083018461121d565b949350505050565b63ffffffff8416815282602082015260606040820152600061156d606083018461121d565b95945050505050565b60006020828403121561158857600080fd5b5051919050565b6001600160f81b031960f88e811b821683528d811b821660018401526001600160f01b03198d1660028401526001600160c01b03198c166004840152600c83018b905289901b16602c82015260006001600160f01b03198816602d83015261160b602f83018860601b6bffffffffffffffffffffffff19169052565b506001600160e01b031994851660438201526001600160c01b0319938416604782015291909316604f82015291166053820152605b019897505050505050505056fea26469706673582212208fbd906c678fcb1b385e88739ef3bae3735fddee25c6bb2c7f76320953aa09d664736f6c63430008180033"} + +} diff --git a/ts-tests/utils/rails.ts b/ts-tests/utils/rails.ts new file mode 100644 index 0000000000..67383278a6 --- /dev/null +++ b/ts-tests/utils/rails.ts @@ -0,0 +1,375 @@ +/** + * Helpers for the rails e2e suite (suites/rails): rig manifest access, + * ethers handles to both local chains, GatewayEnvelope wire encoding, and + * substrate-side setup (subnet creation, delivery polling). + * + * Everything reads the rig manifest written by `just rails-up`, so the suite + * has zero hardcoded addresses. + */ +import { readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import type { ApiPromise } from "@polkadot/api"; +import { Keyring } from "@polkadot/keyring"; +import type { KeyringPair } from "@polkadot/keyring/types"; +import { hexToU8a, isHex, stringToU8a, u8aConcat, u8aToHex } from "@polkadot/util"; +import { blake2AsU8a, decodeAddress, encodeAddress } from "@polkadot/util-crypto"; +import { ethers } from "ethers"; +import artifacts from "./rails-artifacts.json"; + +const THIS_DIR = dirname(fileURLToPath(import.meta.url)); +const MANIFEST_PATH = join(THIS_DIR, "..", "..", ".rails", "manifest.json"); + +// Anvil developer key #0: the rig deployer/owner on both chains. +export const DEPLOYER_PK = "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80"; + +export interface RailsManifest { + version: number; + chains: { + btlocal: { + chainId: number; + domain: number; + rpcHttp: string; + rpcWs: string; + mailbox: string; + canonicalUsd: string; + gateway: string; + hubSender: string; + netuid: number; + usdRailsPrecompile: string; + psmEscrow: string; + }; + baselocal: { + chainId: number; + domain: number; + rpcHttp: string; + mailbox: string; + mockUsdc: string; + portal: string; + /** Alias for the first catalog token (kept for existing suites). */ + chutes: string; + /** One rebasing share token per demo subnet, identity read from chain. */ + tokens: Array<{ + netuid: number; + address: string; + symbol: string; + name: string; + description: string; + logo: string; + url: string; + }>; + }; + }; + accounts: { deployer: string; hyperlaneValidator: string; relayer: string }; +} + +export function loadManifest(): RailsManifest { + return JSON.parse(readFileSync(MANIFEST_PATH, "utf8")) as RailsManifest; +} + +/** Live ethers handles to every rig contract, wallet-connected as deployer. */ +export interface RailsRig { + manifest: RailsManifest; + btProvider: ethers.JsonRpcProvider; + baseProvider: ethers.JsonRpcProvider; + btDeployer: ethers.Wallet; + baseDeployer: ethers.Wallet; + mockUsdc: ethers.Contract; + portal: ethers.Contract; + chutes: ethers.Contract; + gateway: ethers.Contract; + canonicalUsd: ethers.Contract; +} + +export function connectRig(): RailsRig { + const manifest = loadManifest(); + const btProvider = new ethers.JsonRpcProvider(manifest.chains.btlocal.rpcHttp, undefined, { + cacheTimeout: -1, + }); + const baseProvider = new ethers.JsonRpcProvider(manifest.chains.baselocal.rpcHttp, undefined, { + cacheTimeout: -1, + }); + const btDeployer = new ethers.Wallet(DEPLOYER_PK, btProvider); + const baseDeployer = new ethers.Wallet(DEPLOYER_PK, baseProvider); + return { + manifest, + btProvider, + baseProvider, + btDeployer, + baseDeployer, + mockUsdc: new ethers.Contract(manifest.chains.baselocal.mockUsdc, artifacts.MockUSDC.abi, baseDeployer), + portal: new ethers.Contract(manifest.chains.baselocal.portal, artifacts.RailsPortal.abi, baseDeployer), + chutes: new ethers.Contract(manifest.chains.baselocal.chutes, artifacts.Chutes.abi, baseDeployer), + gateway: new ethers.Contract(manifest.chains.btlocal.gateway, artifacts.Gateway.abi, btDeployer), + canonicalUsd: new ethers.Contract( + manifest.chains.btlocal.canonicalUsd, + artifacts.CanonicalShareToken.abi, + btDeployer + ), + }; +} + +// ---------------------------------------------------------------- addresses + +/** SS58 mirror of an H160: blake2_256("evm:" ++ h160) — Frontier's HashedAddressMapping. */ +export function h160ToSS58(ethAddress: string): string { + const prefixed = u8aConcat(stringToU8a("evm:"), hexToU8a(ethAddress)); + return encodeAddress(blake2AsU8a(prefixed, 256), 42); +} + +/** Left-pad an H160 to the bytes32 form used as Hyperlane recipient/sender. */ +export function addr32(ethAddress: string): string { + return `0x${ethAddress.replace(/^0x/, "").toLowerCase().padStart(64, "0")}`; +} + +// ------------------------------------------------------- envelope encoding + +function u32le(n: number): Uint8Array { + const b = new Uint8Array(4); + new DataView(b.buffer).setUint32(0, n, true); + return b; +} + +function u64le(n: bigint): Uint8Array { + const b = new Uint8Array(8); + new DataView(b.buffer).setBigUint64(0, n, true); + return b; +} + +function u16le(n: number): Uint8Array { + const b = new Uint8Array(2); + new DataView(b.buffer).setUint16(0, n, true); + return b; +} + +function accountId32(dest: string): Uint8Array { + if (isHex(dest) && dest.length === 66) { + return hexToU8a(dest); + } + return decodeAddress(dest); +} + +const ENVELOPE_VERSION_V1 = 1; + +export type EnvelopeAction = + | { kind: "credit" } + | { kind: "stake"; netuid: number; hotkey: string; minAlpha: bigint } + | { kind: "buyShares"; netuid: number; recipient: string; minAlpha: bigint; domain: number } + | { + kind: "sellShares"; + netuid: number; + recipient: string; + usdAssetId: number; + minUsd: bigint; + domain: number; + }; + +export interface EnvelopeInput { + /** PSM asset id for USD-carrying envelopes; ignored for sellShares (alpha asset). */ + usdAssetId?: number; + amount: bigint; + /** SS58 address or 0x pubkey hex of the runtime destination account. */ + dest: string; + action: EnvelopeAction; + nonce: bigint; +} + +function h160Bytes(ethAddress: string): Uint8Array { + return hexToU8a(ethAddress); +} + +/** + * Encode a v1 GatewayEnvelope to wire hex — mirror of + * `subtensor_runtime_common::rails::GatewayEnvelope::to_wire`. + */ +export function encodeEnvelope(input: EnvelopeInput): string { + // AssetId: Alpha(netuid) = index 2 + u16 LE; Usd(id) = index 3 + u32 LE. + const asset = + input.action.kind === "sellShares" + ? u8aConcat(new Uint8Array([2]), u16le(input.action.netuid)) + : u8aConcat(new Uint8Array([3]), u32le(input.usdAssetId ?? 0)); + + let action: Uint8Array; + switch (input.action.kind) { + case "credit": + action = new Uint8Array([0]); + break; + case "stake": + action = u8aConcat( + new Uint8Array([2]), + u16le(input.action.netuid), + accountId32(input.action.hotkey), + u64le(input.action.minAlpha) + ); + break; + case "buyShares": + action = u8aConcat( + new Uint8Array([4]), + u16le(input.action.netuid), + h160Bytes(input.action.recipient), + u64le(input.action.minAlpha), + u32le(input.action.domain) + ); + break; + case "sellShares": + action = u8aConcat( + new Uint8Array([5]), + u16le(input.action.netuid), + h160Bytes(input.action.recipient), + u32le(input.action.usdAssetId), + u64le(input.action.minUsd), + u32le(input.action.domain) + ); + break; + default: { + const exhaustive: never = input.action; + throw new Error(`unknown action ${JSON.stringify(exhaustive)}`); + } + } + + return u8aToHex( + u8aConcat( + new Uint8Array([ENVELOPE_VERSION_V1]), + asset, + u64le(input.amount), + accountId32(input.dest), + action, + u64le(input.nonce) + ) + ); +} + +// ----------------------------------------------------------------- polling + +export async function waitUntil( + probe: () => Promise, + label: string, + timeoutMs = 120_000, + intervalMs = 1_000 +): Promise { + const deadline = Date.now() + timeoutMs; + for (;;) { + const value = await probe(); + if (value !== undefined) { + return value; + } + if (Date.now() > deadline) { + throw new Error(`timed out after ${timeoutMs}ms waiting for ${label}`); + } + await new Promise((resolve) => setTimeout(resolve, intervalMs)); + } +} + +/** Poll pallet-usd-psm for an inbound receipt of `nonce`. */ +export async function waitForReceipt( + api: ApiPromise, + nonce: bigint, + timeoutMs = 120_000 +): Promise<{ block: number; fallback: string | null }> { + return waitUntil( + async () => { + const raw = (await api.query.usdPsm.processedNonces(nonce)).toJSON() as { + block: number; + fallback: string | null; + } | null; + return raw ?? undefined; + }, + `inbound receipt for nonce ${nonce}`, + timeoutMs + ); +} + +// ----------------------------------------------------------- substrate side + +export async function signAndWait(api: ApiPromise, tx: any, signer: KeyringPair, label: string): Promise { + await new Promise((resolve, reject) => { + tx.signAndSend(signer, ({ status, dispatchError }: any) => { + if (dispatchError) { + if (dispatchError.isModule) { + const meta = api.registry.findMetaError(dispatchError.asModule); + reject(new Error(`${label}: ${meta.section}.${meta.name}`)); + } else { + reject(new Error(`${label}: ${dispatchError.toString()}`)); + } + } else if (status.isInBlock || status.isFinalized) { + resolve(); + } + }).catch(reject); + }); +} + +export function alicePair(): KeyringPair { + return new Keyring({ type: "sr25519" }).addFromUri("//Alice"); +} + +/** + * Alpha staked by (hotkey, coldkey) on `netuid`, in rao-scale alpha, read + * through the StakeInfo runtime API (the raw storage is a lazily-migrated + * share pool and not stable to query directly). + */ +export async function alphaStakeOf(api: ApiPromise, hotkey: string, coldkey: string, netuid: number): Promise { + const info = ( + await (api.call as any).stakeInfoRuntimeApi.getStakeInfoForHotkeyColdkeyNetuid(hotkey, coldkey, netuid) + ).toJSON() as { stake?: number | string } | null; + return BigInt(info?.stake ?? 0); +} + +/** + * Create a fresh subnet owned by Alice with `hotkey` registered and started + * (emissions running). Returns its netuid. + */ +export async function createStartedSubnet(api: ApiPromise, hotkey: KeyringPair): Promise { + const alice = alicePair(); + + const rateLimit = Number((await api.query.subtensorModule.networkRateLimit()).toPrimitive()); + if (rateLimit !== 0) { + await signAndWait( + api, + api.tx.sudo.sudo(api.tx.adminUtils.sudoSetNetworkRateLimit(0)), + alice, + "zero network rate limit" + ); + } + + // The network lock cost doubles with every registration and only decays + // over the reduction interval; repeated suite runs would otherwise price + // Alice out. Pin it to a fixed minimum with instant decay. The minimum + // must not be too small: registration seeds the subnet's AMM pool with + // exactly `network_min_lock` TAO, and a 1-TAO-deep pool rejects ordinary + // stakes with InsufficientLiquidity. + const MIN_LOCK_RAO = 100_000_000_000n; // 100 TAO + const reduction = Number((await api.query.subtensorModule.networkLockReductionInterval()).toPrimitive()); + const minLock = BigInt((await api.query.subtensorModule.networkMinLockCost()).toPrimitive() as string | number); + if (reduction > 1 || minLock !== MIN_LOCK_RAO) { + await signAndWait( + api, + api.tx.sudo.sudo(api.tx.adminUtils.sudoSetLockReductionInterval(1)), + alice, + "shrink lock reduction interval" + ); + await signAndWait( + api, + api.tx.sudo.sudo(api.tx.adminUtils.sudoSetNetworkMinLockCost(MIN_LOCK_RAO)), + alice, + "set min network lock cost" + ); + } + + const before = (await api.query.subtensorModule.totalNetworks()).toPrimitive() as number; + await signAndWait(api, api.tx.subtensorModule.registerNetwork(hotkey.address), alice, "register_network"); + const netuid = before; + + // start_call is gated by a post-registration delay measured in blocks. + const registeredAt = (await api.query.subtensorModule.networkRegisteredAt(netuid)).toPrimitive() as number; + const delay = Number(api.consts.subtensorModule.initialStartCallDelay?.toPrimitive() ?? 5); + await waitUntil( + async () => { + const now = (await api.query.system.number()).toPrimitive() as number; + return now - registeredAt > delay ? true : undefined; + }, + `start_call delay for netuid ${netuid}`, + 180_000 + ); + await signAndWait(api, api.tx.subtensorModule.startCall(netuid), alice, "start_call"); + return netuid; +} From 5d6b70bcd2c3d8174fe992e99b754d572519d4fe Mon Sep 17 00:00:00 2001 From: unarbos Date: Mon, 24 Aug 2026 11:50:01 -0300 Subject: [PATCH 2/2] Make rig restarts survive chain resets: verify on-chain state, not files. The .rails registry, agent databases, and CREATE2 deployments outlive a chain restart from genesis, leaving the rig half-wired. Hyperlane deploy now checks the mailbox has code before trusting the registry, the forge deploy scripts skip creation when code already sits at the CREATE2 address, and agents.sh wipes validator/relayer state when the mailbox set changes. Salt bumped to v2 for a clean local address space. Co-authored-by: Cursor --- contracts/evm/script/DeployBase.s.sol | 71 ++++++++++++++++------ contracts/evm/script/DeployBittensor.s.sol | 36 +++++++++-- scripts/rails/agents.sh | 20 ++++++ scripts/rails/env.sh | 4 ++ scripts/rails/hyperlane-deploy.sh | 16 ++++- 5 files changed, 119 insertions(+), 28 deletions(-) diff --git a/contracts/evm/script/DeployBase.s.sol b/contracts/evm/script/DeployBase.s.sol index 9ddfc7430e..c5354520fd 100644 --- a/contracts/evm/script/DeployBase.s.sol +++ b/contracts/evm/script/DeployBase.s.sol @@ -18,42 +18,73 @@ import {RailsPortal} from "../src/RailsPortal.sol"; contract DeployBase is Script { function run() external { address owner = vm.envAddress("RAILS_OWNER"); - address mailbox = vm.envAddress("RAILS_MAILBOX"); - uint32 hubDomain = uint32(vm.envUint("RAILS_HUB_DOMAIN")); - address gateway = vm.envAddress("RAILS_GATEWAY"); - uint32 usdAssetId = uint32(vm.envOr("RAILS_USD_ASSET_ID", uint256(0))); bytes32 salt = keccak256(bytes(vm.envOr("RAILS_SALT", string("rails-local-v1")))); - string memory tokens = vm.envOr("RAILS_TOKENS", string("Chutes|CHUTES")); vm.startBroadcast(); - MockUSDC usdc = new MockUSDC{salt: salt}(); - RailsPortal portal = new RailsPortal{salt: salt}( - owner, - address(usdc), - mailbox, - hubDomain, - usdAssetId, - bytes32(uint256(uint160(gateway))) - ); + // Skip creation when code already sits at the CREATE2 address, so a + // re-run against a live chain re-wires instead of reverting with a + // create collision. + address usdc = vm.computeCreate2Address(salt, keccak256(type(MockUSDC).creationCode)); + if (usdc.code.length == 0) { + usdc = address(new MockUSDC{salt: salt}()); + } // Consumed by the rig manifest writer. - console2.log("MOCK_USDC", address(usdc)); - console2.log("PORTAL", address(portal)); + console2.log("MOCK_USDC", usdc); + console2.log("PORTAL", deployPortal(salt, owner, usdc)); // One share token per "Name|SYMBOL" entry; the salt folds in the // symbol so every token gets a stable CREATE2 address. - string[] memory entries = split(tokens, ","); + string[] memory entries = split(vm.envOr("RAILS_TOKENS", string("Chutes|CHUTES")), ","); for (uint256 i = 0; i < entries.length; i++) { string[] memory parts = split(entries[i], "|"); require(parts.length == 2, "bad RAILS_TOKENS entry"); - Chutes token = new Chutes{salt: keccak256(abi.encodePacked(salt, parts[1]))}( - owner, parts[0], parts[1] + console2.log( + string.concat("TOKEN_", vm.toString(i)), + deployToken(salt, owner, parts[0], parts[1]) ); - console2.log(string.concat("TOKEN_", vm.toString(i)), address(token)); } vm.stopBroadcast(); } + function deployPortal(bytes32 salt, address owner, address usdc) + internal + returns (address portal) + { + address mailbox = vm.envAddress("RAILS_MAILBOX"); + uint32 hubDomain = uint32(vm.envUint("RAILS_HUB_DOMAIN")); + uint32 usdAssetId = uint32(vm.envOr("RAILS_USD_ASSET_ID", uint256(0))); + bytes32 gateway32 = bytes32(uint256(uint160(vm.envAddress("RAILS_GATEWAY")))); + portal = vm.computeCreate2Address( + salt, + keccak256( + abi.encodePacked( + type(RailsPortal).creationCode, + abi.encode(owner, usdc, mailbox, hubDomain, usdAssetId, gateway32) + ) + ) + ); + if (portal.code.length == 0) { + portal = address( + new RailsPortal{salt: salt}(owner, usdc, mailbox, hubDomain, usdAssetId, gateway32) + ); + } + } + + function deployToken(bytes32 salt, address owner, string memory name, string memory symbol) + internal + returns (address token) + { + bytes32 tokenSalt = keccak256(abi.encodePacked(salt, symbol)); + token = vm.computeCreate2Address( + tokenSalt, + keccak256(abi.encodePacked(type(Chutes).creationCode, abi.encode(owner, name, symbol))) + ); + if (token.code.length == 0) { + token = address(new Chutes{salt: tokenSalt}(owner, name, symbol)); + } + } + function split(string memory input, string memory sep) internal pure diff --git a/contracts/evm/script/DeployBittensor.s.sol b/contracts/evm/script/DeployBittensor.s.sol index eff32f20ba..502b4c15ff 100644 --- a/contracts/evm/script/DeployBittensor.s.sol +++ b/contracts/evm/script/DeployBittensor.s.sol @@ -17,14 +17,38 @@ contract DeployBittensor is Script { bytes32 salt = keccak256(bytes(vm.envOr("RAILS_SALT", string("rails-local-v1")))); vm.startBroadcast(); - CanonicalShareToken canonicalUsd = - new CanonicalShareToken{salt: salt}("Canonical USD", "cUSD", owner); - Gateway gateway = - new Gateway{salt: salt}(owner, mailbox, address(canonicalUsd), psmEscrow); + // Skip creation when code already sits at the CREATE2 address, so a + // re-run against a live chain re-wires instead of reverting with a + // create collision. + address canonicalUsd = vm.computeCreate2Address( + salt, + keccak256( + abi.encodePacked( + type(CanonicalShareToken).creationCode, + abi.encode("Canonical USD", "cUSD", owner) + ) + ) + ); + if (canonicalUsd.code.length == 0) { + canonicalUsd = + address(new CanonicalShareToken{salt: salt}("Canonical USD", "cUSD", owner)); + } + address gateway = vm.computeCreate2Address( + salt, + keccak256( + abi.encodePacked( + type(Gateway).creationCode, + abi.encode(owner, mailbox, canonicalUsd, psmEscrow) + ) + ) + ); + if (gateway.code.length == 0) { + gateway = address(new Gateway{salt: salt}(owner, mailbox, canonicalUsd, psmEscrow)); + } vm.stopBroadcast(); // Consumed by the rig manifest writer. - console2.log("CANONICAL_USD", address(canonicalUsd)); - console2.log("GATEWAY", address(gateway)); + console2.log("CANONICAL_USD", canonicalUsd); + console2.log("GATEWAY", gateway); } } diff --git a/scripts/rails/agents.sh b/scripts/rails/agents.sh index f4b0bf23aa..5f966c020a 100755 --- a/scripts/rails/agents.sh +++ b/scripts/rails/agents.sh @@ -64,9 +64,29 @@ start_relayer() { echo "[rails] started rails-relayer" } +# Validator databases and signed checkpoints are only valid for the mailboxes +# they were built against. When a redeploy changes the mailboxes, stale state +# makes validators fail with "Incorrect tree root", so wipe it. +reset_stale_state() { + local fingerprint_file="$RAILS_STATE_DIR/agents.fingerprint" + local fingerprint + fingerprint="$(jq -r '[.chains[].mailbox] | sort | join(",")' \ + "$RAILS_AGENT_DIR/agent-config.docker.json")" + if [ -f "$fingerprint_file" ] && [ "$(cat "$fingerprint_file")" = "$fingerprint" ]; then + return 0 + fi + echo "[rails] mailbox set changed; wiping agent databases and checkpoints" + rm -rf "$RAILS_CHECKPOINT_DIR" "$RAILS_STATE_DIR/relayer-db" \ + "$RAILS_STATE_DIR/validator-db-$BT_CHAIN_NAME" \ + "$RAILS_STATE_DIR/validator-db-$BASE_CHAIN_NAME" + mkdir -p "$RAILS_STATE_DIR" + echo "$fingerprint" >"$fingerprint_file" +} + case "$CMD" in start) stop_all + reset_stale_state start_validator "$BT_CHAIN_NAME" start_validator "$BASE_CHAIN_NAME" start_relayer diff --git a/scripts/rails/env.sh b/scripts/rails/env.sh index 1dd9fcbdb9..b8e10d77fa 100755 --- a/scripts/rails/env.sh +++ b/scripts/rails/env.sh @@ -41,6 +41,10 @@ VALIDATOR_ADDR="0x70997970C51812dc3A010C7d01b50e0d17dc79C8" RELAYER_PK="0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a" RELAYER_ADDR="0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC" +# CREATE2 salt for all rails contracts. Bump the suffix to force a full set +# of fresh contract addresses on the next deploy. +export RAILS_SALT="rails-local-v2" + # The USD rails precompile address (2068 = 0x814). The precompile itself is # the PSM escrow: it holds the canonical USD ERC-20 reserves and moves them # via EVM subcalls (msg.sender = 0x814). diff --git a/scripts/rails/hyperlane-deploy.sh b/scripts/rails/hyperlane-deploy.sh index 22c551e055..90629653f3 100755 --- a/scripts/rails/hyperlane-deploy.sh +++ b/scripts/rails/hyperlane-deploy.sh @@ -17,11 +17,23 @@ for chain in "$BT_CHAIN_NAME" "$BASE_CHAIN_NAME"; do "$RAILS_REGISTRY_DIR/chains/$chain/metadata.yaml" done +rpc_for_chain() { # chain -> rpc url + if [ "$1" = "$BT_CHAIN_NAME" ]; then echo "$BT_RPC_HTTP"; else echo "$BASE_RPC_HTTP"; fi +} + for chain in "$BT_CHAIN_NAME" "$BASE_CHAIN_NAME"; do addresses="$RAILS_REGISTRY_DIR/chains/$chain/addresses.yaml" if [ -f "$addresses" ] && grep -q mailbox "$addresses"; then - echo "[rails] hyperlane core already deployed on $chain" - continue + # The registry survives chain restarts; trust it only if the mailbox + # actually has code on the (possibly fresh-from-genesis) chain. + mailbox="$(awk '$1 == "mailbox:" { print $2; exit }' "$addresses" | tr -d '"')" + if [ -n "$mailbox" ] && \ + [ "$(cast code "$mailbox" --rpc-url "$(rpc_for_chain "$chain")")" != "0x" ]; then + echo "[rails] hyperlane core already deployed on $chain" + continue + fi + echo "[rails] registry has $chain addresses but chain has no code; redeploying ..." + rm -f "$addresses" fi echo "[rails] deploying hyperlane core to $chain ..." $HL core deploy \