Files
eoa-contracts/deployments/localhost/solcInputs/a0fb009eea5ca5b9041c7af510cbdc17.json

410 lines
571 KiB
JSON

{
"language": "Solidity",
"sources": {
"@account-abstraction/contracts/core/Helpers.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.12;\n\n/* solhint-disable no-inline-assembly */\n\n/**\n * returned data from validateUserOp.\n * validateUserOp returns a uint256, with is created by `_packedValidationData` and parsed by `_parseValidationData`\n * @param aggregator - address(0) - the account validated the signature by itself.\n * address(1) - the account failed to validate the signature.\n * otherwise - this is an address of a signature aggregator that must be used to validate the signature.\n * @param validAfter - this UserOp is valid only after this timestamp.\n * @param validaUntil - this UserOp is valid only up to this timestamp.\n */\n struct ValidationData {\n address aggregator;\n uint48 validAfter;\n uint48 validUntil;\n }\n\n//extract sigFailed, validAfter, validUntil.\n// also convert zero validUntil to type(uint48).max\n function _parseValidationData(uint validationData) pure returns (ValidationData memory data) {\n address aggregator = address(uint160(validationData));\n uint48 validUntil = uint48(validationData >> 160);\n if (validUntil == 0) {\n validUntil = type(uint48).max;\n }\n uint48 validAfter = uint48(validationData >> (48 + 160));\n return ValidationData(aggregator, validAfter, validUntil);\n }\n\n// intersect account and paymaster ranges.\n function _intersectTimeRange(uint256 validationData, uint256 paymasterValidationData) pure returns (ValidationData memory) {\n ValidationData memory accountValidationData = _parseValidationData(validationData);\n ValidationData memory pmValidationData = _parseValidationData(paymasterValidationData);\n address aggregator = accountValidationData.aggregator;\n if (aggregator == address(0)) {\n aggregator = pmValidationData.aggregator;\n }\n uint48 validAfter = accountValidationData.validAfter;\n uint48 validUntil = accountValidationData.validUntil;\n uint48 pmValidAfter = pmValidationData.validAfter;\n uint48 pmValidUntil = pmValidationData.validUntil;\n\n if (validAfter < pmValidAfter) validAfter = pmValidAfter;\n if (validUntil > pmValidUntil) validUntil = pmValidUntil;\n return ValidationData(aggregator, validAfter, validUntil);\n }\n\n/**\n * helper to pack the return value for validateUserOp\n * @param data - the ValidationData to pack\n */\n function _packValidationData(ValidationData memory data) pure returns (uint256) {\n return uint160(data.aggregator) | (uint256(data.validUntil) << 160) | (uint256(data.validAfter) << (160 + 48));\n }\n\n/**\n * helper to pack the return value for validateUserOp, when not using an aggregator\n * @param sigFailed - true for signature failure, false for success\n * @param validUntil last timestamp this UserOperation is valid (or zero for infinite)\n * @param validAfter first timestamp this UserOperation is valid\n */\n function _packValidationData(bool sigFailed, uint48 validUntil, uint48 validAfter) pure returns (uint256) {\n return (sigFailed ? 1 : 0) | (uint256(validUntil) << 160) | (uint256(validAfter) << (160 + 48));\n }\n\n/**\n * keccak function over calldata.\n * @dev copy calldata into memory, do keccak and drop allocated memory. Strangely, this is more efficient than letting solidity do it.\n */\n function calldataKeccak(bytes calldata data) pure returns (bytes32 ret) {\n assembly {\n let mem := mload(0x40)\n let len := data.length\n calldatacopy(mem, data.offset, len)\n ret := keccak256(mem, len)\n }\n }\n\n"
},
"@account-abstraction/contracts/interfaces/IAccount.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.12;\n\nimport \"./UserOperation.sol\";\n\ninterface IAccount {\n\n /**\n * Validate user's signature and nonce\n * the entryPoint will make the call to the recipient only if this validation call returns successfully.\n * signature failure should be reported by returning SIG_VALIDATION_FAILED (1).\n * This allows making a \"simulation call\" without a valid signature\n * Other failures (e.g. nonce mismatch, or invalid signature format) should still revert to signal failure.\n *\n * @dev Must validate caller is the entryPoint.\n * Must validate the signature and nonce\n * @param userOp the operation that is about to be executed.\n * @param userOpHash hash of the user's request data. can be used as the basis for signature.\n * @param missingAccountFunds missing funds on the account's deposit in the entrypoint.\n * This is the minimum amount to transfer to the sender(entryPoint) to be able to make the call.\n * The excess is left as a deposit in the entrypoint, for future calls.\n * can be withdrawn anytime using \"entryPoint.withdrawTo()\"\n * In case there is a paymaster in the request (or the current deposit is high enough), this value will be zero.\n * @return validationData packaged ValidationData structure. use `_packValidationData` and `_unpackValidationData` to encode and decode\n * <20-byte> sigAuthorizer - 0 for valid signature, 1 to mark signature failure,\n * otherwise, an address of an \"authorizer\" contract.\n * <6-byte> validUntil - last timestamp this operation is valid. 0 for \"indefinite\"\n * <6-byte> validAfter - first timestamp this operation is valid\n * If an account doesn't use time-range, it is enough to return SIG_VALIDATION_FAILED value (1) for signature failure.\n * Note that the validation code cannot use block.timestamp (or block.number) directly.\n */\n function validateUserOp(UserOperation calldata userOp, bytes32 userOpHash, uint256 missingAccountFunds)\n external returns (uint256 validationData);\n}\n"
},
"@account-abstraction/contracts/interfaces/IAggregator.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.12;\n\nimport \"./UserOperation.sol\";\n\n/**\n * Aggregated Signatures validator.\n */\ninterface IAggregator {\n\n /**\n * validate aggregated signature.\n * revert if the aggregated signature does not match the given list of operations.\n */\n function validateSignatures(UserOperation[] calldata userOps, bytes calldata signature) external view;\n\n /**\n * validate signature of a single userOp\n * This method is should be called by bundler after EntryPoint.simulateValidation() returns (reverts) with ValidationResultWithAggregation\n * First it validates the signature over the userOp. Then it returns data to be used when creating the handleOps.\n * @param userOp the userOperation received from the user.\n * @return sigForUserOp the value to put into the signature field of the userOp when calling handleOps.\n * (usually empty, unless account and aggregator support some kind of \"multisig\"\n */\n function validateUserOpSignature(UserOperation calldata userOp)\n external view returns (bytes memory sigForUserOp);\n\n /**\n * aggregate multiple signatures into a single value.\n * This method is called off-chain to calculate the signature to pass with handleOps()\n * bundler MAY use optimized custom code perform this aggregation\n * @param userOps array of UserOperations to collect the signatures from.\n * @return aggregatedSignature the aggregated signature\n */\n function aggregateSignatures(UserOperation[] calldata userOps) external view returns (bytes memory aggregatedSignature);\n}\n"
},
"@account-abstraction/contracts/interfaces/IEntryPoint.sol": {
"content": "/**\n ** Account-Abstraction (EIP-4337) singleton EntryPoint implementation.\n ** Only one instance required on each chain.\n **/\n// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.12;\n\n/* solhint-disable avoid-low-level-calls */\n/* solhint-disable no-inline-assembly */\n/* solhint-disable reason-string */\n\nimport \"./UserOperation.sol\";\nimport \"./IStakeManager.sol\";\nimport \"./IAggregator.sol\";\nimport \"./INonceManager.sol\";\n\ninterface IEntryPoint is IStakeManager, INonceManager {\n\n /***\n * An event emitted after each successful request\n * @param userOpHash - unique identifier for the request (hash its entire content, except signature).\n * @param sender - the account that generates this request.\n * @param paymaster - if non-null, the paymaster that pays for this request.\n * @param nonce - the nonce value from the request.\n * @param success - true if the sender transaction succeeded, false if reverted.\n * @param actualGasCost - actual amount paid (by account or paymaster) for this UserOperation.\n * @param actualGasUsed - total gas used by this UserOperation (including preVerification, creation, validation and execution).\n */\n event UserOperationEvent(bytes32 indexed userOpHash, address indexed sender, address indexed paymaster, uint256 nonce, bool success, uint256 actualGasCost, uint256 actualGasUsed);\n\n /**\n * account \"sender\" was deployed.\n * @param userOpHash the userOp that deployed this account. UserOperationEvent will follow.\n * @param sender the account that is deployed\n * @param factory the factory used to deploy this account (in the initCode)\n * @param paymaster the paymaster used by this UserOp\n */\n event AccountDeployed(bytes32 indexed userOpHash, address indexed sender, address factory, address paymaster);\n\n /**\n * An event emitted if the UserOperation \"callData\" reverted with non-zero length\n * @param userOpHash the request unique identifier.\n * @param sender the sender of this request\n * @param nonce the nonce used in the request\n * @param revertReason - the return bytes from the (reverted) call to \"callData\".\n */\n event UserOperationRevertReason(bytes32 indexed userOpHash, address indexed sender, uint256 nonce, bytes revertReason);\n\n /**\n * an event emitted by handleOps(), before starting the execution loop.\n * any event emitted before this event, is part of the validation.\n */\n event BeforeExecution();\n\n /**\n * signature aggregator used by the following UserOperationEvents within this bundle.\n */\n event SignatureAggregatorChanged(address indexed aggregator);\n\n /**\n * a custom revert error of handleOps, to identify the offending op.\n * NOTE: if simulateValidation passes successfully, there should be no reason for handleOps to fail on it.\n * @param opIndex - index into the array of ops to the failed one (in simulateValidation, this is always zero)\n * @param reason - revert reason\n * The string starts with a unique code \"AAmn\", where \"m\" is \"1\" for factory, \"2\" for account and \"3\" for paymaster issues,\n * so a failure can be attributed to the correct entity.\n * Should be caught in off-chain handleOps simulation and not happen on-chain.\n * Useful for mitigating DoS attempts against batchers or for troubleshooting of factory/account/paymaster reverts.\n */\n error FailedOp(uint256 opIndex, string reason);\n\n /**\n * error case when a signature aggregator fails to verify the aggregated signature it had created.\n */\n error SignatureValidationFailed(address aggregator);\n\n /**\n * Successful result from simulateValidation.\n * @param returnInfo gas and time-range returned values\n * @param senderInfo stake information about the sender\n * @param factoryInfo stake information about the factory (if any)\n * @param paymasterInfo stake information about the paymaster (if any)\n */\n error ValidationResult(ReturnInfo returnInfo,\n StakeInfo senderInfo, StakeInfo factoryInfo, StakeInfo paymasterInfo);\n\n /**\n * Successful result from simulateValidation, if the account returns a signature aggregator\n * @param returnInfo gas and time-range returned values\n * @param senderInfo stake information about the sender\n * @param factoryInfo stake information about the factory (if any)\n * @param paymasterInfo stake information about the paymaster (if any)\n * @param aggregatorInfo signature aggregation info (if the account requires signature aggregator)\n * bundler MUST use it to verify the signature, or reject the UserOperation\n */\n error ValidationResultWithAggregation(ReturnInfo returnInfo,\n StakeInfo senderInfo, StakeInfo factoryInfo, StakeInfo paymasterInfo,\n AggregatorStakeInfo aggregatorInfo);\n\n /**\n * return value of getSenderAddress\n */\n error SenderAddressResult(address sender);\n\n /**\n * return value of simulateHandleOp\n */\n error ExecutionResult(uint256 preOpGas, uint256 paid, uint48 validAfter, uint48 validUntil, bool targetSuccess, bytes targetResult);\n\n //UserOps handled, per aggregator\n struct UserOpsPerAggregator {\n UserOperation[] userOps;\n\n // aggregator address\n IAggregator aggregator;\n // aggregated signature\n bytes signature;\n }\n\n /**\n * Execute a batch of UserOperation.\n * no signature aggregator is used.\n * if any account requires an aggregator (that is, it returned an aggregator when\n * performing simulateValidation), then handleAggregatedOps() must be used instead.\n * @param ops the operations to execute\n * @param beneficiary the address to receive the fees\n */\n function handleOps(UserOperation[] calldata ops, address payable beneficiary) external;\n\n /**\n * Execute a batch of UserOperation with Aggregators\n * @param opsPerAggregator the operations to execute, grouped by aggregator (or address(0) for no-aggregator accounts)\n * @param beneficiary the address to receive the fees\n */\n function handleAggregatedOps(\n UserOpsPerAggregator[] calldata opsPerAggregator,\n address payable beneficiary\n ) external;\n\n /**\n * generate a request Id - unique identifier for this request.\n * the request ID is a hash over the content of the userOp (except the signature), the entrypoint and the chainid.\n */\n function getUserOpHash(UserOperation calldata userOp) external view returns (bytes32);\n\n /**\n * Simulate a call to account.validateUserOp and paymaster.validatePaymasterUserOp.\n * @dev this method always revert. Successful result is ValidationResult error. other errors are failures.\n * @dev The node must also verify it doesn't use banned opcodes, and that it doesn't reference storage outside the account's data.\n * @param userOp the user operation to validate.\n */\n function simulateValidation(UserOperation calldata userOp) external;\n\n /**\n * gas and return values during simulation\n * @param preOpGas the gas used for validation (including preValidationGas)\n * @param prefund the required prefund for this operation\n * @param sigFailed validateUserOp's (or paymaster's) signature check failed\n * @param validAfter - first timestamp this UserOp is valid (merging account and paymaster time-range)\n * @param validUntil - last timestamp this UserOp is valid (merging account and paymaster time-range)\n * @param paymasterContext returned by validatePaymasterUserOp (to be passed into postOp)\n */\n struct ReturnInfo {\n uint256 preOpGas;\n uint256 prefund;\n bool sigFailed;\n uint48 validAfter;\n uint48 validUntil;\n bytes paymasterContext;\n }\n\n /**\n * returned aggregated signature info.\n * the aggregator returned by the account, and its current stake.\n */\n struct AggregatorStakeInfo {\n address aggregator;\n StakeInfo stakeInfo;\n }\n\n /**\n * Get counterfactual sender address.\n * Calculate the sender contract address that will be generated by the initCode and salt in the UserOperation.\n * this method always revert, and returns the address in SenderAddressResult error\n * @param initCode the constructor code to be passed into the UserOperation.\n */\n function getSenderAddress(bytes memory initCode) external;\n\n\n /**\n * simulate full execution of a UserOperation (including both validation and target execution)\n * this method will always revert with \"ExecutionResult\".\n * it performs full validation of the UserOperation, but ignores signature error.\n * an optional target address is called after the userop succeeds, and its value is returned\n * (before the entire call is reverted)\n * Note that in order to collect the the success/failure of the target call, it must be executed\n * with trace enabled to track the emitted events.\n * @param op the UserOperation to simulate\n * @param target if nonzero, a target address to call after userop simulation. If called, the targetSuccess and targetResult\n * are set to the return from that call.\n * @param targetCallData callData to pass to target address\n */\n function simulateHandleOp(UserOperation calldata op, address target, bytes calldata targetCallData) external;\n}\n\n"
},
"@account-abstraction/contracts/interfaces/INonceManager.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.12;\n\ninterface INonceManager {\n\n /**\n * Return the next nonce for this sender.\n * Within a given key, the nonce values are sequenced (starting with zero, and incremented by one on each userop)\n * But UserOp with different keys can come with arbitrary order.\n *\n * @param sender the account address\n * @param key the high 192 bit of the nonce\n * @return nonce a full nonce to pass for next UserOp with this sender.\n */\n function getNonce(address sender, uint192 key)\n external view returns (uint256 nonce);\n\n /**\n * Manually increment the nonce of the sender.\n * This method is exposed just for completeness..\n * Account does NOT need to call it, neither during validation, nor elsewhere,\n * as the EntryPoint will update the nonce regardless.\n * Possible use-case is call it with various keys to \"initialize\" their nonces to one, so that future\n * UserOperations will not pay extra for the first transaction with a given key.\n */\n function incrementNonce(uint192 key) external;\n}\n"
},
"@account-abstraction/contracts/interfaces/IPaymaster.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.12;\n\nimport \"./UserOperation.sol\";\n\n/**\n * the interface exposed by a paymaster contract, who agrees to pay the gas for user's operations.\n * a paymaster must hold a stake to cover the required entrypoint stake and also the gas for the transaction.\n */\ninterface IPaymaster {\n\n enum PostOpMode {\n opSucceeded, // user op succeeded\n opReverted, // user op reverted. still has to pay for gas.\n postOpReverted //user op succeeded, but caused postOp to revert. Now it's a 2nd call, after user's op was deliberately reverted.\n }\n\n /**\n * payment validation: check if paymaster agrees to pay.\n * Must verify sender is the entryPoint.\n * Revert to reject this request.\n * Note that bundlers will reject this method if it changes the state, unless the paymaster is trusted (whitelisted)\n * The paymaster pre-pays using its deposit, and receive back a refund after the postOp method returns.\n * @param userOp the user operation\n * @param userOpHash hash of the user's request data.\n * @param maxCost the maximum cost of this transaction (based on maximum gas and gas price from userOp)\n * @return context value to send to a postOp\n * zero length to signify postOp is not required.\n * @return validationData signature and time-range of this operation, encoded the same as the return value of validateUserOperation\n * <20-byte> sigAuthorizer - 0 for valid signature, 1 to mark signature failure,\n * otherwise, an address of an \"authorizer\" contract.\n * <6-byte> validUntil - last timestamp this operation is valid. 0 for \"indefinite\"\n * <6-byte> validAfter - first timestamp this operation is valid\n * Note that the validation code cannot use block.timestamp (or block.number) directly.\n */\n function validatePaymasterUserOp(UserOperation calldata userOp, bytes32 userOpHash, uint256 maxCost)\n external returns (bytes memory context, uint256 validationData);\n\n /**\n * post-operation handler.\n * Must verify sender is the entryPoint\n * @param mode enum with the following options:\n * opSucceeded - user operation succeeded.\n * opReverted - user op reverted. still has to pay for gas.\n * postOpReverted - user op succeeded, but caused postOp (in mode=opSucceeded) to revert.\n * Now this is the 2nd call, after user's op was deliberately reverted.\n * @param context - the context value returned by validatePaymasterUserOp\n * @param actualGasCost - actual gas used so far (without this postOp call).\n */\n function postOp(PostOpMode mode, bytes calldata context, uint256 actualGasCost) external;\n}\n"
},
"@account-abstraction/contracts/interfaces/IStakeManager.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.12;\n\n/**\n * manage deposits and stakes.\n * deposit is just a balance used to pay for UserOperations (either by a paymaster or an account)\n * stake is value locked for at least \"unstakeDelay\" by the staked entity.\n */\ninterface IStakeManager {\n\n event Deposited(\n address indexed account,\n uint256 totalDeposit\n );\n\n event Withdrawn(\n address indexed account,\n address withdrawAddress,\n uint256 amount\n );\n\n /// Emitted when stake or unstake delay are modified\n event StakeLocked(\n address indexed account,\n uint256 totalStaked,\n uint256 unstakeDelaySec\n );\n\n /// Emitted once a stake is scheduled for withdrawal\n event StakeUnlocked(\n address indexed account,\n uint256 withdrawTime\n );\n\n event StakeWithdrawn(\n address indexed account,\n address withdrawAddress,\n uint256 amount\n );\n\n /**\n * @param deposit the entity's deposit\n * @param staked true if this entity is staked.\n * @param stake actual amount of ether staked for this entity.\n * @param unstakeDelaySec minimum delay to withdraw the stake.\n * @param withdrawTime - first block timestamp where 'withdrawStake' will be callable, or zero if already locked\n * @dev sizes were chosen so that (deposit,staked, stake) fit into one cell (used during handleOps)\n * and the rest fit into a 2nd cell.\n * 112 bit allows for 10^15 eth\n * 48 bit for full timestamp\n * 32 bit allows 150 years for unstake delay\n */\n struct DepositInfo {\n uint112 deposit;\n bool staked;\n uint112 stake;\n uint32 unstakeDelaySec;\n uint48 withdrawTime;\n }\n\n //API struct used by getStakeInfo and simulateValidation\n struct StakeInfo {\n uint256 stake;\n uint256 unstakeDelaySec;\n }\n\n /// @return info - full deposit information of given account\n function getDepositInfo(address account) external view returns (DepositInfo memory info);\n\n /// @return the deposit (for gas payment) of the account\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * add to the deposit of the given account\n */\n function depositTo(address account) external payable;\n\n /**\n * add to the account's stake - amount and delay\n * any pending unstake is first cancelled.\n * @param _unstakeDelaySec the new lock duration before the deposit can be withdrawn.\n */\n function addStake(uint32 _unstakeDelaySec) external payable;\n\n /**\n * attempt to unlock the stake.\n * the value can be withdrawn (using withdrawStake) after the unstake delay.\n */\n function unlockStake() external;\n\n /**\n * withdraw from the (unlocked) stake.\n * must first call unlockStake and wait for the unstakeDelay to pass\n * @param withdrawAddress the address to send withdrawn value.\n */\n function withdrawStake(address payable withdrawAddress) external;\n\n /**\n * withdraw from the deposit.\n * @param withdrawAddress the address to send withdrawn value.\n * @param withdrawAmount the amount to withdraw.\n */\n function withdrawTo(address payable withdrawAddress, uint256 withdrawAmount) external;\n}\n"
},
"@account-abstraction/contracts/interfaces/UserOperation.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.12;\n\n/* solhint-disable no-inline-assembly */\n\nimport {calldataKeccak} from \"../core/Helpers.sol\";\n\n/**\n * User Operation struct\n * @param sender the sender account of this request.\n * @param nonce unique value the sender uses to verify it is not a replay.\n * @param initCode if set, the account contract will be created by this constructor/\n * @param callData the method call to execute on this account.\n * @param callGasLimit the gas limit passed to the callData method call.\n * @param verificationGasLimit gas used for validateUserOp and validatePaymasterUserOp.\n * @param preVerificationGas gas not calculated by the handleOps method, but added to the gas paid. Covers batch overhead.\n * @param maxFeePerGas same as EIP-1559 gas parameter.\n * @param maxPriorityFeePerGas same as EIP-1559 gas parameter.\n * @param paymasterAndData if set, this field holds the paymaster address and paymaster-specific data. the paymaster will pay for the transaction instead of the sender.\n * @param signature sender-verified signature over the entire request, the EntryPoint address and the chain ID.\n */\n struct UserOperation {\n\n address sender;\n uint256 nonce;\n bytes initCode;\n bytes callData;\n uint256 callGasLimit;\n uint256 verificationGasLimit;\n uint256 preVerificationGas;\n uint256 maxFeePerGas;\n uint256 maxPriorityFeePerGas;\n bytes paymasterAndData;\n bytes signature;\n }\n\n/**\n * Utility functions helpful when working with UserOperation structs.\n */\nlibrary UserOperationLib {\n\n function getSender(UserOperation calldata userOp) internal pure returns (address) {\n address data;\n //read sender from userOp, which is first userOp member (saves 800 gas...)\n assembly {data := calldataload(userOp)}\n return address(uint160(data));\n }\n\n //relayer/block builder might submit the TX with higher priorityFee, but the user should not\n // pay above what he signed for.\n function gasPrice(UserOperation calldata userOp) internal view returns (uint256) {\n unchecked {\n uint256 maxFeePerGas = userOp.maxFeePerGas;\n uint256 maxPriorityFeePerGas = userOp.maxPriorityFeePerGas;\n if (maxFeePerGas == maxPriorityFeePerGas) {\n //legacy mode (for networks that don't support basefee opcode)\n return maxFeePerGas;\n }\n return min(maxFeePerGas, maxPriorityFeePerGas + block.basefee);\n }\n }\n\n function pack(UserOperation calldata userOp) internal pure returns (bytes memory ret) {\n address sender = getSender(userOp);\n uint256 nonce = userOp.nonce;\n bytes32 hashInitCode = calldataKeccak(userOp.initCode);\n bytes32 hashCallData = calldataKeccak(userOp.callData);\n uint256 callGasLimit = userOp.callGasLimit;\n uint256 verificationGasLimit = userOp.verificationGasLimit;\n uint256 preVerificationGas = userOp.preVerificationGas;\n uint256 maxFeePerGas = userOp.maxFeePerGas;\n uint256 maxPriorityFeePerGas = userOp.maxPriorityFeePerGas;\n bytes32 hashPaymasterAndData = calldataKeccak(userOp.paymasterAndData);\n\n return abi.encode(\n sender, nonce,\n hashInitCode, hashCallData,\n callGasLimit, verificationGasLimit, preVerificationGas,\n maxFeePerGas, maxPriorityFeePerGas,\n hashPaymasterAndData\n );\n }\n\n function hash(UserOperation calldata userOp) internal pure returns (bytes32) {\n return keccak256(pack(userOp));\n }\n\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n}\n"
},
"@openzeppelin/contracts/access/Ownable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n constructor() {\n _transferOwnership(_msgSender());\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n _checkOwner();\n _;\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if the sender is not the owner.\n */\n function _checkOwner() internal view virtual {\n require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n _transferOwnership(address(0));\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n _transferOwnership(newOwner);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Internal function without access restriction.\n */\n function _transferOwnership(address newOwner) internal virtual {\n address oldOwner = _owner;\n _owner = newOwner;\n emit OwnershipTransferred(oldOwner, newOwner);\n }\n}\n"
},
"@openzeppelin/contracts/interfaces/draft-IERC1822.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified\n * proxy whose upgrades are fully controlled by the current implementation.\n */\ninterface IERC1822Proxiable {\n /**\n * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation\n * address.\n *\n * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n * function revert if invoked through a proxy.\n */\n function proxiableUUID() external view returns (bytes32);\n}\n"
},
"@openzeppelin/contracts/proxy/beacon/IBeacon.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IBeacon {\n /**\n * @dev Must return an address that can be used as a delegate call target.\n *\n * {BeaconProxy} will check that this address is a contract.\n */\n function implementation() external view returns (address);\n}\n"
},
"@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/ERC1967/ERC1967Proxy.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../Proxy.sol\";\nimport \"./ERC1967Upgrade.sol\";\n\n/**\n * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an\n * implementation address that can be changed. This address is stored in storage in the location specified by\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the\n * implementation behind the proxy.\n */\ncontract ERC1967Proxy is Proxy, ERC1967Upgrade {\n /**\n * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.\n *\n * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded\n * function call, and allows initializing the storage of the proxy like a Solidity constructor.\n */\n constructor(address _logic, bytes memory _data) payable {\n _upgradeToAndCall(_logic, _data, false);\n }\n\n /**\n * @dev Returns the current implementation address.\n */\n function _implementation() internal view virtual override returns (address impl) {\n return ERC1967Upgrade._getImplementation();\n }\n}\n"
},
"@openzeppelin/contracts/proxy/ERC1967/ERC1967Upgrade.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../beacon/IBeacon.sol\";\nimport \"../../interfaces/draft-IERC1822.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/StorageSlot.sol\";\n\n/**\n * @dev This abstract contract provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.\n *\n * _Available since v4.1._\n *\n * @custom:oz-upgrades-unsafe-allow delegatecall\n */\nabstract contract ERC1967Upgrade {\n // This is the keccak-256 hash of \"eip1967.proxy.rollback\" subtracted by 1\n bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;\n\n /**\n * @dev Storage slot with the address of the current implementation.\n * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1, and is\n * validated in the constructor.\n */\n bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n /**\n * @dev Emitted when the implementation is upgraded.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Returns the current implementation address.\n */\n function _getImplementation() internal view returns (address) {\n return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the EIP1967 implementation slot.\n */\n function _setImplementation(address newImplementation) private {\n require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n }\n\n /**\n * @dev Perform implementation upgrade\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeTo(address newImplementation) internal {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n }\n\n /**\n * @dev Perform implementation upgrade with additional setup call.\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeToAndCall(\n address newImplementation,\n bytes memory data,\n bool forceCall\n ) internal {\n _upgradeTo(newImplementation);\n if (data.length > 0 || forceCall) {\n Address.functionDelegateCall(newImplementation, data);\n }\n }\n\n /**\n * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeToAndCallUUPS(\n address newImplementation,\n bytes memory data,\n bool forceCall\n ) internal {\n // Upgrades from old implementations will perform a rollback test. This test requires the new\n // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing\n // this special case will break upgrade paths from old UUPS implementation to new ones.\n if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {\n _setImplementation(newImplementation);\n } else {\n try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {\n require(slot == _IMPLEMENTATION_SLOT, \"ERC1967Upgrade: unsupported proxiableUUID\");\n } catch {\n revert(\"ERC1967Upgrade: new implementation is not UUPS\");\n }\n _upgradeToAndCall(newImplementation, data, forceCall);\n }\n }\n\n /**\n * @dev Storage slot with the admin of the contract.\n * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1, and is\n * validated in the constructor.\n */\n bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n /**\n * @dev Emitted when the admin account has changed.\n */\n event AdminChanged(address previousAdmin, address newAdmin);\n\n /**\n * @dev Returns the current admin.\n */\n function _getAdmin() internal view returns (address) {\n return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the EIP1967 admin slot.\n */\n function _setAdmin(address newAdmin) private {\n require(newAdmin != address(0), \"ERC1967: new admin is the zero address\");\n StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;\n }\n\n /**\n * @dev Changes the admin of the proxy.\n *\n * Emits an {AdminChanged} event.\n */\n function _changeAdmin(address newAdmin) internal {\n emit AdminChanged(_getAdmin(), newAdmin);\n _setAdmin(newAdmin);\n }\n\n /**\n * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\n * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.\n */\n bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\n\n /**\n * @dev Emitted when the beacon is upgraded.\n */\n event BeaconUpgraded(address indexed beacon);\n\n /**\n * @dev Returns the current beacon.\n */\n function _getBeacon() internal view returns (address) {\n return StorageSlot.getAddressSlot(_BEACON_SLOT).value;\n }\n\n /**\n * @dev Stores a new beacon in the EIP1967 beacon slot.\n */\n function _setBeacon(address newBeacon) private {\n require(Address.isContract(newBeacon), \"ERC1967: new beacon is not a contract\");\n require(\n Address.isContract(IBeacon(newBeacon).implementation()),\n \"ERC1967: beacon implementation is not a contract\"\n );\n StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;\n }\n\n /**\n * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does\n * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).\n *\n * Emits a {BeaconUpgraded} event.\n */\n function _upgradeBeaconToAndCall(\n address newBeacon,\n bytes memory data,\n bool forceCall\n ) internal {\n _setBeacon(newBeacon);\n emit BeaconUpgraded(newBeacon);\n if (data.length > 0 || forceCall) {\n Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\n }\n }\n}\n"
},
"@openzeppelin/contracts/proxy/Proxy.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\n * be specified by overriding the virtual {_implementation} function.\n *\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\n * different contract through the {_delegate} function.\n *\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\n */\nabstract contract Proxy {\n /**\n * @dev Delegates the current call to `implementation`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _delegate(address implementation) internal virtual {\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 because we don't know the size yet.\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n /**\n * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function\n * and {_fallback} should delegate.\n */\n function _implementation() internal view virtual returns (address);\n\n /**\n * @dev Delegates the current call to the address returned by `_implementation()`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _fallback() internal virtual {\n _beforeFallback();\n _delegate(_implementation());\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n * function in the contract matches the call data.\n */\n fallback() external payable virtual {\n _fallback();\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data\n * is empty.\n */\n receive() external payable virtual {\n _fallback();\n }\n\n /**\n * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`\n * call, or as part of the Solidity `fallback` or `receive` functions.\n *\n * If overridden should call `super._beforeFallback()`.\n */\n function _beforeFallback() internal virtual {}\n}\n"
},
"@openzeppelin/contracts/proxy/utils/Initializable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.1) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../../utils/Address.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Indicates that the contract has been initialized.\n * @custom:oz-retyped-from bool\n */\n uint8 private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint8 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts.\n *\n * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a\n * constructor.\n *\n * Emits an {Initialized} event.\n */\n modifier initializer() {\n bool isTopLevelCall = !_initializing;\n require(\n (isTopLevelCall && _initialized < 1) || (!Address.isContract(address(this)) && _initialized == 1),\n \"Initializable: contract is already initialized\"\n );\n _initialized = 1;\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n * are added through upgrades and that require initialization.\n *\n * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n * cannot be nested. If one is invoked in the context of another, execution will revert.\n *\n * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n * a contract, executing them in the right order is up to the developer or operator.\n *\n * WARNING: setting the version to 255 will prevent any future reinitialization.\n *\n * Emits an {Initialized} event.\n */\n modifier reinitializer(uint8 version) {\n require(!_initializing && _initialized < version, \"Initializable: contract is already initialized\");\n _initialized = version;\n _initializing = true;\n _;\n _initializing = false;\n emit Initialized(version);\n }\n\n /**\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n * {initializer} and {reinitializer} modifiers, directly or indirectly.\n */\n modifier onlyInitializing() {\n require(_initializing, \"Initializable: contract is not initializing\");\n _;\n }\n\n /**\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n * through proxies.\n *\n * Emits an {Initialized} event the first time it is successfully executed.\n */\n function _disableInitializers() internal virtual {\n require(!_initializing, \"Initializable: contract is initializing\");\n if (_initialized < type(uint8).max) {\n _initialized = type(uint8).max;\n emit Initialized(type(uint8).max);\n }\n }\n\n /**\n * @dev Returns the highest version that has been initialized. See {reinitializer}.\n */\n function _getInitializedVersion() internal view returns (uint8) {\n return _initialized;\n }\n\n /**\n * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.\n */\n function _isInitializing() internal view returns (bool) {\n return _initializing;\n }\n}\n"
},
"@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (proxy/utils/UUPSUpgradeable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../interfaces/draft-IERC1822.sol\";\nimport \"../ERC1967/ERC1967Upgrade.sol\";\n\n/**\n * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an\n * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.\n *\n * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is\n * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing\n * `UUPSUpgradeable` with a custom implementation of upgrades.\n *\n * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.\n *\n * _Available since v4.1._\n */\nabstract contract UUPSUpgradeable is IERC1822Proxiable, ERC1967Upgrade {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment\n address private immutable __self = address(this);\n\n /**\n * @dev Check that the execution is being performed through a delegatecall call and that the execution context is\n * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case\n * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a\n * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to\n * fail.\n */\n modifier onlyProxy() {\n require(address(this) != __self, \"Function must be called through delegatecall\");\n require(_getImplementation() == __self, \"Function must be called through active proxy\");\n _;\n }\n\n /**\n * @dev Check that the execution is not being performed through a delegate call. This allows a function to be\n * callable on the implementing contract but not through proxies.\n */\n modifier notDelegated() {\n require(address(this) == __self, \"UUPSUpgradeable: must not be called through delegatecall\");\n _;\n }\n\n /**\n * @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the\n * implementation. It is used to validate the implementation's compatibility when performing an upgrade.\n *\n * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.\n */\n function proxiableUUID() external view virtual override notDelegated returns (bytes32) {\n return _IMPLEMENTATION_SLOT;\n }\n\n /**\n * @dev Upgrade the implementation of the proxy to `newImplementation`.\n *\n * Calls {_authorizeUpgrade}.\n *\n * Emits an {Upgraded} event.\n */\n function upgradeTo(address newImplementation) external virtual onlyProxy {\n _authorizeUpgrade(newImplementation);\n _upgradeToAndCallUUPS(newImplementation, new bytes(0), false);\n }\n\n /**\n * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call\n * encoded in `data`.\n *\n * Calls {_authorizeUpgrade}.\n *\n * Emits an {Upgraded} event.\n */\n function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {\n _authorizeUpgrade(newImplementation);\n _upgradeToAndCallUUPS(newImplementation, data, true);\n }\n\n /**\n * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by\n * {upgradeTo} and {upgradeToAndCall}.\n *\n * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.\n *\n * ```solidity\n * function _authorizeUpgrade(address) internal override onlyOwner {}\n * ```\n */\n function _authorizeUpgrade(address newImplementation) internal virtual;\n}\n"
},
"@openzeppelin/contracts/security/ReentrancyGuard.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n // Booleans are more expensive than uint256 or any type that takes up a full\n // word because each write operation emits an extra SLOAD to first read the\n // slot's contents, replace the bits taken up by the boolean, and then write\n // back. This is the compiler's defense against contract upgrades and\n // pointer aliasing, and it cannot be disabled.\n\n // The values being non-zero value makes deployment a bit more expensive,\n // but in exchange the refund on every call to nonReentrant will be lower in\n // amount. Since refunds are capped to a percentage of the total\n // transaction's gas, it is best to keep them low in cases like this one, to\n // increase the likelihood of the full refund coming into effect.\n uint256 private constant _NOT_ENTERED = 1;\n uint256 private constant _ENTERED = 2;\n\n uint256 private _status;\n\n constructor() {\n _status = _NOT_ENTERED;\n }\n\n /**\n * @dev Prevents a contract from calling itself, directly or indirectly.\n * Calling a `nonReentrant` function from another `nonReentrant`\n * function is not supported. It is possible to prevent this from happening\n * by making the `nonReentrant` function external, and making it call a\n * `private` function that does the actual work.\n */\n modifier nonReentrant() {\n _nonReentrantBefore();\n _;\n _nonReentrantAfter();\n }\n\n function _nonReentrantBefore() private {\n // On the first call to nonReentrant, _status will be _NOT_ENTERED\n require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n // Any calls to nonReentrant after this point will fail\n _status = _ENTERED;\n }\n\n function _nonReentrantAfter() private {\n // By storing the original value once again, a refund is triggered (see\n // https://eips.ethereum.org/EIPS/eip-2200)\n _status = _NOT_ENTERED;\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev _Available since v3.1._\n */\ninterface IERC1155Receiver is IERC165 {\n /**\n * @dev Handles the receipt of a single ERC1155 token type. This function is\n * called at the end of a `safeTransferFrom` after the balance has been updated.\n *\n * NOTE: To accept the transfer, this must return\n * `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))`\n * (i.e. 0xf23a6e61, or its own function selector).\n *\n * @param operator The address which initiated the transfer (i.e. msg.sender)\n * @param from The address which previously owned the token\n * @param id The ID of the token being transferred\n * @param value The amount of tokens being transferred\n * @param data Additional data with no specified format\n * @return `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))` if transfer is allowed\n */\n function onERC1155Received(\n address operator,\n address from,\n uint256 id,\n uint256 value,\n bytes calldata data\n ) external returns (bytes4);\n\n /**\n * @dev Handles the receipt of a multiple ERC1155 token types. This function\n * is called at the end of a `safeBatchTransferFrom` after the balances have\n * been updated.\n *\n * NOTE: To accept the transfer(s), this must return\n * `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))`\n * (i.e. 0xbc197c81, or its own function selector).\n *\n * @param operator The address which initiated the batch transfer (i.e. msg.sender)\n * @param from The address which previously owned the token\n * @param ids An array containing ids of each token being transferred (order and length must match values array)\n * @param values An array containing amounts of each token being transferred (order and length must match ids array)\n * @param data Additional data with no specified format\n * @return `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))` if transfer is allowed\n */\n function onERC1155BatchReceived(\n address operator,\n address from,\n uint256[] calldata ids,\n uint256[] calldata values,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by\n // decrementing then incrementing.\n _balances[to] += amount;\n }\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n unchecked {\n // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.\n _balances[account] += amount;\n }\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n // Overflow not possible: amount <= accountBalance <= totalSupply.\n _totalSupply -= amount;\n }\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20Permit {\n /**\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n * given ``owner``'s signed approval.\n *\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n * ordering also apply here.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `deadline` must be a timestamp in the future.\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n * over the EIP712-formatted function arguments.\n * - the signature must use ``owner``'s current nonce (see {nonces}).\n *\n * For more information on the signature format, see the\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n * section].\n */\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n /**\n * @dev Returns the current nonce for `owner`. This value must be\n * included whenever a signature is generated for {permit}.\n *\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\n * prevents a signature from being used multiple times.\n */\n function nonces(address owner) external view returns (uint256);\n\n /**\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n */\n // solhint-disable-next-line func-name-mixedcase\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../extensions/draft-IERC20Permit.sol\";\nimport \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using Address for address;\n\n function safeTransfer(\n IERC20 token,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(\n IERC20 token,\n address from,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n uint256 newAllowance = token.allowance(address(this), spender) + value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n uint256 newAllowance = oldAllowance - value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n }\n\n function safePermit(\n IERC20Permit token,\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal {\n uint256 nonceBefore = token.nonces(owner);\n token.permit(owner, spender, value, deadline, v, r, s);\n uint256 nonceAfter = token.nonces(owner);\n require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) {\n // Return data is optional\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC777/IERC777Recipient.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777Recipient.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP.\n *\n * Accounts can be notified of {IERC777} tokens being sent to them by having a\n * contract implement this interface (contract holders can be their own\n * implementer) and registering it on the\n * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].\n *\n * See {IERC1820Registry} and {ERC1820Implementer}.\n */\ninterface IERC777Recipient {\n /**\n * @dev Called by an {IERC777} token contract whenever tokens are being\n * moved or created into a registered account (`to`). The type of operation\n * is conveyed by `from` being the zero address or not.\n *\n * This call occurs _after_ the token contract's state is updated, so\n * {IERC777-balanceOf}, etc., can be used to query the post-operation state.\n *\n * This function may revert to prevent the operation from being executed.\n */\n function tokensReceived(\n address operator,\n address from,\n address to,\n uint256 amount,\n bytes calldata userData,\n bytes calldata operatorData\n ) external;\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n *\n * _Available since v4.8._\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n if (success) {\n if (returndata.length == 0) {\n // only check isContract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n require(isContract(target), \"Address: call to non-contract\");\n }\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason or using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n function _revert(bytes memory returndata, string memory errorMessage) private pure {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Create2.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/Create2.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.\n * `CREATE2` can be used to compute in advance the address where a smart\n * contract will be deployed, which allows for interesting new mechanisms known\n * as 'counterfactual interactions'.\n *\n * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more\n * information.\n */\nlibrary Create2 {\n /**\n * @dev Deploys a contract using `CREATE2`. The address where the contract\n * will be deployed can be known in advance via {computeAddress}.\n *\n * The bytecode for a contract can be obtained from Solidity with\n * `type(contractName).creationCode`.\n *\n * Requirements:\n *\n * - `bytecode` must not be empty.\n * - `salt` must have not been used for `bytecode` already.\n * - the factory must have a balance of at least `amount`.\n * - if `amount` is non-zero, `bytecode` must have a `payable` constructor.\n */\n function deploy(\n uint256 amount,\n bytes32 salt,\n bytes memory bytecode\n ) internal returns (address addr) {\n require(address(this).balance >= amount, \"Create2: insufficient balance\");\n require(bytecode.length != 0, \"Create2: bytecode length is zero\");\n /// @solidity memory-safe-assembly\n assembly {\n addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)\n }\n require(addr != address(0), \"Create2: Failed on deploy\");\n }\n\n /**\n * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the\n * `bytecodeHash` or `salt` will result in a new destination address.\n */\n function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {\n return computeAddress(salt, bytecodeHash, address(this));\n }\n\n /**\n * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at\n * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.\n */\n function computeAddress(\n bytes32 salt,\n bytes32 bytecodeHash,\n address deployer\n ) internal pure returns (address addr) {\n /// @solidity memory-safe-assembly\n assembly {\n let ptr := mload(0x40) // Get free memory pointer\n\n // | | ↓ ptr ... ↓ ptr + 0x0B (start) ... ↓ ptr + 0x20 ... ↓ ptr + 0x40 ... |\n // |-------------------|---------------------------------------------------------------------------|\n // | bytecodeHash | CCCCCCCCCCCCC...CC |\n // | salt | BBBBBBBBBBBBB...BB |\n // | deployer | 000000...0000AAAAAAAAAAAAAAAAAAA...AA |\n // | 0xFF | FF |\n // |-------------------|---------------------------------------------------------------------------|\n // | memory | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC |\n // | keccak(start, 85) | ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |\n\n mstore(add(ptr, 0x40), bytecodeHash)\n mstore(add(ptr, 0x20), salt)\n mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes\n let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff\n mstore8(start, 0xff)\n addr := keccak256(start, 85)\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/cryptography/ECDSA.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/ECDSA.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../Strings.sol\";\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSA {\n enum RecoverError {\n NoError,\n InvalidSignature,\n InvalidSignatureLength,\n InvalidSignatureS,\n InvalidSignatureV // Deprecated in v4.8\n }\n\n function _throwError(RecoverError error) private pure {\n if (error == RecoverError.NoError) {\n return; // no error: do nothing\n } else if (error == RecoverError.InvalidSignature) {\n revert(\"ECDSA: invalid signature\");\n } else if (error == RecoverError.InvalidSignatureLength) {\n revert(\"ECDSA: invalid signature length\");\n } else if (error == RecoverError.InvalidSignatureS) {\n revert(\"ECDSA: invalid signature 's' value\");\n }\n }\n\n /**\n * @dev Returns the address that signed a hashed message (`hash`) with\n * `signature` or error string. This address can then be used for verification purposes.\n *\n * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n * this function rejects them by requiring the `s` value to be in the lower\n * half order, and the `v` value to be either 27 or 28.\n *\n * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n * verification to be secure: it is possible to craft signatures that\n * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n * this is by receiving a hash of the original message (which may otherwise\n * be too long), and then calling {toEthSignedMessageHash} on it.\n *\n * Documentation for signature generation:\n * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]\n * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]\n *\n * _Available since v4.3._\n */\n function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {\n if (signature.length == 65) {\n bytes32 r;\n bytes32 s;\n uint8 v;\n // ecrecover takes the signature parameters, and the only way to get them\n // currently is to use assembly.\n /// @solidity memory-safe-assembly\n assembly {\n r := mload(add(signature, 0x20))\n s := mload(add(signature, 0x40))\n v := byte(0, mload(add(signature, 0x60)))\n }\n return tryRecover(hash, v, r, s);\n } else {\n return (address(0), RecoverError.InvalidSignatureLength);\n }\n }\n\n /**\n * @dev Returns the address that signed a hashed message (`hash`) with\n * `signature`. This address can then be used for verification purposes.\n *\n * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n * this function rejects them by requiring the `s` value to be in the lower\n * half order, and the `v` value to be either 27 or 28.\n *\n * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n * verification to be secure: it is possible to craft signatures that\n * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n * this is by receiving a hash of the original message (which may otherwise\n * be too long), and then calling {toEthSignedMessageHash} on it.\n */\n function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {\n (address recovered, RecoverError error) = tryRecover(hash, signature);\n _throwError(error);\n return recovered;\n }\n\n /**\n * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.\n *\n * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]\n *\n * _Available since v4.3._\n */\n function tryRecover(\n bytes32 hash,\n bytes32 r,\n bytes32 vs\n ) internal pure returns (address, RecoverError) {\n bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);\n uint8 v = uint8((uint256(vs) >> 255) + 27);\n return tryRecover(hash, v, r, s);\n }\n\n /**\n * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.\n *\n * _Available since v4.2._\n */\n function recover(\n bytes32 hash,\n bytes32 r,\n bytes32 vs\n ) internal pure returns (address) {\n (address recovered, RecoverError error) = tryRecover(hash, r, vs);\n _throwError(error);\n return recovered;\n }\n\n /**\n * @dev Overload of {ECDSA-tryRecover} that receives the `v`,\n * `r` and `s` signature fields separately.\n *\n * _Available since v4.3._\n */\n function tryRecover(\n bytes32 hash,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal pure returns (address, RecoverError) {\n // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature\n // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines\n // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most\n // signatures from current libraries generate a unique signature with an s-value in the lower half order.\n //\n // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value\n // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or\n // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept\n // these malleable signatures as well.\n if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {\n return (address(0), RecoverError.InvalidSignatureS);\n }\n\n // If the signature is valid (and not malleable), return the signer address\n address signer = ecrecover(hash, v, r, s);\n if (signer == address(0)) {\n return (address(0), RecoverError.InvalidSignature);\n }\n\n return (signer, RecoverError.NoError);\n }\n\n /**\n * @dev Overload of {ECDSA-recover} that receives the `v`,\n * `r` and `s` signature fields separately.\n */\n function recover(\n bytes32 hash,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal pure returns (address) {\n (address recovered, RecoverError error) = tryRecover(hash, v, r, s);\n _throwError(error);\n return recovered;\n }\n\n /**\n * @dev Returns an Ethereum Signed Message, created from a `hash`. This\n * produces hash corresponding to the one signed with the\n * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\n * JSON-RPC method as part of EIP-191.\n *\n * See {recover}.\n */\n function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {\n // 32 is the length in bytes of hash,\n // enforced by the type signature above\n return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", hash));\n }\n\n /**\n * @dev Returns an Ethereum Signed Message, created from `s`. This\n * produces hash corresponding to the one signed with the\n * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\n * JSON-RPC method as part of EIP-191.\n *\n * See {recover}.\n */\n function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n\", Strings.toString(s.length), s));\n }\n\n /**\n * @dev Returns an Ethereum Signed Typed Data, created from a\n * `domainSeparator` and a `structHash`. This produces hash corresponding\n * to the one signed with the\n * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]\n * JSON-RPC method as part of EIP-712.\n *\n * See {recover}.\n */\n function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(\"\\x19\\x01\", domainSeparator, structHash));\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/math/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n enum Rounding {\n Down, // Toward negative infinity\n Up, // Toward infinity\n Zero // Toward zero\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds up instead\n * of rounding down.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n * with further edits by Uniswap Labs also under MIT license.\n */\n function mulDiv(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod0 := mul(x, y)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n require(denominator > prod1);\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n // See https://cs.stackexchange.com/q/138556/92363.\n\n // Does not overflow because the denominator cannot be zero at this stage in the function.\n uint256 twos = denominator & (~denominator + 1);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n // in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(\n uint256 x,\n uint256 y,\n uint256 denominator,\n Rounding rounding\n ) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n //\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n //\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n //\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1 << (log2(a) >> 1);\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = sqrt(a);\n return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 2, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 128;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 64;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 32;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 16;\n }\n if (value >> 8 > 0) {\n value >>= 8;\n result += 8;\n }\n if (value >> 4 > 0) {\n value >>= 4;\n result += 4;\n }\n if (value >> 2 > 0) {\n value >>= 2;\n result += 2;\n }\n if (value >> 1 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 10, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10**64) {\n value /= 10**64;\n result += 64;\n }\n if (value >= 10**32) {\n value /= 10**32;\n result += 32;\n }\n if (value >= 10**16) {\n value /= 10**16;\n result += 16;\n }\n if (value >= 10**8) {\n value /= 10**8;\n result += 8;\n }\n if (value >= 10**4) {\n value /= 10**4;\n result += 4;\n }\n if (value >= 10**2) {\n value /= 10**2;\n result += 2;\n }\n if (value >= 10**1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 256, rounded down, of a positive value.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 16;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 8;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 4;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 2;\n }\n if (value >> 8 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/StorageSlot.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC1967 implementation slot:\n * ```\n * contract ERC1967 {\n * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n * function _getImplementation() internal view returns (address) {\n * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n * }\n *\n * function _setImplementation(address newImplementation) internal {\n * require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n * }\n * }\n * ```\n *\n * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._\n */\nlibrary StorageSlot {\n struct AddressSlot {\n address value;\n }\n\n struct BooleanSlot {\n bool value;\n }\n\n struct Bytes32Slot {\n bytes32 value;\n }\n\n struct Uint256Slot {\n uint256 value;\n }\n\n /**\n * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n */\n function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\n */\n function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\n */\n function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\n */\n function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./math/Math.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n unchecked {\n uint256 length = Math.log10(value) + 1;\n string memory buffer = new string(length);\n uint256 ptr;\n /// @solidity memory-safe-assembly\n assembly {\n ptr := add(buffer, add(32, length))\n }\n while (true) {\n ptr--;\n /// @solidity memory-safe-assembly\n assembly {\n mstore8(ptr, byte(mod(value, 10), _SYMBOLS))\n }\n value /= 10;\n if (value == 0) break;\n }\n return buffer;\n }\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n unchecked {\n return toHexString(value, Math.log256(value) + 1);\n }\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/core/BaseAccount.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\n/* solhint-disable avoid-low-level-calls */\n/* solhint-disable no-empty-blocks */\n\nimport {IAccount} from \"../interfaces/IAccount.sol\";\nimport {IEntryPoint} from \"../interfaces/IEntryPoint.sol\";\nimport {UserOperationLib, UserOperation} from \"../interfaces/UserOperation.sol\";\nimport \"./Helpers.sol\";\n\n/**\n * Basic account implementation.\n * this contract provides the basic logic for implementing the IAccount interface - validateUserOp\n * specific account implementation should inherit it and provide the account-specific logic\n */\nabstract contract BaseAccount is IAccount {\n using UserOperationLib for UserOperation;\n\n //return value in case of signature failure, with no time-range.\n // equivalent to _packValidationData(true,0,0);\n uint256 internal constant SIG_VALIDATION_FAILED = 1;\n\n /**\n * Return the account nonce.\n * This method returns the next sequential nonce.\n * For a nonce of a specific key, use `entrypoint.getNonce(account, key)`\n */\n function getNonce() public view virtual returns (uint256) {\n return entryPoint().getNonce(address(this), 0);\n }\n\n /**\n * return the entryPoint used by this account.\n * subclass should return the current entryPoint used by this account.\n */\n function entryPoint() public view virtual returns (IEntryPoint);\n\n /**\n * Validate user's signature and nonce.\n * subclass doesn't need to override this method. Instead, it should override the specific internal validation methods.\n */\n function validateUserOp(\n UserOperation calldata userOp,\n bytes32 userOpHash,\n uint256 missingAccountFunds\n ) external virtual override returns (uint256 validationData) {\n _requireFromEntryPoint();\n validationData = _validateSignature(userOp, userOpHash);\n _validateNonce(userOp.nonce);\n _payPrefund(missingAccountFunds);\n }\n\n /**\n * ensure the request comes from the known entrypoint.\n */\n function _requireFromEntryPoint() internal view virtual {\n require(\n msg.sender == address(entryPoint()),\n \"account: not from EntryPoint\"\n );\n }\n\n /**\n * validate the signature is valid for this message.\n * @param userOp validate the userOp.signature field\n * @param userOpHash convenient field: the hash of the request, to check the signature against\n * (also hashes the entrypoint and chain id)\n * @return validationData signature and time-range of this operation\n * <20-byte> sigAuthorizer - 0 for valid signature, 1 to mark signature failure,\n * otherwise, an address of an \"authorizer\" contract.\n * <6-byte> validUntil - last timestamp this operation is valid. 0 for \"indefinite\"\n * <6-byte> validAfter - first timestamp this operation is valid\n * If the account doesn't use time-range, it is enough to return SIG_VALIDATION_FAILED value (1) for signature failure.\n * Note that the validation code cannot use block.timestamp (or block.number) directly.\n */\n function _validateSignature(\n UserOperation calldata userOp,\n bytes32 userOpHash\n ) internal virtual returns (uint256 validationData);\n\n /**\n * Validate the nonce of the UserOperation.\n * This method may validate the nonce requirement of this account.\n * e.g.\n * To limit the nonce to use sequenced UserOps only (no \"out of order\" UserOps):\n * `require(nonce < type(uint64).max)`\n * For a hypothetical account that *requires* the nonce to be out-of-order:\n * `require(nonce & type(uint64).max == 0)`\n *\n * The actual nonce uniqueness is managed by the EntryPoint, and thus no other\n * action is needed by the account itself.\n *\n * @param nonce to validate\n *\n * solhint-disable-next-line no-empty-blocks\n */\n function _validateNonce(uint256 nonce) internal view virtual {}\n\n /**\n * sends to the entrypoint (msg.sender) the missing funds for this transaction.\n * subclass MAY override this method for better funds management\n * (e.g. send to the entryPoint more than the minimum required, so that in future transactions\n * it will not be required to send again)\n * @param missingAccountFunds the minimum value this method should send the entrypoint.\n * this value MAY be zero, in case there is enough deposit, or the userOp has a paymaster.\n */\n function _payPrefund(uint256 missingAccountFunds) internal virtual {\n if (missingAccountFunds != 0) {\n (bool success, ) = payable(msg.sender).call{\n value: missingAccountFunds,\n gas: type(uint256).max\n }(\"\");\n (success);\n //ignore failure (its EntryPoint's job to verify, not account.)\n }\n }\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/core/BasePaymaster.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\n/* solhint-disable reason-string */\n\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\nimport \"../interfaces/IPaymaster.sol\";\nimport \"../interfaces/IEntryPoint.sol\";\nimport \"./Helpers.sol\";\n\n/**\n * Helper class for creating a paymaster.\n * provides helper methods for staking.\n * validates that the postOp is called only by the entryPoint\n */\nabstract contract BasePaymaster is IPaymaster, Ownable {\n IEntryPoint public immutable entryPoint;\n\n constructor(IEntryPoint _entryPoint) {\n entryPoint = _entryPoint;\n }\n\n /// @inheritdoc IPaymaster\n function validatePaymasterUserOp(\n UserOperation calldata userOp,\n bytes32 userOpHash,\n uint256 maxCost\n ) external override returns (bytes memory context, uint256 validationData) {\n _requireFromEntryPoint();\n return _validatePaymasterUserOp(userOp, userOpHash, maxCost);\n }\n\n function _validatePaymasterUserOp(\n UserOperation calldata userOp,\n bytes32 userOpHash,\n uint256 maxCost\n ) internal virtual returns (bytes memory context, uint256 validationData);\n\n /// @inheritdoc IPaymaster\n function postOp(\n PostOpMode mode,\n bytes calldata context,\n uint256 actualGasCost\n ) external override {\n _requireFromEntryPoint();\n _postOp(mode, context, actualGasCost);\n }\n\n /**\n * post-operation handler.\n * (verified to be called only through the entryPoint)\n * @dev if subclass returns a non-empty context from validatePaymasterUserOp, it must also implement this method.\n * @param mode enum with the following options:\n * opSucceeded - user operation succeeded.\n * opReverted - user op reverted. still has to pay for gas.\n * postOpReverted - user op succeeded, but caused postOp (in mode=opSucceeded) to revert.\n * Now this is the 2nd call, after user's op was deliberately reverted.\n * @param context - the context value returned by validatePaymasterUserOp\n * @param actualGasCost - actual gas used so far (without this postOp call).\n */\n function _postOp(\n PostOpMode mode,\n bytes calldata context,\n uint256 actualGasCost\n ) internal virtual {\n (mode, context, actualGasCost); // unused params\n // subclass must override this method if validatePaymasterUserOp returns a context\n revert(\"must override\");\n }\n\n /**\n * add a deposit for this paymaster, used for paying for transaction fees\n */\n function deposit() public payable {\n entryPoint.depositTo{value: msg.value}(address(this));\n }\n\n /**\n * withdraw value from the deposit\n * @param withdrawAddress target to send to\n * @param amount to withdraw\n */\n function withdrawTo(\n address payable withdrawAddress,\n uint256 amount\n ) public onlyOwner {\n entryPoint.withdrawTo(withdrawAddress, amount);\n }\n\n /**\n * add stake for this paymaster.\n * This method can also carry eth value to add to the current stake.\n * @param unstakeDelaySec - the unstake delay for this paymaster. Can only be increased.\n */\n function addStake(uint32 unstakeDelaySec) external payable onlyOwner {\n entryPoint.addStake{value: msg.value}(unstakeDelaySec);\n }\n\n /**\n * return current paymaster's deposit on the entryPoint.\n */\n function getDeposit() public view returns (uint256) {\n return entryPoint.balanceOf(address(this));\n }\n\n /**\n * unlock the stake, in order to withdraw it.\n * The paymaster can't serve requests once unlocked, until it calls addStake again\n */\n function unlockStake() external onlyOwner {\n entryPoint.unlockStake();\n }\n\n /**\n * withdraw the entire paymaster's stake.\n * stake must be unlocked first (and then wait for the unstakeDelay to be over)\n * @param withdrawAddress the address to send withdrawn value.\n */\n function withdrawStake(address payable withdrawAddress) external onlyOwner {\n entryPoint.withdrawStake(withdrawAddress);\n }\n\n /// validate the call is made from a valid entrypoint\n function _requireFromEntryPoint() internal virtual {\n require(msg.sender == address(entryPoint), \"Sender not EntryPoint\");\n }\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/core/EntryPoint.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\n/**\n ** Account-Abstraction (EIP-4337) singleton EntryPoint implementation.\n ** Only one instance required on each chain.\n **/\npragma solidity 0.8.17;\n\n/* solhint-disable avoid-low-level-calls */\n/* solhint-disable no-inline-assembly */\n\nimport \"../interfaces/IAccount.sol\";\nimport \"../interfaces/IPaymaster.sol\";\nimport \"../interfaces/IEntryPoint.sol\";\n\nimport \"../utils/Exec.sol\";\nimport \"./StakeManager.sol\";\nimport \"./SenderCreator.sol\";\nimport \"./Helpers.sol\";\nimport \"./NonceManager.sol\";\nimport \"@openzeppelin/contracts/security/ReentrancyGuard.sol\";\n\ncontract EntryPoint is\n IEntryPoint,\n StakeManager,\n NonceManager,\n ReentrancyGuard\n{\n using UserOperationLib for UserOperation;\n\n SenderCreator private immutable senderCreator = new SenderCreator();\n\n // internal value used during simulation: need to query aggregator.\n address private constant SIMULATE_FIND_AGGREGATOR = address(1);\n\n // marker for inner call revert on out of gas\n bytes32 private constant INNER_OUT_OF_GAS = hex\"deaddead\";\n\n uint256 private constant REVERT_REASON_MAX_LEN = 2048;\n\n /**\n * for simulation purposes, validateUserOp (and validatePaymasterUserOp) must return this value\n * in case of signature failure, instead of revert.\n */\n uint256 public constant SIG_VALIDATION_FAILED = 1;\n\n /**\n * compensate the caller's beneficiary address with the collected fees of all UserOperations.\n * @param beneficiary the address to receive the fees\n * @param amount amount to transfer.\n */\n function _compensate(address payable beneficiary, uint256 amount) internal {\n require(beneficiary != address(0), \"AA90 invalid beneficiary\");\n (bool success, ) = beneficiary.call{value: amount}(\"\");\n require(success, \"AA91 failed send to beneficiary\");\n }\n\n /**\n * execute a user op\n * @param opIndex index into the opInfo array\n * @param userOp the userOp to execute\n * @param opInfo the opInfo filled by validatePrepayment for this userOp.\n * @return collected the total amount this userOp paid.\n */\n function _executeUserOp(\n uint256 opIndex,\n UserOperation calldata userOp,\n UserOpInfo memory opInfo\n ) private returns (uint256 collected) {\n uint256 preGas = gasleft();\n bytes memory context = getMemoryBytesFromOffset(opInfo.contextOffset);\n\n try this.innerHandleOp(userOp.callData, opInfo, context) returns (\n uint256 _actualGasCost\n ) {\n collected = _actualGasCost;\n } catch {\n bytes32 innerRevertCode;\n assembly {\n returndatacopy(0, 0, 32)\n innerRevertCode := mload(0)\n }\n // handleOps was called with gas limit too low. abort entire bundle.\n if (innerRevertCode == INNER_OUT_OF_GAS) {\n //report paymaster, since if it is not deliberately caused by the bundler,\n // it must be a revert caused by paymaster.\n revert FailedOp(opIndex, \"AA95 out of gas\");\n }\n\n uint256 actualGas = preGas - gasleft() + opInfo.preOpGas;\n collected = _handlePostOp(\n opIndex,\n IPaymaster.PostOpMode.postOpReverted,\n opInfo,\n context,\n actualGas\n );\n }\n }\n\n /**\n * Execute a batch of UserOperations.\n * no signature aggregator is used.\n * if any account requires an aggregator (that is, it returned an aggregator when\n * performing simulateValidation), then handleAggregatedOps() must be used instead.\n * @param ops the operations to execute\n * @param beneficiary the address to receive the fees\n */\n function handleOps(\n UserOperation[] calldata ops,\n address payable beneficiary\n ) public nonReentrant {\n uint256 opslen = ops.length;\n UserOpInfo[] memory opInfos = new UserOpInfo[](opslen);\n\n unchecked {\n for (uint256 i = 0; i < opslen; i++) {\n UserOpInfo memory opInfo = opInfos[i];\n (\n uint256 validationData,\n uint256 pmValidationData\n ) = _validatePrepayment(i, ops[i], opInfo);\n _validateAccountAndPaymasterValidationData(\n i,\n validationData,\n pmValidationData,\n address(0)\n );\n }\n\n uint256 collected = 0;\n emit BeforeExecution();\n\n for (uint256 i = 0; i < opslen; i++) {\n collected += _executeUserOp(i, ops[i], opInfos[i]);\n }\n\n _compensate(beneficiary, collected);\n } //unchecked\n }\n\n /**\n * Execute a batch of UserOperation with Aggregators\n * @param opsPerAggregator the operations to execute, grouped by aggregator (or address(0) for no-aggregator accounts)\n * @param beneficiary the address to receive the fees\n */\n function handleAggregatedOps(\n UserOpsPerAggregator[] calldata opsPerAggregator,\n address payable beneficiary\n ) public nonReentrant {\n uint256 opasLen = opsPerAggregator.length;\n uint256 totalOps = 0;\n for (uint256 i = 0; i < opasLen; i++) {\n UserOpsPerAggregator calldata opa = opsPerAggregator[i];\n UserOperation[] calldata ops = opa.userOps;\n IAggregator aggregator = opa.aggregator;\n\n //address(1) is special marker of \"signature error\"\n require(\n address(aggregator) != address(1),\n \"AA96 invalid aggregator\"\n );\n\n if (address(aggregator) != address(0)) {\n \n try aggregator.validateSignatures(ops, opa.signature) {} catch {\n revert SignatureValidationFailed(address(aggregator));\n }\n }\n\n totalOps += ops.length;\n }\n\n UserOpInfo[] memory opInfos = new UserOpInfo[](totalOps);\n\n emit BeforeExecution();\n\n uint256 opIndex = 0;\n for (uint256 a = 0; a < opasLen; a++) {\n UserOpsPerAggregator calldata opa = opsPerAggregator[a];\n UserOperation[] calldata ops = opa.userOps;\n IAggregator aggregator = opa.aggregator;\n\n uint256 opslen = ops.length;\n for (uint256 i = 0; i < opslen; i++) {\n UserOpInfo memory opInfo = opInfos[opIndex];\n (\n uint256 validationData,\n uint256 paymasterValidationData\n ) = _validatePrepayment(opIndex, ops[i], opInfo);\n _validateAccountAndPaymasterValidationData(\n i,\n validationData,\n paymasterValidationData,\n address(aggregator)\n );\n opIndex++;\n }\n }\n\n uint256 collected = 0;\n opIndex = 0;\n for (uint256 a = 0; a < opasLen; a++) {\n UserOpsPerAggregator calldata opa = opsPerAggregator[a];\n emit SignatureAggregatorChanged(address(opa.aggregator));\n UserOperation[] calldata ops = opa.userOps;\n uint256 opslen = ops.length;\n\n for (uint256 i = 0; i < opslen; i++) {\n collected += _executeUserOp(opIndex, ops[i], opInfos[opIndex]);\n opIndex++;\n }\n }\n emit SignatureAggregatorChanged(address(0));\n\n _compensate(beneficiary, collected);\n }\n\n /// @inheritdoc IEntryPoint\n function simulateHandleOp(\n UserOperation calldata op,\n address target,\n bytes calldata targetCallData\n ) external override {\n UserOpInfo memory opInfo;\n _simulationOnlyValidations(op);\n (\n uint256 validationData,\n uint256 paymasterValidationData\n ) = _validatePrepayment(0, op, opInfo);\n ValidationData memory data = _intersectTimeRange(\n validationData,\n paymasterValidationData\n );\n\n numberMarker();\n uint256 paid = _executeUserOp(0, op, opInfo);\n numberMarker();\n bool targetSuccess;\n bytes memory targetResult;\n if (target != address(0)) {\n (targetSuccess, targetResult) = target.call(targetCallData);\n }\n revert ExecutionResult(\n opInfo.preOpGas,\n paid,\n data.validAfter,\n data.validUntil,\n targetSuccess,\n targetResult\n );\n }\n\n // A memory copy of UserOp static fields only.\n // Excluding: callData, initCode and signature. Replacing paymasterAndData with paymaster.\n struct MemoryUserOp {\n address sender;\n uint256 nonce;\n uint256 callGasLimit;\n uint256 verificationGasLimit;\n uint256 preVerificationGas;\n address paymaster;\n uint256 maxFeePerGas;\n uint256 maxPriorityFeePerGas;\n }\n\n struct UserOpInfo {\n MemoryUserOp mUserOp;\n bytes32 userOpHash;\n uint256 prefund;\n uint256 contextOffset;\n uint256 preOpGas;\n }\n\n /**\n * inner function to handle a UserOperation.\n * Must be declared \"external\" to open a call context, but it can only be called by handleOps.\n */\n function innerHandleOp(\n bytes memory callData,\n UserOpInfo memory opInfo,\n bytes calldata context\n ) external returns (uint256 actualGasCost) {\n uint256 preGas = gasleft();\n require(msg.sender == address(this), \"AA92 internal call only\");\n MemoryUserOp memory mUserOp = opInfo.mUserOp;\n\n uint callGasLimit = mUserOp.callGasLimit;\n unchecked {\n // handleOps was called with gas limit too low. abort entire bundle.\n if (\n gasleft() < callGasLimit + mUserOp.verificationGasLimit + 5000\n ) {\n assembly {\n mstore(0, INNER_OUT_OF_GAS)\n revert(0, 32)\n }\n }\n }\n\n IPaymaster.PostOpMode mode = IPaymaster.PostOpMode.opSucceeded;\n if (callData.length > 0) {\n bool success = Exec.call(mUserOp.sender, 0, callData, callGasLimit);\n if (!success) {\n bytes memory result = Exec.getReturnData(REVERT_REASON_MAX_LEN);\n if (result.length > 0) {\n emit UserOperationRevertReason(\n opInfo.userOpHash,\n mUserOp.sender,\n mUserOp.nonce,\n result\n );\n }\n mode = IPaymaster.PostOpMode.opReverted;\n }\n }\n\n unchecked {\n uint256 actualGas = preGas - gasleft() + opInfo.preOpGas;\n //note: opIndex is ignored (relevant only if mode==postOpReverted, which is only possible outside of innerHandleOp)\n return _handlePostOp(0, mode, opInfo, context, actualGas);\n }\n }\n\n /**\n * generate a request Id - unique identifier for this request.\n * the request ID is a hash over the content of the userOp (except the signature), the entrypoint and the chainid.\n */\n function getUserOpHash(\n UserOperation calldata userOp\n ) public view returns (bytes32) {\n return\n keccak256(abi.encode(userOp.hash(), address(this), block.chainid));\n }\n\n /**\n * copy general fields from userOp into the memory opInfo structure.\n */\n function _copyUserOpToMemory(\n UserOperation calldata userOp,\n MemoryUserOp memory mUserOp\n ) internal pure {\n mUserOp.sender = userOp.sender;\n mUserOp.nonce = userOp.nonce;\n mUserOp.callGasLimit = userOp.callGasLimit;\n mUserOp.verificationGasLimit = userOp.verificationGasLimit;\n mUserOp.preVerificationGas = userOp.preVerificationGas;\n mUserOp.maxFeePerGas = userOp.maxFeePerGas;\n mUserOp.maxPriorityFeePerGas = userOp.maxPriorityFeePerGas;\n bytes calldata paymasterAndData = userOp.paymasterAndData;\n if (paymasterAndData.length > 0) {\n require(\n paymasterAndData.length >= 20,\n \"AA93 invalid paymasterAndData\"\n );\n mUserOp.paymaster = address(bytes20(paymasterAndData[:20]));\n } else {\n mUserOp.paymaster = address(0);\n }\n }\n\n /**\n * Simulate a call to account.validateUserOp and paymaster.validatePaymasterUserOp.\n * @dev this method always revert. Successful result is ValidationResult error. other errors are failures.\n * @dev The node must also verify it doesn't use banned opcodes, and that it doesn't reference storage outside the account's data.\n * @param userOp the user operation to validate.\n */\n function simulateValidation(UserOperation calldata userOp) external {\n UserOpInfo memory outOpInfo;\n\n _simulationOnlyValidations(userOp);\n (\n uint256 validationData,\n uint256 paymasterValidationData\n ) = _validatePrepayment(0, userOp, outOpInfo);\n StakeInfo memory paymasterInfo = _getStakeInfo(\n outOpInfo.mUserOp.paymaster\n );\n StakeInfo memory senderInfo = _getStakeInfo(outOpInfo.mUserOp.sender);\n StakeInfo memory factoryInfo;\n {\n bytes calldata initCode = userOp.initCode;\n address factory = initCode.length >= 20\n ? address(bytes20(initCode[0:20]))\n : address(0);\n factoryInfo = _getStakeInfo(factory);\n }\n\n ValidationData memory data = _intersectTimeRange(\n validationData,\n paymasterValidationData\n );\n address aggregator = data.aggregator;\n bool sigFailed = aggregator == address(1);\n ReturnInfo memory returnInfo = ReturnInfo(\n outOpInfo.preOpGas,\n outOpInfo.prefund,\n sigFailed,\n data.validAfter,\n data.validUntil,\n getMemoryBytesFromOffset(outOpInfo.contextOffset)\n );\n\n if (aggregator != address(0) && aggregator != address(1)) {\n AggregatorStakeInfo memory aggregatorInfo = AggregatorStakeInfo(\n aggregator,\n _getStakeInfo(aggregator)\n );\n revert ValidationResultWithAggregation(\n returnInfo,\n senderInfo,\n factoryInfo,\n paymasterInfo,\n aggregatorInfo\n );\n }\n revert ValidationResult(\n returnInfo,\n senderInfo,\n factoryInfo,\n paymasterInfo\n );\n }\n\n function _getRequiredPrefund(\n MemoryUserOp memory mUserOp\n ) internal pure returns (uint256 requiredPrefund) {\n unchecked {\n //when using a Paymaster, the verificationGasLimit is used also to as a limit for the postOp call.\n // our security model might call postOp eventually twice\n uint256 mul = mUserOp.paymaster != address(0) ? 3 : 1;\n uint256 requiredGas = mUserOp.callGasLimit +\n mUserOp.verificationGasLimit *\n mul +\n mUserOp.preVerificationGas;\n\n requiredPrefund = requiredGas * mUserOp.maxFeePerGas;\n }\n }\n\n // create the sender's contract if needed.\n function _createSenderIfNeeded(\n uint256 opIndex,\n UserOpInfo memory opInfo,\n bytes calldata initCode\n ) internal {\n if (initCode.length != 0) {\n address sender = opInfo.mUserOp.sender;\n if (sender.code.length != 0)\n revert FailedOp(opIndex, \"AA10 sender already constructed\");\n address sender1 = senderCreator.createSender{\n gas: opInfo.mUserOp.verificationGasLimit\n }(initCode);\n if (sender1 == address(0))\n revert FailedOp(opIndex, \"AA13 initCode failed or OOG\");\n if (sender1 != sender)\n revert FailedOp(opIndex, \"AA14 initCode must return sender\");\n if (sender1.code.length == 0)\n revert FailedOp(opIndex, \"AA15 initCode must create sender\");\n address factory = address(bytes20(initCode[0:20]));\n emit AccountDeployed(\n opInfo.userOpHash,\n sender,\n factory,\n opInfo.mUserOp.paymaster\n );\n }\n }\n\n /**\n * Get counterfactual sender address.\n * Calculate the sender contract address that will be generated by the initCode and salt in the UserOperation.\n * this method always revert, and returns the address in SenderAddressResult error\n * @param initCode the constructor code to be passed into the UserOperation.\n */\n function getSenderAddress(bytes calldata initCode) public {\n address sender = senderCreator.createSender(initCode);\n revert SenderAddressResult(sender);\n }\n\n function _simulationOnlyValidations(\n UserOperation calldata userOp\n ) internal view {\n \n try\n this._validateSenderAndPaymaster(\n userOp.initCode,\n userOp.sender,\n userOp.paymasterAndData\n )\n {} catch Error(string memory revertReason) {\n if (bytes(revertReason).length != 0) {\n revert FailedOp(0, revertReason);\n }\n }\n }\n\n /**\n * Called only during simulation.\n * This function always reverts to prevent warm/cold storage differentiation in simulation vs execution.\n */\n function _validateSenderAndPaymaster(\n bytes calldata initCode,\n address sender,\n bytes calldata paymasterAndData\n ) external view {\n if (initCode.length == 0 && sender.code.length == 0) {\n // it would revert anyway. but give a meaningful message\n revert(\"AA20 account not deployed\");\n }\n if (paymasterAndData.length >= 20) {\n address paymaster = address(bytes20(paymasterAndData[0:20]));\n if (paymaster.code.length == 0) {\n // it would revert anyway. but give a meaningful message\n revert(\"AA30 paymaster not deployed\");\n }\n }\n // always revert\n revert(\"\");\n }\n\n /**\n * call account.validateUserOp.\n * revert (with FailedOp) in case validateUserOp reverts, or account didn't send required prefund.\n * decrement account's deposit if needed\n */\n function _validateAccountPrepayment(\n uint256 opIndex,\n UserOperation calldata op,\n UserOpInfo memory opInfo,\n uint256 requiredPrefund\n )\n internal\n returns (\n uint256 gasUsedByValidateAccountPrepayment,\n uint256 validationData\n )\n {\n unchecked {\n uint256 preGas = gasleft();\n MemoryUserOp memory mUserOp = opInfo.mUserOp;\n address sender = mUserOp.sender;\n _createSenderIfNeeded(opIndex, opInfo, op.initCode);\n address paymaster = mUserOp.paymaster;\n numberMarker();\n uint256 missingAccountFunds = 0;\n if (paymaster == address(0)) {\n uint256 bal = balanceOf(sender);\n missingAccountFunds = bal > requiredPrefund\n ? 0\n : requiredPrefund - bal;\n }\n try\n IAccount(sender).validateUserOp{\n gas: mUserOp.verificationGasLimit\n }(op, opInfo.userOpHash, missingAccountFunds)\n returns (uint256 _validationData) {\n validationData = _validationData;\n } catch Error(string memory revertReason) {\n revert FailedOp(\n opIndex,\n string.concat(\"AA23 reverted: \", revertReason)\n );\n } catch {\n revert FailedOp(opIndex, \"AA23 reverted (or OOG)\");\n }\n if (paymaster == address(0)) {\n DepositInfo storage senderInfo = deposits[sender];\n uint256 deposit = senderInfo.deposit;\n if (requiredPrefund > deposit) {\n revert FailedOp(opIndex, \"AA21 didn't pay prefund\");\n }\n senderInfo.deposit = uint112(deposit - requiredPrefund);\n }\n gasUsedByValidateAccountPrepayment = preGas - gasleft();\n }\n }\n\n /**\n * In case the request has a paymaster:\n * Validate paymaster has enough deposit.\n * Call paymaster.validatePaymasterUserOp.\n * Revert with proper FailedOp in case paymaster reverts.\n * Decrement paymaster's deposit\n */\n function _validatePaymasterPrepayment(\n uint256 opIndex,\n UserOperation calldata op,\n UserOpInfo memory opInfo,\n uint256 requiredPreFund,\n uint256 gasUsedByValidateAccountPrepayment\n ) internal returns (bytes memory context, uint256 validationData) {\n unchecked {\n MemoryUserOp memory mUserOp = opInfo.mUserOp;\n uint256 verificationGasLimit = mUserOp.verificationGasLimit;\n require(\n verificationGasLimit > gasUsedByValidateAccountPrepayment,\n \"AA41 too little verificationGas\"\n );\n uint256 gas = verificationGasLimit -\n gasUsedByValidateAccountPrepayment;\n\n address paymaster = mUserOp.paymaster;\n DepositInfo storage paymasterInfo = deposits[paymaster];\n uint256 deposit = paymasterInfo.deposit;\n if (deposit < requiredPreFund) {\n revert FailedOp(opIndex, \"AA31 paymaster deposit too low\");\n }\n paymasterInfo.deposit = uint112(deposit - requiredPreFund);\n try\n IPaymaster(paymaster).validatePaymasterUserOp{gas: gas}(\n op,\n opInfo.userOpHash,\n requiredPreFund\n )\n returns (bytes memory _context, uint256 _validationData) {\n context = _context;\n validationData = _validationData;\n } catch Error(string memory revertReason) {\n revert FailedOp(\n opIndex,\n string.concat(\"AA33 reverted: \", revertReason)\n );\n } catch {\n revert FailedOp(opIndex, \"AA33 reverted (or OOG)\");\n }\n }\n }\n\n /**\n * revert if either account validationData or paymaster validationData is expired\n */\n function _validateAccountAndPaymasterValidationData(\n uint256 opIndex,\n uint256 validationData,\n uint256 paymasterValidationData,\n address expectedAggregator\n ) internal view {\n (address aggregator, bool outOfTimeRange) = _getValidationData(\n validationData\n );\n if (expectedAggregator != aggregator) {\n revert FailedOp(opIndex, \"AA24 signature error\");\n }\n if (outOfTimeRange) {\n revert FailedOp(opIndex, \"AA22 expired or not due\");\n }\n //pmAggregator is not a real signature aggregator: we don't have logic to handle it as address.\n // non-zero address means that the paymaster fails due to some signature check (which is ok only during estimation)\n address pmAggregator;\n (pmAggregator, outOfTimeRange) = _getValidationData(\n paymasterValidationData\n );\n if (pmAggregator != address(0)) {\n revert FailedOp(opIndex, \"AA34 signature error\");\n }\n if (outOfTimeRange) {\n revert FailedOp(opIndex, \"AA32 paymaster expired or not due\");\n }\n }\n\n function _getValidationData(\n uint256 validationData\n ) internal view returns (address aggregator, bool outOfTimeRange) {\n if (validationData == 0) {\n return (address(0), false);\n }\n ValidationData memory data = _parseValidationData(validationData);\n // solhint-disable-next-line not-rely-on-time\n outOfTimeRange =\n block.timestamp > data.validUntil ||\n block.timestamp < data.validAfter;\n aggregator = data.aggregator;\n }\n\n /**\n * validate account and paymaster (if defined).\n * also make sure total validation doesn't exceed verificationGasLimit\n * this method is called off-chain (simulateValidation()) and on-chain (from handleOps)\n * @param opIndex the index of this userOp into the \"opInfos\" array\n * @param userOp the userOp to validate\n */\n function _validatePrepayment(\n uint256 opIndex,\n UserOperation calldata userOp,\n UserOpInfo memory outOpInfo\n )\n private\n returns (uint256 validationData, uint256 paymasterValidationData)\n {\n uint256 preGas = gasleft();\n MemoryUserOp memory mUserOp = outOpInfo.mUserOp;\n _copyUserOpToMemory(userOp, mUserOp);\n outOpInfo.userOpHash = getUserOpHash(userOp);\n\n // validate all numeric values in userOp are well below 128 bit, so they can safely be added\n // and multiplied without causing overflow\n uint256 maxGasValues = mUserOp.preVerificationGas |\n mUserOp.verificationGasLimit |\n mUserOp.callGasLimit |\n userOp.maxFeePerGas |\n userOp.maxPriorityFeePerGas;\n require(maxGasValues <= type(uint120).max, \"AA94 gas values overflow\");\n\n uint256 gasUsedByValidateAccountPrepayment;\n uint256 requiredPreFund = _getRequiredPrefund(mUserOp);\n (\n gasUsedByValidateAccountPrepayment,\n validationData\n ) = _validateAccountPrepayment(\n opIndex,\n userOp,\n outOpInfo,\n requiredPreFund\n );\n\n if (!_validateAndUpdateNonce(mUserOp.sender, mUserOp.nonce)) {\n revert FailedOp(opIndex, \"AA25 invalid account nonce\");\n }\n\n //a \"marker\" where account opcode validation is done and paymaster opcode validation is about to start\n // (used only by off-chain simulateValidation)\n numberMarker();\n\n bytes memory context;\n if (mUserOp.paymaster != address(0)) {\n (context, paymasterValidationData) = _validatePaymasterPrepayment(\n opIndex,\n userOp,\n outOpInfo,\n requiredPreFund,\n gasUsedByValidateAccountPrepayment\n );\n }\n unchecked {\n uint256 gasUsed = preGas - gasleft();\n\n if (userOp.verificationGasLimit < gasUsed) {\n revert FailedOp(opIndex, \"AA40 over verificationGasLimit\");\n }\n outOpInfo.prefund = requiredPreFund;\n outOpInfo.contextOffset = getOffsetOfMemoryBytes(context);\n outOpInfo.preOpGas = preGas - gasleft() + userOp.preVerificationGas;\n }\n }\n\n /**\n * process post-operation.\n * called just after the callData is executed.\n * if a paymaster is defined and its validation returned a non-empty context, its postOp is called.\n * the excess amount is refunded to the account (or paymaster - if it was used in the request)\n * @param opIndex index in the batch\n * @param mode - whether is called from innerHandleOp, or outside (postOpReverted)\n * @param opInfo userOp fields and info collected during validation\n * @param context the context returned in validatePaymasterUserOp\n * @param actualGas the gas used so far by this user operation\n */\n function _handlePostOp(\n uint256 opIndex,\n IPaymaster.PostOpMode mode,\n UserOpInfo memory opInfo,\n bytes memory context,\n uint256 actualGas\n ) private returns (uint256 actualGasCost) {\n uint256 preGas = gasleft();\n unchecked {\n address refundAddress;\n MemoryUserOp memory mUserOp = opInfo.mUserOp;\n uint256 gasPrice = getUserOpGasPrice(mUserOp);\n\n address paymaster = mUserOp.paymaster;\n if (paymaster == address(0)) {\n refundAddress = mUserOp.sender;\n } else {\n refundAddress = paymaster;\n if (context.length > 0) {\n actualGasCost = actualGas * gasPrice;\n if (mode != IPaymaster.PostOpMode.postOpReverted) {\n IPaymaster(paymaster).postOp{\n gas: mUserOp.verificationGasLimit\n }(mode, context, actualGasCost);\n } else {\n \n try\n IPaymaster(paymaster).postOp{\n gas: mUserOp.verificationGasLimit\n }(mode, context, actualGasCost)\n {} catch Error(string memory reason) {\n revert FailedOp(\n opIndex,\n string.concat(\"AA50 postOp reverted: \", reason)\n );\n } catch {\n revert FailedOp(opIndex, \"AA50 postOp revert\");\n }\n }\n }\n }\n actualGas += preGas - gasleft();\n actualGasCost = actualGas * gasPrice;\n if (opInfo.prefund < actualGasCost) {\n revert FailedOp(opIndex, \"AA51 prefund below actualGasCost\");\n }\n uint256 refund = opInfo.prefund - actualGasCost;\n _incrementDeposit(refundAddress, refund);\n bool success = mode == IPaymaster.PostOpMode.opSucceeded;\n emit UserOperationEvent(\n opInfo.userOpHash,\n mUserOp.sender,\n mUserOp.paymaster,\n mUserOp.nonce,\n success,\n actualGasCost,\n actualGas\n );\n } // unchecked\n }\n\n /**\n * the gas price this UserOp agrees to pay.\n * relayer/block builder might submit the TX with higher priorityFee, but the user should not\n */\n function getUserOpGasPrice(\n MemoryUserOp memory mUserOp\n ) internal view returns (uint256) {\n unchecked {\n uint256 maxFeePerGas = mUserOp.maxFeePerGas;\n uint256 maxPriorityFeePerGas = mUserOp.maxPriorityFeePerGas;\n if (maxFeePerGas == maxPriorityFeePerGas) {\n //legacy mode (for networks that don't support basefee opcode)\n return maxFeePerGas;\n }\n return min(maxFeePerGas, maxPriorityFeePerGas + block.basefee);\n }\n }\n\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n function getOffsetOfMemoryBytes(\n bytes memory data\n ) internal pure returns (uint256 offset) {\n assembly {\n offset := data\n }\n }\n\n function getMemoryBytesFromOffset(\n uint256 offset\n ) internal pure returns (bytes memory data) {\n assembly {\n data := offset\n }\n }\n\n //place the NUMBER opcode in the code.\n // this is used as a marker during simulation, as this OP is completely banned from the simulated code of the\n // account and paymaster.\n function numberMarker() internal view {\n assembly {\n mstore(0, number())\n }\n }\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/core/Helpers.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\n/* solhint-disable no-inline-assembly */\n\n/**\n * returned data from validateUserOp.\n * validateUserOp returns a uint256, with is created by `_packedValidationData` and parsed by `_parseValidationData`\n * @param aggregator - address(0) - the account validated the signature by itself.\n * address(1) - the account failed to validate the signature.\n * otherwise - this is an address of a signature aggregator that must be used to validate the signature.\n * @param validAfter - this UserOp is valid only after this timestamp.\n * @param validaUntil - this UserOp is valid only up to this timestamp.\n */\nstruct ValidationData {\n address aggregator;\n uint48 validAfter;\n uint48 validUntil;\n}\n\n//extract sigFailed, validAfter, validUntil.\n// also convert zero validUntil to type(uint48).max\nfunction _parseValidationData(\n uint validationData\n) pure returns (ValidationData memory data) {\n address aggregator = address(uint160(validationData));\n uint48 validUntil = uint48(validationData >> 160);\n if (validUntil == 0) {\n validUntil = type(uint48).max;\n }\n uint48 validAfter = uint48(validationData >> (48 + 160));\n return ValidationData(aggregator, validAfter, validUntil);\n}\n\n// intersect account and paymaster ranges.\nfunction _intersectTimeRange(\n uint256 validationData,\n uint256 paymasterValidationData\n) pure returns (ValidationData memory) {\n ValidationData memory accountValidationData = _parseValidationData(\n validationData\n );\n ValidationData memory pmValidationData = _parseValidationData(\n paymasterValidationData\n );\n address aggregator = accountValidationData.aggregator;\n if (aggregator == address(0)) {\n aggregator = pmValidationData.aggregator;\n }\n uint48 validAfter = accountValidationData.validAfter;\n uint48 validUntil = accountValidationData.validUntil;\n uint48 pmValidAfter = pmValidationData.validAfter;\n uint48 pmValidUntil = pmValidationData.validUntil;\n\n if (validAfter < pmValidAfter) validAfter = pmValidAfter;\n if (validUntil > pmValidUntil) validUntil = pmValidUntil;\n return ValidationData(aggregator, validAfter, validUntil);\n}\n\n/**\n * helper to pack the return value for validateUserOp\n * @param data - the ValidationData to pack\n */\nfunction _packValidationData(\n ValidationData memory data\n) pure returns (uint256) {\n return\n uint160(data.aggregator) |\n (uint256(data.validUntil) << 160) |\n (uint256(data.validAfter) << (160 + 48));\n}\n\n/**\n * helper to pack the return value for validateUserOp, when not using an aggregator\n * @param sigFailed - true for signature failure, false for success\n * @param validUntil last timestamp this UserOperation is valid (or zero for infinite)\n * @param validAfter first timestamp this UserOperation is valid\n */\nfunction _packValidationData(\n bool sigFailed,\n uint48 validUntil,\n uint48 validAfter\n) pure returns (uint256) {\n return\n (sigFailed ? 1 : 0) |\n (uint256(validUntil) << 160) |\n (uint256(validAfter) << (160 + 48));\n}\n\n/**\n * keccak function over calldata.\n * @dev copy calldata into memory, do keccak and drop allocated memory. Strangely, this is more efficient than letting solidity do it.\n */\nfunction calldataKeccak(bytes calldata data) pure returns (bytes32 ret) {\n assembly {\n let mem := mload(0x40)\n let len := data.length\n calldatacopy(mem, data.offset, len)\n ret := keccak256(mem, len)\n }\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/core/NonceManager.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\nimport {IEntryPoint} from \"../interfaces/IEntryPoint.sol\";\nimport {INonceManager} from \"../interfaces/INonceManager.sol\";\n\n/**\n * nonce management functionality\n */\ncontract NonceManager is INonceManager {\n /**\n * The next valid sequence number for a given nonce key.\n */\n mapping(address => mapping(uint192 => uint256)) public nonceSequenceNumber;\n\n function getNonce(\n address sender,\n uint192 key\n ) public view override returns (uint256 nonce) {\n return nonceSequenceNumber[sender][key] | (uint256(key) << 64);\n }\n\n // allow an account to manually increment its own nonce.\n // (mainly so that during construction nonce can be made non-zero,\n // to \"absorb\" the gas cost of first nonce increment to 1st transaction (construction),\n // not to 2nd transaction)\n function incrementNonce(uint192 key) public override {\n nonceSequenceNumber[msg.sender][key]++;\n }\n\n /**\n * validate nonce uniqueness for this account.\n * called just after validateUserOp()\n */\n function _validateAndUpdateNonce(\n address sender,\n uint256 nonce\n ) internal returns (bool) {\n uint192 key = uint192(nonce >> 64);\n uint64 seq = uint64(nonce);\n return nonceSequenceNumber[sender][key]++ == seq;\n }\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/core/SenderCreator.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\n/**\n * helper contract for EntryPoint, to call userOp.initCode from a \"neutral\" address,\n * which is explicitly not the entryPoint itself.\n */\ncontract SenderCreator {\n /**\n * call the \"initCode\" factory to create and return the sender account address\n * @param initCode the initCode value from a UserOp. contains 20 bytes of factory address, followed by calldata\n * @return sender the returned address of the created account, or zero address on failure.\n */\n function createSender(\n bytes calldata initCode\n ) external returns (address sender) {\n address factory = address(bytes20(initCode[0:20]));\n bytes memory initCallData = initCode[20:];\n bool success;\n /* solhint-disable no-inline-assembly */\n assembly {\n success := call(\n gas(),\n factory,\n 0,\n add(initCallData, 0x20),\n mload(initCallData),\n 0,\n 32\n )\n sender := mload(0)\n }\n if (!success) {\n sender = address(0);\n }\n }\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/core/StakeManager.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.8.17;\n\nimport \"../interfaces/IStakeManager.sol\";\n\n/* solhint-disable avoid-low-level-calls */\n/* solhint-disable not-rely-on-time */\n/**\n * manage deposits and stakes.\n * deposit is just a balance used to pay for UserOperations (either by a paymaster or an account)\n * stake is value locked for at least \"unstakeDelay\" by a paymaster.\n */\nabstract contract StakeManager is IStakeManager {\n /// maps paymaster to their deposits and stakes\n mapping(address => DepositInfo) public deposits;\n\n /// @inheritdoc IStakeManager\n function getDepositInfo(\n address account\n ) public view returns (DepositInfo memory info) {\n return deposits[account];\n }\n\n // internal method to return just the stake info\n function _getStakeInfo(\n address addr\n ) internal view returns (StakeInfo memory info) {\n DepositInfo storage depositInfo = deposits[addr];\n info.stake = depositInfo.stake;\n info.unstakeDelaySec = depositInfo.unstakeDelaySec;\n }\n\n /// return the deposit (for gas payment) of the account\n function balanceOf(address account) public view returns (uint256) {\n return deposits[account].deposit;\n }\n\n receive() external payable {\n depositTo(msg.sender);\n }\n\n function _incrementDeposit(address account, uint256 amount) internal {\n DepositInfo storage info = deposits[account];\n uint256 newAmount = info.deposit + amount;\n require(newAmount <= type(uint112).max, \"deposit overflow\");\n info.deposit = uint112(newAmount);\n }\n\n /**\n * add to the deposit of the given account\n */\n function depositTo(address account) public payable {\n _incrementDeposit(account, msg.value);\n DepositInfo storage info = deposits[account];\n emit Deposited(account, info.deposit);\n }\n\n /**\n * add to the account's stake - amount and delay\n * any pending unstake is first cancelled.\n * @param unstakeDelaySec the new lock duration before the deposit can be withdrawn.\n */\n function addStake(uint32 unstakeDelaySec) public payable {\n DepositInfo storage info = deposits[msg.sender];\n require(unstakeDelaySec > 0, \"must specify unstake delay\");\n require(\n unstakeDelaySec >= info.unstakeDelaySec,\n \"cannot decrease unstake time\"\n );\n uint256 stake = info.stake + msg.value;\n require(stake > 0, \"no stake specified\");\n require(stake <= type(uint112).max, \"stake overflow\");\n deposits[msg.sender] = DepositInfo(\n info.deposit,\n true,\n uint112(stake),\n unstakeDelaySec,\n 0\n );\n emit StakeLocked(msg.sender, stake, unstakeDelaySec);\n }\n\n /**\n * attempt to unlock the stake.\n * the value can be withdrawn (using withdrawStake) after the unstake delay.\n */\n function unlockStake() external {\n DepositInfo storage info = deposits[msg.sender];\n require(info.unstakeDelaySec != 0, \"not staked\");\n require(info.staked, \"already unstaking\");\n uint48 withdrawTime = uint48(block.timestamp) + info.unstakeDelaySec;\n info.withdrawTime = withdrawTime;\n info.staked = false;\n emit StakeUnlocked(msg.sender, withdrawTime);\n }\n\n /**\n * withdraw from the (unlocked) stake.\n * must first call unlockStake and wait for the unstakeDelay to pass\n * @param withdrawAddress the address to send withdrawn value.\n */\n function withdrawStake(address payable withdrawAddress) external {\n DepositInfo storage info = deposits[msg.sender];\n uint256 stake = info.stake;\n require(stake > 0, \"No stake to withdraw\");\n require(info.withdrawTime > 0, \"must call unlockStake() first\");\n require(\n info.withdrawTime <= block.timestamp,\n \"Stake withdrawal is not due\"\n );\n info.unstakeDelaySec = 0;\n info.withdrawTime = 0;\n info.stake = 0;\n emit StakeWithdrawn(msg.sender, withdrawAddress, stake);\n (bool success, ) = withdrawAddress.call{value: stake}(\"\");\n require(success, \"failed to withdraw stake\");\n }\n\n /**\n * withdraw from the deposit.\n * @param withdrawAddress the address to send withdrawn value.\n * @param withdrawAmount the amount to withdraw.\n */\n function withdrawTo(\n address payable withdrawAddress,\n uint256 withdrawAmount\n ) external {\n DepositInfo storage info = deposits[msg.sender];\n require(withdrawAmount <= info.deposit, \"Withdraw amount too large\");\n info.deposit = uint112(info.deposit - withdrawAmount);\n emit Withdrawn(msg.sender, withdrawAddress, withdrawAmount);\n (bool success, ) = withdrawAddress.call{value: withdrawAmount}(\"\");\n require(success, \"failed to withdraw\");\n }\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/interfaces/IAccount.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\nimport {UserOperation} from \"./UserOperation.sol\";\n\ninterface IAccount {\n /**\n * Validate user's signature and nonce\n * the entryPoint will make the call to the recipient only if this validation call returns successfully.\n * signature failure should be reported by returning SIG_VALIDATION_FAILED (1).\n * This allows making a \"simulation call\" without a valid signature\n * Other failures (e.g. nonce mismatch, or invalid signature format) should still revert to signal failure.\n *\n * @dev Must validate caller is the entryPoint.\n * Must validate the signature and nonce\n * @param userOp the operation that is about to be executed.\n * @param userOpHash hash of the user's request data. can be used as the basis for signature.\n * @param missingAccountFunds missing funds on the account's deposit in the entrypoint.\n * This is the minimum amount to transfer to the sender(entryPoint) to be able to make the call.\n * The excess is left as a deposit in the entrypoint, for future calls.\n * can be withdrawn anytime using \"entryPoint.withdrawTo()\"\n * In case there is a paymaster in the request (or the current deposit is high enough), this value will be zero.\n * @return validationData packaged ValidationData structure. use `_packValidationData` and `_unpackValidationData` to encode and decode\n * <20-byte> sigAuthorizer - 0 for valid signature, 1 to mark signature failure,\n * otherwise, an address of an \"authorizer\" contract.\n * <6-byte> validUntil - last timestamp this operation is valid. 0 for \"indefinite\"\n * <6-byte> validAfter - first timestamp this operation is valid\n * If an account doesn't use time-range, it is enough to return SIG_VALIDATION_FAILED value (1) for signature failure.\n * Note that the validation code cannot use block.timestamp (or block.number) directly.\n */\n function validateUserOp(\n UserOperation calldata userOp,\n bytes32 userOpHash,\n uint256 missingAccountFunds\n ) external returns (uint256 validationData);\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/interfaces/IAggregator.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\nimport \"./UserOperation.sol\";\n\n/**\n * Aggregated Signatures validator.\n */\ninterface IAggregator {\n /**\n * validate aggregated signature.\n * revert if the aggregated signature does not match the given list of operations.\n */\n function validateSignatures(\n UserOperation[] calldata userOps,\n bytes calldata signature\n ) external view;\n\n /**\n * validate signature of a single userOp\n * This method is should be called by bundler after EntryPoint.simulateValidation() returns (reverts) with ValidationResultWithAggregation\n * First it validates the signature over the userOp. Then it returns data to be used when creating the handleOps.\n * @param userOp the userOperation received from the user.\n * @return sigForUserOp the value to put into the signature field of the userOp when calling handleOps.\n * (usually empty, unless account and aggregator support some kind of \"multisig\"\n */\n function validateUserOpSignature(\n UserOperation calldata userOp\n ) external view returns (bytes memory sigForUserOp);\n\n /**\n * aggregate multiple signatures into a single value.\n * This method is called off-chain to calculate the signature to pass with handleOps()\n * bundler MAY use optimized custom code perform this aggregation\n * @param userOps array of UserOperations to collect the signatures from.\n * @return aggregatedSignature the aggregated signature\n */\n function aggregateSignatures(\n UserOperation[] calldata userOps\n ) external view returns (bytes memory aggregatedSignature);\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/interfaces/IEntryPoint.sol": {
"content": "/**\n ** Account-Abstraction (EIP-4337) singleton EntryPoint implementation.\n ** Only one instance required on each chain.\n **/\n// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\n/* solhint-disable avoid-low-level-calls */\n/* solhint-disable no-inline-assembly */\n/* solhint-disable reason-string */\n\nimport \"./UserOperation.sol\";\nimport \"./IStakeManager.sol\";\nimport \"./IAggregator.sol\";\nimport \"./INonceManager.sol\";\n\ninterface IEntryPoint is IStakeManager, INonceManager {\n /***\n * An event emitted after each successful request\n * @param userOpHash - unique identifier for the request (hash its entire content, except signature).\n * @param sender - the account that generates this request.\n * @param paymaster - if non-null, the paymaster that pays for this request.\n * @param nonce - the nonce value from the request.\n * @param success - true if the sender transaction succeeded, false if reverted.\n * @param actualGasCost - actual amount paid (by account or paymaster) for this UserOperation.\n * @param actualGasUsed - total gas used by this UserOperation (including preVerification, creation, validation and execution).\n */\n event UserOperationEvent(\n bytes32 indexed userOpHash,\n address indexed sender,\n address indexed paymaster,\n uint256 nonce,\n bool success,\n uint256 actualGasCost,\n uint256 actualGasUsed\n );\n\n /**\n * account \"sender\" was deployed.\n * @param userOpHash the userOp that deployed this account. UserOperationEvent will follow.\n * @param sender the account that is deployed\n * @param factory the factory used to deploy this account (in the initCode)\n * @param paymaster the paymaster used by this UserOp\n */\n event AccountDeployed(\n bytes32 indexed userOpHash,\n address indexed sender,\n address factory,\n address paymaster\n );\n\n /**\n * An event emitted if the UserOperation \"callData\" reverted with non-zero length\n * @param userOpHash the request unique identifier.\n * @param sender the sender of this request\n * @param nonce the nonce used in the request\n * @param revertReason - the return bytes from the (reverted) call to \"callData\".\n */\n event UserOperationRevertReason(\n bytes32 indexed userOpHash,\n address indexed sender,\n uint256 nonce,\n bytes revertReason\n );\n\n /**\n * an event emitted by handleOps(), before starting the execution loop.\n * any event emitted before this event, is part of the validation.\n */\n event BeforeExecution();\n\n /**\n * signature aggregator used by the following UserOperationEvents within this bundle.\n */\n event SignatureAggregatorChanged(address indexed aggregator);\n\n /**\n * a custom revert error of handleOps, to identify the offending op.\n * NOTE: if simulateValidation passes successfully, there should be no reason for handleOps to fail on it.\n * @param opIndex - index into the array of ops to the failed one (in simulateValidation, this is always zero)\n * @param reason - revert reason\n * The string starts with a unique code \"AAmn\", where \"m\" is \"1\" for factory, \"2\" for account and \"3\" for paymaster issues,\n * so a failure can be attributed to the correct entity.\n * Should be caught in off-chain handleOps simulation and not happen on-chain.\n * Useful for mitigating DoS attempts against batchers or for troubleshooting of factory/account/paymaster reverts.\n */\n error FailedOp(uint256 opIndex, string reason);\n\n /**\n * error case when a signature aggregator fails to verify the aggregated signature it had created.\n */\n error SignatureValidationFailed(address aggregator);\n\n /**\n * Successful result from simulateValidation.\n * @param returnInfo gas and time-range returned values\n * @param senderInfo stake information about the sender\n * @param factoryInfo stake information about the factory (if any)\n * @param paymasterInfo stake information about the paymaster (if any)\n */\n error ValidationResult(\n ReturnInfo returnInfo,\n StakeInfo senderInfo,\n StakeInfo factoryInfo,\n StakeInfo paymasterInfo\n );\n\n /**\n * Successful result from simulateValidation, if the account returns a signature aggregator\n * @param returnInfo gas and time-range returned values\n * @param senderInfo stake information about the sender\n * @param factoryInfo stake information about the factory (if any)\n * @param paymasterInfo stake information about the paymaster (if any)\n * @param aggregatorInfo signature aggregation info (if the account requires signature aggregator)\n * bundler MUST use it to verify the signature, or reject the UserOperation\n */\n error ValidationResultWithAggregation(\n ReturnInfo returnInfo,\n StakeInfo senderInfo,\n StakeInfo factoryInfo,\n StakeInfo paymasterInfo,\n AggregatorStakeInfo aggregatorInfo\n );\n\n /**\n * return value of getSenderAddress\n */\n error SenderAddressResult(address sender);\n\n /**\n * return value of simulateHandleOp\n */\n error ExecutionResult(\n uint256 preOpGas,\n uint256 paid,\n uint48 validAfter,\n uint48 validUntil,\n bool targetSuccess,\n bytes targetResult\n );\n\n //UserOps handled, per aggregator\n struct UserOpsPerAggregator {\n UserOperation[] userOps;\n // aggregator address\n IAggregator aggregator;\n // aggregated signature\n bytes signature;\n }\n\n /**\n * Execute a batch of UserOperation.\n * no signature aggregator is used.\n * if any account requires an aggregator (that is, it returned an aggregator when\n * performing simulateValidation), then handleAggregatedOps() must be used instead.\n * @param ops the operations to execute\n * @param beneficiary the address to receive the fees\n */\n function handleOps(\n UserOperation[] calldata ops,\n address payable beneficiary\n ) external;\n\n /**\n * Execute a batch of UserOperation with Aggregators\n * @param opsPerAggregator the operations to execute, grouped by aggregator (or address(0) for no-aggregator accounts)\n * @param beneficiary the address to receive the fees\n */\n function handleAggregatedOps(\n UserOpsPerAggregator[] calldata opsPerAggregator,\n address payable beneficiary\n ) external;\n\n /**\n * generate a request Id - unique identifier for this request.\n * the request ID is a hash over the content of the userOp (except the signature), the entrypoint and the chainid.\n */\n function getUserOpHash(\n UserOperation calldata userOp\n ) external view returns (bytes32);\n\n /**\n * Simulate a call to account.validateUserOp and paymaster.validatePaymasterUserOp.\n * @dev this method always revert. Successful result is ValidationResult error. other errors are failures.\n * @dev The node must also verify it doesn't use banned opcodes, and that it doesn't reference storage outside the account's data.\n * @param userOp the user operation to validate.\n */\n function simulateValidation(UserOperation calldata userOp) external;\n\n /**\n * gas and return values during simulation\n * @param preOpGas the gas used for validation (including preValidationGas)\n * @param prefund the required prefund for this operation\n * @param sigFailed validateUserOp's (or paymaster's) signature check failed\n * @param validAfter - first timestamp this UserOp is valid (merging account and paymaster time-range)\n * @param validUntil - last timestamp this UserOp is valid (merging account and paymaster time-range)\n * @param paymasterContext returned by validatePaymasterUserOp (to be passed into postOp)\n */\n struct ReturnInfo {\n uint256 preOpGas;\n uint256 prefund;\n bool sigFailed;\n uint48 validAfter;\n uint48 validUntil;\n bytes paymasterContext;\n }\n\n /**\n * returned aggregated signature info.\n * the aggregator returned by the account, and its current stake.\n */\n struct AggregatorStakeInfo {\n address aggregator;\n StakeInfo stakeInfo;\n }\n\n /**\n * Get counterfactual sender address.\n * Calculate the sender contract address that will be generated by the initCode and salt in the UserOperation.\n * this method always revert, and returns the address in SenderAddressResult error\n * @param initCode the constructor code to be passed into the UserOperation.\n */\n function getSenderAddress(bytes memory initCode) external;\n\n /**\n * simulate full execution of a UserOperation (including both validation and target execution)\n * this method will always revert with \"ExecutionResult\".\n * it performs full validation of the UserOperation, but ignores signature error.\n * an optional target address is called after the userop succeeds, and its value is returned\n * (before the entire call is reverted)\n * Note that in order to collect the the success/failure of the target call, it must be executed\n * with trace enabled to track the emitted events.\n * @param op the UserOperation to simulate\n * @param target if nonzero, a target address to call after userop simulation. If called, the targetSuccess and targetResult\n * are set to the return from that call.\n * @param targetCallData callData to pass to target address\n */\n function simulateHandleOp(\n UserOperation calldata op,\n address target,\n bytes calldata targetCallData\n ) external;\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/interfaces/INonceManager.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\ninterface INonceManager {\n /**\n * Return the next nonce for this sender.\n * Within a given key, the nonce values are sequenced (starting with zero, and incremented by one on each userop)\n * But UserOp with different keys can come with arbitrary order.\n *\n * @param sender the account address\n * @param key the high 192 bit of the nonce\n * @return nonce a full nonce to pass for next UserOp with this sender.\n */\n function getNonce(\n address sender,\n uint192 key\n ) external view returns (uint256 nonce);\n\n /**\n * Manually increment the nonce of the sender.\n * This method is exposed just for completeness..\n * Account does NOT need to call it, neither during validation, nor elsewhere,\n * as the EntryPoint will update the nonce regardless.\n * Possible use-case is call it with various keys to \"initialize\" their nonces to one, so that future\n * UserOperations will not pay extra for the first transaction with a given key.\n */\n function incrementNonce(uint192 key) external;\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/interfaces/IPaymaster.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\nimport \"./UserOperation.sol\";\n\n/**\n * the interface exposed by a paymaster contract, who agrees to pay the gas for user's operations.\n * a paymaster must hold a stake to cover the required entrypoint stake and also the gas for the transaction.\n */\ninterface IPaymaster {\n enum PostOpMode {\n opSucceeded, // user op succeeded\n opReverted, // user op reverted. still has to pay for gas.\n postOpReverted //user op succeeded, but caused postOp to revert. Now it's a 2nd call, after user's op was deliberately reverted.\n }\n\n /**\n * payment validation: check if paymaster agrees to pay.\n * Must verify sender is the entryPoint.\n * Revert to reject this request.\n * Note that bundlers will reject this method if it changes the state, unless the paymaster is trusted (whitelisted)\n * The paymaster pre-pays using its deposit, and receive back a refund after the postOp method returns.\n * @param userOp the user operation\n * @param userOpHash hash of the user's request data.\n * @param maxCost the maximum cost of this transaction (based on maximum gas and gas price from userOp)\n * @return context value to send to a postOp\n * zero length to signify postOp is not required.\n * @return validationData signature and time-range of this operation, encoded the same as the return value of validateUserOperation\n * <20-byte> sigAuthorizer - 0 for valid signature, 1 to mark signature failure,\n * otherwise, an address of an \"authorizer\" contract.\n * <6-byte> validUntil - last timestamp this operation is valid. 0 for \"indefinite\"\n * <6-byte> validAfter - first timestamp this operation is valid\n * Note that the validation code cannot use block.timestamp (or block.number) directly.\n */\n function validatePaymasterUserOp(\n UserOperation calldata userOp,\n bytes32 userOpHash,\n uint256 maxCost\n ) external returns (bytes memory context, uint256 validationData);\n\n /**\n * post-operation handler.\n * Must verify sender is the entryPoint\n * @param mode enum with the following options:\n * opSucceeded - user operation succeeded.\n * opReverted - user op reverted. still has to pay for gas.\n * postOpReverted - user op succeeded, but caused postOp (in mode=opSucceeded) to revert.\n * Now this is the 2nd call, after user's op was deliberately reverted.\n * @param context - the context value returned by validatePaymasterUserOp\n * @param actualGasCost - actual gas used so far (without this postOp call).\n */\n function postOp(\n PostOpMode mode,\n bytes calldata context,\n uint256 actualGasCost\n ) external;\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/interfaces/IStakeManager.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.8.17;\n\n/**\n * manage deposits and stakes.\n * deposit is just a balance used to pay for UserOperations (either by a paymaster or an account)\n * stake is value locked for at least \"unstakeDelay\" by the staked entity.\n */\ninterface IStakeManager {\n event Deposited(address indexed account, uint256 totalDeposit);\n\n event Withdrawn(\n address indexed account,\n address withdrawAddress,\n uint256 amount\n );\n\n /// Emitted when stake or unstake delay are modified\n event StakeLocked(\n address indexed account,\n uint256 totalStaked,\n uint256 unstakeDelaySec\n );\n\n /// Emitted once a stake is scheduled for withdrawal\n event StakeUnlocked(address indexed account, uint256 withdrawTime);\n\n event StakeWithdrawn(\n address indexed account,\n address withdrawAddress,\n uint256 amount\n );\n\n /**\n * @param deposit the entity's deposit\n * @param staked true if this entity is staked.\n * @param stake actual amount of ether staked for this entity.\n * @param unstakeDelaySec minimum delay to withdraw the stake.\n * @param withdrawTime - first block timestamp where 'withdrawStake' will be callable, or zero if already locked\n * @dev sizes were chosen so that (deposit,staked, stake) fit into one cell (used during handleOps)\n * and the rest fit into a 2nd cell.\n * 112 bit allows for 10^15 eth\n * 48 bit for full timestamp\n * 32 bit allows 150 years for unstake delay\n */\n struct DepositInfo {\n uint112 deposit;\n bool staked;\n uint112 stake;\n uint32 unstakeDelaySec;\n uint48 withdrawTime;\n }\n\n //API struct used by getStakeInfo and simulateValidation\n struct StakeInfo {\n uint256 stake;\n uint256 unstakeDelaySec;\n }\n\n /// @return info - full deposit information of given account\n function getDepositInfo(\n address account\n ) external view returns (DepositInfo memory info);\n\n /// @return the deposit (for gas payment) of the account\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * add to the deposit of the given account\n */\n function depositTo(address account) external payable;\n\n /**\n * add to the account's stake - amount and delay\n * any pending unstake is first cancelled.\n * @param _unstakeDelaySec the new lock duration before the deposit can be withdrawn.\n */\n function addStake(uint32 _unstakeDelaySec) external payable;\n\n /**\n * attempt to unlock the stake.\n * the value can be withdrawn (using withdrawStake) after the unstake delay.\n */\n function unlockStake() external;\n\n /**\n * withdraw from the (unlocked) stake.\n * must first call unlockStake and wait for the unstakeDelay to pass\n * @param withdrawAddress the address to send withdrawn value.\n */\n function withdrawStake(address payable withdrawAddress) external;\n\n /**\n * withdraw from the deposit.\n * @param withdrawAddress the address to send withdrawn value.\n * @param withdrawAmount the amount to withdraw.\n */\n function withdrawTo(\n address payable withdrawAddress,\n uint256 withdrawAmount\n ) external;\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/interfaces/UserOperation.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\n/* solhint-disable no-inline-assembly */\n\nimport {calldataKeccak} from \"../core/Helpers.sol\";\n\n/**\n * User Operation struct\n * @param sender the sender account of this request.\n * @param nonce unique value the sender uses to verify it is not a replay.\n * @param initCode if set, the account contract will be created by this constructor/\n * @param callData the method call to execute on this account.\n * @param callGasLimit the gas limit passed to the callData method call.\n * @param verificationGasLimit gas used for validateUserOp and validatePaymasterUserOp.\n * @param preVerificationGas gas not calculated by the handleOps method, but added to the gas paid. Covers batch overhead.\n * @param maxFeePerGas same as EIP-1559 gas parameter.\n * @param maxPriorityFeePerGas same as EIP-1559 gas parameter.\n * @param paymasterAndData if set, this field holds the paymaster address and paymaster-specific data. the paymaster will pay for the transaction instead of the sender.\n * @param signature sender-verified signature over the entire request, the EntryPoint address and the chain ID.\n */\nstruct UserOperation {\n address sender;\n uint256 nonce;\n bytes initCode;\n bytes callData;\n uint256 callGasLimit;\n uint256 verificationGasLimit;\n uint256 preVerificationGas;\n uint256 maxFeePerGas;\n uint256 maxPriorityFeePerGas;\n bytes paymasterAndData;\n bytes signature;\n}\n\n/**\n * Utility functions helpful when working with UserOperation structs.\n */\nlibrary UserOperationLib {\n function getSender(\n UserOperation calldata userOp\n ) internal pure returns (address) {\n address data;\n //read sender from userOp, which is first userOp member (saves 800 gas...)\n assembly {\n data := calldataload(userOp)\n }\n return address(uint160(data));\n }\n\n //relayer/block builder might submit the TX with higher priorityFee, but the user should not\n // pay above what he signed for.\n function gasPrice(\n UserOperation calldata userOp\n ) internal view returns (uint256) {\n unchecked {\n uint256 maxFeePerGas = userOp.maxFeePerGas;\n uint256 maxPriorityFeePerGas = userOp.maxPriorityFeePerGas;\n if (maxFeePerGas == maxPriorityFeePerGas) {\n //legacy mode (for networks that don't support basefee opcode)\n return maxFeePerGas;\n }\n return min(maxFeePerGas, maxPriorityFeePerGas + block.basefee);\n }\n }\n\n function pack(\n UserOperation calldata userOp\n ) internal pure returns (bytes memory ret) {\n address sender = getSender(userOp);\n uint256 nonce = userOp.nonce;\n bytes32 hashInitCode = calldataKeccak(userOp.initCode);\n bytes32 hashCallData = calldataKeccak(userOp.callData);\n uint256 callGasLimit = userOp.callGasLimit;\n uint256 verificationGasLimit = userOp.verificationGasLimit;\n uint256 preVerificationGas = userOp.preVerificationGas;\n uint256 maxFeePerGas = userOp.maxFeePerGas;\n uint256 maxPriorityFeePerGas = userOp.maxPriorityFeePerGas;\n bytes32 hashPaymasterAndData = calldataKeccak(userOp.paymasterAndData);\n\n return\n abi.encode(\n sender,\n nonce,\n hashInitCode,\n hashCallData,\n callGasLimit,\n verificationGasLimit,\n preVerificationGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n hashPaymasterAndData\n );\n }\n\n function hash(\n UserOperation calldata userOp\n ) internal pure returns (bytes32) {\n return keccak256(pack(userOp));\n }\n\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/samples/callback/TokenCallbackHandler.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\n/* solhint-disable no-empty-blocks */\n\nimport \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport \"@openzeppelin/contracts/token/ERC777/IERC777Recipient.sol\";\nimport \"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol\";\nimport \"@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol\";\n\n/**\n * Token callback handler.\n * Handles supported tokens' callbacks, allowing account receiving these tokens.\n */\ncontract TokenCallbackHandler is\n IERC777Recipient,\n IERC721Receiver,\n IERC1155Receiver\n{\n function tokensReceived(\n address,\n address,\n address,\n uint256,\n bytes calldata,\n bytes calldata\n ) external pure override {}\n\n function onERC721Received(\n address,\n address,\n uint256,\n bytes calldata\n ) external pure override returns (bytes4) {\n return IERC721Receiver.onERC721Received.selector;\n }\n\n function onERC1155Received(\n address,\n address,\n uint256,\n uint256,\n bytes calldata\n ) external pure override returns (bytes4) {\n return IERC1155Receiver.onERC1155Received.selector;\n }\n\n function onERC1155BatchReceived(\n address,\n address,\n uint256[] calldata,\n uint256[] calldata,\n bytes calldata\n ) external pure override returns (bytes4) {\n return IERC1155Receiver.onERC1155BatchReceived.selector;\n }\n\n function supportsInterface(\n bytes4 interfaceId\n ) external view virtual override returns (bool) {\n return\n interfaceId == type(IERC721Receiver).interfaceId ||\n interfaceId == type(IERC1155Receiver).interfaceId ||\n interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/samples/DepositPaymaster.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\n/* solhint-disable reason-string */\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\nimport \"../core/BasePaymaster.sol\";\nimport \"./IOracle.sol\";\n\n/**\n * A token-based paymaster that accepts token deposits\n * The deposit is only a safeguard: the user pays with his token balance.\n * only if the user didn't approve() the paymaster, or if the token balance is not enough, the deposit will be used.\n * thus the required deposit is to cover just one method call.\n * The deposit is locked for the current block: the user must issue unlockTokenDeposit() to be allowed to withdraw\n * (but can't use the deposit for this or further operations)\n *\n * paymasterAndData holds the paymaster address followed by the token address to use.\n * @notice This paymaster will be rejected by the standard rules of EIP4337, as it uses an external oracle.\n * (the standard rules ban accessing data of an external contract)\n * It can only be used if it is \"whitelisted\" by the bundler.\n * (technically, it can be used by an \"oracle\" which returns a static value, without accessing any storage)\n */\ncontract DepositPaymaster is BasePaymaster {\n using UserOperationLib for UserOperation;\n using SafeERC20 for IERC20;\n\n //calculated cost of the postOp\n uint256 public constant COST_OF_POST = 35000;\n\n IOracle private constant NULL_ORACLE = IOracle(address(0));\n mapping(IERC20 => IOracle) public oracles;\n mapping(IERC20 => mapping(address => uint256)) public balances;\n mapping(address => uint256) public unlockBlock;\n\n constructor(IEntryPoint _entryPoint) BasePaymaster(_entryPoint) {\n //owner account is unblocked, to allow withdraw of paid tokens;\n unlockTokenDeposit();\n }\n\n /**\n * owner of the paymaster should add supported tokens\n */\n function addToken(\n IERC20 token,\n IOracle tokenPriceOracle\n ) external onlyOwner {\n require(oracles[token] == NULL_ORACLE, \"Token already set\");\n oracles[token] = tokenPriceOracle;\n }\n\n /**\n * deposit tokens that a specific account can use to pay for gas.\n * The sender must first approve this paymaster to withdraw these tokens (they are only withdrawn in this method).\n * Note depositing the tokens is equivalent to transferring them to the \"account\" - only the account can later\n * use them - either as gas, or using withdrawTo()\n *\n * @param token the token to deposit.\n * @param account the account to deposit for.\n * @param amount the amount of token to deposit.\n */\n function addDepositFor(\n IERC20 token,\n address account,\n uint256 amount\n ) external {\n //(sender must have approval for the paymaster)\n token.safeTransferFrom(msg.sender, address(this), amount);\n require(oracles[token] != NULL_ORACLE, \"unsupported token\");\n balances[token][account] += amount;\n if (msg.sender == account) {\n lockTokenDeposit();\n }\n }\n\n /**\n * @return amount - the amount of given token deposited to the Paymaster.\n * @return _unlockBlock - the block height at which the deposit can be withdrawn.\n */\n function depositInfo(\n IERC20 token,\n address account\n ) public view returns (uint256 amount, uint256 _unlockBlock) {\n amount = balances[token][account];\n _unlockBlock = unlockBlock[account];\n }\n\n /**\n * unlock deposit, so that it can be withdrawn.\n * can't be called in the same block as withdrawTo()\n */\n function unlockTokenDeposit() public {\n unlockBlock[msg.sender] = block.number;\n }\n\n /**\n * lock the tokens deposited for this account so they can be used to pay for gas.\n * after calling unlockTokenDeposit(), the account can't use this paymaster until the deposit is locked.\n */\n function lockTokenDeposit() public {\n unlockBlock[msg.sender] = 0;\n }\n\n /**\n * withdraw tokens.\n * can only be called after unlock() is called in a previous block.\n * @param token the token deposit to withdraw\n * @param target address to send to\n * @param amount amount to withdraw\n */\n function withdrawTokensTo(\n IERC20 token,\n address target,\n uint256 amount\n ) public {\n require(\n unlockBlock[msg.sender] != 0 &&\n block.number > unlockBlock[msg.sender],\n \"DepositPaymaster: must unlockTokenDeposit\"\n );\n balances[token][msg.sender] -= amount;\n token.safeTransfer(target, amount);\n }\n\n /**\n * translate the given eth value to token amount\n * @param token the token to use\n * @param ethBought the required eth value we want to \"buy\"\n * @return requiredTokens the amount of tokens required to get this amount of eth\n */\n function getTokenValueOfEth(\n IERC20 token,\n uint256 ethBought\n ) internal view virtual returns (uint256 requiredTokens) {\n IOracle oracle = oracles[token];\n require(oracle != NULL_ORACLE, \"DepositPaymaster: unsupported token\");\n return oracle.getTokenValueOfEth(ethBought);\n }\n\n /**\n * Validate the request:\n * The sender should have enough deposit to pay the max possible cost.\n * Note that the sender's balance is not checked. If it fails to pay from its balance,\n * this deposit will be used to compensate the paymaster for the transaction.\n */\n function _validatePaymasterUserOp(\n UserOperation calldata userOp,\n bytes32 userOpHash,\n uint256 maxCost\n )\n internal\n view\n override\n returns (bytes memory context, uint256 validationData)\n {\n (userOpHash);\n // verificationGasLimit is dual-purposed, as gas limit for postOp. make sure it is high enough\n require(\n userOp.verificationGasLimit > COST_OF_POST,\n \"DepositPaymaster: gas too low for postOp\"\n );\n\n bytes calldata paymasterAndData = userOp.paymasterAndData;\n require(\n paymasterAndData.length == 20 + 20,\n \"DepositPaymaster: paymasterAndData must specify token\"\n );\n IERC20 token = IERC20(address(bytes20(paymasterAndData[20:])));\n address account = userOp.getSender();\n uint256 maxTokenCost = getTokenValueOfEth(token, maxCost);\n uint256 gasPriceUserOp = userOp.gasPrice();\n require(\n unlockBlock[account] == 0,\n \"DepositPaymaster: deposit not locked\"\n );\n require(\n balances[token][account] >= maxTokenCost,\n \"DepositPaymaster: deposit too low\"\n );\n return (\n abi.encode(account, token, gasPriceUserOp, maxTokenCost, maxCost),\n 0\n );\n }\n\n /**\n * perform the post-operation to charge the sender for the gas.\n * in normal mode, use transferFrom to withdraw enough tokens from the sender's balance.\n * in case the transferFrom fails, the _postOp reverts and the entryPoint will call it again,\n * this time in *postOpReverted* mode.\n * In this mode, we use the deposit to pay (which we validated to be large enough)\n */\n function _postOp(\n PostOpMode mode,\n bytes calldata context,\n uint256 actualGasCost\n ) internal override {\n (\n address account,\n IERC20 token,\n uint256 gasPricePostOp,\n uint256 maxTokenCost,\n uint256 maxCost\n ) = abi.decode(context, (address, IERC20, uint256, uint256, uint256));\n //use same conversion rate as used for validation.\n uint256 actualTokenCost = ((actualGasCost +\n COST_OF_POST *\n gasPricePostOp) * maxTokenCost) / maxCost;\n if (mode != PostOpMode.postOpReverted) {\n // attempt to pay with tokens:\n token.safeTransferFrom(account, address(this), actualTokenCost);\n } else {\n //in case above transferFrom failed, pay with deposit:\n balances[token][account] -= actualTokenCost;\n }\n balances[token][owner()] += actualTokenCost;\n }\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/samples/IOracle.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\ninterface IOracle {\n /**\n * return amount of tokens that are required to receive that much eth.\n */\n function getTokenValueOfEth(\n uint256 ethOutput\n ) external view returns (uint256 tokenInput);\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/samples/SimpleAccount.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\n/* solhint-disable avoid-low-level-calls */\n/* solhint-disable no-inline-assembly */\n/* solhint-disable reason-string */\n\nimport \"@openzeppelin/contracts/utils/cryptography/ECDSA.sol\";\nimport \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol\";\n\nimport \"../core/BaseAccount.sol\";\nimport \"./callback/TokenCallbackHandler.sol\";\n\n/**\n * minimal account.\n * this is sample minimal account.\n * has execute, eth handling methods\n * has a single signer that can send requests through the entryPoint.\n */\ncontract SimpleAccount is\n BaseAccount,\n TokenCallbackHandler,\n UUPSUpgradeable,\n Initializable\n{\n using ECDSA for bytes32;\n\n address public owner;\n\n IEntryPoint private immutable _entryPoint;\n\n event SimpleAccountInitialized(\n IEntryPoint indexed entryPoint,\n address indexed owner\n );\n\n modifier onlyOwner() {\n _onlyOwner();\n _;\n }\n\n /// @inheritdoc BaseAccount\n function entryPoint() public view virtual override returns (IEntryPoint) {\n return _entryPoint;\n }\n\n \n receive() external payable {}\n\n constructor(IEntryPoint anEntryPoint) {\n _entryPoint = anEntryPoint;\n _disableInitializers();\n }\n\n function _onlyOwner() internal view {\n //directly from EOA owner, or through the account itself (which gets redirected through execute())\n require(\n msg.sender == owner || msg.sender == address(this),\n \"only owner\"\n );\n }\n\n /**\n * execute a transaction (called directly from owner, or by entryPoint)\n */\n function execute(\n address dest,\n uint256 value,\n bytes calldata func\n ) external {\n _requireFromEntryPointOrOwner();\n _call(dest, value, func);\n }\n\n /**\n * execute a sequence of transactions\n */\n function executeBatch(\n address[] calldata dest,\n bytes[] calldata func\n ) external {\n _requireFromEntryPointOrOwner();\n require(dest.length == func.length, \"wrong array lengths\");\n for (uint256 i = 0; i < dest.length; i++) {\n _call(dest[i], 0, func[i]);\n }\n }\n\n /**\n * @dev The _entryPoint member is immutable, to reduce gas consumption. To upgrade EntryPoint,\n * a new implementation of SimpleAccount must be deployed with the new EntryPoint address, then upgrading\n * the implementation by calling `upgradeTo()`\n */\n function initialize(address anOwner) public virtual initializer {\n _initialize(anOwner);\n }\n\n function _initialize(address anOwner) internal virtual {\n owner = anOwner;\n emit SimpleAccountInitialized(_entryPoint, owner);\n }\n\n // Require the function call went through EntryPoint or owner\n function _requireFromEntryPointOrOwner() internal view {\n require(\n msg.sender == address(entryPoint()) || msg.sender == owner,\n \"account: not Owner or EntryPoint\"\n );\n }\n\n /// implement template method of BaseAccount\n function _validateSignature(\n UserOperation calldata userOp,\n bytes32 userOpHash\n ) internal virtual override returns (uint256 validationData) {\n bytes32 hash = userOpHash.toEthSignedMessageHash();\n if (owner != hash.recover(userOp.signature))\n return SIG_VALIDATION_FAILED;\n return 0;\n }\n\n function _call(address target, uint256 value, bytes memory data) internal {\n (bool success, bytes memory result) = target.call{value: value}(data);\n if (!success) {\n assembly {\n revert(add(result, 32), mload(result))\n }\n }\n }\n\n /**\n * check current account deposit in the entryPoint\n */\n function getDeposit() public view returns (uint256) {\n return entryPoint().balanceOf(address(this));\n }\n\n /**\n * deposit more funds for this account in the entryPoint\n */\n function addDeposit() public payable {\n entryPoint().depositTo{value: msg.value}(address(this));\n }\n\n /**\n * withdraw value from the account's deposit\n * @param withdrawAddress target to send to\n * @param amount to withdraw\n */\n function withdrawDepositTo(\n address payable withdrawAddress,\n uint256 amount\n ) public onlyOwner {\n entryPoint().withdrawTo(withdrawAddress, amount);\n }\n\n function _authorizeUpgrade(\n address newImplementation\n ) internal view override {\n (newImplementation);\n _onlyOwner();\n }\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/samples/SimpleAccountFactory.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\nimport \"@openzeppelin/contracts/utils/Create2.sol\";\nimport \"@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol\";\n\nimport \"./SimpleAccount.sol\";\n\n/**\n * A sample factory contract for SimpleAccount\n * A UserOperations \"initCode\" holds the address of the factory, and a method call (to createAccount, in this sample factory).\n * The factory's createAccount returns the target account address even if it is already installed.\n * This way, the entryPoint.getSenderAddress() can be called either before or after the account is created.\n */\ncontract SimpleAccountFactory {\n SimpleAccount public immutable accountImplementation;\n\n constructor(IEntryPoint _entryPoint) {\n accountImplementation = new SimpleAccount(_entryPoint);\n }\n\n /**\n * create an account, and return its address.\n * returns the address even if the account is already deployed.\n * Note that during UserOperation execution, this method is called only if the account is not deployed.\n * This method returns an existing account address so that entryPoint.getSenderAddress() would work even after account creation\n */\n function createAccount(\n address owner,\n uint256 salt\n ) public returns (SimpleAccount ret) {\n address addr = getAddress(owner, salt);\n uint codeSize = addr.code.length;\n if (codeSize > 0) {\n return SimpleAccount(payable(addr));\n }\n ret = SimpleAccount(\n payable(\n new ERC1967Proxy{salt: bytes32(salt)}(\n address(accountImplementation),\n abi.encodeCall(SimpleAccount.initialize, (owner))\n )\n )\n );\n }\n\n /**\n * calculate the counterfactual address of this account as it would be returned by createAccount()\n */\n function getAddress(\n address owner,\n uint256 salt\n ) public view returns (address) {\n return\n Create2.computeAddress(\n bytes32(salt),\n keccak256(\n abi.encodePacked(\n type(ERC1967Proxy).creationCode,\n abi.encode(\n address(accountImplementation),\n abi.encodeCall(SimpleAccount.initialize, (owner))\n )\n )\n )\n );\n }\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/samples/TokenPaymaster.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\n/* solhint-disable reason-string */\n\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"../core/BasePaymaster.sol\";\n\n/**\n * A sample paymaster that defines itself as a token to pay for gas.\n * The paymaster IS the token to use, since a paymaster cannot use an external contract.\n * Also, the exchange rate has to be fixed, since it can't reference an external Uniswap or other exchange contract.\n * subclass should override \"getTokenValueOfEth\" to provide actual token exchange rate, settable by the owner.\n * Known Limitation: this paymaster is exploitable when put into a batch with multiple ops (of different accounts):\n * - while a single op can't exploit the paymaster (if postOp fails to withdraw the tokens, the user's op is reverted,\n * and then we know we can withdraw the tokens), multiple ops with different senders (all using this paymaster)\n * in a batch can withdraw funds from 2nd and further ops, forcing the paymaster itself to pay (from its deposit)\n * - Possible workarounds are either use a more complex paymaster scheme (e.g. the DepositPaymaster) or\n * to whitelist the account and the called method ids.\n */\ncontract TokenPaymaster is BasePaymaster, ERC20 {\n //calculated cost of the postOp\n uint256 public constant COST_OF_POST = 15000;\n\n address public immutable theFactory;\n\n constructor(\n address accountFactory,\n string memory _symbol,\n IEntryPoint _entryPoint\n ) ERC20(_symbol, _symbol) BasePaymaster(_entryPoint) {\n theFactory = accountFactory;\n //make it non-empty\n _mint(address(this), 1);\n\n //owner is allowed to withdraw tokens from the paymaster's balance\n _approve(address(this), msg.sender, type(uint).max);\n }\n\n /**\n * helpers for owner, to mint and withdraw tokens.\n * @param recipient - the address that will receive the minted tokens.\n * @param amount - the amount it will receive.\n */\n function mintTokens(address recipient, uint256 amount) external onlyOwner {\n _mint(recipient, amount);\n }\n\n /**\n * transfer paymaster ownership.\n * owner of this paymaster is allowed to withdraw funds (tokens transferred to this paymaster's balance)\n * when changing owner, the old owner's withdrawal rights are revoked.\n */\n function transferOwnership(\n address newOwner\n ) public virtual override onlyOwner {\n // remove allowance of current owner\n _approve(address(this), owner(), 0);\n super.transferOwnership(newOwner);\n // new owner is allowed to withdraw tokens from the paymaster's balance\n _approve(address(this), newOwner, type(uint).max);\n }\n\n //Note: this method assumes a fixed ratio of token-to-eth. subclass should override to supply oracle\n // or a setter.\n function getTokenValueOfEth(\n uint256 valueEth\n ) internal view virtual returns (uint256 valueToken) {\n return valueEth / 100;\n }\n\n /**\n * validate the request:\n * if this is a constructor call, make sure it is a known account.\n * verify the sender has enough tokens.\n * (since the paymaster is also the token, there is no notion of \"approval\")\n */\n function _validatePaymasterUserOp(\n UserOperation calldata userOp,\n bytes32 /*userOpHash*/,\n uint256 requiredPreFund\n )\n internal\n view\n override\n returns (bytes memory context, uint256 validationData)\n {\n uint256 tokenPrefund = getTokenValueOfEth(requiredPreFund);\n\n // verificationGasLimit is dual-purposed, as gas limit for postOp. make sure it is high enough\n // make sure that verificationGasLimit is high enough to handle postOp\n require(\n userOp.verificationGasLimit > COST_OF_POST,\n \"TokenPaymaster: gas too low for postOp\"\n );\n\n if (userOp.initCode.length != 0) {\n _validateConstructor(userOp);\n require(\n balanceOf(userOp.sender) >= tokenPrefund,\n \"TokenPaymaster: no balance (pre-create)\"\n );\n } else {\n require(\n balanceOf(userOp.sender) >= tokenPrefund,\n \"TokenPaymaster: no balance\"\n );\n }\n\n return (abi.encode(userOp.sender), 0);\n }\n\n // when constructing an account, validate constructor code and parameters\n // we trust our factory (and that it doesn't have any other public methods)\n function _validateConstructor(\n UserOperation calldata userOp\n ) internal view virtual {\n address factory = address(bytes20(userOp.initCode[0:20]));\n require(factory == theFactory, \"TokenPaymaster: wrong account factory\");\n }\n\n /**\n * actual charge of user.\n * this method will be called just after the user's TX with mode==OpSucceeded|OpReverted (account pays in both cases)\n * BUT: if the user changed its balance in a way that will cause postOp to revert, then it gets called again, after reverting\n * the user's TX , back to the state it was before the transaction started (before the validatePaymasterUserOp),\n * and the transaction should succeed there.\n */\n function _postOp(\n PostOpMode mode,\n bytes calldata context,\n uint256 actualGasCost\n ) internal override {\n //we don't really care about the mode, we just pay the gas with the user's tokens.\n (mode);\n address sender = abi.decode(context, (address));\n uint256 charge = getTokenValueOfEth(actualGasCost + COST_OF_POST);\n //actualGasCost is known to be no larger than the above requiredPreFund, so the transfer should succeed.\n _transfer(sender, address(this), charge);\n }\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/samples/VerifyingPaymaster.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\n/* solhint-disable reason-string */\n/* solhint-disable no-inline-assembly */\n\nimport \"../core/BasePaymaster.sol\";\nimport \"@openzeppelin/contracts/utils/cryptography/ECDSA.sol\";\n\n/**\n * A sample paymaster that uses external service to decide whether to pay for the UserOp.\n * The paymaster trusts an external signer to sign the transaction.\n * The calling user must pass the UserOp to that external signer first, which performs\n * whatever off-chain verification before signing the UserOp.\n * Note that this signature is NOT a replacement for the account-specific signature:\n * - the paymaster checks a signature to agree to PAY for GAS.\n * - the account checks a signature to prove identity and account ownership.\n */\ncontract VerifyingPaymaster is BasePaymaster {\n using ECDSA for bytes32;\n using UserOperationLib for UserOperation;\n\n address public immutable verifyingSigner;\n\n uint256 private constant VALID_TIMESTAMP_OFFSET = 20;\n\n uint256 private constant SIGNATURE_OFFSET = 84;\n\n constructor(\n IEntryPoint _entryPoint,\n address _verifyingSigner\n ) BasePaymaster(_entryPoint) {\n verifyingSigner = _verifyingSigner;\n }\n\n mapping(address => uint256) public senderNonce;\n\n function pack(\n UserOperation calldata userOp\n ) internal pure returns (bytes memory ret) {\n // lighter signature scheme. must match UserOp.ts#packUserOp\n bytes calldata pnd = userOp.paymasterAndData;\n // copy directly the userOp from calldata up to (but not including) the paymasterAndData.\n // this encoding depends on the ABI encoding of calldata, but is much lighter to copy\n // than referencing each field separately.\n assembly {\n let ofs := userOp\n let len := sub(sub(pnd.offset, ofs), 32)\n ret := mload(0x40)\n mstore(0x40, add(ret, add(len, 32)))\n mstore(ret, len)\n calldatacopy(add(ret, 32), ofs, len)\n }\n }\n\n /**\n * return the hash we're going to sign off-chain (and validate on-chain)\n * this method is called by the off-chain service, to sign the request.\n * it is called on-chain from the validatePaymasterUserOp, to validate the signature.\n * note that this signature covers all fields of the UserOperation, except the \"paymasterAndData\",\n * which will carry the signature itself.\n */\n function getHash(\n UserOperation calldata userOp,\n uint48 validUntil,\n uint48 validAfter\n ) public view returns (bytes32) {\n //can't use userOp.hash(), since it contains also the paymasterAndData itself.\n\n return\n keccak256(\n abi.encode(\n pack(userOp),\n block.chainid,\n address(this),\n senderNonce[userOp.getSender()],\n validUntil,\n validAfter\n )\n );\n }\n\n function getSenderPaymasterNonce(\n UserOperation calldata userOp\n ) public view returns (uint256) {\n address account = userOp.getSender();\n return senderNonce[account];\n }\n\n function getSenderPaymasterNonce(\n address account\n ) public view returns (uint256) {\n return senderNonce[account];\n }\n\n /**\n * verify our external signer signed this request.\n * the \"paymasterAndData\" is expected to be the paymaster and a signature over the entire request params\n * paymasterAndData[:20] : address(this)\n * paymasterAndData[20:84] : abi.encode(validUntil, validAfter)\n * paymasterAndData[84:] : signature\n */\n function _validatePaymasterUserOp(\n UserOperation calldata userOp,\n bytes32 /*userOpHash*/,\n uint256 requiredPreFund\n ) internal override returns (bytes memory context, uint256 validationData) {\n (requiredPreFund);\n\n (\n uint48 validUntil,\n uint48 validAfter,\n bytes calldata signature\n ) = parsePaymasterAndData(userOp.paymasterAndData);\n //ECDSA library supports both 64 and 65-byte long signatures.\n // we only \"require\" it here so that the revert reason on invalid signature will be of \"VerifyingPaymaster\", and not \"ECDSA\"\n require(\n signature.length == 64 || signature.length == 65,\n \"VerifyingPaymaster: invalid signature length in paymasterAndData\"\n );\n bytes32 hash = ECDSA.toEthSignedMessageHash(\n getHash(userOp, validUntil, validAfter)\n );\n senderNonce[userOp.getSender()]++;\n\n //don't revert on signature failure: return SIG_VALIDATION_FAILED\n if (verifyingSigner != ECDSA.recover(hash, signature)) {\n return (\"\", _packValidationData(true, validUntil, validAfter));\n }\n\n //no need for other on-chain validation: entire UserOp should have been checked\n // by the external service prior to signing it.\n return (\"\", _packValidationData(false, validUntil, validAfter));\n }\n\n function parsePaymasterAndData(\n bytes calldata paymasterAndData\n )\n public\n pure\n returns (uint48 validUntil, uint48 validAfter, bytes calldata signature)\n {\n (validUntil, validAfter) = abi.decode(\n paymasterAndData[VALID_TIMESTAMP_OFFSET:SIGNATURE_OFFSET],\n (uint48, uint48)\n );\n signature = paymasterAndData[SIGNATURE_OFFSET:];\n }\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/test/MaliciousAccount.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\nimport \"../interfaces/IAccount.sol\";\nimport \"../interfaces/IEntryPoint.sol\";\nimport \"../core/EntryPoint.sol\";\n\ncontract MaliciousAccount is IAccount {\n IEntryPoint private ep;\n\n constructor(IEntryPoint _ep) payable {\n ep = _ep;\n }\n\n function validateUserOp(\n UserOperation calldata userOp,\n bytes32,\n uint256 missingAccountFunds\n ) external returns (uint256 validationData) {\n ep.depositTo{value: missingAccountFunds}(address(this));\n // Now calculate basefee per EntryPoint.getUserOpGasPrice() and compare it to the basefe we pass off-chain in the signature\n uint256 externalBaseFee = abi.decode(userOp.signature, (uint256));\n uint256 requiredGas = userOp.callGasLimit +\n userOp.verificationGasLimit +\n userOp.preVerificationGas;\n uint256 gasPrice = missingAccountFunds / requiredGas;\n uint256 basefee = gasPrice - userOp.maxPriorityFeePerGas;\n require(basefee == externalBaseFee, \"Revert after first validation\");\n return 0;\n }\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/test/TestAggregatedAccount.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\nimport \"../samples/SimpleAccount.sol\";\n\n/**\n * test aggregated-signature account.\n * works only with TestAggregatedSignature, which doesn't really check signature, but nonce sum\n * a true aggregated account should expose data (e.g. its public key) to the aggregator.\n */\ncontract TestAggregatedAccount is SimpleAccount {\n address public immutable aggregator;\n\n // The constructor is used only for the \"implementation\" and only sets immutable values.\n // Mutable value slots for proxy accounts are set by the 'initialize' function.\n constructor(\n IEntryPoint anEntryPoint,\n address anAggregator\n ) SimpleAccount(anEntryPoint) {\n aggregator = anAggregator;\n }\n\n /// @inheritdoc SimpleAccount\n function initialize(address) public virtual override initializer {\n super._initialize(address(0));\n }\n\n function _validateSignature(\n UserOperation calldata userOp,\n bytes32 userOpHash\n ) internal view override returns (uint256 validationData) {\n (userOp, userOpHash);\n return _packValidationData(ValidationData(aggregator, 0, 0));\n }\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/test/TestAggregatedAccountFactory.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\nimport \"@openzeppelin/contracts/utils/Create2.sol\";\nimport \"@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol\";\n\nimport \"./TestAggregatedAccount.sol\";\n\n/**\n * Based on SimpleAccountFactory.\n * Cannot be a subclass since both constructor and createAccount depend on the\n * constructor and initializer of the actual account contract.\n */\ncontract TestAggregatedAccountFactory {\n TestAggregatedAccount public immutable accountImplementation;\n\n constructor(IEntryPoint anEntryPoint, address anAggregator) {\n accountImplementation = new TestAggregatedAccount(\n anEntryPoint,\n anAggregator\n );\n }\n\n /**\n * create an account, and return its address.\n * returns the address even if the account is already deployed.\n * Note that during UserOperation execution, this method is called only if the account is not deployed.\n * This method returns an existing account address so that entryPoint.getSenderAddress() would work even after account creation\n */\n function createAccount(\n address owner,\n uint256 salt\n ) public returns (TestAggregatedAccount ret) {\n address addr = getAddress(owner, salt);\n uint codeSize = addr.code.length;\n if (codeSize > 0) {\n return TestAggregatedAccount(payable(addr));\n }\n ret = TestAggregatedAccount(\n payable(\n new ERC1967Proxy{salt: bytes32(salt)}(\n address(accountImplementation),\n abi.encodeCall(TestAggregatedAccount.initialize, (owner))\n )\n )\n );\n }\n\n /**\n * calculate the counterfactual address of this account as it would be returned by createAccount()\n */\n function getAddress(\n address owner,\n uint256 salt\n ) public view returns (address) {\n return\n Create2.computeAddress(\n bytes32(salt),\n keccak256(\n abi.encodePacked(\n type(ERC1967Proxy).creationCode,\n abi.encode(\n address(accountImplementation),\n abi.encodeCall(\n TestAggregatedAccount.initialize,\n (owner)\n )\n )\n )\n )\n );\n }\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/test/TestCounter.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\n//sample \"receiver\" contract, for testing \"exec\" from account.\ncontract TestCounter {\n mapping(address => uint256) public counters;\n\n function count() public {\n counters[msg.sender] = counters[msg.sender] + 1;\n }\n\n function countFail() public pure {\n revert(\"count failed\");\n }\n\n function justemit() public {\n emit CalledFrom(msg.sender);\n }\n\n event CalledFrom(address sender);\n\n //helper method to waste gas\n // repeat - waste gas on writing storage in a loop\n // junk - dynamic buffer to stress the function size.\n mapping(uint256 => uint256) public xxx;\n uint256 public offset;\n\n function gasWaster(uint256 repeat, string calldata /*junk*/) external {\n for (uint256 i = 1; i <= repeat; i++) {\n offset++;\n xxx[offset] = i;\n }\n }\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/test/TestExpirePaymaster.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.8.17;\n\nimport \"../core/BasePaymaster.sol\";\n\n/**\n * test expiry mechanism: paymasterData encodes the \"validUntil\" and validAfter\" times\n */\ncontract TestExpirePaymaster is BasePaymaster {\n // solhint-disable no-empty-blocks\n constructor(IEntryPoint _entryPoint) BasePaymaster(_entryPoint) {}\n\n function _validatePaymasterUserOp(\n UserOperation calldata userOp,\n bytes32 userOpHash,\n uint256 maxCost\n )\n internal\n view\n virtual\n override\n returns (bytes memory context, uint256 validationData)\n {\n (userOp, userOpHash, maxCost);\n (uint48 validAfter, uint48 validUntil) = abi.decode(\n userOp.paymasterAndData[20:],\n (uint48, uint48)\n );\n validationData = _packValidationData(false, validUntil, validAfter);\n context = \"\";\n }\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/test/TestExpiryAccount.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.8.17;\n\nimport \"../samples/SimpleAccount.sol\";\n\n/**\n * A test account, for testing expiry.\n * add \"temporary\" owners, each with a time range (since..till) times for each.\n * NOTE: this is not a full \"session key\" implementation: a real session key should probably limit\n * other things, like target contracts and methods to be called.\n * also, the \"since\" value is not really useful, only for testing the entrypoint.\n */\ncontract TestExpiryAccount is SimpleAccount {\n using ECDSA for bytes32;\n\n mapping(address => uint48) public ownerAfter;\n mapping(address => uint48) public ownerUntil;\n\n \n constructor(IEntryPoint anEntryPoint) SimpleAccount(anEntryPoint) {}\n\n function initialize(address anOwner) public virtual override initializer {\n super._initialize(anOwner);\n addTemporaryOwner(anOwner, 0, type(uint48).max);\n }\n\n // As this is a test contract, no need for proxy, so no need to disable init\n \n function _disableInitializers() internal override {}\n\n function addTemporaryOwner(\n address owner,\n uint48 _after,\n uint48 _until\n ) public onlyOwner {\n require(_until > _after, \"wrong until/after\");\n ownerAfter[owner] = _after;\n ownerUntil[owner] = _until;\n }\n\n /// implement template method of BaseAccount\n function _validateSignature(\n UserOperation calldata userOp,\n bytes32 userOpHash\n ) internal view override returns (uint256 validationData) {\n bytes32 hash = userOpHash.toEthSignedMessageHash();\n address signer = hash.recover(userOp.signature);\n uint48 _until = ownerUntil[signer];\n uint48 _after = ownerAfter[signer];\n\n //we have \"until\" value for all valid owners. so zero means \"invalid signature\"\n bool sigFailed = _until == 0;\n return _packValidationData(sigFailed, _until, _after);\n }\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/test/TestOracle.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\nimport \"../samples/IOracle.sol\";\n\ncontract TestOracle is IOracle {\n function getTokenValueOfEth(\n uint256 ethOutput\n ) external pure override returns (uint256 tokenInput) {\n return ethOutput * 2;\n }\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/test/TestPaymasterAcceptAll.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.8.17;\n\nimport \"../core/BasePaymaster.sol\";\n\n/**\n * test paymaster, that pays for everything, without any check.\n */\ncontract TestPaymasterAcceptAll is BasePaymaster {\n constructor(IEntryPoint _entryPoint) BasePaymaster(_entryPoint) {\n // to support \"deterministic address\" factory\n // solhint-disable avoid-tx-origin\n if (tx.origin != msg.sender) {\n _transferOwnership(tx.origin);\n }\n }\n\n function _validatePaymasterUserOp(\n UserOperation calldata userOp,\n bytes32 userOpHash,\n uint256 maxCost\n )\n internal\n view\n virtual\n override\n returns (bytes memory context, uint256 validationData)\n {\n (userOp, userOpHash, maxCost);\n return (\"\", maxCost == 12345 ? 1 : 0);\n }\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/test/TestRevertAccount.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.8.17;\n/* solhint-disable no-inline-assembly */\n\nimport \"../samples/SimpleAccount.sol\";\n\ncontract TestRevertAccount is IAccount {\n IEntryPoint private ep;\n\n constructor(IEntryPoint _ep) payable {\n ep = _ep;\n }\n\n function validateUserOp(\n UserOperation calldata,\n bytes32,\n uint256 missingAccountFunds\n ) external override returns (uint256 validationData) {\n ep.depositTo{value: missingAccountFunds}(address(this));\n return 0;\n }\n\n function revertLong(uint256 length) public pure {\n assembly {\n revert(0, length)\n }\n }\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/test/TestSignatureAggregator.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\n/* solhint-disable reason-string */\n\nimport \"../interfaces/IAggregator.sol\";\nimport \"../interfaces/IEntryPoint.sol\";\nimport \"../samples/SimpleAccount.sol\";\n\n/**\n * test signature aggregator.\n * the aggregated signature is the SUM of the nonce fields..\n */\ncontract TestSignatureAggregator is IAggregator {\n /// @inheritdoc IAggregator\n function validateSignatures(\n UserOperation[] calldata userOps,\n bytes calldata signature\n ) external pure override {\n uint sum = 0;\n for (uint i = 0; i < userOps.length; i++) {\n uint nonce = userOps[i].nonce;\n sum += nonce;\n }\n require(\n signature.length == 32,\n \"TestSignatureValidator: sig must be uint\"\n );\n uint sig = abi.decode(signature, (uint));\n require(\n sig == sum,\n \"TestSignatureValidator: aggregated signature mismatch (nonce sum)\"\n );\n }\n\n /// @inheritdoc IAggregator\n function validateUserOpSignature(\n UserOperation calldata\n ) external pure returns (bytes memory) {\n return \"\";\n }\n\n /**\n * dummy test aggregator: sum all nonce values of UserOps.\n */\n function aggregateSignatures(\n UserOperation[] calldata userOps\n ) external pure returns (bytes memory aggregatedSignature) {\n uint sum = 0;\n for (uint i = 0; i < userOps.length; i++) {\n sum += userOps[i].nonce;\n }\n return abi.encode(sum);\n }\n\n /**\n * Calls the 'addStake' method of the EntryPoint. Forwards the entire msg.value to this call.\n * @param entryPoint - the EntryPoint to send the stake to.\n * @param delay - the new lock duration before the deposit can be withdrawn.\n */\n function addStake(IEntryPoint entryPoint, uint32 delay) external payable {\n entryPoint.addStake{value: msg.value}(delay);\n }\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/test/TestToken.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\n\ncontract TestToken is ERC20 {\n constructor()\n \n ERC20(\"TST\", \"TestToken\")\n {}\n\n function mint(address sender, uint256 amount) external {\n _mint(sender, amount);\n }\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/test/TestUtil.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\nimport \"../interfaces/UserOperation.sol\";\n\ncontract TestUtil {\n using UserOperationLib for UserOperation;\n\n function packUserOp(\n UserOperation calldata op\n ) external pure returns (bytes memory) {\n return op.pack();\n }\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/test/TestWarmColdAccount.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.8.17;\n/* solhint-disable no-inline-assembly */\n\nimport \"../interfaces/IEntryPoint.sol\";\nimport \"../interfaces/IAccount.sol\";\n\n// Using eip-2929 (https://eips.ethereum.org/EIPS/eip-2929) warm/cold storage access gas costs to detect simulation vs execution\n// COLD_ACCOUNT_ACCESS_COST == 2600, COLD_SLOAD_COST == 2100, WARM_STORAGE_READ_COST == 100\ncontract TestWarmColdAccount is IAccount {\n IEntryPoint private ep;\n uint public state = 1;\n\n constructor(IEntryPoint _ep) payable {\n ep = _ep;\n }\n\n function validateUserOp(\n UserOperation calldata userOp,\n bytes32,\n uint256 missingAccountFunds\n ) external override returns (uint256 validationData) {\n ep.depositTo{value: missingAccountFunds}(address(this));\n if (userOp.nonce == 1) {\n // can only succeed if storage is already warm\n this.touchStorage{gas: 1000}();\n } else if (userOp.nonce == 2) {\n address paymaster = address(bytes20(userOp.paymasterAndData[:20]));\n // can only succeed if storage is already warm\n this.touchPaymaster{gas: 1000}(paymaster);\n }\n return 0;\n }\n\n function touchStorage() public view returns (uint256) {\n return state;\n }\n\n function touchPaymaster(address paymaster) public view returns (uint256) {\n return paymaster.code.length;\n }\n}\n"
},
"contracts/smart-contract-wallet/aa-4337/utils/Exec.sol": {
"content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity 0.8.17;\n\n// solhint-disable no-inline-assembly\n\n/**\n * Utility functions helpful when making different kinds of contract calls in Solidity.\n */\nlibrary Exec {\n function call(\n address to,\n uint256 value,\n bytes memory data,\n uint256 txGas\n ) internal returns (bool success) {\n assembly {\n success := call(\n txGas,\n to,\n value,\n add(data, 0x20),\n mload(data),\n 0,\n 0\n )\n }\n }\n\n function staticcall(\n address to,\n bytes memory data,\n uint256 txGas\n ) internal view returns (bool success) {\n assembly {\n success := staticcall(txGas, to, add(data, 0x20), mload(data), 0, 0)\n }\n }\n\n function delegateCall(\n address to,\n bytes memory data,\n uint256 txGas\n ) internal returns (bool success) {\n assembly {\n success := delegatecall(\n txGas,\n to,\n add(data, 0x20),\n mload(data),\n 0,\n 0\n )\n }\n }\n\n // get returned data from last call or calldelegate\n function getReturnData(\n uint256 maxLen\n ) internal pure returns (bytes memory returnData) {\n assembly {\n let len := returndatasize()\n if gt(len, maxLen) {\n len := maxLen\n }\n let ptr := mload(0x40)\n mstore(0x40, add(ptr, add(len, 0x20)))\n mstore(ptr, len)\n returndatacopy(add(ptr, 0x20), 0, len)\n returnData := ptr\n }\n }\n\n // revert with explicit byte array (probably reverted info from call)\n function revertWithData(bytes memory returnData) internal pure {\n assembly {\n revert(add(returnData, 32), mload(returnData))\n }\n }\n\n function callAndRevert(\n address to,\n bytes memory data,\n uint256 maxLen\n ) internal {\n bool success = call(to, 0, data, gasleft());\n if (!success) {\n revertWithData(getReturnData(maxLen));\n }\n }\n}\n"
},
"contracts/smart-contract-wallet/base/Executor.sol": {
"content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity 0.8.17;\n\nimport {Enum} from \"../common/Enum.sol\";\n\n/// @title Executor - A contract that can execute transactions\nabstract contract Executor {\n // Could add a flag fromEntryPoint for AA txn\n event ExecutionFailure(\n address indexed to,\n uint256 indexed value,\n bytes indexed data,\n Enum.Operation operation,\n uint256 txGas\n );\n event ExecutionSuccess(\n address indexed to,\n uint256 indexed value,\n bytes indexed data,\n Enum.Operation operation,\n uint256 txGas\n );\n\n function execute(\n address to,\n uint256 value,\n bytes memory data,\n Enum.Operation operation,\n uint256 txGas\n ) internal returns (bool success) {\n if (operation == Enum.Operation.DelegateCall) {\n \n assembly {\n success := delegatecall(\n txGas,\n to,\n add(data, 0x20),\n mload(data),\n 0,\n 0\n )\n }\n } else {\n \n assembly {\n success := call(\n txGas,\n to,\n value,\n add(data, 0x20),\n mload(data),\n 0,\n 0\n )\n }\n }\n if (success) emit ExecutionSuccess(to, value, data, operation, txGas);\n else emit ExecutionFailure(to, value, data, operation, txGas);\n }\n}\n"
},
"contracts/smart-contract-wallet/base/FallbackManager.sol": {
"content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity 0.8.17;\n\nimport {SelfAuthorized} from \"../common/SelfAuthorized.sol\";\nimport {FallbackManagerErrors} from \"../common/Errors.sol\";\n\n/**\n * @title Fallback Manager - A contract that manages fallback calls made to the Smart Account\n * @dev Fallback calls are handled by a `handler` contract that is stored at FALLBACK_HANDLER_STORAGE_SLOT\n * fallback calls are not delegated to the `handler` so they can not directly change Smart Account storage\n */\ncontract FallbackManager is SelfAuthorized, FallbackManagerErrors {\n // keccak-256 hash of \"fallback_manager.handler.address\" subtracted by 1\n bytes32 internal constant FALLBACK_HANDLER_STORAGE_SLOT =\n 0x6c9a6c4a39284e37ed1cf53d337577d14212a4870fb976a4366c693b939918d4;\n\n event ChangedFallbackHandler(\n address indexed previousHandler,\n address indexed handler\n );\n\n // solhint-disable-next-line payable-fallback,no-complex-fallback\n fallback() external {\n bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT;\n \n assembly {\n let handler := sload(slot)\n if iszero(handler) {\n return(0, 0)\n }\n calldatacopy(0, 0, calldatasize())\n // The msg.sender address is shifted to the left by 12 bytes to remove the padding\n // Then the address without padding is stored right after the calldata\n mstore(calldatasize(), shl(96, caller()))\n // Add 20 bytes for the address appended add the end\n let success := call(\n gas(),\n handler,\n 0,\n 0,\n add(calldatasize(), 20),\n 0,\n 0\n )\n returndatacopy(0, 0, returndatasize())\n if iszero(success) {\n revert(0, returndatasize())\n }\n return(0, returndatasize())\n }\n }\n\n function getFallbackHandler() external view returns (address _handler) {\n \n assembly {\n _handler := sload(FALLBACK_HANDLER_STORAGE_SLOT)\n }\n }\n\n /// @dev Allows to add a contract to handle fallback calls.\n /// Only fallback calls without value and with data will be forwarded.\n /// This can only be done via a smartAccount transaction.\n /// @param handler contract to handle fallback calls.\n function setFallbackHandler(address handler) public authorized {\n address previousHandler;\n \n assembly {\n previousHandler := sload(FALLBACK_HANDLER_STORAGE_SLOT)\n }\n _setFallbackHandler(handler);\n emit ChangedFallbackHandler(previousHandler, handler);\n }\n\n function _setFallbackHandler(address handler) internal {\n if (handler == address(0)) revert HandlerCannotBeZero();\n bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT;\n \n assembly {\n sstore(slot, handler)\n }\n }\n\n uint256[24] private __gap;\n}\n"
},
"contracts/smart-contract-wallet/base/ModuleManager.sol": {
"content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity 0.8.17;\n\nimport {SelfAuthorized} from \"../common/SelfAuthorized.sol\";\nimport {Executor, Enum} from \"./Executor.sol\";\nimport {ModuleManagerErrors} from \"../common/Errors.sol\";\n\n/**\n * @title Module Manager - A contract that manages modules that can execute transactions\n * on behalf of the Smart Account via this contract.\n */\nabstract contract ModuleManager is\n SelfAuthorized,\n Executor,\n ModuleManagerErrors\n{\n address internal constant SENTINEL_MODULES = address(0x1);\n\n mapping(address => address) internal modules;\n\n // Events\n event EnabledModule(address module);\n event DisabledModule(address module);\n event ExecutionFromModuleSuccess(address indexed module);\n event ExecutionFromModuleFailure(address indexed module);\n event ModuleTransaction(\n address module,\n address to,\n uint256 value,\n bytes data,\n Enum.Operation operation\n );\n\n /**\n * @dev Returns array of modules. Useful for a widget\n * @param start Start of the page.\n * @param pageSize Maximum number of modules that should be returned.\n * @return array Array of modules.\n * @return next Start of the next page.\n */\n function getModulesPaginated(\n address start,\n uint256 pageSize\n ) external view returns (address[] memory array, address next) {\n // Init array with max page size\n array = new address[](pageSize);\n\n // Populate return array\n uint256 moduleCount;\n address currentModule = modules[start];\n while (\n currentModule != address(0x0) &&\n currentModule != SENTINEL_MODULES &&\n moduleCount < pageSize\n ) {\n array[moduleCount] = currentModule;\n currentModule = modules[currentModule];\n moduleCount++;\n }\n next = currentModule;\n // Set correct size of returned array\n \n assembly {\n mstore(array, moduleCount)\n }\n }\n\n /**\n * @dev Adds a module to the allowlist.\n * @notice This SHOULD only be done via userOp or a selfcall.\n */\n function enableModule(address module) external virtual;\n\n /**\n * @dev Adds a module to the allowlist.\n * @notice This can only be done via a userOp or a selfcall.\n * @notice Enables the module `module` for the wallet.\n * @param module Module to be allow-listed.\n */\n function _enableModule(address module) internal virtual {\n // Module address cannot be null or sentinel.\n if (module == address(0) || module == SENTINEL_MODULES)\n revert ModuleCannotBeZeroOrSentinel(module);\n // Module cannot be added twice.\n if (modules[module] != address(0)) revert ModuleAlreadyEnabled(module);\n\n modules[module] = modules[SENTINEL_MODULES];\n modules[SENTINEL_MODULES] = module;\n\n emit EnabledModule(module);\n }\n\n /**\n * @dev Setups module for this Smart Account and enables it.\n * @notice This SHOULD only be done via userOp or a selfcall.\n */\n function setupAndEnableModule(\n address setupContract,\n bytes memory setupData\n ) external virtual returns (address);\n\n /**\n * @dev Setups module for this Smart Account and enables it.\n * @notice This can only be done via userOp or a selfcall.\n */\n function _setupAndEnableModule(\n address setupContract,\n bytes memory setupData\n ) internal virtual returns (address) {\n if (setupContract == address(0)) revert(\"Wrong Module Setup Address\");\n address module = _setupModule(setupContract, setupData);\n\n // Module address cannot be null or sentinel.\n if (module == address(0) || module == SENTINEL_MODULES)\n revert ModuleCannotBeZeroOrSentinel(module);\n // Module cannot be added twice.\n if (modules[module] != address(0)) revert ModuleAlreadyEnabled(module);\n\n modules[module] = modules[SENTINEL_MODULES];\n modules[SENTINEL_MODULES] = module;\n\n emit EnabledModule(module);\n return module;\n }\n\n /**\n * @dev Removes a module from the allowlist.\n * @notice This can only be done via a wallet transaction.\n * @notice Disables the module `module` for the wallet.\n * @param prevModule Module that pointed to the module to be removed in the linked list\n * @param module Module to be removed.\n */\n function _disableModule(\n address prevModule,\n address module\n ) internal virtual {\n // Validate module address and check that it corresponds to module index.\n if (module == address(0) || module == SENTINEL_MODULES)\n revert ModuleCannotBeZeroOrSentinel(module);\n if (modules[prevModule] != module)\n revert ModuleAndPrevModuleMismatch(\n module,\n modules[prevModule],\n prevModule\n );\n modules[prevModule] = modules[module];\n delete modules[module];\n emit DisabledModule(module);\n }\n\n // TODO: can use not executor.execute, but SmartAccount._call for the unification\n\n /**\n * @dev Allows a Module to execute a Smart Account transaction without any further confirmations.\n * @param to Destination address of module transaction.\n * @param value Ether value of module transaction.\n * @param data Data payload of module transaction.\n * @param operation Operation type of module transaction.\n */\n function execTransactionFromModule(\n address to,\n uint256 value,\n bytes memory data,\n Enum.Operation operation\n ) public virtual returns (bool success) {\n // Only whitelisted modules are allowed.\n if (msg.sender == SENTINEL_MODULES || modules[msg.sender] == address(0))\n revert ModuleNotEnabled(msg.sender);\n // Execute transaction without further confirmations.\n success = execute(to, value, data, operation, gasleft());\n if (success) {\n emit ModuleTransaction(msg.sender, to, value, data, operation);\n emit ExecutionFromModuleSuccess(msg.sender);\n } else emit ExecutionFromModuleFailure(msg.sender);\n }\n\n /**\n * @dev Allows a Module to execute a wallet transaction without any further confirmations and returns data\n * @param to Destination address of module transaction.\n * @param value Ether value of module transaction.\n * @param data Data payload of module transaction.\n * @param operation Operation type of module transaction.\n */\n function execTransactionFromModuleReturnData(\n address to,\n uint256 value,\n bytes memory data,\n Enum.Operation operation\n ) public returns (bool success, bytes memory returnData) {\n success = execTransactionFromModule(to, value, data, operation);\n \n assembly {\n // Load free memory location\n let ptr := mload(0x40)\n // We allocate memory for the return data by setting the free memory location to\n // current free memory location + data size + 32 bytes for data size value\n mstore(0x40, add(ptr, add(returndatasize(), 0x20)))\n // Store the size\n mstore(ptr, returndatasize())\n // Store the data\n returndatacopy(add(ptr, 0x20), 0, returndatasize())\n // Point the return data to the correct memory location\n returnData := ptr\n }\n }\n\n /**\n * @dev Allows a Module to execute a batch of Smart Account transactions without any further confirmations.\n * @param to Destination address of module transaction.\n * @param value Ether value of module transaction.\n * @param data Data payload of module transaction.\n * @param operations Operation type of module transaction.\n */\n function execBatchTransactionFromModule(\n address[] calldata to,\n uint256[] calldata value,\n bytes[] calldata data,\n Enum.Operation[] calldata operations\n ) public virtual returns (bool success) {\n if (\n to.length == 0 ||\n to.length != value.length ||\n value.length != data.length ||\n data.length != operations.length\n )\n revert WrongBatchProvided(\n to.length,\n value.length,\n data.length,\n operations.length\n );\n\n // Only whitelisted modules are allowed.\n if (msg.sender == SENTINEL_MODULES || modules[msg.sender] == address(0))\n revert ModuleNotEnabled(msg.sender);\n\n for (uint256 i; i < to.length; ) {\n // Execute transaction without further confirmations.\n success = execute(\n to[i],\n value[i],\n data[i],\n operations[i],\n gasleft()\n );\n if (success) {\n emit ModuleTransaction(\n msg.sender,\n to[i],\n value[i],\n data[i],\n operations[i]\n );\n emit ExecutionFromModuleSuccess(msg.sender);\n } else emit ExecutionFromModuleFailure(msg.sender);\n unchecked {\n ++i;\n }\n }\n }\n\n /**\n * @dev Returns if a module is enabled\n * @return True if the module is enabled\n */\n function isModuleEnabled(address module) public view returns (bool) {\n return SENTINEL_MODULES != module && modules[module] != address(0);\n }\n\n /**\n * @notice Setup function sets the initial storage of the contract.\n * Optionally executes a delegate call to another contract to setup the modules.\n * @param setupContract Contract, that setups initial auth module for this smart account. It can be a module factory or\n * a registry module that serves several smart accounts\n * @param setupData modules setup data (a standard calldata for the module setup contract)\n */\n function _initialSetupModules(\n address setupContract,\n bytes memory setupData\n ) internal virtual returns (address) {\n if (modules[SENTINEL_MODULES] != address(0))\n revert ModulesAlreadyInitialized();\n\n if (setupContract == address(0)) revert(\"Wrong Module Setup Address\");\n address initialAuthorizationModule = _setupModule(\n setupContract,\n setupData\n );\n modules[initialAuthorizationModule] = SENTINEL_MODULES;\n modules[SENTINEL_MODULES] = initialAuthorizationModule;\n return initialAuthorizationModule;\n }\n\n function _setupModule(\n address setupContract,\n bytes memory setupData\n ) internal returns (address module) {\n if (setupContract == address(0)) revert(\"Wrong Module Setup Address\");\n assembly {\n let success := call(\n gas(),\n setupContract,\n 0,\n add(setupData, 0x20),\n mload(setupData),\n 0,\n 0\n )\n let ptr := mload(0x40)\n returndatacopy(ptr, 0, returndatasize())\n if iszero(success) {\n revert(ptr, returndatasize())\n }\n module := mload(ptr)\n }\n }\n\n uint256[24] private __gap;\n}\n"
},
"contracts/smart-contract-wallet/BaseSmartAccount.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\n/* solhint-disable avoid-low-level-calls */\n/* solhint-disable no-inline-assembly */\n/* solhint-disable reason-string */\n\nimport {IAccount} from \"@account-abstraction/contracts/interfaces/IAccount.sol\";\nimport {IEntryPoint} from \"@account-abstraction/contracts/interfaces/IEntryPoint.sol\";\nimport {UserOperationLib, UserOperation} from \"@account-abstraction/contracts/interfaces/UserOperation.sol\";\nimport {Enum} from \"./common/Enum.sol\";\nimport {BaseSmartAccountErrors} from \"./common/Errors.sol\";\nimport \"@account-abstraction/contracts/core/Helpers.sol\";\n\nstruct Transaction {\n address to;\n Enum.Operation operation;\n uint256 value;\n bytes data;\n uint256 targetTxGas;\n}\n\nstruct FeeRefund {\n uint256 baseGas;\n uint256 gasPrice; //gasPrice or tokenGasPrice\n uint256 tokenGasPriceFactor;\n address gasToken;\n address payable refundReceiver;\n}\n\n/**\n * Basic account implementation.\n * This contract provides the basic logic for implementing the IAccount interface: validateUserOp function\n * Specific account implementation should inherit it and provide the account-specific logic\n */\nabstract contract BaseSmartAccount is IAccount, BaseSmartAccountErrors {\n using UserOperationLib for UserOperation;\n\n //return value in case of signature failure, with no time-range.\n // equivalent to _packValidationData(true,0,0);\n uint256 internal constant SIG_VALIDATION_FAILED = 1;\n\n /**\n * @return nonce the account nonce.\n * @dev This method returns the next sequential nonce.\n * @notice For a nonce of a specific key, use `entrypoint.getNonce(account, key)`\n */\n function nonce() public view virtual returns (uint256) {\n return entryPoint().getNonce(address(this), 0);\n }\n\n /**\n * return the entryPoint used by this account.\n * subclass should return the current entryPoint used by this account.\n */\n function entryPoint() public view virtual returns (IEntryPoint);\n\n /**\n * Validates the userOp.\n * @param userOp validate the userOp.signature field\n * @param userOpHash convenient field: the hash of the request, to check the signature against\n * (also hashes the entrypoint and chain id)\n * @param missingAccountFunds the amount of funds required to pay to EntryPoint to pay for the userOp execution.\n * @return validationData signature and time-range of this operation\n * <20-byte> sigAuthorizer - 0 for valid signature, 1 to mark signature failure,\n * otherwise, an address of an \"authorizer\" contract.\n * <6-byte> validUntil - last timestamp this operation is valid. 0 for \"indefinite\"\n * <6-byte> validAfter - first timestamp this operation is valid\n * If the account doesn't use time-range, it is enough to return SIG_VALIDATION_FAILED value (1) for signature failure.\n * Note that the validation code cannot use block.timestamp (or block.number) directly.\n */\n function validateUserOp(\n UserOperation calldata userOp,\n bytes32 userOpHash,\n uint256 missingAccountFunds\n ) external virtual override returns (uint256);\n\n /**\n * Validate the nonce of the UserOperation.\n * This method may validate the nonce requirement of this account.\n * e.g.\n * To limit the nonce to use sequenced UserOps only (no \"out of order\" UserOps):\n * `require(nonce < type(uint64).max)`\n * For a hypothetical account that *requires* the nonce to be out-of-order:\n * `require(nonce & type(uint64).max == 0)`\n *\n * The actual nonce uniqueness is managed by the EntryPoint, and thus no other\n * action is needed by the account itself.\n *\n * @param nonce to validate\n *\n * solhint-disable-next-line no-empty-blocks\n */\n function _validateNonce(uint256 nonce) internal view virtual {}\n\n /**\n * sends to the entrypoint (msg.sender) the missing funds for this transaction.\n * subclass MAY override this method for better funds management\n * (e.g. send to the entryPoint more than the minimum required, so that in future transactions\n * it will not be required to send again)\n * @param missingAccountFunds the minimum value this method should send the entrypoint.\n * this value MAY be zero, in case there is enough deposit, or the userOp has a paymaster.\n */\n function _payPrefund(uint256 missingAccountFunds) internal virtual {\n if (missingAccountFunds != 0) {\n payable(msg.sender).call{\n value: missingAccountFunds,\n gas: type(uint256).max\n }(\"\");\n //ignore failure (its EntryPoint's job to verify, not account.)\n }\n }\n\n /**\n * @dev Initialize the Smart Account with required states\n * @param handler Default fallback handler provided in Smart Account\n * @param moduleSetupContract Contract, that setups initial auth module for this smart account. It can be a module factory or\n * a registry module that serves several smart accounts.\n * @param moduleSetupData data containing address of the Setup Contract and a setup data\n * @notice devs need to make sure it is only callble once by initiazer or state check restrictions\n */\n function init(\n address handler,\n address moduleSetupContract,\n bytes calldata moduleSetupData\n ) external virtual returns (address);\n\n /**\n * @dev Gnosis style transaction with optional repay in native tokens OR ERC20\n * @dev Allows to execute a transaction confirmed by required signature/s and then pays the account that submitted the transaction.\n * @notice The fees are always transferred, even if the user transaction fails.\n * @param _tx Smart Account transaction\n * @param refundInfo Required information for gas refunds\n * @param signatures Packed signature/s data ({bytes32 r}{bytes32 s}{uint8 v})\n */\n function execTransaction(\n Transaction memory _tx,\n FeeRefund memory refundInfo,\n bytes memory signatures\n ) external payable virtual returns (bool success);\n}\n"
},
"contracts/smart-contract-wallet/common/Enum.sol": {
"content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity 0.8.17;\n\n/// @title Enum - Collection of enums\nabstract contract Enum {\n enum Operation {\n Call,\n DelegateCall\n }\n}\n"
},
"contracts/smart-contract-wallet/common/Errors.sol": {
"content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity 0.8.17;\n\ncontract BaseSmartAccountErrors {\n /**\n * @notice Throws at onlyEntryPoint when msg.sender is not an EntryPoint set for this Smart Account\n * @param caller address that tried to call onlyEntryPoint-protected method\n */\n error CallerIsNotAnEntryPoint(address caller);\n}\n\ncontract FallbackManagerErrors {\n /**\n * @notice Throws if zero address has been provided as Fallback Handler address\n */\n error HandlerCannotBeZero();\n}\n\ncontract ModuleManagerErrors {\n /**\n * @notice Throws when trying to initialize module manager that already been initialized\n */\n error ModulesAlreadyInitialized();\n\n /**\n * @notice Throws when a delegatecall in course of module manager initialization has failed\n */\n error ModulesSetupExecutionFailed();\n\n /**\n * @notice Throws when address(0) or SENTINEL_MODULES constant has been provided as a module address\n * @param module Module address provided\n */\n error ModuleCannotBeZeroOrSentinel(address module);\n\n /**\n * @notice Throws when trying to enable module that has already been enabled\n * @param module Module address provided\n */\n error ModuleAlreadyEnabled(address module);\n\n /**\n * @notice Throws when module and previous module mismatch\n * @param expectedModule expected module at modules[prevModule]\n * @param returnedModule the module that has been found at modules[prevModule]\n * @param prevModule previous module address provided at call\n */\n error ModuleAndPrevModuleMismatch(\n address expectedModule,\n address returnedModule,\n address prevModule\n );\n\n /**\n * @notice Throws when trying to execute transaction from module that is not enabled\n * @param module Module address provided\n */\n error ModuleNotEnabled(address module);\n\n /**\n * @notice Throws when data for executeBatchCall provided in wrong format (i.e. empty array or lengths mismatch)\n * @param destLength length of destination contracts array\n * @param valueLength length of txn values array\n * @param funcLength length of function signatures array\n * @param operationLength length of operation types array. 0 if there's no operations\n */\n error WrongBatchProvided(\n uint256 destLength,\n uint256 valueLength,\n uint256 funcLength,\n uint256 operationLength\n );\n}\n\ncontract SmartAccountErrors is BaseSmartAccountErrors, ModuleManagerErrors {\n /**\n * @notice Throws if zero address has been provided as Entry Point address\n */\n error EntryPointCannotBeZero();\n\n /**\n * @notice Throws at mixedAuth when msg.sender is not an owner neither _self\n * @param caller address that tried to call mixedAuth-protected method\n */\n error MixedAuthFail(address caller);\n\n /**\n * @notice Throws if transfer of tokens failed\n * @param token token contract address\n * @param dest token transfer receiver\n * @param amount the amount of tokens in a failed transfer\n */\n error TokenTransferFailed(address token, address dest, uint256 amount);\n\n /**\n * @notice Throws if trying to change an owner of a SmartAccount to the zero address\n */\n error OwnerCannotBeZero();\n\n /**\n * @notice Throws if zero address has been provided as Base Implementation address\n */\n error BaseImplementationCannotBeZero();\n\n /**\n * @notice Throws if there is no code at implementationAddress\n * @param implementationAddress implementation address provided\n */\n error InvalidImplementation(address implementationAddress);\n\n /**\n * @notice Throws at onlyOwner when msg.sender is not an owner\n * @param caller address that tried to call onlyOwner method\n */\n error CallerIsNotOwner(address caller);\n\n /**\n * @notice Throws at _requireFromEntryPointOrOwner when msg.sender is not an EntryPoint neither an owner\n * @param caller address that tried to call _requireFromEntryPointOrOwner-protected method\n */\n error CallerIsNotEntryPointOrOwner(address caller);\n\n /**\n * @notice Throws at _requireFromEntryPointOrSelf when msg.sender is not an EntryPoint neither self\n * @param caller address that tried to call _requireFromEntryPointOrSelf-protected method\n */\n error CallerIsNotEntryPointOrSelf(address caller);\n\n /**\n * @notice Throws at _requireFromEntryPoint when msg.sender is not an EntryPoint\n * @param caller address that tried to call _requireFromEntryPoint-protected method\n */\n error CallerIsNotEntryPoint(address caller);\n\n /**\n * @notice Throws if trying to initialize a Smart Account that has already been initialized\n * @param smartAccount Smart Account Address\n */\n error AlreadyInitialized(address smartAccount);\n\n /**\n * @notice Throws if not enough gas is left at some point\n * @param gasLeft how much gas left at the moment of a check\n * @param gasRequired how much gas required to proceed\n */\n error NotEnoughGasLeft(uint256 gasLeft, uint256 gasRequired);\n\n /**\n * @notice Throws if not able to estimate gas\n * It can be when amount of gas and its price are both zero and at the same time\n * transaction has failed to be executed\n * @param targetTxGas gas required for target transaction\n * @param gasPrice gas price passed in Refund Info\n * @param success whether transaction has been executed successfully or not\n */\n error CanNotEstimateGas(\n uint256 targetTxGas,\n uint256 gasPrice,\n bool success\n );\n\n /**\n * @notice Throws if contract signature is provided in frong format\n * @param uintS s converted to uint256\n * @param contractSignatureLength length of a contract signature\n * @param signatureLength the whole signature length\n */\n error WrongContractSignatureFormat(\n uint256 uintS,\n uint256 contractSignatureLength,\n uint256 signatureLength\n );\n\n /**\n * @notice Throws when isValidSignature for the conrtact signature and data hash return differs from EIP1271 Magic Value\n * @param contractSignature the contract signature that has been verified\n */\n error WrongContractSignature(bytes contractSignature);\n\n /**\n * @notice Throws when the address that signed the data (restored from signature)\n * differs from the address we expected to sign the data (i.e. some authorized address)\n */\n error InvalidSignature();\n\n /**\n * @notice Throws when the transaction execution fails\n */\n error ExecutionFailed();\n\n /**\n * @notice Throws when if trying to transfer to zero address\n */\n error TransferToZeroAddressAttempt();\n\n /**\n * @notice Throws when module address taken from signature is not enabled\n * @param moduleAddressProvided module address taken from signature\n */\n error WrongValidationModule(address moduleAddressProvided);\n\n /**\n * @notice Thrown when the function that must be called only via delegatecall is called directly\n */\n error DelegateCallsOnly();\n\n /**\n * @notice Thrown when trying to use address of the Smart Account as an owner for itself\n */\n error OwnerCanNotBeSelf();\n\n /**\n * @notice Thrown when trying to use current owner as a new owner in a _setOwner() call\n */\n error OwnerProvidedIsSame();\n\n /**\n * @notice Thrown when trying to use 0 as tokenGasPriceFactor\n */\n error TokenGasPriceFactorCanNotBeZero();\n}\n\ncontract SmartAccountFactoryErrors is SmartAccountErrors {\n /**\n * @notice Throws when the new Proxy deployment fails\n * @param owner Owner of a Proxy (Smart Account)\n * @param index Deployment index\n */\n error ProxyDeploymentFailed(address owner, uint256 index);\n}\n\ncontract SelfAuthorizedErrors {\n /**\n * @notice Throws when the caller is not address(this)\n * @param caller Caller address\n */\n error CallerIsNotSelf(address caller);\n}\n\ncontract SingletonPaymasterErrors {\n /**\n * @notice Throws when the Entrypoint address provided is address(0)\n */\n error EntryPointCannotBeZero();\n\n /**\n * @notice Throws when the verifiying signer address provided is address(0)\n */\n error VerifyingSignerCannotBeZero();\n\n /**\n * @notice Throws when the paymaster address provided is address(0)\n */\n error PaymasterIdCannotBeZero();\n\n /**\n * @notice Throws when the 0 has been provided as deposit\n */\n error DepositCanNotBeZero();\n\n /**\n * @notice Throws when trying to withdraw to address(0)\n */\n error CanNotWithdrawToZeroAddress();\n\n /**\n * @notice Throws when trying to withdraw more than balance available\n * @param amountRequired required balance\n * @param currentBalance available balance\n */\n error InsufficientBalance(uint256 amountRequired, uint256 currentBalance);\n\n /**\n * @notice Throws when signature provided has invalid length\n * @param sigLength length oif the signature provided\n */\n error InvalidPaymasterSignatureLength(uint256 sigLength);\n}\n\n//\n"
},
"contracts/smart-contract-wallet/common/ReentrancyGuard.sol": {
"content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity 0.8.17;\n\n/// @title Reentrancy Guard - reentrancy protection\nabstract contract ReentrancyGuard {\n error ReentrancyProtectionActivated();\n\n uint256 private constant NOT_ENTERED = 1;\n uint256 private constant ENTERED = 2;\n\n uint256 private reentrancyStatus;\n\n constructor() {\n reentrancyStatus = NOT_ENTERED;\n }\n\n modifier nonReentrant() {\n if (reentrancyStatus == ENTERED) revert ReentrancyProtectionActivated();\n reentrancyStatus = ENTERED;\n _;\n reentrancyStatus = NOT_ENTERED;\n }\n\n function _isReentrancyGuardEntered() internal view returns (bool) {\n return reentrancyStatus == ENTERED;\n }\n}\n"
},
"contracts/smart-contract-wallet/common/SecuredTokenTransfer.sol": {
"content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity 0.8.17;\n\n/// @title SecuredTokenTransfer - Secure token transfer\nabstract contract SecuredTokenTransfer {\n /// @dev Transfers a token and returns if it was a success\n /// @param token Token that should be transferred\n /// @param receiver Receiver to whom the token should be transferred\n /// @param amount The amount of tokens that should be transferred\n function transferToken(\n address token,\n address receiver,\n uint256 amount\n ) internal returns (bool transferred) {\n require(token != address(0), \"token can not be zero address\");\n require(token.code.length > 0, \"token contract doesn't exist\");\n // 0xa9059cbb - keccack(\"transfer(address,uint256)\")\n bytes memory data = abi.encodeWithSelector(\n 0xa9059cbb,\n receiver,\n amount\n );\n \n assembly {\n // We write the return value to scratch space.\n // See https://docs.soliditylang.org/en/v0.8.17/internals/layout_in_memory.html#layout-in-memory\n let success := call(\n sub(gas(), 10000),\n token,\n 0,\n add(data, 0x20),\n mload(data),\n 0,\n 0x20\n )\n switch returndatasize()\n case 0 {\n transferred := success\n }\n case 0x20 {\n transferred := iszero(or(iszero(success), iszero(mload(0))))\n }\n default {\n transferred := 0\n }\n }\n }\n}\n"
},
"contracts/smart-contract-wallet/common/SelfAuthorized.sol": {
"content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity 0.8.17;\n\nimport {SelfAuthorizedErrors} from \"../common/Errors.sol\";\n\n/// @title SelfAuthorized - authorizes current contract to perform actions\ncontract SelfAuthorized is SelfAuthorizedErrors {\n function requireSelfCall() private view {\n if (msg.sender != address(this)) revert CallerIsNotSelf(msg.sender);\n }\n\n modifier authorized() {\n // This is a function call as it minimized the bytecode size\n requireSelfCall();\n _;\n }\n}\n"
},
"contracts/smart-contract-wallet/common/SignatureDecoder.sol": {
"content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity 0.8.17;\n\n/// @title SignatureDecoder - Decodes signatures that a encoded as bytes\nabstract contract SignatureDecoder {\n /// @dev divides bytes signature into `uint8 v, bytes32 r, bytes32 s`.\n /// @param signature concatenated rsv signatures\n function signatureSplit(\n bytes memory signature\n ) internal pure returns (uint8 v, bytes32 r, bytes32 s) {\n // The signature format is a compact form of:\n // {bytes32 r}{bytes32 s}{uint8 v}\n // Compact means, uint8 is not padded to 32 bytes.\n \n assembly {\n r := mload(add(signature, 0x20))\n s := mload(add(signature, 0x40))\n // Here we are loading the last 32 bytes, including 31 bytes\n // of 's'. There is no 'mload8' to do this.\n //\n // 'byte' is not working due to the Solidity parser, so let's\n // use the second best option, 'and'\n v := and(mload(add(signature, 0x41)), 0xff)\n }\n }\n}\n"
},
"contracts/smart-contract-wallet/deployer/Create3.sol": {
"content": "//SPDX-License-Identifier: Unlicense\npragma solidity 0.8.17;\n\n/**\n @title A library for deploying contracts EIP-3171 style.\n @author Agustin Aguilar <[email protected]>\n*/\nlibrary Create3 {\n error ErrorCreatingProxy();\n error ErrorCreatingContract();\n error TargetAlreadyExists();\n\n /**\n @notice The bytecode for a contract that proxies the creation of another contract\n @dev If this code is deployed using CREATE2 it can be used to decouple `creationCode` from the child contract address\n\n 0x67363d3d37363d34f03d5260086018f3:\n 0x00 0x67 0x67XXXXXXXXXXXXXXXX PUSH8 bytecode 0x363d3d37363d34f0\n 0x01 0x3d 0x3d RETURNDATASIZE 0 0x363d3d37363d34f0\n 0x02 0x52 0x52 MSTORE\n 0x03 0x60 0x6008 PUSH1 08 8\n 0x04 0x60 0x6018 PUSH1 18 24 8\n 0x05 0xf3 0xf3 RETURN\n\n 0x363d3d37363d34f0:\n 0x00 0x36 0x36 CALLDATASIZE cds\n 0x01 0x3d 0x3d RETURNDATASIZE 0 cds\n 0x02 0x3d 0x3d RETURNDATASIZE 0 0 cds\n 0x03 0x37 0x37 CALLDATACOPY\n 0x04 0x36 0x36 CALLDATASIZE cds\n 0x05 0x3d 0x3d RETURNDATASIZE 0 cds\n 0x06 0x34 0x34 CALLVALUE val 0 cds\n 0x07 0xf0 0xf0 CREATE addr\n */\n\n bytes internal constant PROXY_CHILD_BYTECODE =\n hex\"67_36_3d_3d_37_36_3d_34_f0_3d_52_60_08_60_18_f3\";\n\n // KECCAK256_PROXY_CHILD_BYTECODE = keccak256(PROXY_CHILD_BYTECODE);\n bytes32 internal constant KECCAK256_PROXY_CHILD_BYTECODE =\n 0x21c35dbe1b344a2488cf3321d6ce542f8e9f305544ff09e4993a62319a497c1f;\n\n /**\n @notice Returns the size of the code on a given address\n @param _addr Address that may or may not contain code\n @return size of the code on the given `_addr`\n */\n function codeSize(address _addr) internal view returns (uint256 size) {\n assembly {\n size := extcodesize(_addr)\n }\n }\n\n /**\n @notice Creates a new contract with given `_creationCode` and `_salt`\n @param _salt Salt of the contract creation, resulting address will be derivated from this value only\n @param _creationCode Creation code (constructor) of the contract to be deployed, this value doesn't affect the resulting address\n @return addr of the deployed contract, reverts on error\n */\n function create3(\n bytes32 _salt,\n bytes memory _creationCode\n ) internal returns (address addr) {\n return create3(_salt, _creationCode, 0);\n }\n\n /**\n @notice Creates a new contract with given `_creationCode` and `_salt`\n @param _salt Salt of the contract creation, resulting address will be derivated from this value only\n @param _creationCode Creation code (constructor) of the contract to be deployed, this value doesn't affect the resulting address\n @param _value In WEI of ETH to be forwarded to child contract\n @return addr of the deployed contract, reverts on error\n */\n function create3(\n bytes32 _salt,\n bytes memory _creationCode,\n uint256 _value\n ) internal returns (address addr) {\n // Creation code\n bytes memory creationCode = PROXY_CHILD_BYTECODE;\n\n // Get target final address\n addr = addressOf(_salt);\n if (codeSize(addr) != 0) revert TargetAlreadyExists();\n\n // Create CREATE2 proxy\n address proxy;\n assembly {\n proxy := create2(\n 0,\n add(creationCode, 32),\n mload(creationCode),\n _salt\n )\n }\n if (proxy == address(0)) revert ErrorCreatingProxy();\n\n // Call proxy with final init code\n (bool success, ) = proxy.call{value: _value}(_creationCode);\n if (!success || codeSize(addr) == 0) revert ErrorCreatingContract();\n }\n\n function addressOfProxy(bytes32 _salt) internal view returns (address) {\n return\n address(\n uint160(\n uint256(\n keccak256(\n abi.encodePacked(\n hex\"ff\",\n address(this),\n _salt,\n KECCAK256_PROXY_CHILD_BYTECODE\n )\n )\n )\n )\n );\n }\n\n /**\n @notice Computes the resulting address of a contract deployed using address(this) and the given `_salt`\n @param _salt Salt of the contract creation, resulting address will be derivated from this value only\n @return addr of the deployed contract, reverts on error\n\n @dev The address creation formula is: keccak256(rlp([keccak256(0xff ++ address(this) ++ _salt ++ keccak256(childBytecode))[12:], 0x01]))\n */\n function addressOf(bytes32 _salt) internal view returns (address) {\n address proxy = addressOfProxy(_salt);\n return\n address(\n uint160(\n uint256(\n keccak256(abi.encodePacked(hex\"d6_94\", proxy, hex\"01\"))\n )\n )\n );\n }\n}\n"
},
"contracts/smart-contract-wallet/deployer/Deployer.sol": {
"content": "//SPDX-License-Identifier: Unlicense\npragma solidity 0.8.17;\n\nimport \"./Create3.sol\";\n\ncontract Deployer {\n event ContractDeployed(address indexed contractAddress);\n\n function deploy(bytes32 _salt, bytes calldata _creationCode) external {\n address deployedContract = Create3.create3(_salt, _creationCode);\n emit ContractDeployed(deployedContract);\n }\n\n function addressOf(bytes32 _salt) external view returns (address) {\n return Create3.addressOf(_salt);\n }\n}\n"
},
"contracts/smart-contract-wallet/handler/DefaultCallbackHandler.sol": {
"content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity 0.8.17;\n\nimport {IERC1155TokenReceiver} from \"../interfaces/IERC1155TokenReceiver.sol\";\nimport {IERC721TokenReceiver} from \"../interfaces/IERC721TokenReceiver.sol\";\nimport {IERC777TokensRecipient} from \"../interfaces/IERC777TokensRecipient.sol\";\nimport {IERC165} from \"../interfaces/IERC165.sol\";\nimport {SmartAccount} from \"../SmartAccount.sol\";\n\n/** @title Default Callback Handler - returns true for known token callbacks\n * @dev Handles EIP-1271 compliant isValidSignature requests.\n * @notice inspired by Richard Meissner's <[email protected]> implementation\n */\ncontract DefaultCallbackHandler is\n IERC1155TokenReceiver,\n IERC777TokensRecipient,\n IERC721TokenReceiver,\n IERC165\n{\n string public constant NAME = \"Default Callback Handler\";\n string public constant VERSION = \"1.0.0\";\n\n function onERC1155Received(\n address,\n address,\n uint256,\n uint256,\n bytes calldata\n ) external pure override returns (bytes4) {\n return IERC1155TokenReceiver.onERC1155Received.selector;\n }\n\n function onERC1155BatchReceived(\n address,\n address,\n uint256[] calldata,\n uint256[] calldata,\n bytes calldata\n ) external pure override returns (bytes4) {\n return IERC1155TokenReceiver.onERC1155BatchReceived.selector;\n }\n\n function onERC721Received(\n address,\n address,\n uint256,\n bytes calldata\n ) external pure override returns (bytes4) {\n return IERC721TokenReceiver.onERC721Received.selector;\n }\n\n function tokensReceived(\n address,\n address,\n address,\n uint256,\n bytes calldata,\n bytes calldata\n ) external pure override {\n // We implement this for completeness, doesn't really have any value\n }\n\n function supportsInterface(\n bytes4 interfaceId\n ) external view virtual override returns (bool) {\n return\n interfaceId == type(IERC1155TokenReceiver).interfaceId ||\n interfaceId == type(IERC721TokenReceiver).interfaceId ||\n interfaceId == type(IERC777TokensRecipient).interfaceId ||\n interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"contracts/smart-contract-wallet/interfaces/IERC1155TokenReceiver.sol": {
"content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity 0.8.17;\n\n/**\n Note: The ERC-165 identifier for this interface is 0x4e2312e0.\n*/\ninterface IERC1155TokenReceiver {\n /**\n @notice Handle the receipt of a single ERC1155 token type.\n @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated. \n This function MUST return `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))` (i.e. 0xf23a6e61) if it accepts the transfer.\n This function MUST revert if it rejects the transfer.\n Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.\n @param _operator The address which initiated the transfer (i.e. msg.sender)\n @param _from The address which previously owned the token\n @param _id The ID of the token being transferred\n @param _value The amount of tokens being transferred\n @param _data Additional data with no specified format\n @return `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))`\n */\n function onERC1155Received(\n address _operator,\n address _from,\n uint256 _id,\n uint256 _value,\n bytes calldata _data\n ) external returns (bytes4);\n\n /**\n @notice Handle the receipt of multiple ERC1155 token types.\n @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated. \n This function MUST return `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))` (i.e. 0xbc197c81) if it accepts the transfer(s).\n This function MUST revert if it rejects the transfer(s).\n Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.\n @param _operator The address which initiated the batch transfer (i.e. msg.sender)\n @param _from The address which previously owned the token\n @param _ids An array containing ids of each token being transferred (order and length must match _values array)\n @param _values An array containing amounts of each token being transferred (order and length must match _ids array)\n @param _data Additional data with no specified format\n @return `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))`\n */\n function onERC1155BatchReceived(\n address _operator,\n address _from,\n uint256[] calldata _ids,\n uint256[] calldata _values,\n bytes calldata _data\n ) external returns (bytes4);\n}\n"
},
"contracts/smart-contract-wallet/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity 0.8.17;\n\n/// @notice More details at https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/introspection/IERC165.sol\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"contracts/smart-contract-wallet/interfaces/IERC721TokenReceiver.sol": {
"content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity 0.8.17;\n\n/// @dev Note: the ERC-165 identifier for this interface is 0x150b7a02.\ninterface IERC721TokenReceiver {\n /// @notice Handle the receipt of an NFT\n /// @dev The ERC721 smart contract calls this function on the recipient\n /// after a `transfer`. This function MAY throw to revert and reject the\n /// transfer. Return of other than the magic value MUST result in the\n /// transaction being reverted.\n /// Note: the contract address is always the message sender.\n /// @param _operator The address which called `safeTransferFrom` function\n /// @param _from The address which previously owned the token\n /// @param _tokenId The NFT identifier which is being transferred\n /// @param _data Additional data with no specified format\n /// @return `bytes4(keccak256(\"onERC721Received(address,address,uint256,bytes)\"))`\n /// unless throwing\n function onERC721Received(\n address _operator,\n address _from,\n uint256 _tokenId,\n bytes calldata _data\n ) external returns (bytes4);\n}\n"
},
"contracts/smart-contract-wallet/interfaces/IERC777TokensRecipient.sol": {
"content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity 0.8.17;\n\ninterface IERC777TokensRecipient {\n function tokensReceived(\n address operator,\n address from,\n address to,\n uint256 amount,\n bytes calldata data,\n bytes calldata operatorData\n ) external;\n}\n"
},
"contracts/smart-contract-wallet/interfaces/IModule.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\nimport {UserOperation} from \"@account-abstraction/contracts/interfaces/UserOperation.sol\";\n\n// interface for modules to verify singatures signed over userOpHash\ninterface IModule {\n function validateUserOp(\n UserOperation calldata userOp,\n bytes32 userOpHash\n ) external returns (uint256 validationData);\n}\n"
},
"contracts/smart-contract-wallet/interfaces/ISignatureValidator.sol": {
"content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity 0.8.17;\n\ncontract ISignatureValidatorConstants {\n // bytes4(keccak256(\"isValidSignature(bytes32,bytes)\")\n bytes4 internal constant EIP1271_MAGIC_VALUE = 0x1626ba7e;\n}\n\nabstract contract ISignatureValidator is ISignatureValidatorConstants {\n /**\n * @dev Should return whether the signature provided is valid for the provided data\n * @param _dataHash Arbitrary length data signed on behalf of address(this)\n * @param _signature Signature byte array associated with _data\n *\n * MUST return the bytes4 magic value 0x20c13b0b when function passes.\n * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)\n * MUST allow external calls\n */\n function isValidSignature(\n bytes32 _dataHash,\n bytes memory _signature\n ) public view virtual returns (bytes4);\n}\n"
},
"contracts/smart-contract-wallet/libs/LibAddress.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nlibrary LibAddress {\n /**\n * @notice Will return true if provided address is a contract\n * @param account Address to verify if contract or not\n * @dev This contract will return false if called within the constructor of\n * a contract's deployment, as the code is not yet stored on-chain.\n */\n function isContract(address account) internal view returns (bool) {\n uint256 csize;\n \n assembly {\n csize := extcodesize(account)\n }\n return csize != 0;\n }\n}\n"
},
"contracts/smart-contract-wallet/libs/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)\n\npragma solidity 0.8.17;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n enum Rounding {\n Down, // Toward negative infinity\n Up, // Toward infinity\n Zero // Toward zero\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds up instead\n * of rounding down.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n * with further edits by Uniswap Labs also under MIT license.\n */\n function mulDiv(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod0 := mul(x, y)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n // The surrounding unchecked block does not change this fact.\n // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n require(denominator > prod1, \"Math: mulDiv overflow\");\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n // See https://cs.stackexchange.com/q/138556/92363.\n\n // Does not overflow because the denominator cannot be zero at this stage in the function.\n uint256 twos = denominator & (~denominator + 1);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n // in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(\n uint256 x,\n uint256 y,\n uint256 denominator,\n Rounding rounding\n ) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n //\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n //\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n //\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1 << (log2(a) >> 1);\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(\n uint256 a,\n Rounding rounding\n ) internal pure returns (uint256) {\n unchecked {\n uint256 result = sqrt(a);\n return\n result +\n (rounding == Rounding.Up && result * result < a ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 2, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 128;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 64;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 32;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 16;\n }\n if (value >> 8 > 0) {\n value >>= 8;\n result += 8;\n }\n if (value >> 4 > 0) {\n value >>= 4;\n result += 4;\n }\n if (value >> 2 > 0) {\n value >>= 2;\n result += 2;\n }\n if (value >> 1 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(\n uint256 value,\n Rounding rounding\n ) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return\n result +\n (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 10, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10 ** 64) {\n value /= 10 ** 64;\n result += 64;\n }\n if (value >= 10 ** 32) {\n value /= 10 ** 32;\n result += 32;\n }\n if (value >= 10 ** 16) {\n value /= 10 ** 16;\n result += 16;\n }\n if (value >= 10 ** 8) {\n value /= 10 ** 8;\n result += 8;\n }\n if (value >= 10 ** 4) {\n value /= 10 ** 4;\n result += 4;\n }\n if (value >= 10 ** 2) {\n value /= 10 ** 2;\n result += 2;\n }\n if (value >= 10 ** 1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(\n uint256 value,\n Rounding rounding\n ) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return\n result +\n (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 256, rounded down, of a positive value.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 16;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 8;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 4;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 2;\n }\n if (value >> 8 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(\n uint256 value,\n Rounding rounding\n ) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return\n result +\n (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);\n }\n }\n}\n"
},
"contracts/smart-contract-wallet/libs/MultiSend.sol": {
"content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity 0.8.17;\n\n/// @title Multi Send - Allows to batch multiple transactions into one.\n/// @author Nick Dodson - <[email protected]>\n/// @author Gonçalo Sá - <[email protected]>\n/// @author Stefan George - <[email protected]>\n/// @author Richard Meissner - <[email protected]>\ncontract MultiSend {\n address private immutable multisendSingleton;\n\n constructor() {\n multisendSingleton = address(this);\n }\n\n /// @dev Sends multiple transactions and reverts all if one fails.\n /// @param transactions Encoded transactions. Each transaction is encoded as a packed bytes of\n /// operation as a uint8 with 0 for a call or 1 for a delegatecall (=> 1 byte),\n /// to as a address (=> 20 bytes),\n /// value as a uint256 (=> 32 bytes),\n /// data length as a uint256 (=> 32 bytes),\n /// data as bytes.\n /// see abi.encodePacked for more information on packed encoding\n /// @notice This method is payable as delegatecalls keep the msg.value from the previous call\n /// If the calling method (e.g. execTransaction) received ETH this would revert otherwise\n function multiSend(bytes memory transactions) external {\n require(\n address(this) != multisendSingleton,\n \"MultiSend should only be called via delegatecall\"\n );\n \n assembly {\n let length := mload(transactions)\n let i := 0x20\n for {\n // Pre block is not used in \"while mode\"\n } lt(i, length) {\n // Post block is not used in \"while mode\"\n } {\n // First byte of the data is the operation.\n // We shift by 248 bits (256 - 8 [operation byte]) it right since mload will always load 32 bytes (a word).\n // This will also zero out unused data.\n let operation := shr(0xf8, mload(add(transactions, i)))\n // We offset the load address by 1 byte (operation byte)\n // We shift it right by 96 bits (256 - 160 [20 address bytes]) to right-align the data and zero out unused data.\n let to := shr(0x60, mload(add(transactions, add(i, 0x01))))\n // We offset the load address by 21 byte (operation byte + 20 address bytes)\n let value := mload(add(transactions, add(i, 0x15)))\n // We offset the load address by 53 byte (operation byte + 20 address bytes + 32 value bytes)\n let dataLength := mload(add(transactions, add(i, 0x35)))\n // We offset the load address by 85 byte (operation byte + 20 address bytes + 32 value bytes + 32 data length bytes)\n let data := add(transactions, add(i, 0x55))\n let success := 0\n switch operation\n case 0 {\n success := call(gas(), to, value, data, dataLength, 0, 0)\n }\n case 1 {\n success := delegatecall(gas(), to, data, dataLength, 0, 0)\n }\n if eq(success, 0) {\n revert(0, 0)\n }\n // Next entry starts at 85 byte + data length\n i := add(i, add(0x55, dataLength))\n }\n }\n }\n}\n"
},
"contracts/smart-contract-wallet/libs/MultiSendCallOnly.sol": {
"content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity 0.8.17;\n\n/// @title Multi Send Call Only - Allows to batch multiple transactions into one, but only calls\n/// @author Stefan George - <[email protected]>\n/// @author Richard Meissner - <[email protected]>\n/// @notice The guard logic is not required here as this contract doesn't support nested delegate calls\ncontract MultiSendCallOnly {\n /// @dev Sends multiple transactions and reverts all if one fails.\n /// @param transactions Encoded transactions. Each transaction is encoded as a packed bytes of\n /// operation has to be uint8(0) in this version (=> 1 byte),\n /// to as a address (=> 20 bytes),\n /// value as a uint256 (=> 32 bytes),\n /// data length as a uint256 (=> 32 bytes),\n /// data as bytes.\n /// see abi.encodePacked for more information on packed encoding\n /// @notice The code is for most part the same as the normal MultiSend (to keep compatibility),\n /// but reverts if a transaction tries to use a delegatecall.\n /// @notice This method is payable as delegatecalls keep the msg.value from the previous call\n /// If the calling method (e.g. execTransaction) received ETH this would revert otherwise\n function multiSend(bytes memory transactions) external {\n \n assembly {\n let length := mload(transactions)\n let i := 0x20\n for {\n // Pre block is not used in \"while mode\"\n } lt(i, length) {\n // Post block is not used in \"while mode\"\n } {\n // First byte of the data is the operation.\n // We shift by 248 bits (256 - 8 [operation byte]) it right since mload will always load 32 bytes (a word).\n // This will also zero out unused data.\n let operation := shr(0xf8, mload(add(transactions, i)))\n // We offset the load address by 1 byte (operation byte)\n // We shift it right by 96 bits (256 - 160 [20 address bytes]) to right-align the data and zero out unused data.\n let to := shr(0x60, mload(add(transactions, add(i, 0x01))))\n // We offset the load address by 21 byte (operation byte + 20 address bytes)\n let value := mload(add(transactions, add(i, 0x15)))\n // We offset the load address by 53 byte (operation byte + 20 address bytes + 32 value bytes)\n let dataLength := mload(add(transactions, add(i, 0x35)))\n // We offset the load address by 85 byte (operation byte + 20 address bytes + 32 value bytes + 32 data length bytes)\n let data := add(transactions, add(i, 0x55))\n let success := 0\n switch operation\n case 0 {\n success := call(gas(), to, value, data, dataLength, 0, 0)\n }\n // This version does not allow delegatecalls\n case 1 {\n revert(0, 0)\n }\n if eq(success, 0) {\n revert(0, 0)\n }\n // Next entry starts at 85 byte + data length\n i := add(i, add(0x55, dataLength))\n }\n }\n }\n}\n"
},
"contracts/smart-contract-wallet/libs/SmartAccountStorage.sol": {
"content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity ^0.8.0;\n\n/// @title SmartAccountStorage - Storage layout of the Smart Account contracts to be used in libraries\n/// @dev Should reflect the SmartAccount.sol storage structure (order of inheritance matters).\ncontract SmartAccountStorage {\n // ModuleManager storage\n mapping(address => address) internal modules;\n\n uint256[24] private __moduleManagerGap;\n\n uint256[24] private __fallbackManagerGap;\n\n uint256 private reentrancyStatus;\n\n // Smart Account Storage\n address internal owner;\n\n mapping(uint256 => uint256) internal nonces;\n}\n"
},
"contracts/smart-contract-wallet/libs/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity 0.8.17;\n\nimport \"./Math.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n unchecked {\n uint256 length = Math.log10(value) + 1;\n string memory buffer = new string(length);\n uint256 ptr;\n /// @solidity memory-safe-assembly\n assembly {\n ptr := add(buffer, add(32, length))\n }\n while (true) {\n ptr--;\n /// @solidity memory-safe-assembly\n assembly {\n mstore8(ptr, byte(mod(value, 10), _SYMBOLS))\n }\n value /= 10;\n if (value == 0) break;\n }\n return buffer;\n }\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n unchecked {\n return toHexString(value, Math.log256(value) + 1);\n }\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(\n uint256 value,\n uint256 length\n ) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"contracts/smart-contract-wallet/modules/BaseAuthorizationModule.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport {IModule} from \"../interfaces/IModule.sol\";\nimport {ISignatureValidator} from \"../interfaces/ISignatureValidator.sol\";\n\nabstract contract BaseAuthorizationModule is IModule, ISignatureValidator {\n uint256 internal constant SIG_VALIDATION_FAILED = 1;\n}\n"
},
"contracts/smart-contract-wallet/modules/EOAOwnershipRegistryModule.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport {BaseAuthorizationModule} from \"./BaseAuthorizationModule.sol\";\nimport {UserOperation} from \"@account-abstraction/contracts/interfaces/UserOperation.sol\";\nimport {ECDSA} from \"@openzeppelin/contracts/utils/cryptography/ECDSA.sol\";\n\ncontract EOAOwnershipRegistryModule is BaseAuthorizationModule {\n string public constant NAME = \"EOA Ownership Registry Module\";\n string public constant VERSION = \"0.1.0\";\n\n error NoOwnerRegisteredForSmartAccount(address smartAccount);\n\n using ECDSA for bytes32;\n\n mapping(address => address) public smartAccountOwners;\n\n function initForSmartAccount(address owner) external returns (address) {\n smartAccountOwners[msg.sender] = owner;\n return address(this);\n }\n\n function setOwner(address owner) external {\n smartAccountOwners[msg.sender] = owner;\n }\n\n function validateUserOp(\n UserOperation calldata userOp,\n bytes32 userOpHash\n ) external view virtual returns (uint256) {\n (bytes memory moduleSignature, ) = abi.decode(\n userOp.signature,\n (bytes, address)\n );\n // validateUserOp gets a hash not prepended with 'x\\x19Ethereum Signed Message:\\n32'\n // so we have to do it manually\n bytes32 ethSignedHash = userOpHash.toEthSignedMessageHash();\n return _validateSignature(userOp, ethSignedHash, moduleSignature);\n }\n\n function _validateSignature(\n UserOperation calldata userOp,\n bytes32 ethSignedUserOpHash,\n bytes memory moduleSignature\n ) internal view virtual returns (uint256 sigValidationResult) {\n if (\n _verifySignature(\n ethSignedUserOpHash,\n moduleSignature,\n userOp.sender\n )\n ) {\n return 0;\n }\n return SIG_VALIDATION_FAILED;\n }\n\n // isValidSignature expects a hash prepended with 'x\\x19Ethereum Signed Message:\\n32'\n function isValidSignature(\n bytes32 ethSignedDataHash,\n bytes memory moduleSignature\n ) public view virtual override returns (bytes4) {\n return\n isValidSignatureForAddress(\n ethSignedDataHash,\n moduleSignature,\n msg.sender\n );\n }\n\n function isValidSignatureForAddress(\n bytes32 ethSignedDataHash,\n bytes memory moduleSignature,\n address smartAccount\n ) public view virtual returns (bytes4) {\n if (\n _verifySignature(ethSignedDataHash, moduleSignature, smartAccount)\n ) {\n return EIP1271_MAGIC_VALUE;\n }\n return bytes4(0xffffffff);\n }\n\n // Only EOA owners supported, no smart contracts.\n // To support smart contracts, can add a check if expectedSigner.isContract()\n // then call expectedSigner.isValidSignature(ethSignedHash, signature)\n // to check if the signature is valid.\n function _verifySignature(\n bytes32 ethSignedHash,\n bytes memory signature,\n address account\n ) internal view returns (bool) {\n address expectedSigner = smartAccountOwners[account];\n if (expectedSigner == address(0))\n revert NoOwnerRegisteredForSmartAccount(account);\n return expectedSigner == ethSignedHash.recover(signature);\n }\n}\n"
},
"contracts/smart-contract-wallet/paymasters/BasePaymaster.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\n/* solhint-disable reason-string */\n\nimport {Ownable} from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport {IPaymaster} from \"@account-abstraction/contracts/interfaces/IPaymaster.sol\";\nimport {IEntryPoint} from \"@account-abstraction/contracts/interfaces/IEntryPoint.sol\";\nimport {UserOperation, UserOperationLib} from \"@account-abstraction/contracts/interfaces/UserOperation.sol\";\nimport {BaseSmartAccountErrors} from \"../common/Errors.sol\";\nimport \"@account-abstraction/contracts/core/Helpers.sol\";\n\n/**\n * Helper class for creating a paymaster.\n * provides helper methods for staking.\n * validates that the postOp is called only by the entryPoint\n */\n// @notice Could have Ownable2Step\nabstract contract BasePaymaster is IPaymaster, Ownable, BaseSmartAccountErrors {\n IEntryPoint public immutable entryPoint;\n\n constructor(address _owner, IEntryPoint _entryPoint) {\n entryPoint = _entryPoint;\n _transferOwnership(_owner);\n }\n\n /// @inheritdoc IPaymaster\n function validatePaymasterUserOp(\n UserOperation calldata userOp,\n bytes32 userOpHash,\n uint256 maxCost\n ) external override returns (bytes memory context, uint256 validationData) {\n _requireFromEntryPoint();\n return _validatePaymasterUserOp(userOp, userOpHash, maxCost);\n }\n\n function _validatePaymasterUserOp(\n UserOperation calldata userOp,\n bytes32 userOpHash,\n uint256 maxCost\n ) internal virtual returns (bytes memory context, uint256 validationData);\n\n /// @inheritdoc IPaymaster\n function postOp(\n PostOpMode mode,\n bytes calldata context,\n uint256 actualGasCost\n ) external override {\n _requireFromEntryPoint();\n _postOp(mode, context, actualGasCost);\n }\n\n /**\n * post-operation handler.\n * (verified to be called only through the entryPoint)\n * @dev if subclass returns a non-empty context from validatePaymasterUserOp, it must also implement this method.\n * @param mode enum with the following options:\n * opSucceeded - user operation succeeded.\n * opReverted - user op reverted. still has to pay for gas.\n * postOpReverted - user op succeeded, but caused postOp (in mode=opSucceeded) to revert.\n * Now this is the 2nd call, after user's op was deliberately reverted.\n * @param context - the context value returned by validatePaymasterUserOp\n * @param actualGasCost - actual gas used so far (without this postOp call).\n */\n function _postOp(\n PostOpMode mode,\n bytes calldata context,\n uint256 actualGasCost\n ) internal virtual {\n (mode, context, actualGasCost); // unused params\n // subclass must override this method if validatePaymasterUserOp returns a context\n revert(\"must override\");\n }\n\n /**\n * add a deposit for this paymaster, used for paying for transaction fees\n */\n function deposit() external payable virtual;\n\n /**\n * withdraw value from the deposit\n * @param withdrawAddress target to send to\n * @param amount to withdraw\n */\n function withdrawTo(\n address payable withdrawAddress,\n uint256 amount\n ) external virtual;\n\n /**\n * add stake for this paymaster.\n * This method can also carry eth value to add to the current stake.\n * @param unstakeDelaySec - the unstake delay for this paymaster. Can only be increased.\n */\n function addStake(uint32 unstakeDelaySec) external payable onlyOwner {\n entryPoint.addStake{value: msg.value}(unstakeDelaySec);\n }\n\n /**\n * return current paymaster's deposit on the entryPoint.\n */\n function getDeposit() public view returns (uint256) {\n return entryPoint.balanceOf(address(this));\n }\n\n /**\n * unlock the stake, in order to withdraw it.\n * The paymaster can't serve requests once unlocked, until it calls addStake again\n */\n function unlockStake() external onlyOwner {\n entryPoint.unlockStake();\n }\n\n /**\n * withdraw the entire paymaster's stake.\n * stake must be unlocked first (and then wait for the unstakeDelay to be over)\n * @param withdrawAddress the address to send withdrawn value.\n */\n function withdrawStake(address payable withdrawAddress) external onlyOwner {\n entryPoint.withdrawStake(withdrawAddress);\n }\n\n /// validate the call is made from a valid entrypoint\n function _requireFromEntryPoint() internal virtual {\n // require(msg.sender == address(entryPoint), \"Sender not EntryPoint\"); // won't need BaseSmartAccountErrors import\n if (msg.sender != address(entryPoint))\n revert CallerIsNotAnEntryPoint(msg.sender);\n }\n}\n"
},
"contracts/smart-contract-wallet/paymasters/PaymasterHelpers.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\nimport {ECDSA} from \"@openzeppelin/contracts/utils/cryptography/ECDSA.sol\";\nimport {UserOperation} from \"@account-abstraction/contracts/interfaces/UserOperation.sol\";\n\nstruct PaymasterData {\n address paymasterId;\n bytes signature;\n uint256 signatureLength;\n}\n\nstruct PaymasterContext {\n address paymasterId;\n uint256 gasPrice;\n}\n\n/**\n * @title PaymasterHelpers - helper functions for paymasters\n */\nlibrary PaymasterHelpers {\n using ECDSA for bytes32;\n\n /**\n * @dev Encodes the paymaster context: paymasterId and gasPrice\n * @param op UserOperation object\n * @param data PaymasterData passed\n * @param gasPrice effective gasPrice\n */\n function paymasterContext(\n UserOperation calldata op,\n PaymasterData memory data,\n uint256 gasPrice\n ) internal pure returns (bytes memory context) {\n return abi.encode(data.paymasterId, gasPrice);\n }\n\n /**\n * @dev Decodes paymaster data assuming it follows PaymasterData\n */\n function _decodePaymasterData(\n UserOperation calldata op\n ) internal pure returns (PaymasterData memory) {\n bytes calldata paymasterAndData = op.paymasterAndData;\n (address paymasterId, bytes memory signature) = abi.decode(\n paymasterAndData[20:],\n (address, bytes)\n );\n return PaymasterData(paymasterId, signature, signature.length);\n }\n\n /**\n * @dev Decodes paymaster context assuming it follows PaymasterContext\n */\n function _decodePaymasterContext(\n bytes memory context\n ) internal pure returns (PaymasterContext memory) {\n (address paymasterId, uint256 gasPrice) = abi.decode(\n context,\n (address, uint256)\n );\n return PaymasterContext(paymasterId, gasPrice);\n }\n}\n"
},
"contracts/smart-contract-wallet/paymasters/verifying/singleton/VerifyingSingletonPaymaster.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\n/* solhint-disable reason-string */\n/* solhint-disable no-inline-assembly */\nimport {ECDSA} from \"@openzeppelin/contracts/utils/cryptography/ECDSA.sol\";\nimport {ReentrancyGuard} from \"@openzeppelin/contracts/security/ReentrancyGuard.sol\";\nimport {UserOperation, UserOperationLib} from \"@account-abstraction/contracts/interfaces/UserOperation.sol\";\nimport {BasePaymaster, IEntryPoint} from \"../../BasePaymaster.sol\";\nimport {PaymasterHelpers, PaymasterData, PaymasterContext} from \"../../PaymasterHelpers.sol\";\nimport {SingletonPaymasterErrors} from \"../../../common/Errors.sol\";\n\n/**\n * @title A sample paymaster that uses external service to decide whether to pay for the UserOp.\n * @dev The paymaster trusts an external signer to sign the transaction.\n * The calling user must pass the UserOp to that external signer first, which performs whatever\n * off-chain verification before signing the UserOp.\n * @notice That this signature is NOT a replacement for wallet signature:\n * - The paymaster signs to agree to PAY for GAS.\n * - The wallet signs to prove identity and wallet ownership.\n */\ncontract VerifyingSingletonPaymaster is\n BasePaymaster,\n ReentrancyGuard,\n SingletonPaymasterErrors\n{\n using ECDSA for bytes32;\n using UserOperationLib for UserOperation;\n using PaymasterHelpers for UserOperation;\n using PaymasterHelpers for bytes;\n using PaymasterHelpers for PaymasterData;\n\n // Gas used in EntryPoint._handlePostOp() method (including this#postOp() call)\n uint256 private unaccountedEPGasOverhead;\n mapping(address => uint256) public paymasterIdBalances;\n\n address public verifyingSigner;\n\n event EPGasOverheadChanged(\n uint256 indexed _oldValue,\n uint256 indexed _newValue\n );\n\n event VerifyingSignerChanged(\n address indexed _oldSigner,\n address indexed _newSigner,\n address indexed _actor\n );\n event GasDeposited(address indexed _paymasterId, uint256 indexed _value);\n event GasWithdrawn(\n address indexed _paymasterId,\n address indexed _to,\n uint256 indexed _value\n );\n event GasBalanceDeducted(\n address indexed _paymasterId,\n uint256 indexed _charge\n );\n\n constructor(\n address _owner,\n IEntryPoint _entryPoint,\n address _verifyingSigner\n ) payable BasePaymaster(_owner, _entryPoint) {\n if (address(_entryPoint) == address(0)) revert EntryPointCannotBeZero();\n if (_verifyingSigner == address(0))\n revert VerifyingSignerCannotBeZero();\n assembly {\n sstore(verifyingSigner.slot, _verifyingSigner)\n }\n unaccountedEPGasOverhead = 9600;\n }\n\n /**\n * @dev Add a deposit for this paymaster and given paymasterId (Dapp Depositor address), used for paying for transaction fees\n * @param paymasterId dapp identifier for which deposit is being made\n */\n function depositFor(address paymasterId) external payable nonReentrant {\n if (paymasterId == address(0)) revert PaymasterIdCannotBeZero();\n if (msg.value == 0) revert DepositCanNotBeZero();\n paymasterIdBalances[paymasterId] =\n paymasterIdBalances[paymasterId] +\n msg.value;\n entryPoint.depositTo{value: msg.value}(address(this));\n emit GasDeposited(paymasterId, msg.value);\n }\n\n /**\n * @dev get the current deposit for paymasterId (Dapp Depositor address)\n * @param paymasterId dapp identifier\n */\n function getBalance(\n address paymasterId\n ) external view returns (uint256 balance) {\n balance = paymasterIdBalances[paymasterId];\n }\n\n /**\n @dev Override the default implementation.\n */\n function deposit() public payable virtual override {\n revert(\"user DepositFor instead\");\n }\n\n /**\n * @dev Withdraws the specified amount of gas tokens from the paymaster's balance and transfers them to the specified address.\n * @param withdrawAddress The address to which the gas tokens should be transferred.\n * @param amount The amount of gas tokens to withdraw.\n */\n function withdrawTo(\n address payable withdrawAddress,\n uint256 amount\n ) public override nonReentrant {\n if (withdrawAddress == address(0)) revert CanNotWithdrawToZeroAddress();\n uint256 currentBalance = paymasterIdBalances[msg.sender];\n if (amount > currentBalance)\n revert InsufficientBalance(amount, currentBalance);\n paymasterIdBalances[msg.sender] =\n paymasterIdBalances[msg.sender] -\n amount;\n entryPoint.withdrawTo(withdrawAddress, amount);\n emit GasWithdrawn(msg.sender, withdrawAddress, amount);\n }\n\n /**\n * @dev Set a new verifying signer address.\n * Can only be called by the owner of the contract.\n * @param _newVerifyingSigner The new address to be set as the verifying signer.\n * @notice If _newVerifyingSigner is set to zero address, it will revert with an error.\n * After setting the new signer address, it will emit an event VerifyingSignerChanged.\n */\n function setSigner(address _newVerifyingSigner) external payable onlyOwner {\n if (_newVerifyingSigner == address(0))\n revert VerifyingSignerCannotBeZero();\n address oldSigner = verifyingSigner;\n assembly {\n sstore(verifyingSigner.slot, _newVerifyingSigner)\n }\n emit VerifyingSignerChanged(oldSigner, _newVerifyingSigner, msg.sender);\n }\n\n function setUnaccountedEPGasOverhead(uint256 value) external onlyOwner {\n uint256 oldValue = unaccountedEPGasOverhead;\n unaccountedEPGasOverhead = value;\n emit EPGasOverheadChanged(oldValue, value);\n }\n\n /**\n * @dev This method is called by the off-chain service, to sign the request.\n * It is called on-chain from the validatePaymasterUserOp, to validate the signature.\n * @notice That this signature covers all fields of the UserOperation, except the \"paymasterAndData\",\n * which will carry the signature itself.\n * @return hash we're going to sign off-chain (and validate on-chain)\n */\n function getHash(\n UserOperation calldata userOp,\n address paymasterId\n ) public view returns (bytes32) {\n //can't use userOp.hash(), since it contains also the paymasterAndData itself.\n address sender = userOp.getSender();\n return\n keccak256(\n abi.encode(\n sender,\n userOp.nonce,\n keccak256(userOp.initCode),\n keccak256(userOp.callData),\n userOp.callGasLimit,\n userOp.verificationGasLimit,\n userOp.preVerificationGas,\n userOp.maxFeePerGas,\n userOp.maxPriorityFeePerGas,\n block.chainid,\n address(this),\n paymasterId\n )\n );\n }\n\n /**\n * @dev Verify that an external signer signed the paymaster data of a user operation.\n * The paymaster data is expected to be the paymaster and a signature over the entire request parameters.\n * @param userOp The UserOperation struct that represents the current user operation.\n * userOpHash The hash of the UserOperation struct.\n * @param requiredPreFund The required amount of pre-funding for the paymaster.\n * @return context A context string returned by the entry point after successful validation.\n * @return validationData An integer returned by the entry point after successful validation.\n */\n function _validatePaymasterUserOp(\n UserOperation calldata userOp,\n bytes32 /*userOpHash*/,\n uint256 requiredPreFund\n ) internal override returns (bytes memory context, uint256 validationData) {\n PaymasterData memory paymasterData = userOp._decodePaymasterData();\n bytes32 hash = getHash(userOp, paymasterData.paymasterId);\n uint256 sigLength = paymasterData.signatureLength;\n // we only \"require\" it here so that the revert reason on invalid signature will be of \"VerifyingPaymaster\", and not \"ECDSA\"\n if (sigLength != 65) revert InvalidPaymasterSignatureLength(sigLength);\n //don't revert on signature failure: return SIG_VALIDATION_FAILED\n if (\n verifyingSigner !=\n hash.toEthSignedMessageHash().recover(paymasterData.signature)\n ) {\n // empty context and sigTimeRange 1\n return (\"\", 1);\n }\n if (requiredPreFund > paymasterIdBalances[paymasterData.paymasterId])\n revert InsufficientBalance(\n requiredPreFund,\n paymasterIdBalances[paymasterData.paymasterId]\n );\n return (userOp.paymasterContext(paymasterData, userOp.gasPrice()), 0);\n }\n\n /**\n * @dev Executes the paymaster's payment conditions\n * @param mode tells whether the op succeeded, reverted, or if the op succeeded but cause the postOp to revert\n * @param context payment conditions signed by the paymaster in `validatePaymasterUserOp`\n * @param actualGasCost amount to be paid to the entry point in wei\n */\n function _postOp(\n PostOpMode mode,\n bytes calldata context,\n uint256 actualGasCost\n ) internal virtual override {\n PaymasterContext memory data = context._decodePaymasterContext();\n address extractedPaymasterId = data.paymasterId;\n uint256 balToDeduct = actualGasCost +\n unaccountedEPGasOverhead *\n data.gasPrice;\n paymasterIdBalances[extractedPaymasterId] =\n paymasterIdBalances[extractedPaymasterId] -\n balToDeduct;\n emit GasBalanceDeducted(extractedPaymasterId, balToDeduct);\n }\n}\n"
},
"contracts/smart-contract-wallet/Proxy.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\n/**\n * @title Proxy // This is the user's Smart Account\n * @notice Basic proxy that delegates all calls to a fixed implementation contract.\n * @dev Implementation address is stored in the slot defined by the Proxy's address\n */\ncontract Proxy {\n constructor(address _implementation) {\n require(\n _implementation != address(0),\n \"Invalid implementation address\"\n );\n \n assembly {\n sstore(address(), _implementation)\n }\n }\n\n fallback() external payable {\n address target;\n \n assembly {\n target := sload(address())\n calldatacopy(0, 0, calldatasize())\n let result := delegatecall(gas(), target, 0, calldatasize(), 0, 0)\n returndatacopy(0, 0, returndatasize())\n switch result\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n}\n"
},
"contracts/smart-contract-wallet/SmartAccount.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport {BaseSmartAccount, IEntryPoint, Transaction, FeeRefund, Enum, UserOperation} from \"./BaseSmartAccount.sol\";\nimport {ModuleManager} from \"./base/ModuleManager.sol\";\nimport {FallbackManager} from \"./base/FallbackManager.sol\";\nimport {SignatureDecoder} from \"./common/SignatureDecoder.sol\";\nimport {SecuredTokenTransfer} from \"./common/SecuredTokenTransfer.sol\";\nimport {LibAddress} from \"./libs/LibAddress.sol\";\nimport {ISignatureValidator} from \"./interfaces/ISignatureValidator.sol\";\nimport {Math} from \"./libs/Math.sol\";\nimport {IERC165} from \"./interfaces/IERC165.sol\";\nimport {ReentrancyGuard} from \"./common/ReentrancyGuard.sol\";\nimport {SmartAccountErrors} from \"./common/Errors.sol\";\nimport {ECDSA} from \"@openzeppelin/contracts/utils/cryptography/ECDSA.sol\";\nimport {IModule} from \"./interfaces/IModule.sol\";\n\n/**\n * @title SmartAccount - EIP-4337 compatible smart contract wallet.\n * @dev This contract is the base for the Smart Account functionality.\n * - It provides the functionality to execute both gnosis-style txns and AA (EIP-4337) userOps\n * - It allows to receive and manage assets.\n * - It is responsible for managing the modules and fallbacks.\n * - The Smart Account can be extended with modules, such as Social Recovery, Session Key and others.\n * @author Chirag Titiya - <[email protected]>\n */\ncontract SmartAccount is\n BaseSmartAccount,\n ModuleManager,\n FallbackManager,\n SignatureDecoder,\n SecuredTokenTransfer,\n IERC165,\n ReentrancyGuard,\n SmartAccountErrors,\n ISignatureValidator\n{\n using ECDSA for bytes32;\n using LibAddress for address;\n\n // Storage Version\n string public constant VERSION = \"1.0.0\";\n\n // Domain Seperators keccak256(\"EIP712Domain(uint256 chainId,address verifyingContract)\");\n bytes32 internal constant DOMAIN_SEPARATOR_TYPEHASH =\n 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218;\n\n // keccak256(\n // \"AccountTx(address to,uint256 value,bytes data,uint8 operation,uint256 targetTxGas,uint256 baseGas,uint256 gasPrice,uint256 tokenGasPriceFactor,address gasToken,address refundReceiver,uint256 nonce)\"\n // );\n bytes32 internal constant ACCOUNT_TX_TYPEHASH =\n 0xda033865d68bf4a40a5a7cb4159a99e33dba8569e65ea3e38222eb12d9e66eee;\n\n // Owner storage. Deprecated. Left for storage layout compatibility\n address public deprecatedOwner;\n\n // changed to 2D nonce below\n // @notice there is no _nonce\n mapping(uint256 => uint256) public nonces;\n\n // AA immutable storage\n IEntryPoint private immutable _entryPoint;\n uint256 private immutable _chainId;\n address private immutable _self;\n\n // Events\n\n event ImplementationUpdated(\n address indexed oldImplementation,\n address indexed newImplementation\n );\n event AccountHandlePayment(bytes32 indexed txHash, uint256 indexed payment);\n event SmartAccountReceivedNativeToken(\n address indexed sender,\n uint256 indexed value\n );\n\n /**\n * @dev Constructor that sets the owner of the contract and the entry point contract.\n * modules[SENTINEL_MODULES] = SENTINEL_MODULES protects implementation from initialization\n * @param anEntryPoint The address of the entry point contract.\n */\n constructor(IEntryPoint anEntryPoint) {\n modules[SENTINEL_MODULES] = SENTINEL_MODULES;\n _self = address(this);\n if (address(anEntryPoint) == address(0))\n revert EntryPointCannotBeZero();\n _entryPoint = anEntryPoint;\n _chainId = block.chainid;\n }\n\n /**\n * @dev This function allows the owner or entry point to execute certain actions.\n * If the caller is not authorized, the function will revert with an error message.\n * @notice This modifier is marked as internal and can only be called within the contract itself.\n */\n function _requireFromEntryPointOrSelf() internal view {\n if (msg.sender != address(entryPoint()) && msg.sender != address(this))\n revert CallerIsNotEntryPointOrSelf(msg.sender);\n }\n\n /**\n * @dev This function allows the owner or entry point to execute certain actions.\n * If the caller is not authorized, the function will revert with an error message.\n * @notice This modifier is marked as internal and can only be called within the contract itself.\n */\n function _requireFromEntryPoint() internal view {\n if (msg.sender != address(entryPoint()))\n revert CallerIsNotEntryPoint(msg.sender);\n }\n\n /**\n * @notice All the new implementations MUST have this method!\n * @notice Updates the implementation of the base wallet\n * @param _implementation New wallet implementation\n */\n function updateImplementation(address _implementation) public virtual {\n _requireFromEntryPointOrSelf();\n require(_implementation != address(0), \"Address cannot be zero\");\n if (!_implementation.isContract())\n revert InvalidImplementation(_implementation);\n address oldImplementation;\n \n assembly {\n oldImplementation := sload(address())\n sstore(address(), _implementation)\n }\n emit ImplementationUpdated(oldImplementation, _implementation);\n }\n\n /// Getters\n /**\n * @dev Returns the address of the implementation contract associated with this contract.\n * @notice The implementation address is stored in the contract's storage slot with index 0.\n */\n function getImplementation()\n external\n view\n returns (address _implementation)\n {\n \n assembly {\n _implementation := sload(address())\n }\n }\n\n /**\n * @dev Returns the domain separator for this contract, as defined in the EIP-712 standard.\n * @return bytes32 The domain separator hash.\n */\n function domainSeparator() public view returns (bytes32) {\n return\n keccak256(\n abi.encode(\n DOMAIN_SEPARATOR_TYPEHASH,\n block.chainid,\n address(this)\n )\n );\n }\n\n /**\n * @notice Returns the ID of the chain the contract is currently deployed on.\n * @return _chainId The ID of the current chain as a uint256.\n */\n function getChainId() public view returns (uint256) {\n return _chainId;\n }\n\n /**\n * @dev returns a value from the nonces 2d mapping\n * @param batchId : the key of the user's batch being queried\n * @return nonce : the number of transactions made within said batch\n */\n function getNonce(uint256 batchId) public view virtual returns (uint256) {\n return nonces[batchId];\n }\n\n /**\n * @dev Returns the current entry point used by this account.\n * @return EntryPoint as an `IEntryPoint` interface.\n * @dev This function should be implemented by the subclass to return the current entry point used by this account.\n */\n function entryPoint() public view virtual override returns (IEntryPoint) {\n return _entryPoint;\n }\n\n /**\n * @dev Initialize the Smart Account with required states\n * @param handler Default fallback handler provided in Smart Account\n * @param moduleSetupContract Contract, that setups initial auth module for this smart account. It can be a module factory or\n * a registry module that serves several smart accounts\n * @param moduleSetupData modules setup data (a standard calldata for the module setup contract)\n * @notice devs need to make sure it is only callble once by initiazer or state check restrictions\n * @notice any further implementations that introduces a new state must have a reinit method\n * @notice reinit is not possible, as _initialSetupModules reverts if the account is already initialized\n * which is when there is at least one enabled module\n */\n function init(\n address handler,\n address moduleSetupContract,\n bytes calldata moduleSetupData\n ) external virtual override returns (address) {\n _setFallbackHandler(handler);\n return _initialSetupModules(moduleSetupContract, moduleSetupData);\n }\n\n /**\n * @dev Gnosis style transaction with optional repay in native tokens OR ERC20\n * @dev Allows to execute a transaction confirmed by required signature/s and then pays the account that submitted the transaction.\n * @dev Function name optimized to have hash started with zeros to make this function calls cheaper\n * @notice The fees are always transferred, even if the user transaction fails.\n * @param _tx Smart Account transaction\n * @param refundInfo Required information for gas refunds\n * @param signatures Packed signature/s data ({bytes32 r}{bytes32 s}{uint8 v})\n */\n function execTransaction_S6W(\n Transaction memory _tx,\n FeeRefund memory refundInfo,\n bytes memory signatures\n ) public payable virtual nonReentrant returns (bool success) {\n uint256 startGas = gasleft();\n bytes32 txHash;\n // Use scope here to limit variable lifetime and prevent `stack too deep` errors\n {\n bytes memory txHashData = encodeTransactionData(\n // Transaction info\n _tx,\n // Payment info\n refundInfo,\n // Signature info\n nonces[1]++\n );\n\n txHash = keccak256(txHashData);\n if (isValidSignature(txHash, signatures) != EIP1271_MAGIC_VALUE)\n revert InvalidSignature();\n }\n\n // We require some gas to emit the events (at least 2500) after the execution and some to perform code until the execution (500)\n // We also include the 1/64 in the check that is not send along with a call to counteract potential shortings because of EIP-150\n // Bitshift left 6 bits means multiplying by 64, just more gas efficient\n if (\n gasleft() <\n Math.max((_tx.targetTxGas << 6) / 63, _tx.targetTxGas + 2500) + 500\n )\n revert NotEnoughGasLeft(\n gasleft(),\n Math.max((_tx.targetTxGas << 6) / 63, _tx.targetTxGas + 2500) +\n 500\n );\n // Use scope here to limit variable lifetime and prevent `stack too deep` errors\n {\n // If the gasPrice is 0 we assume that nearly all available gas can be used (it is always more than targetTxGas)\n // We only substract 2500 (compared to the 3000 before) to ensure that the amount passed is still higher than targetTxGas\n success = execute(\n _tx.to,\n _tx.value,\n _tx.data,\n _tx.operation,\n refundInfo.gasPrice == 0 ? (gasleft() - 2500) : _tx.targetTxGas\n );\n // If no targetTxGas and no gasPrice was set (e.g. both are 0), then the internal tx is required to be successful\n // This makes it possible to use `estimateGas` without issues, as it searches for the minimum gas where the tx doesn't revert\n if (!success && _tx.targetTxGas == 0 && refundInfo.gasPrice == 0)\n revert CanNotEstimateGas(\n _tx.targetTxGas,\n refundInfo.gasPrice,\n success\n );\n // We transfer the calculated tx costs to the tx.origin to avoid sending it to intermediate contracts that have made calls\n uint256 payment;\n if (refundInfo.gasPrice != 0) {\n payment = handlePayment(\n startGas - gasleft(),\n refundInfo.baseGas,\n refundInfo.gasPrice,\n refundInfo.tokenGasPriceFactor,\n refundInfo.gasToken,\n refundInfo.refundReceiver\n );\n emit AccountHandlePayment(txHash, payment);\n }\n }\n }\n\n /**\n * @dev Interface function with the standard name for execTransaction_S6W\n */\n function execTransaction(\n Transaction memory _tx,\n FeeRefund memory refundInfo,\n bytes memory signatures\n ) external payable virtual override returns (bool) {\n return execTransaction_S6W(_tx, refundInfo, signatures);\n }\n\n /**\n * @dev Handles the payment for a transaction refund from Smart Account to Relayer.\n * @param gasUsed Gas used by the transaction.\n * @param baseGas Gas costs that are independent of the transaction execution\n * (e.g. base transaction fee, signature check, payment of the refund, emitted events).\n * @param gasPrice Gas price / TokenGasPrice (gas price in the context of token using offchain price feeds)\n * that should be used for the payment calculation.\n * @param tokenGasPriceFactor factor by which calculated token gas price is already multiplied.\n * @param gasToken Token address (or 0 if ETH) that is used for the payment.\n * @return payment The amount of payment made in the specified token.\n */\n function handlePayment(\n uint256 gasUsed,\n uint256 baseGas,\n uint256 gasPrice,\n uint256 tokenGasPriceFactor,\n address gasToken,\n address payable refundReceiver\n ) private returns (uint256 payment) {\n if (tokenGasPriceFactor == 0) revert TokenGasPriceFactorCanNotBeZero();\n // solhint-disable-next-line avoid-tx-origin\n address payable receiver = refundReceiver == address(0)\n ? payable(tx.origin)\n : refundReceiver;\n if (gasToken == address(0)) {\n // For ETH we will only adjust the gas price to not be higher than the actual used gas price\n payment =\n (gasUsed + baseGas) *\n (gasPrice < tx.gasprice ? gasPrice : tx.gasprice);\n bool success;\n assembly {\n success := call(gas(), receiver, payment, 0, 0, 0, 0)\n }\n if (!success)\n revert TokenTransferFailed(address(0), receiver, payment);\n } else {\n payment =\n ((gasUsed + baseGas) * (gasPrice)) /\n (tokenGasPriceFactor);\n if (!transferToken(gasToken, receiver, payment))\n revert TokenTransferFailed(gasToken, receiver, payment);\n }\n }\n\n /**\n * @dev Allows to estimate a transaction.\n * @notice This method is only meant for estimation purpose, therefore the call will always revert and encode the result in the revert data.\n * @notice Call this method to get an estimate of the handlePayment costs that are deducted with `execTransaction`\n * @param gasUsed Gas used by the transaction.\n * @param baseGas Gas costs that are independent of the transaction execution\n * (e.g. base transaction fee, signature check, payment of the refund, emitted events).\n * @param gasPrice Gas price / TokenGasPrice (gas price in the context of token using offchain price feeds)\n * that should be used for the payment calculation.\n * @param tokenGasPriceFactor factor by which calculated token gas price is already multiplied.\n * @param gasToken Token address (or 0 if ETH) that is used for the payment.\n * @return requiredGas Estimate of refunds\n */\n function handlePaymentRevert(\n uint256 gasUsed,\n uint256 baseGas,\n uint256 gasPrice,\n uint256 tokenGasPriceFactor,\n address gasToken,\n address payable refundReceiver\n ) external returns (uint256 requiredGas) {\n require(tokenGasPriceFactor != 0, \"invalid tokenGasPriceFactor\");\n uint256 startGas = gasleft();\n // solhint-disable-next-line avoid-tx-origin\n address payable receiver = refundReceiver == address(0)\n ? payable(tx.origin)\n : refundReceiver;\n if (gasToken == address(0)) {\n // For ETH we will only adjust the gas price to not be higher than the actual used gas price\n uint256 payment = (gasUsed + baseGas) *\n (gasPrice < tx.gasprice ? gasPrice : tx.gasprice);\n bool success;\n assembly {\n success := call(gas(), receiver, payment, 0, 0, 0, 0)\n }\n if (!success)\n revert TokenTransferFailed(address(0), receiver, payment);\n } else {\n uint256 payment = ((gasUsed + baseGas) * (gasPrice)) /\n (tokenGasPriceFactor);\n if (!transferToken(gasToken, receiver, payment))\n revert TokenTransferFailed(gasToken, receiver, payment);\n }\n unchecked {\n requiredGas = startGas - gasleft();\n }\n revert(string(abi.encodePacked(requiredGas)));\n }\n\n /**\n * @dev Allows to estimate a transaction.\n * This method is only meant for estimation purpose, therefore the call will always revert and encode the result in the revert data.\n * Since the `estimateGas` function includes refunds, call this method to get an estimated of the costs that are deducted from the wallet with `execTransaction`\n * @param to Destination address of the transaction.\n * @param value Ether value of transaction.\n * @param data Data payload of transaction.\n * @param operation Operation type of transaction.\n * @return Estimate without refunds and overhead fees (base transaction and payload data gas costs).\n */\n function requiredTxGas(\n address to,\n uint256 value,\n bytes calldata data,\n Enum.Operation operation\n ) external returns (uint256) {\n uint256 startGas = gasleft();\n // We don't provide an error message here, as we use it to return the estimate\n if (!execute(to, value, data, operation, gasleft()))\n revert ExecutionFailed();\n // Convert response to string and return via error message\n unchecked {\n revert(string(abi.encodePacked(startGas - gasleft())));\n }\n }\n\n /**\n * @dev Returns hash to be signed by owner.\n * @param to Destination address.\n * @param value Ether value.\n * @param data Data payload.\n * @param operation Operation type.\n * @param targetTxGas Fas that should be used for the internal Smart Account transaction.\n * @param baseGas Additional Gas costs for data used to trigger the transaction.\n * @param gasPrice Maximum gas price/ token gas price that should be used for this transaction.\n * @param tokenGasPriceFactor factor by which calculated token gas price is already multiplied.\n * @param gasToken Token address (or 0 if ETH) that is used for the payment.\n * @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).\n * @param _nonce Transaction nonce.\n * @return Transaction hash.\n */\n function getTransactionHash(\n address to,\n uint256 value,\n bytes calldata data,\n Enum.Operation operation,\n uint256 targetTxGas,\n uint256 baseGas,\n uint256 gasPrice,\n uint256 tokenGasPriceFactor,\n address gasToken,\n address payable refundReceiver,\n uint256 _nonce\n ) public view returns (bytes32) {\n Transaction memory _tx = Transaction({\n to: to,\n value: value,\n data: data,\n operation: operation,\n targetTxGas: targetTxGas\n });\n FeeRefund memory refundInfo = FeeRefund({\n baseGas: baseGas,\n gasPrice: gasPrice,\n tokenGasPriceFactor: tokenGasPriceFactor,\n gasToken: gasToken,\n refundReceiver: refundReceiver\n });\n return keccak256(encodeTransactionData(_tx, refundInfo, _nonce));\n }\n\n /**\n * @dev Returns the bytes that are hashed to be signed by owner.\n * @param _tx The wallet transaction to be signed.\n * @param refundInfo Required information for gas refunds.\n * @param _nonce Transaction nonce.\n * @return transactionHash bytes that are hashed to be signed by the owner.\n */\n function encodeTransactionData(\n Transaction memory _tx,\n FeeRefund memory refundInfo,\n uint256 _nonce\n ) public view returns (bytes memory) {\n bytes32 accountTxHash = keccak256(\n abi.encode(\n ACCOUNT_TX_TYPEHASH,\n _tx.to,\n _tx.value,\n keccak256(_tx.data),\n _tx.operation,\n _tx.targetTxGas,\n refundInfo.baseGas,\n refundInfo.gasPrice,\n refundInfo.tokenGasPriceFactor,\n refundInfo.gasToken,\n refundInfo.refundReceiver,\n _nonce\n )\n );\n return\n bytes.concat(\n bytes1(0x19),\n bytes1(0x01),\n domainSeparator(),\n accountTxHash\n );\n }\n\n /**\n * @dev Execute a transaction (called directly from owner, or by entryPoint)\n * @notice Name is optimized for this method to be cheaper to be called\n * @param dest Address of the contract to call\n * @param value Amount of native tokens to send along with the transaction\n * @param func Data of the transaction\n */\n function executeCall_s1m(\n address dest,\n uint256 value,\n bytes calldata func\n ) public {\n _requireFromEntryPoint();\n _call(dest, value, func);\n }\n\n /**\n * @dev Interface function with the standard name for executeCall_s1m\n * @param dest Address of the contract to call\n * @param value Amount of native tokens to send along with the transaction\n * @param func Data of the transaction\n */\n function executeCall(\n address dest,\n uint256 value,\n bytes calldata func\n ) external {\n executeCall_s1m(dest, value, func);\n }\n\n /**\n * @dev Execute a sequence of transactions\n * @notice Name is optimized for this method to be cheaper to be called\n * @param dest Addresses of the contracts to call\n * @param value Amounts of native tokens to send along with the transactions\n * @param func Data of the transactions\n */\n function executeBatchCall_4by(\n address[] calldata dest,\n uint256[] calldata value,\n bytes[] calldata func\n ) public {\n _requireFromEntryPoint();\n if (\n dest.length == 0 ||\n dest.length != value.length ||\n value.length != func.length\n ) revert WrongBatchProvided(dest.length, value.length, func.length, 0);\n for (uint256 i; i < dest.length; ) {\n _call(dest[i], value[i], func[i]);\n unchecked {\n ++i;\n }\n }\n }\n\n /**\n * @dev Interface function with the standard name for executeBatchCall_4by\n * @param dest Addresses of the contracts to call\n * @param value Amounts of native tokens to send along with the transactions\n * @param func Data of the transactions\n */\n function executeBatchCall(\n address[] calldata dest,\n uint256[] calldata value,\n bytes[] calldata func\n ) external {\n executeBatchCall_4by(dest, value, func);\n }\n\n /**\n * @dev internal method that fecilitates the extenral calls from SmartAccount\n * @dev similar to execute() of Executor.sol\n * @param target destination address contract/non-contract\n * @param value amount of native tokens\n * @param data function singature of destination\n */\n function _call(address target, uint256 value, bytes memory data) internal {\n assembly {\n let success := call(\n gas(),\n target,\n value,\n add(data, 0x20),\n mload(data),\n 0,\n 0\n )\n let ptr := mload(0x40)\n returndatacopy(ptr, 0, returndatasize())\n if iszero(success) {\n revert(ptr, returndatasize())\n }\n }\n }\n\n function validateUserOp(\n UserOperation calldata userOp,\n bytes32 userOpHash,\n uint256 missingAccountFunds\n ) external virtual override returns (uint256 validationData) {\n if (msg.sender != address(entryPoint()))\n revert CallerIsNotAnEntryPoint(msg.sender);\n\n (, address validationModule) = abi.decode(\n userOp.signature,\n (bytes, address)\n );\n if (address(modules[validationModule]) != address(0)) {\n validationData = IModule(validationModule).validateUserOp(\n userOp,\n userOpHash\n );\n } else {\n revert WrongValidationModule(validationModule);\n }\n _validateNonce(userOp.nonce);\n _payPrefund(missingAccountFunds);\n }\n\n /**\n * Implementation of ISignatureValidator (see `interfaces/ISignatureValidator.sol`)\n * @dev If owner is a smart-contract (other smart contract wallet or module, that controls\n * signature verifications - like multisig), forward isValidSignature request to it.\n * In case of multisig, _signature can be several concatenated signatures\n * If owner is EOA, perform a regular ecrecover.\n * @param ethSignedDataHash 32 bytes hash of the data signed on the behalf of address(msg.sender)\n * prepended with '\\x19Ethereum Signed Message:\\n'\n * @param signature Signature byte array associated with ethSignedDataHash\n * @return bytes4 value.\n */\n function isValidSignature(\n bytes32 ethSignedDataHash,\n bytes memory signature\n ) public view override returns (bytes4) {\n (bytes memory moduleSignature, address validationModule) = abi.decode(\n signature,\n (bytes, address)\n );\n if (address(modules[validationModule]) != address(0)) {\n return\n ISignatureValidator(validationModule).isValidSignature(\n ethSignedDataHash,\n moduleSignature\n );\n } else {\n revert WrongValidationModule(validationModule);\n }\n }\n\n /**\n * @dev Check current account deposit in the entryPoint\n */\n function getDeposit() public view returns (uint256) {\n return entryPoint().balanceOf(address(this));\n }\n\n /**\n * @dev Deposit more funds for this account in the entryPoint\n */\n function addDeposit() public payable {\n entryPoint().depositTo{value: msg.value}(address(this));\n }\n\n /**\n * @dev Withdraw value from the account's deposit\n * @param withdrawAddress target to send to\n * @param amount to withdraw\n */\n function withdrawDepositTo(\n address payable withdrawAddress,\n uint256 amount\n ) public payable {\n _requireFromEntryPointOrSelf();\n entryPoint().withdrawTo(withdrawAddress, amount);\n }\n\n /**\n * @dev Adds a module to the allowlist.\n * @notice This can only be done via a userOp or a selfcall.\n * @notice Enables the module `module` for the wallet.\n * @param module Module to be allow-listed.\n */\n function enableModule(address module) external virtual override {\n _requireFromEntryPointOrSelf();\n _enableModule(module);\n }\n\n /**\n * @dev Setups module for this Smart Account and enables it.\n * @notice This can only be done via userOp or a selfcall.\n * @notice Enables the module `module` for the wallet.\n */\n function setupAndEnableModule(\n address setupContract,\n bytes memory setupData\n ) external virtual override returns (address) {\n _requireFromEntryPointOrSelf();\n return _setupAndEnableModule(setupContract, setupData);\n }\n\n /**\n * @dev Removes a module from the allowlist.\n * @notice This can only be done via a wallet transaction.\n * @notice Disables the module `module` for the wallet.\n * @param prevModule Module that pointed to the module to be removed in the linked list\n * @param module Module to be removed.\n */\n function disableModule(address prevModule, address module) public virtual {\n _requireFromEntryPointOrSelf();\n _disableModule(prevModule, module);\n }\n\n /**\n * @notice Query if a contract implements an interface\n * @param _interfaceId The interface identifier, as specified in ERC165\n * @return `true` if the contract implements `_interfaceID`\n */\n function supportsInterface(\n bytes4 _interfaceId\n ) external view virtual override returns (bool) {\n return _interfaceId == type(IERC165).interfaceId; // 0x01ffc9a7\n }\n\n /**\n * @dev This function is a special fallback function that is triggered when the contract receives Ether.\n * It logs an event indicating the amount of Ether received and the sender's address.\n * @notice This function is marked as external and payable, meaning it can be called from external\n * sources and accepts Ether as payment.\n */\n receive() external payable {\n if (address(this) == _self) revert DelegateCallsOnly();\n emit SmartAccountReceivedNativeToken(msg.sender, msg.value);\n }\n}\n"
},
"contracts/smart-contract-wallet/SmartAccountFactory.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport \"./Proxy.sol\";\nimport \"./BaseSmartAccount.sol\";\nimport {DefaultCallbackHandler} from \"./handler/DefaultCallbackHandler.sol\";\nimport {SmartAccountFactoryErrors} from \"./common/Errors.sol\";\n\n/**\n * @title Smart Account Factory - factory responsible for deploying Smart Accounts using CREATE2 and CREATE\n * @dev It deploys Smart Accounts as proxies pointing to `basicImplementation` that is immutable.\n * This allows keeping the same address for the same Smart Account owner on various chains via CREATE2\n * @author Chirag Titiya - <[email protected]>\n */\ncontract SmartAccountFactory {\n address public immutable basicImplementation;\n DefaultCallbackHandler public immutable minimalHandler;\n\n event AccountCreation(\n address indexed account,\n address indexed owner,\n uint256 indexed index\n );\n event AccountCreationWithoutIndex(\n address indexed account,\n address indexed owner\n );\n\n constructor(address _basicImplementation) {\n require(\n _basicImplementation != address(0),\n \"implementation cannot be zero\"\n );\n basicImplementation = _basicImplementation;\n minimalHandler = new DefaultCallbackHandler();\n }\n\n /**\n * @dev Allows to retrieve the creation code used for the Proxy deployment.\n * @return The creation code for the Proxy.\n */\n function accountCreationCode() public pure returns (bytes memory) {\n return type(Proxy).creationCode;\n }\n\n /**\n * @notice Deploys account using create2 and points it to basicImplementation\n *\n * @param index extra salt that allows to deploy more account if needed for same EOA (default 0)\n */\n function deployCounterFactualAccount(\n address moduleSetupContract,\n bytes calldata moduleSetupData,\n uint256 index\n ) public returns (address proxy) {\n // create initializer data based on init method and parameters\n bytes memory initializer = getInitializer(\n moduleSetupContract,\n moduleSetupData\n );\n bytes32 salt = keccak256(\n abi.encodePacked(keccak256(initializer), index)\n );\n\n bytes memory deploymentData = abi.encodePacked(\n type(Proxy).creationCode,\n uint256(uint160(basicImplementation))\n );\n\n \n assembly {\n proxy := create2(\n 0x0,\n add(0x20, deploymentData),\n mload(deploymentData),\n salt\n )\n }\n require(address(proxy) != address(0), \"Create2 call failed\");\n\n address initialAuthorizationModule;\n\n if (initializer.length > 0) {\n \n assembly {\n let success := call(\n gas(),\n proxy,\n 0,\n add(initializer, 0x20),\n mload(initializer),\n 0,\n 0\n )\n let ptr := mload(0x40)\n returndatacopy(ptr, 0, returndatasize())\n if iszero(success) {\n revert(ptr, returndatasize())\n }\n initialAuthorizationModule := mload(ptr)\n }\n }\n emit AccountCreation(proxy, initialAuthorizationModule, index);\n }\n\n /**\n * @notice Deploys account using create and points it to _implementation\n \n * @return proxy address of the deployed account\n */\n function deployAccount(\n address moduleSetupContract,\n bytes calldata moduleSetupData\n ) public returns (address proxy) {\n bytes memory deploymentData = abi.encodePacked(\n type(Proxy).creationCode,\n uint256(uint160(basicImplementation))\n );\n\n \n assembly {\n proxy := create(\n 0x0,\n add(0x20, deploymentData),\n mload(deploymentData)\n )\n }\n require(address(proxy) != address(0), \"Create call failed\");\n\n bytes memory initializer = getInitializer(\n moduleSetupContract,\n moduleSetupData\n );\n address initialAuthorizationModule;\n\n if (initializer.length > 0) {\n \n assembly {\n let success := call(\n gas(),\n proxy,\n 0,\n add(initializer, 0x20),\n mload(initializer),\n 0,\n 0\n )\n let ptr := mload(0x40)\n returndatacopy(ptr, 0, returndatasize())\n if iszero(success) {\n revert(ptr, returndatasize())\n }\n initialAuthorizationModule := mload(ptr)\n }\n }\n emit AccountCreationWithoutIndex(proxy, initialAuthorizationModule);\n }\n\n /**\n * @dev Allows to retrieve the initializer data for the account.\n * @param moduleSetupContract Contract, that setups initial auth module for this smart account. It can be a module factory or\n * a registry module that serves several smart accounts\n * @param moduleSetupData modules setup data (a standard calldata for the module setup contract)\n * @return initializer bytes for init method\n */\n function getInitializer(\n address moduleSetupContract,\n bytes calldata moduleSetupData\n ) internal view returns (bytes memory) {\n return\n abi.encodeCall(\n BaseSmartAccount.init,\n (address(minimalHandler), moduleSetupContract, moduleSetupData)\n );\n }\n\n /**\n * @notice Allows to find out account address prior to deployment\n \n * @param index extra salt that allows to deploy more accounts if needed for same EOA (default 0)\n */\n function getAddressForCounterFactualAccount(\n address moduleSetupContract,\n bytes calldata moduleSetupData,\n uint256 index\n ) external view returns (address _account) {\n // create initializer data based on init method, _owner and minimalHandler\n bytes memory initializer = getInitializer(\n moduleSetupContract,\n moduleSetupData\n );\n bytes memory code = abi.encodePacked(\n type(Proxy).creationCode,\n uint256(uint160(basicImplementation))\n );\n bytes32 salt = keccak256(\n abi.encodePacked(keccak256(initializer), index)\n );\n bytes32 hash = keccak256(\n abi.encodePacked(bytes1(0xff), address(this), salt, keccak256(code))\n );\n _account = address(uint160(uint256(hash)));\n }\n // off-chain calculation\n // return ethers.utils.getCreate2Address(<factory address>, <create2 salt>, ethers.utils.keccak256(creationCode + implementation));\n}\n"
},
"contracts/smart-contract-wallet/SmartAccountNoAuth.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport \"./libs/LibAddress.sol\";\nimport \"./BaseSmartAccount.sol\";\nimport \"./base/ModuleManager.sol\";\nimport \"./base/FallbackManager.sol\";\nimport \"./common/SignatureDecoder.sol\";\nimport \"./common/SecuredTokenTransfer.sol\";\nimport {SmartAccountErrors} from \"./common/Errors.sol\";\nimport \"./interfaces/ISignatureValidator.sol\";\nimport \"./interfaces/IERC165.sol\";\nimport \"@openzeppelin/contracts/utils/cryptography/ECDSA.sol\";\nimport {IModule} from \"./interfaces/IModule.sol\";\n\nabstract contract SmartAccountNoAuth is\n BaseSmartAccount,\n ModuleManager,\n FallbackManager,\n SignatureDecoder,\n SecuredTokenTransfer,\n ISignatureValidatorConstants,\n IERC165,\n SmartAccountErrors\n{\n using ECDSA for bytes32;\n using LibAddress for address;\n\n // Storage\n\n // Version\n string public constant VERSION = \"1.0.0\"; // aa 0.4.0 rebase\n\n // Domain Seperators\n // keccak256(\n // \"EIP712Domain(uint256 chainId,address verifyingContract)\"\n // );\n bytes32 internal constant DOMAIN_SEPARATOR_TYPEHASH =\n 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218;\n\n // keccak256(\n // \"WalletTx(address to,uint256 value,bytes data,uint8 operation,uint256 targetTxGas,uint256 baseGas,uint256 gasPrice,address gasToken,address refundReceiver,uint256 nonce)\"\n // );\n bytes32 internal constant ACCOUNT_TX_TYPEHASH =\n 0xeedfef42e81fe8cd0e4185e4320e9f8d52fd97eb890b85fa9bd7ad97c9a18de2;\n\n // Owner storage\n address public owner;\n\n // uint96 private _nonce; //changed to 2D nonce below\n // @notice there is no _nonce\n mapping(uint256 => uint256) public nonces;\n\n // AA storage\n IEntryPoint private immutable _entryPoint;\n\n uint256 public immutable _chainId;\n\n // This constructor ensures that this contract can only be used as a master copy for Proxy accounts\n constructor(IEntryPoint anEntryPoint) {\n // By setting the owner it is not possible to call init anymore,\n // so we create an account with fixed non-zero owner.\n // This is an unusable account, perfect for the singleton\n owner = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);\n require(address(anEntryPoint) != address(0), \"Invalid Entrypoint\");\n _entryPoint = anEntryPoint;\n _chainId = block.chainid;\n }\n\n // Events\n event ImplementationUpdated(\n address indexed oldImplementation,\n address indexed newImplementation\n );\n\n event EOAChanged(\n address indexed _scw,\n address indexed _oldEOA,\n address indexed _newEOA\n );\n event AccountHandlePayment(bytes32 indexed txHash, uint256 indexed payment);\n\n // modifiers\n // onlyOwner\n /**\n * @notice Throws error if the sender is not an owner.\n */\n modifier onlyOwner() {\n require(\n msg.sender == owner,\n \"Smart Account:: Sender is not authorized\"\n );\n _;\n }\n\n // onlyOwner OR self\n modifier mixedAuth() {\n require(\n msg.sender == owner || msg.sender == address(this),\n \"Only owner or self\"\n );\n _;\n }\n\n function entryPoint() public view virtual override returns (IEntryPoint) {\n return _entryPoint;\n }\n\n // @notice authorized modifier (onlySelf) is already inherited\n\n // Setters\n\n function setOwner(address _newOwner) public mixedAuth {\n require(\n _newOwner != address(0),\n \"Smart Account:: new Signatory address cannot be zero\"\n );\n address oldOwner = owner;\n owner = _newOwner;\n emit EOAChanged(address(this), oldOwner, _newOwner);\n }\n\n /**\n * @notice Updates the implementation of the base wallet\n * @param _implementation New wallet implementation\n */\n function updateImplementation(address _implementation) public mixedAuth {\n require(_implementation.isContract(), \"INVALID_IMPLEMENTATION\");\n \n address oldImplementation;\n assembly {\n oldImplementation := sload(address())\n sstore(address(), _implementation)\n }\n emit ImplementationUpdated(oldImplementation, _implementation);\n }\n\n // Getters\n\n function domainSeparator() public view returns (bytes32) {\n return\n keccak256(\n abi.encode(\n DOMAIN_SEPARATOR_TYPEHASH,\n getChainId(),\n address(this)\n )\n );\n }\n\n /// @dev Returns the chain id used by this contract.\n function getChainId() public view returns (uint256) {\n return _chainId;\n }\n\n /**\n * @dev returns a value from the nonces 2d mapping\n * @param batchId : the key of the user's batch being queried\n * @return nonce : the number of transaction made within said batch\n */\n function getNonce(uint256 batchId) public view returns (uint256) {\n return nonces[batchId];\n }\n\n // init\n // Initialize / Setup\n // Used to setup\n // i. owner ii. entry point address iii. handler\n function init(\n address handler,\n address moduleSetupContract,\n bytes calldata moduleSetupData\n ) external virtual override returns (address) {\n _setFallbackHandler(handler);\n return _initialSetupModules(moduleSetupContract, moduleSetupData);\n }\n\n // Gnosis style transaction with optional repay in native tokens OR ERC20\n /**\n * @dev Allows to execute a Safe transaction confirmed by required number of owners and then pays the account that submitted the transaction.\n * @notice The fees are always transferred, even if the user transaction fails.\n * @param _tx Wallet transaction\n * @param refundInfo Required information for gas refunds\n * @param signatures Packed signature data ({bytes32 r}{bytes32 s}{uint8 v})\n */\n function execTransaction(\n Transaction memory _tx,\n FeeRefund memory refundInfo,\n bytes memory signatures\n ) external payable virtual override returns (bool success) {\n uint256 startGas = gasleft();\n bytes32 txHash;\n // Use scope here to limit variable lifetime and prevent `stack too deep` errors\n {\n bytes memory txHashData = encodeTransactionData(\n // Transaction info\n _tx,\n // Payment info\n refundInfo,\n // Signature info\n nonces[1]++\n );\n // Execute transaction.\n txHash = keccak256(txHashData);\n checkSignatures(txHash, txHashData, signatures);\n }\n\n // We require some gas to emit the events (at least 2500) after the execution and some to perform code until the execution (500)\n // We also include the 1/64 in the check that is not send along with a call to counteract potential shortings because of EIP-150\n // Bitshift left 6 bits means multiplying by 64, just more gas efficient\n require(\n gasleft() >=\n Math.max((_tx.targetTxGas << 6) / 63, _tx.targetTxGas + 2500) +\n 500,\n \"BSA010\"\n );\n // Use scope here to limit variable lifetime and prevent `stack too deep` errors\n {\n // If the gasPrice is 0 we assume that nearly all available gas can be used (it is always more than targetTxGas)\n // We only substract 2500 (compared to the 3000 before) to ensure that the amount passed is still higher than targetTxGas\n success = execute(\n _tx.to,\n _tx.value,\n _tx.data,\n _tx.operation,\n refundInfo.gasPrice == 0 ? (gasleft() - 2500) : _tx.targetTxGas\n );\n // If no targetTxGas and no gasPrice was set (e.g. both are 0), then the internal tx is required to be successful\n // This makes it possible to use `estimateGas` without issues, as it searches for the minimum gas where the tx doesn't revert\n require(\n success || _tx.targetTxGas != 0 || refundInfo.gasPrice != 0,\n \"BSA013\"\n );\n // We transfer the calculated tx costs to the tx.origin to avoid sending it to intermediate contracts that have made calls\n uint256 payment;\n // uint256 extraGas;\n if (refundInfo.gasPrice != 0) {\n //console.log(\"sent %s\", startGas - gasleft());\n // extraGas = gasleft();\n payment = handlePayment(\n startGas - gasleft(),\n refundInfo.baseGas,\n refundInfo.gasPrice,\n refundInfo.tokenGasPriceFactor,\n refundInfo.gasToken,\n refundInfo.refundReceiver\n );\n emit AccountHandlePayment(txHash, payment);\n }\n // extraGas = extraGas - gasleft();\n //console.log(\"extra gas %s \", extraGas);\n }\n }\n\n function handlePayment(\n uint256 gasUsed,\n uint256 baseGas,\n uint256 gasPrice,\n uint256 tokenGasPriceFactor,\n address gasToken,\n address payable refundReceiver\n ) public returns (uint256 payment) {\n require(tokenGasPriceFactor != 0, \"invalid tokenGasPriceFactor\");\n // uint256 startGas = gasleft();\n // solhint-disable-next-line avoid-tx-origin\n address payable receiver = refundReceiver == address(0)\n ? payable(tx.origin)\n : refundReceiver;\n if (gasToken == address(0)) {\n // For ETH we will only adjust the gas price to not be higher than the actual used gas price\n payment =\n (gasUsed + baseGas) *\n (gasPrice < tx.gasprice ? gasPrice : tx.gasprice);\n (bool success, ) = receiver.call{value: payment}(\"\");\n require(success, \"BSA011\");\n } else {\n payment =\n ((gasUsed + baseGas) * (gasPrice)) /\n (tokenGasPriceFactor);\n require(transferToken(gasToken, receiver, payment), \"BSA012\");\n }\n // uint256 requiredGas = startGas - gasleft();\n //console.log(\"hp %s\", requiredGas);\n }\n\n function handlePaymentRevert(\n uint256 gasUsed,\n uint256 baseGas,\n uint256 gasPrice,\n uint256 tokenGasPriceFactor,\n address gasToken,\n address payable refundReceiver\n ) external returns (uint256 payment) {\n require(tokenGasPriceFactor != 0, \"invalid tokenGasPriceFactor\");\n // solhint-disable-next-line avoid-tx-origin\n address payable receiver = refundReceiver == address(0)\n ? payable(tx.origin)\n : refundReceiver;\n if (gasToken == address(0)) {\n // For ETH we will only adjust the gas price to not be higher than the actual used gas price\n payment =\n (gasUsed + baseGas) *\n (gasPrice < tx.gasprice ? gasPrice : tx.gasprice);\n (bool success, ) = receiver.call{value: payment}(\"\");\n require(success, \"BSA011\");\n } else {\n payment =\n ((gasUsed + baseGas) * (gasPrice)) /\n (tokenGasPriceFactor);\n require(transferToken(gasToken, receiver, payment), \"BSA012\");\n }\n }\n\n /**\n * @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise.\n * @param dataHash Hash of the data (could be either a message hash or transaction hash)\n * @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash.\n */\n function checkSignatures(\n bytes32 dataHash,\n bytes memory data,\n bytes memory signatures\n ) public view virtual {\n uint8 v;\n bytes32 r;\n bytes32 s;\n address _signer;\n (v, r, s) = signatureSplit(signatures);\n if (v == 0) {\n // If v is 0 then it is a contract signature\n // When handling contract signatures the address of the contract is encoded into r\n _signer = address(uint160(uint256(r)));\n\n // Check that signature data pointer (s) is not pointing inside the static part of the signatures bytes\n // This check is not completely accurate, since it is possible that more signatures than the threshold are send.\n // Here we only check that the pointer is not pointing inside the part that is being processed\n require(uint256(s) >= uint256(1) * 65, \"BSA021\");\n\n // Check that signature data pointer (s) is in bounds (points to the length of data -> 32 bytes)\n require(uint256(s) + 32 <= signatures.length, \"BSA022\");\n\n // Check if the contract signature is in bounds: start of data is s + 32 and end is start + signature length\n uint256 contractSignatureLen;\n \n assembly {\n contractSignatureLen := mload(add(add(signatures, s), 0x20))\n }\n require(\n uint256(s) + 32 + contractSignatureLen <= signatures.length,\n \"BSA023\"\n );\n\n // Check signature\n bytes memory contractSignature;\n \n assembly {\n // The signature data for contract signatures is appended to the concatenated signatures and the offset is stored in s\n contractSignature := add(add(signatures, s), 0x20)\n }\n require(\n ISignatureValidator(_signer).isValidSignature(\n dataHash,\n contractSignature\n ) == EIP1271_MAGIC_VALUE,\n \"BSA024\"\n );\n } else if (v > 30) {\n // If v > 30 then default va (27,28) has been adjusted for eth_sign flow\n // To support eth_sign and similar we adjust v and hash the messageHash with the Ethereum message prefix before applying ecrecover\n (_signer, ) = dataHash.toEthSignedMessageHash().tryRecover(\n v - 4,\n r,\n s\n );\n } else {\n (_signer, ) = dataHash.tryRecover(v, r, s);\n }\n require(_signer == owner || true, \"INVALID_SIGNATURE\");\n }\n\n /// @dev Allows to estimate a transaction.\n /// This method is only meant for estimation purpose, therefore the call will always revert and encode the result in the revert data.\n /// Since the `estimateGas` function includes refunds, call this method to get an estimated of the costs that are deducted from the safe with `execTransaction`\n /// @param to Destination address of Safe transaction.\n /// @param value Ether value of transaction.\n /// @param data Data payload of transaction.\n /// @param operation Operation type of transaction.\n function requiredTxGas(\n address to,\n uint256 value,\n bytes calldata data,\n Enum.Operation operation\n ) external {\n // We don't provide an error message here, as we use it to return the estimate\n require(execute(to, value, data, operation, gasleft()));\n }\n\n /// @dev Returns hash to be signed by owner.\n /// @param to Destination address.\n /// @param value Ether value.\n /// @param data Data payload.\n /// @param operation Operation type.\n /// @param targetTxGas Fas that should be used for the safe transaction.\n /// @param baseGas Gas costs for data used to trigger the safe transaction.\n /// @param gasPrice Maximum gas price that should be used for this transaction.\n /// @param gasToken Token address (or 0 if ETH) that is used for the payment.\n /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).\n /// @param _nonce Transaction nonce.\n /// @return Transaction hash.\n function getTransactionHash(\n address to,\n uint256 value,\n bytes calldata data,\n Enum.Operation operation,\n uint256 targetTxGas,\n uint256 baseGas,\n uint256 gasPrice,\n uint256 tokenGasPriceFactor,\n address gasToken,\n address payable refundReceiver,\n uint256 _nonce\n ) public view returns (bytes32) {\n Transaction memory _tx = Transaction({\n to: to,\n value: value,\n data: data,\n operation: operation,\n targetTxGas: targetTxGas\n });\n FeeRefund memory refundInfo = FeeRefund({\n baseGas: baseGas,\n gasPrice: gasPrice,\n tokenGasPriceFactor: tokenGasPriceFactor,\n gasToken: gasToken,\n refundReceiver: refundReceiver\n });\n return keccak256(encodeTransactionData(_tx, refundInfo, _nonce));\n }\n\n /// @dev Returns the bytes that are hashed to be signed by owner.\n /// @param _tx Wallet transaction\n /// @param refundInfo Required information for gas refunds\n /// @param _nonce Transaction nonce.\n /// @return Transaction hash bytes.\n function encodeTransactionData(\n Transaction memory _tx,\n FeeRefund memory refundInfo,\n uint256 _nonce\n ) public view returns (bytes memory) {\n bytes32 accountTxHash = keccak256(\n abi.encode(\n ACCOUNT_TX_TYPEHASH,\n _tx.to,\n _tx.value,\n keccak256(_tx.data),\n _tx.operation,\n _tx.targetTxGas,\n refundInfo.baseGas,\n refundInfo.gasPrice,\n refundInfo.gasToken,\n refundInfo.refundReceiver,\n _nonce\n )\n );\n return\n bytes.concat(\n bytes1(0x19),\n bytes1(0x01),\n domainSeparator(),\n accountTxHash\n );\n }\n\n // Extra Utils\n function transfer(address payable dest, uint256 amount) external onlyOwner {\n require(dest != address(0), \"this action will burn your funds\");\n (bool success, ) = dest.call{value: amount}(\"\");\n require(success, \"transfer failed\");\n }\n\n function pullTokens(\n address token,\n address dest,\n uint256 amount\n ) external onlyOwner {\n if (!transferToken(token, dest, amount))\n revert TokenTransferFailed(token, dest, amount);\n }\n\n function execute(\n address dest,\n uint256 value,\n bytes calldata func\n ) external {\n _requireFromEntryPointOrOwner();\n _call(dest, value, func);\n }\n\n function executeBatch(\n address[] calldata dest,\n bytes[] calldata func\n ) external {\n _requireFromEntryPointOrOwner();\n require(dest.length == func.length, \"wrong array lengths\");\n for (uint256 i = 0; i < dest.length; ) {\n _call(dest[i], 0, func[i]);\n unchecked {\n ++i;\n }\n }\n }\n\n // AA implementation\n function _call(address target, uint256 value, bytes memory data) internal {\n (bool success, bytes memory result) = target.call{value: value}(data);\n if (!success) {\n assembly {\n revert(add(result, 32), mload(result))\n }\n }\n }\n\n function _requireFromEntryPointOrOwner() internal view {\n require(\n msg.sender == address(entryPoint()) || msg.sender == owner,\n \"account: not Owner or EntryPoint\"\n );\n }\n\n function validateUserOp(\n UserOperation calldata userOp,\n bytes32 userOpHash,\n uint256 missingAccountFunds\n ) external virtual override returns (uint256 validationData) {\n if (msg.sender != address(entryPoint()))\n revert CallerIsNotAnEntryPoint(msg.sender);\n\n (, address validationModule) = abi.decode(\n userOp.signature,\n (bytes, address)\n );\n if (address(modules[validationModule]) != address(0)) {\n validationData = IModule(validationModule).validateUserOp(\n userOp,\n userOpHash\n );\n } else {\n revert WrongValidationModule(validationModule);\n }\n _validateNonce(userOp.nonce);\n _payPrefund(missingAccountFunds);\n }\n\n /**\n * @dev implement template method of BaseAccount\n */\n function _validateSignature(\n UserOperation calldata userOp,\n bytes32 userOpHash\n ) internal virtual returns (uint256 validationData) {\n bytes32 hash = userOpHash.toEthSignedMessageHash();\n if (owner != hash.recover(userOp.signature))\n return SIG_VALIDATION_FAILED;\n return 0;\n }\n\n /**\n * check current account deposit in the entryPoint\n */\n function getDeposit() public view returns (uint256) {\n return entryPoint().balanceOf(address(this));\n }\n\n /**\n * deposit more funds for this account in the entryPoint\n */\n function addDeposit() external payable {\n entryPoint().depositTo{value: msg.value}(address(this));\n }\n\n /**\n * withdraw value from the account's deposit\n * @param withdrawAddress target to send to\n * @param amount to withdraw\n */\n function withdrawDepositTo(\n address payable withdrawAddress,\n uint256 amount\n ) external onlyOwner {\n entryPoint().withdrawTo(withdrawAddress, amount);\n }\n\n /**\n * @notice Query if a contract implements an interface\n * @param interfaceId The interface identifier, as specified in ERC165\n * @return `true` if the contract implements `_interfaceID`\n */\n function supportsInterface(\n bytes4 interfaceId\n ) external view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId; // 0x01ffc9a7\n }\n\n \n receive() external payable {}\n}\n"
},
"contracts/smart-contract-wallet/test/Button.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\n\ncontract Button is Ownable {\n event ButtonPushed(address pusher, uint256 pushes);\n uint256 public pushes;\n\n function pushButton() public onlyOwner {\n pushes++;\n emit ButtonPushed(msg.sender, pushes);\n }\n}\n"
},
"contracts/smart-contract-wallet/test/Fake1271SignatureContracts.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\ncontract FakeSigner {\n // bytes4(keccak256(\"isValidSignature(bytes32,bytes)\")\n bytes4 internal constant EIP1271_MAGIC_VALUE = 0x1626ba7e;\n\n function getSignature() public view returns (bytes memory signature) {\n bytes32 fakeSignerPadded = bytes32(uint256(uint160(address(this))));\n // Add fake signature (r,s,v) to pass all requirments.\n // v=0 to indicate eip-1271 signer \"fakeSignerPadded\" which will always return true\n signature = abi.encodePacked(\n fakeSignerPadded,\n bytes32(uint256(65)),\n uint8(0),\n bytes32(0x0)\n );\n }\n\n // Always return valid EIP1271_MAGIC_VALUE\n function isValidSignature(\n bytes32 dataHash,\n bytes memory contractSignature\n ) external pure returns (bytes4) {\n return EIP1271_MAGIC_VALUE;\n }\n}\n\ncontract SelfDestructingContract {\n // All this does is self destruct and send funds to \"to\"\n function selfDestruct(address to) external {\n selfdestruct(payable(to));\n }\n}\n"
},
"contracts/smart-contract-wallet/test/MockToken.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\n\ncontract MockToken is ERC20 {\n constructor() ERC20(\"TST\", \"MockToken\") {}\n\n function mint(address sender, uint256 amount) external {\n _mint(sender, amount);\n }\n\n function decimals() public view virtual override returns (uint8) {\n return 6;\n }\n}\n"
},
"contracts/smart-contract-wallet/test/SocialRecoveryModule.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\nimport \"../SmartAccount.sol\";\nimport {IModule} from \"../interfaces/IModule.sol\";\n\ncontract SocialRecoveryModule is IModule {\n string public constant NAME = \"Social Recovery Module\";\n string public constant VERSION = \"0.1.0\";\n uint256 internal constant SIG_VALIDATION_FAILED = 1;\n\n // @review\n // Might as well keep a state to mark seen userOpHashes\n mapping(bytes32 => bool) public opsSeen;\n\n // @todo\n // Notice validateAndUpdateNonce in just skipped in case of modules. To avoid replay of same userOpHash I think it should be done.\n\n struct Friends {\n address[] friends; // the list of friends\n uint256 threshold; // minimum number of friends required to recover\n }\n mapping(address => Friends) internal friendsEntries;\n mapping(address => mapping(address => bool)) public isFriend;\n\n // isConfirmed - map of [recoveryHash][friend] to bool\n mapping(bytes32 => mapping(address => bool)) public isConfirmed;\n mapping(address => uint256) internal walletsNonces;\n\n /**\n * @dev Setup function sets initial storage of contract. Only by SCW owner.\n */\n function setup(address[] memory _friends, uint256 _threshold) public {\n require(\n _threshold <= _friends.length,\n \"Threshold exceeds friends count\"\n );\n require(_threshold >= 2, \"At least 2 friends required\");\n Friends storage entry = friendsEntries[msg.sender];\n // check for duplicates in friends list\n for (uint256 i = 0; i < _friends.length; i++) {\n address friend = _friends[i];\n require(friend != address(0), \"Invalid friend address provided\");\n require(\n !isFriend[msg.sender][friend],\n \"Duplicate friends provided\"\n );\n isFriend[msg.sender][friend] = true;\n }\n // update friends list and threshold for smart account\n entry.friends = _friends;\n entry.threshold = _threshold;\n }\n\n function validateUserOp(\n UserOperation calldata userOp,\n bytes32 userOpHash\n ) external virtual returns (uint256) {\n (bytes memory moduleSignature, ) = abi.decode(\n userOp.signature,\n (bytes, address)\n );\n return _validateSignature(userOp, userOpHash, moduleSignature);\n }\n\n /**\n * @dev standard validateSignature for modules to validate and mark userOpHash as seen\n * @param userOp the operation that is about to be executed.\n * @param userOpHash hash of the user's request data. can be used as the basis for signature.\n * @return sigValidationResult sigAuthorizer to be passed back to trusting Account, aligns with validationData\n */\n function _validateSignature(\n UserOperation calldata userOp,\n bytes32 userOpHash,\n bytes memory moduleSignature\n ) internal virtual returns (uint256 sigValidationResult) {\n if (opsSeen[userOpHash] == true) return SIG_VALIDATION_FAILED;\n opsSeen[userOpHash] = true;\n // can perform it's own access control logic, verify agaisnt expected signer and return SIG_VALIDATION_FAILED\n return 0;\n }\n\n /**\n * @dev Confirm friend recovery transaction. Only by friends.\n */\n function confirmTransaction(address _wallet, address _newOwner) public {\n require(_onlyFriends(_wallet, msg.sender), \"sender not a friend\");\n bytes32 recoveryHash = getRecoveryHash(\n _wallet,\n _newOwner,\n walletsNonces[_wallet]\n );\n isConfirmed[recoveryHash][msg.sender] = true;\n }\n\n function recoverAccess(address payable _wallet, address _newOwner) public {\n // require(_onlyFriends(_wallet, msg.sender), \"sender not a friend\");\n bytes32 recoveryHash = getRecoveryHash(\n _wallet,\n _newOwner,\n walletsNonces[_wallet]\n );\n require(\n isConfirmedByRequiredFriends(recoveryHash, _wallet),\n \"Not enough confirmations\"\n );\n SmartAccount smartAccount = SmartAccount(payable(_wallet));\n require(\n smartAccount.execTransactionFromModule(\n _wallet,\n 0,\n // abi.encodeCall(\"setOwner\", (newOwner)),\n abi.encodeWithSignature(\"setOwner(address)\", _newOwner),\n Enum.Operation.Call\n ),\n \"Could not execute recovery\"\n );\n walletsNonces[_wallet]++;\n }\n\n function isConfirmedByRequiredFriends(\n bytes32 recoveryHash,\n address _wallet\n ) public view returns (bool) {\n uint256 confirmationCount;\n Friends storage entry = friendsEntries[_wallet];\n for (uint256 i = 0; i < entry.friends.length; i++) {\n if (isConfirmed[recoveryHash][entry.friends[i]])\n confirmationCount++;\n if (confirmationCount == entry.threshold) return true;\n }\n return false;\n }\n\n function _onlyFriends(\n address _wallet,\n address _friend\n ) public view returns (bool) {\n Friends storage entry = friendsEntries[_wallet];\n for (uint256 i = 0; i < entry.friends.length; i++) {\n if (entry.friends[i] == _friend) return true;\n }\n return false;\n }\n\n /// @dev Returns hash of data encoding owner replacement.\n /// @return Data hash.\n function getRecoveryHash(\n address _wallet,\n address _newOwner,\n uint256 _nonce\n ) public pure returns (bytes32) {\n return keccak256(abi.encode(_wallet, _newOwner, _nonce));\n }\n}\n"
},
"contracts/smart-contract-wallet/test/StakedTestToken.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\ncontract StakedTestToken is ERC20 {\n address public STAKED_TOKEN;\n\n constructor(address _token) ERC20(\"stTST\", \"StakedTestToken\") {\n STAKED_TOKEN = _token;\n }\n\n function mint(address sender, uint256 amount) external {\n _mint(sender, amount);\n }\n\n function stake(address _for, uint256 amount) external {\n IERC20(STAKED_TOKEN).transferFrom(msg.sender, address(this), amount);\n _mint(_for, amount);\n }\n}\n"
},
"contracts/smart-contract-wallet/test/StorageSetter.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\ncontract StorageSetter {\n function setStorage(bytes3 data) public {\n bytes32 slot = 0x4242424242424242424242424242424242424242424242424242424242424242;\n \n assembly {\n sstore(slot, data)\n }\n }\n}\n"
},
"contracts/smart-contract-wallet/test/TestIncreaseNonceLib.sol": {
"content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity ^0.8.0;\n\nimport \"../libs/SmartAccountStorage.sol\";\nimport \"../SmartAccount.sol\";\n\n/// @title TestIncreaseNonceLib - Test Lib to Increase Nonce\n/// @notice used to test delegatecalls from Smart Account\ncontract TestIncreaseNonceLib is SmartAccountStorage {\n event NonceIncreasedFromLib(uint256 batchId, uint256 newNonce);\n\n function increaseNonce(uint256 batchId) external {\n emit NonceIncreasedFromLib(batchId, ++nonces[batchId]);\n }\n}\n"
},
"contracts/smart-contract-wallet/test/Upgrader.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\ncontract Upgrader {\n bytes32 internal constant _IMPLEMENTATION_SLOT =\n 0x37722d148fb373b961a84120b6c8d209709b45377878a466db32bbc40d95af26;\n\n function upgrade(address _to) external {\n assembly {\n sstore(_IMPLEMENTATION_SLOT, _to)\n }\n }\n}\n"
},
"contracts/smart-contract-wallet/test/upgrades/BaseSmartAccountNew.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\n/* solhint-disable avoid-low-level-calls */\n/* solhint-disable no-inline-assembly */\n/* solhint-disable reason-string */\n\nimport {IAccount} from \"@account-abstraction/contracts/interfaces/IAccount.sol\";\nimport {IEntryPoint} from \"@account-abstraction/contracts/interfaces/IEntryPoint.sol\";\nimport {UserOperationLib, UserOperation} from \"@account-abstraction/contracts/interfaces/UserOperation.sol\";\nimport {Enum} from \"../../common/Enum.sol\";\nimport {BaseSmartAccountErrors} from \"../../common/Errors.sol\";\nimport \"@account-abstraction/contracts/core/Helpers.sol\";\n\nstruct Transaction {\n address to;\n uint256 value;\n bytes data;\n Enum.Operation operation;\n uint256 targetTxGas;\n}\n\nstruct FeeRefund {\n uint256 baseGas;\n uint256 gasPrice; //gasPrice or tokenGasPrice\n uint256 tokenGasPriceFactor;\n address gasToken;\n address payable refundReceiver;\n}\n\n/**\n * Basic account implementation.\n * this contract provides the basic logic for implementing the IAccount interface - validateUserOp\n * specific account implementation should inherit it and provide the account-specific logic\n */\nabstract contract BaseSmartAccountNew is IAccount, BaseSmartAccountErrors {\n using UserOperationLib for UserOperation;\n\n //return value in case of signature failure, with no time-range.\n // equivalent to _packValidationData(true,0,0);\n uint256 internal constant SIG_VALIDATION_FAILED = 1;\n\n /**\n * @return nonce the account nonce.\n * @dev This method returns the next sequential nonce.\n * @notice For a nonce of a specific key, use `entrypoint.getNonce(account, key)`\n */\n function nonce() public view virtual returns (uint256) {\n return entryPoint().getNonce(address(this), 0);\n }\n\n /**\n * return the entryPoint used by this account.\n * subclass should return the current entryPoint used by this account.\n */\n function entryPoint() public view virtual returns (IEntryPoint);\n\n /**\n * Validate user's signature and nonce.\n * subclass doesn't need to override this method. Instead, it should override the specific internal validation methods.\n */\n function validateUserOp(\n UserOperation calldata userOp,\n bytes32 userOpHash,\n uint256 missingAccountFunds\n ) external virtual override returns (uint256 validationData) {\n if (msg.sender != address(entryPoint()))\n revert CallerIsNotAnEntryPoint(msg.sender);\n validationData = _validateSignature(userOp, userOpHash);\n _validateNonce(userOp.nonce);\n _payPrefund(missingAccountFunds);\n }\n\n /**\n * ensure the request comes from the known entrypoint.\n */\n function _requireFromEntryPoint() internal view virtual {\n require(\n msg.sender == address(entryPoint()),\n \"account: not from EntryPoint\"\n );\n }\n\n /**\n * validate the signature is valid for this message.\n * @param userOp validate the userOp.signature field\n * @param userOpHash convenient field: the hash of the request, to check the signature against\n * (also hashes the entrypoint and chain id)\n * @return validationData signature and time-range of this operation\n * <20-byte> sigAuthorizer - 0 for valid signature, 1 to mark signature failure,\n * otherwise, an address of an \"authorizer\" contract.\n * <6-byte> validUntil - last timestamp this operation is valid. 0 for \"indefinite\"\n * <6-byte> validAfter - first timestamp this operation is valid\n * If the account doesn't use time-range, it is enough to return SIG_VALIDATION_FAILED value (1) for signature failure.\n * Note that the validation code cannot use block.timestamp (or block.number) directly.\n */\n function _validateSignature(\n UserOperation calldata userOp,\n bytes32 userOpHash\n ) internal virtual returns (uint256 validationData);\n\n /**\n * Validate the nonce of the UserOperation.\n * This method may validate the nonce requirement of this account.\n * e.g.\n * To limit the nonce to use sequenced UserOps only (no \"out of order\" UserOps):\n * `require(nonce < type(uint64).max)`\n * For a hypothetical account that *requires* the nonce to be out-of-order:\n * `require(nonce & type(uint64).max == 0)`\n *\n * The actual nonce uniqueness is managed by the EntryPoint, and thus no other\n * action is needed by the account itself.\n *\n * @param nonce to validate\n *\n * solhint-disable-next-line no-empty-blocks\n */\n function _validateNonce(uint256 nonce) internal view virtual {}\n\n /**\n * sends to the entrypoint (msg.sender) the missing funds for this transaction.\n * subclass MAY override this method for better funds management\n * (e.g. send to the entryPoint more than the minimum required, so that in future transactions\n * it will not be required to send again)\n * @param missingAccountFunds the minimum value this method should send the entrypoint.\n * this value MAY be zero, in case there is enough deposit, or the userOp has a paymaster.\n */\n function _payPrefund(uint256 missingAccountFunds) internal virtual {\n if (missingAccountFunds != 0) {\n (bool success, ) = payable(msg.sender).call{\n value: missingAccountFunds,\n gas: type(uint256).max\n }(\"\");\n (success);\n //ignore failure (its EntryPoint's job to verify, not account.)\n }\n }\n\n function init(address _owner, address _handler) external virtual;\n\n function execTransaction(\n Transaction memory _tx,\n uint256 _batchId,\n FeeRefund memory refundInfo,\n bytes memory signatures\n ) external payable virtual returns (bool success);\n}\n"
},
"contracts/smart-contract-wallet/test/upgrades/Guards/DelegateCallTransactionGuard.sol": {
"content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity 0.8.17;\n\nimport {Enum} from \"../../../common/Enum.sol\";\nimport {BaseGuard} from \"./GuardManager.sol\";\nimport {Transaction, FeeRefund} from \"../../../BaseSmartAccount.sol\";\n\ncontract DelegateCallTransactionGuard is BaseGuard {\n error DelegateCallGuardRestricted();\n\n address public immutable allowedTarget;\n\n constructor(address target) {\n allowedTarget = target;\n }\n\n // solhint-disable-next-line payable-fallback\n fallback() external {\n // We don't revert on fallback to avoid issues in case of a SmartAccount upgrade\n // E.g. The expected check method might change and then the Smart Account would be locked.\n }\n\n function checkTransaction(\n Transaction memory _tx,\n FeeRefund memory,\n bytes memory,\n address\n ) external view override {\n if (\n _tx.operation == Enum.Operation.DelegateCall &&\n _tx.to != allowedTarget\n ) revert DelegateCallGuardRestricted();\n }\n\n function checkAfterExecution(bytes32, bool) external view override {}\n}\n"
},
"contracts/smart-contract-wallet/test/upgrades/Guards/GuardManager.sol": {
"content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity 0.8.17;\n\nimport {Enum} from \"../../../common/Enum.sol\";\nimport {Transaction, FeeRefund} from \"../../../BaseSmartAccount.sol\";\nimport {SelfAuthorized} from \"../../../common/SelfAuthorized.sol\";\nimport {IERC165} from \"../../../interfaces/IERC165.sol\";\n\ninterface Guard is IERC165 {\n function checkTransaction(\n Transaction memory _tx,\n FeeRefund memory refundInfo,\n bytes memory signatures,\n address msgSender\n ) external;\n\n function checkAfterExecution(bytes32 txHash, bool success) external;\n}\n\nabstract contract BaseGuard is Guard {\n function supportsInterface(\n bytes4 interfaceId\n ) external view virtual override returns (bool) {\n return\n interfaceId == type(Guard).interfaceId || // 0xe6d7a83a\n interfaceId == type(IERC165).interfaceId; // 0x01ffc9a7\n }\n}\n\n/// @title Guard Manager - A contract that manages transaction guards which perform pre and post-checks on execution by multisig owners\n/// @author Inspired by Richard Meissner's <[email protected]> implementation\ncontract GuardManager is SelfAuthorized {\n event GuardChanged(address guard);\n error InvalidGuard(address guard);\n // keccak256(\"guard_manager.guard.address\")\n bytes32 internal constant GUARD_STORAGE_SLOT =\n 0x4a204f620c8c5ccdca3fd54d003badd85ba500436a431f0cbda4f558c93c34c7;\n\n /// @dev Set a guard that checks transactions before execution\n /// @param guard The address of the guard to be used or the 0 address to disable the guard\n function setGuard(address guard) external authorized {\n if (guard != address(0)) {\n if (!Guard(guard).supportsInterface(type(Guard).interfaceId))\n revert InvalidGuard(guard);\n }\n bytes32 slot = GUARD_STORAGE_SLOT;\n \n assembly {\n sstore(slot, guard)\n }\n emit GuardChanged(guard);\n }\n\n function getGuard() public view returns (address guard) {\n bytes32 slot = GUARD_STORAGE_SLOT;\n \n assembly {\n guard := sload(slot)\n }\n }\n}\n"
},
"contracts/smart-contract-wallet/test/upgrades/ModuleManagerNew.sol": {
"content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity 0.8.17;\n\nimport \"../../common/Enum.sol\";\nimport \"../../common/SelfAuthorized.sol\";\nimport \"../../base/Executor.sol\";\n\n/// @title Module Manager - A contract that manages modules that can execute transactions via this contract\ncontract ModuleManagerNew is SelfAuthorized, Executor {\n // Events\n event EnabledModule(address module);\n event DisabledModule(address module);\n event ExecutionFromModuleSuccess(address indexed module);\n event ExecutionFromModuleFailure(address indexed module);\n\n address internal constant SENTINEL_MODULES = address(0x1);\n bytes32 internal constant version = \"1.0.1\";\n\n mapping(address => address) internal modules;\n bool internal isActive = true;\n\n function _setupModules(address to, bytes memory data) internal {\n require(modules[SENTINEL_MODULES] == address(0), \"BSA100\");\n modules[SENTINEL_MODULES] = SENTINEL_MODULES;\n if (to != address(0))\n // Setup has to complete successfully or transaction fails.\n require(\n execute(to, 0, data, Enum.Operation.DelegateCall, gasleft()),\n \"BSA000\"\n );\n }\n\n /// @dev Allows to add a module to the whitelist.\n /// This can only be done via a wallet transaction.\n /// @notice Enables the module `module` for the wallet.\n /// @param module Module to be whitelisted.\n function enableModule(address module) public authorized {\n // Module address cannot be null or sentinel.\n require(module != address(0) && module != SENTINEL_MODULES, \"BSA101\");\n // Module cannot be added twice.\n require(modules[module] == address(0), \"BSA102\");\n modules[module] = modules[SENTINEL_MODULES];\n modules[SENTINEL_MODULES] = module;\n emit EnabledModule(module);\n }\n\n /// @dev Allows to remove a module from the whitelist.\n /// This can only be done via a wallet transaction.\n /// @notice Disables the module `module` for the wallet.\n /// @param prevModule Module that pointed to the module to be removed in the linked list\n /// @param module Module to be removed.\n function disableModule(\n address prevModule,\n address module\n ) public authorized {\n // Validate module address and check that it corresponds to module index.\n require(module != address(0) && module != SENTINEL_MODULES, \"BSA101\");\n require(modules[prevModule] == module, \"BSA103\");\n modules[prevModule] = modules[module];\n delete modules[module];\n emit DisabledModule(module);\n }\n\n /// @dev Allows a Module to execute a wallet transaction without any further confirmations.\n /// @param to Destination address of module transaction.\n /// @param value Ether value of module transaction.\n /// @param data Data payload of module transaction.\n /// @param operation Operation type of module transaction.\n function execTransactionFromModule(\n address to,\n uint256 value,\n bytes memory data,\n Enum.Operation operation\n ) public virtual returns (bool success) {\n require(isActive == true, \"disabled\");\n // Only whitelisted modules are allowed.\n require(\n msg.sender != SENTINEL_MODULES && modules[msg.sender] != address(0),\n \"BSA104\"\n );\n // Execute transaction without further confirmations.\n success = execute(to, value, data, operation, gasleft());\n if (success) emit ExecutionFromModuleSuccess(msg.sender);\n else emit ExecutionFromModuleFailure(msg.sender);\n }\n\n /// @dev Allows a Module to execute a wallet transaction without any further confirmations and return data\n /// @param to Destination address of module transaction.\n /// @param value Ether value of module transaction.\n /// @param data Data payload of module transaction.\n /// @param operation Operation type of module transaction.\n function execTransactionFromModuleReturnData(\n address to,\n uint256 value,\n bytes memory data,\n Enum.Operation operation\n ) public returns (bool success, bytes memory returnData) {\n success = execTransactionFromModule(to, value, data, operation);\n \n assembly {\n // Load free memory location\n let ptr := mload(0x40)\n // We allocate memory for the return data by setting the free memory location to\n // current free memory location + data size + 32 bytes for data size value\n mstore(0x40, add(ptr, add(returndatasize(), 0x20)))\n // Store the size\n mstore(ptr, returndatasize())\n // Store the data\n returndatacopy(add(ptr, 0x20), 0, returndatasize())\n // Point the return data to the correct memory location\n returnData := ptr\n }\n }\n\n /// @dev Returns if an module is enabled\n /// @return True if the module is enabled\n function isModuleEnabled(address module) public view returns (bool) {\n return SENTINEL_MODULES != module && modules[module] != address(0);\n }\n\n /// @dev Returns array of modules. Useful for a widget\n /// @param start Start of the page.\n /// @param pageSize Maximum number of modules that should be returned.\n /// @return array Array of modules.\n /// @return next Start of the next page.\n function getModulesPaginated(\n address start,\n uint256 pageSize\n ) external view returns (address[] memory array, address next) {\n // Init array with max page size\n array = new address[](pageSize);\n\n // Populate return array\n uint256 moduleCount;\n address currentModule = modules[start];\n while (\n currentModule != address(0x0) &&\n currentModule != SENTINEL_MODULES &&\n moduleCount < pageSize\n ) {\n array[moduleCount] = currentModule;\n currentModule = modules[currentModule];\n moduleCount++;\n }\n next = currentModule;\n // Set correct size of returned array\n \n assembly {\n mstore(array, moduleCount)\n }\n }\n\n // Must reduce the gap this way!\n uint256[23] private __gap;\n}\n"
},
"contracts/smart-contract-wallet/test/upgrades/SmartAccount12Guard.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport \"../../SmartAccount.sol\";\nimport {GuardManager, Guard} from \"./Guards/GuardManager.sol\";\nimport \"hardhat/console.sol\";\n\ncontract SmartAccount12Guard is SmartAccount, GuardManager {\n constructor(IEntryPoint anEntryPoint) SmartAccount(anEntryPoint) {}\n\n function execTransaction_S6W(\n Transaction memory _tx,\n FeeRefund memory refundInfo,\n bytes memory signatures\n ) public payable virtual override nonReentrant returns (bool success) {\n uint256 startGas = gasleft();\n bytes32 txHash;\n // Use scope here to limit variable lifetime and prevent `stack too deep` errors\n {\n bytes memory txHashData = encodeTransactionData(\n // Transaction info\n _tx,\n // Payment info\n refundInfo,\n // Signature info\n nonces[1]++\n );\n txHash = keccak256(txHashData);\n if (isValidSignature(txHash, signatures) != EIP1271_MAGIC_VALUE)\n revert InvalidSignature();\n }\n\n address guard = getGuard();\n {\n if (guard != address(0)) {\n Guard(guard).checkTransaction(\n _tx,\n refundInfo,\n signatures,\n msg.sender\n );\n }\n }\n\n // We require some gas to emit the events (at least 2500) after the execution and some to perform code until the execution (500)\n // We also include the 1/64 in the check that is not send along with a call to counteract potential shortings because of EIP-150\n // Bitshift left 6 bits means multiplying by 64, just more gas efficient\n if (\n gasleft() <\n Math.max((_tx.targetTxGas << 6) / 63, _tx.targetTxGas + 2500) + 500\n )\n revert NotEnoughGasLeft(\n gasleft(),\n Math.max((_tx.targetTxGas << 6) / 63, _tx.targetTxGas + 2500) +\n 500\n );\n // Use scope here to limit variable lifetime and prevent `stack too deep` errors\n {\n // If the gasPrice is 0 we assume that nearly all available gas can be used (it is always more than targetTxGas)\n // We only substract 2500 (compared to the 3000 before) to ensure that the amount passed is still higher than targetTxGas\n success = execute(\n _tx.to,\n _tx.value,\n _tx.data,\n _tx.operation,\n refundInfo.gasPrice == 0 ? (gasleft() - 2500) : _tx.targetTxGas\n );\n // If no targetTxGas and no gasPrice was set (e.g. both are 0), then the internal tx is required to be successful\n // This makes it possible to use `estimateGas` without issues, as it searches for the minimum gas where the tx doesn't revert\n if (!success && _tx.targetTxGas == 0 && refundInfo.gasPrice == 0)\n revert CanNotEstimateGas(\n _tx.targetTxGas,\n refundInfo.gasPrice,\n success\n );\n // We transfer the calculated tx costs to the tx.origin to avoid sending it to intermediate contracts that have made calls\n uint256 payment;\n if (refundInfo.gasPrice != 0) {\n payment = handlePaymentV12(\n startGas - gasleft(),\n refundInfo.baseGas,\n refundInfo.gasPrice,\n refundInfo.tokenGasPriceFactor,\n refundInfo.gasToken,\n refundInfo.refundReceiver\n );\n emit AccountHandlePayment(txHash, payment);\n }\n }\n {\n if (guard != address(0)) {\n Guard(guard).checkAfterExecution(txHash, success);\n }\n }\n }\n\n /**\n * @dev Handles the payment for a transaction refund from Smart Account to Relayer.\n * @param gasUsed Gas used by the transaction.\n * @param baseGas Gas costs that are independent of the transaction execution\n * (e.g. base transaction fee, signature check, payment of the refund, emitted events).\n * @param gasPrice Gas price / TokenGasPrice (gas price in the context of token using offchain price feeds)\n * that should be used for the payment calculation.\n * @param tokenGasPriceFactor factor by which calculated token gas price is already multiplied.\n * @param gasToken Token address (or 0 if ETH) that is used for the payment.\n * @return payment The amount of payment made in the specified token.\n */\n function handlePaymentV12(\n uint256 gasUsed,\n uint256 baseGas,\n uint256 gasPrice,\n uint256 tokenGasPriceFactor,\n address gasToken,\n address payable refundReceiver\n ) private returns (uint256 payment) {\n require(tokenGasPriceFactor != 0, \"invalid tokenGasPriceFactor\");\n // solhint-disable-next-line avoid-tx-origin\n address payable receiver = refundReceiver == address(0)\n ? payable(tx.origin)\n : refundReceiver;\n if (gasToken == address(0)) {\n // For ETH we will only adjust the gas price to not be higher than the actual used gas price\n payment =\n (gasUsed + baseGas) *\n (gasPrice < tx.gasprice ? gasPrice : tx.gasprice);\n bool success;\n assembly {\n success := call(gas(), receiver, payment, 0, 0, 0, 0)\n }\n if (!success)\n revert TokenTransferFailed(address(0), receiver, payment);\n } else {\n payment =\n ((gasUsed + baseGas) * (gasPrice)) /\n (tokenGasPriceFactor);\n if (!transferToken(gasToken, receiver, payment))\n revert TokenTransferFailed(gasToken, receiver, payment);\n }\n }\n}\n"
},
"contracts/smart-contract-wallet/test/upgrades/v1/BaseSmartAccountV1.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\n/* solhint-disable avoid-low-level-calls */\n/* solhint-disable no-inline-assembly */\n/* solhint-disable reason-string */\n\nimport {IAccount} from \"@account-abstraction/contracts/interfaces/IAccount.sol\";\nimport {IEntryPoint} from \"@account-abstraction/contracts/interfaces/IEntryPoint.sol\";\nimport {UserOperationLib, UserOperation} from \"@account-abstraction/contracts/interfaces/UserOperation.sol\";\nimport {Enum} from \"../../../common/Enum.sol\";\nimport {BaseSmartAccountErrors} from \"../../../common/Errors.sol\";\nimport \"@account-abstraction/contracts/core/Helpers.sol\";\n\nstruct Transaction {\n address to;\n Enum.Operation operation;\n uint256 value;\n bytes data;\n uint256 targetTxGas;\n}\n\nstruct FeeRefund {\n uint256 baseGas;\n uint256 gasPrice; //gasPrice or tokenGasPrice\n uint256 tokenGasPriceFactor;\n address gasToken;\n address payable refundReceiver;\n}\n\n/**\n * Basic account implementation.\n * This contract provides the basic logic for implementing the IAccount interface: validateUserOp function\n * Specific account implementation should inherit it and provide the account-specific logic\n */\nabstract contract BaseSmartAccount is IAccount, BaseSmartAccountErrors {\n using UserOperationLib for UserOperation;\n\n //return value in case of signature failure, with no time-range.\n // equivalent to _packValidationData(true,0,0);\n uint256 internal constant SIG_VALIDATION_FAILED = 1;\n\n /**\n * @return nonce the account nonce.\n * @dev This method returns the next sequential nonce.\n * @notice For a nonce of a specific key, use `entrypoint.getNonce(account, key)`\n */\n function nonce() public view virtual returns (uint256) {\n return entryPoint().getNonce(address(this), 0);\n }\n\n /**\n * return the entryPoint used by this account.\n * subclass should return the current entryPoint used by this account.\n */\n function entryPoint() public view virtual returns (IEntryPoint);\n\n /**\n * Validate user's signature and nonce.\n * Subclass doesn't need to override this method.\n * Instead, it should override the specific internal validation methods.\n */\n function validateUserOp(\n UserOperation calldata userOp,\n bytes32 userOpHash,\n uint256 missingAccountFunds\n ) external virtual override returns (uint256 validationData) {\n if (msg.sender != address(entryPoint()))\n revert CallerIsNotAnEntryPoint(msg.sender);\n validationData = _validateSignature(userOp, userOpHash);\n _validateNonce(userOp.nonce);\n _payPrefund(missingAccountFunds);\n }\n\n /**\n * validate the signature is valid for this message.\n * @param userOp validate the userOp.signature field\n * @param userOpHash convenient field: the hash of the request, to check the signature against\n * (also hashes the entrypoint and chain id)\n * @return validationData signature and time-range of this operation\n * <20-byte> sigAuthorizer - 0 for valid signature, 1 to mark signature failure,\n * otherwise, an address of an \"authorizer\" contract.\n * <6-byte> validUntil - last timestamp this operation is valid. 0 for \"indefinite\"\n * <6-byte> validAfter - first timestamp this operation is valid\n * If the account doesn't use time-range, it is enough to return SIG_VALIDATION_FAILED value (1) for signature failure.\n * Note that the validation code cannot use block.timestamp (or block.number) directly.\n */\n function _validateSignature(\n UserOperation calldata userOp,\n bytes32 userOpHash\n ) internal virtual returns (uint256 validationData);\n\n /**\n * Validate the nonce of the UserOperation.\n * This method may validate the nonce requirement of this account.\n * e.g.\n * To limit the nonce to use sequenced UserOps only (no \"out of order\" UserOps):\n * `require(nonce < type(uint64).max)`\n * For a hypothetical account that *requires* the nonce to be out-of-order:\n * `require(nonce & type(uint64).max == 0)`\n *\n * The actual nonce uniqueness is managed by the EntryPoint, and thus no other\n * action is needed by the account itself.\n *\n * @param nonce to validate\n *\n * solhint-disable-next-line no-empty-blocks\n */\n function _validateNonce(uint256 nonce) internal view virtual {}\n\n /**\n * sends to the entrypoint (msg.sender) the missing funds for this transaction.\n * subclass MAY override this method for better funds management\n * (e.g. send to the entryPoint more than the minimum required, so that in future transactions\n * it will not be required to send again)\n * @param missingAccountFunds the minimum value this method should send the entrypoint.\n * this value MAY be zero, in case there is enough deposit, or the userOp has a paymaster.\n */\n function _payPrefund(uint256 missingAccountFunds) internal virtual {\n if (missingAccountFunds != 0) {\n payable(msg.sender).call{\n value: missingAccountFunds,\n gas: type(uint256).max\n }(\"\");\n //ignore failure (its EntryPoint's job to verify, not account.)\n }\n }\n\n /**\n * @dev Initialize the Smart Account with required states\n * @param _owner Signatory of the Smart Account\n * @param _handler Default fallback handler provided in Smart Account\n * @notice devs need to make sure it is only callble once by initiazer or state check restrictions\n */\n function init(address _owner, address _handler) external virtual;\n\n /**\n * @dev Gnosis style transaction with optional repay in native tokens OR ERC20\n * @dev Allows to execute a transaction confirmed by required signature/s and then pays the account that submitted the transaction.\n * @notice The fees are always transferred, even if the user transaction fails.\n * @param _tx Smart Account transaction\n * @param refundInfo Required information for gas refunds\n * @param signatures Packed signature/s data ({bytes32 r}{bytes32 s}{uint8 v})\n */\n function execTransaction(\n Transaction memory _tx,\n FeeRefund memory refundInfo,\n bytes memory signatures\n ) external payable virtual returns (bool success);\n}\n"
},
"contracts/smart-contract-wallet/test/upgrades/v1/IModuleV1.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\nimport {UserOperation} from \"@account-abstraction/contracts/interfaces/UserOperation.sol\";\n\n// interface for modules to verify singatures signed over userOpHash\ninterface IModule {\n /**\n * @dev standard validateSignature for modules to validate and mark userOpHash as seen\n * @param userOp the operation that is about to be executed.\n * @param userOpHash hash of the user's request data. can be used as the basis for signature.\n * @return sigValidationResult sigAuthorizer to be passed back to trusting Account, aligns with validationData\n */\n function validateSignature(\n UserOperation calldata userOp,\n bytes32 userOpHash\n ) external returns (uint256 sigValidationResult);\n}\n"
},
"contracts/smart-contract-wallet/test/upgrades/v1/ModuleManagerV1.sol": {
"content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity 0.8.17;\n\nimport {SelfAuthorized} from \"../../../common/SelfAuthorized.sol\";\nimport {Executor, Enum} from \"../../../base/Executor.sol\";\nimport {ModuleManagerErrors} from \"../../../common/Errors.sol\";\n\n/**\n * @title Module Manager - A contract that manages modules that can execute transactions\n * on behalf of the Smart Account via this contract.\n */\ncontract ModuleManager is SelfAuthorized, Executor, ModuleManagerErrors {\n address internal constant SENTINEL_MODULES = address(0x1);\n\n mapping(address => address) internal modules;\n\n // Events\n event EnabledModule(address module);\n event DisabledModule(address module);\n event ExecutionFromModuleSuccess(address indexed module);\n event ExecutionFromModuleFailure(address indexed module);\n event ModuleTransaction(\n address module,\n address to,\n uint256 value,\n bytes data,\n Enum.Operation operation\n );\n\n /**\n * @dev Returns array of modules. Useful for a widget\n * @param start Start of the page.\n * @param pageSize Maximum number of modules that should be returned.\n * @return array Array of modules.\n * @return next Start of the next page.\n */\n function getModulesPaginated(\n address start,\n uint256 pageSize\n ) external view returns (address[] memory array, address next) {\n // Init array with max page size\n array = new address[](pageSize);\n\n // Populate return array\n uint256 moduleCount;\n address currentModule = modules[start];\n while (\n currentModule != address(0x0) &&\n currentModule != SENTINEL_MODULES &&\n moduleCount < pageSize\n ) {\n array[moduleCount] = currentModule;\n currentModule = modules[currentModule];\n moduleCount++;\n }\n next = currentModule;\n // Set correct size of returned array\n \n assembly {\n mstore(array, moduleCount)\n }\n }\n\n /**\n * @dev Adds a module to the allowlist.\n * @notice This can only be done via a wallet transaction.\n * @notice Enables the module `module` for the wallet.\n * @param module Module to be allow-listed.\n */\n function enableModule(address module) public authorized {\n // Module address cannot be null or sentinel.\n if (module == address(0) || module == SENTINEL_MODULES)\n revert ModuleCannotBeZeroOrSentinel(module);\n // Module cannot be added twice.\n if (modules[module] != address(0)) revert ModuleAlreadyEnabled(module);\n modules[module] = modules[SENTINEL_MODULES];\n modules[SENTINEL_MODULES] = module;\n emit EnabledModule(module);\n }\n\n /**\n * @dev Removes a module from the allowlist.\n * @notice This can only be done via a wallet transaction.\n * @notice Disables the module `module` for the wallet.\n * @param prevModule Module that pointed to the module to be removed in the linked list\n * @param module Module to be removed.\n */\n function disableModule(\n address prevModule,\n address module\n ) public authorized {\n // Validate module address and check that it corresponds to module index.\n if (module == address(0) || module == SENTINEL_MODULES)\n revert ModuleCannotBeZeroOrSentinel(module);\n if (modules[prevModule] != module)\n revert ModuleAndPrevModuleMismatch(\n module,\n modules[prevModule],\n prevModule\n );\n modules[prevModule] = modules[module];\n delete modules[module];\n emit DisabledModule(module);\n }\n\n /**\n * @dev Allows a Module to execute a Smart Account transaction without any further confirmations.\n * @param to Destination address of module transaction.\n * @param value Ether value of module transaction.\n * @param data Data payload of module transaction.\n * @param operation Operation type of module transaction.\n */\n function execTransactionFromModule(\n address to,\n uint256 value,\n bytes memory data,\n Enum.Operation operation\n ) public virtual returns (bool success) {\n // Only whitelisted modules are allowed.\n if (msg.sender == SENTINEL_MODULES || modules[msg.sender] == address(0))\n revert ModuleNotEnabled(msg.sender);\n // Execute transaction without further confirmations.\n success = execute(to, value, data, operation, gasleft());\n if (success) {\n emit ModuleTransaction(msg.sender, to, value, data, operation);\n emit ExecutionFromModuleSuccess(msg.sender);\n } else emit ExecutionFromModuleFailure(msg.sender);\n }\n\n /**\n * @dev Allows a Module to execute a wallet transaction without any further confirmations and returns data\n * @param to Destination address of module transaction.\n * @param value Ether value of module transaction.\n * @param data Data payload of module transaction.\n * @param operation Operation type of module transaction.\n */\n function execTransactionFromModuleReturnData(\n address to,\n uint256 value,\n bytes memory data,\n Enum.Operation operation\n ) public returns (bool success, bytes memory returnData) {\n success = execTransactionFromModule(to, value, data, operation);\n \n assembly {\n // Load free memory location\n let ptr := mload(0x40)\n // We allocate memory for the return data by setting the free memory location to\n // current free memory location + data size + 32 bytes for data size value\n mstore(0x40, add(ptr, add(returndatasize(), 0x20)))\n // Store the size\n mstore(ptr, returndatasize())\n // Store the data\n returndatacopy(add(ptr, 0x20), 0, returndatasize())\n // Point the return data to the correct memory location\n returnData := ptr\n }\n }\n\n /**\n * @dev Returns if a module is enabled\n * @return True if the module is enabled\n */\n function isModuleEnabled(address module) public view returns (bool) {\n return SENTINEL_MODULES != module && modules[module] != address(0);\n }\n\n /**\n * @notice Setup function sets the initial storage of the contract.\n * Optionally executes a delegate call to another contract to setup the modules.\n * @param to Optional destination address of call to execute.\n * @param data Optional data of call to execute.\n */\n function _setupModules(address to, bytes memory data) internal {\n if (modules[SENTINEL_MODULES] != address(0))\n revert ModulesAlreadyInitialized();\n modules[SENTINEL_MODULES] = SENTINEL_MODULES;\n if (to != address(0))\n if (!execute(to, 0, data, Enum.Operation.DelegateCall, gasleft()))\n // Setup has to complete successfully or transaction fails.\n revert ModulesSetupExecutionFailed();\n }\n\n uint256[24] private __gap;\n}\n"
},
"contracts/smart-contract-wallet/test/upgrades/v1/Proxy.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\n/**\n * @title Proxy // This is the user's Smart Account\n * @notice Basic proxy that delegates all calls to a fixed implementation contract.\n * @dev Implementation address is stored in the slot defined by the Proxy's address\n */\ncontract Proxy {\n constructor(address _implementation) {\n require(\n _implementation != address(0),\n \"Invalid implementation address\"\n );\n \n assembly {\n sstore(address(), _implementation)\n }\n }\n\n fallback() external payable {\n address target;\n \n assembly {\n target := sload(address())\n calldatacopy(0, 0, calldatasize())\n let result := delegatecall(gas(), target, 0, calldatasize(), 0, 0)\n returndatacopy(0, 0, returndatasize())\n switch result\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n}\n"
},
"contracts/smart-contract-wallet/test/upgrades/v1/SmartAccountFactoryV1.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport \"./Proxy.sol\";\nimport \"./BaseSmartAccountV1.sol\";\nimport {DefaultCallbackHandler} from \"../../../handler/DefaultCallbackHandler.sol\";\nimport {SmartAccountFactoryErrors} from \"../../../common/Errors.sol\";\n\n/**\n * @title Smart Account Factory - factory responsible for deploying Smart Accounts using CREATE2 and CREATE\n * @dev It deploys Smart Accounts as proxies pointing to `basicImplementation` that is immutable.\n * This allows keeping the same address for the same Smart Account owner on various chains via CREATE2\n * @author Chirag Titiya - <[email protected]>\n */\ncontract SmartAccountFactoryV1 {\n address public immutable basicImplementation;\n DefaultCallbackHandler public immutable minimalHandler;\n\n event AccountCreation(\n address indexed account,\n address indexed owner,\n uint256 indexed index\n );\n event AccountCreationWithoutIndex(\n address indexed account,\n address indexed owner\n );\n\n constructor(address _basicImplementation) {\n require(\n _basicImplementation != address(0),\n \"implementation cannot be zero\"\n );\n basicImplementation = _basicImplementation;\n minimalHandler = new DefaultCallbackHandler();\n }\n\n /**\n * @dev Allows to retrieve the creation code used for the Proxy deployment.\n * @return The creation code for the Proxy.\n */\n function accountCreationCode() public pure returns (bytes memory) {\n return type(Proxy).creationCode;\n }\n\n /**\n * @notice Deploys account using create2 and points it to basicImplementation\n * @param _owner EOA signatory for the account to be deployed\n * @param _index extra salt that allows to deploy more account if needed for same EOA (default 0)\n */\n function deployCounterFactualAccount(\n address _owner,\n uint256 _index\n ) public returns (address proxy) {\n // create initializer data based on init method, _owner and minimalHandler\n bytes memory initializer = getInitializer(_owner);\n\n bytes32 salt = keccak256(\n abi.encodePacked(keccak256(initializer), _index)\n );\n\n bytes memory deploymentData = abi.encodePacked(\n type(Proxy).creationCode,\n uint256(uint160(basicImplementation))\n );\n\n \n assembly {\n proxy := create2(\n 0x0,\n add(0x20, deploymentData),\n mload(deploymentData),\n salt\n )\n }\n require(address(proxy) != address(0), \"Create2 call failed\");\n\n // calldata for init method\n if (initializer.length > 0) {\n \n assembly {\n if eq(\n call(\n gas(),\n proxy,\n 0,\n add(initializer, 0x20),\n mload(initializer),\n 0,\n 0\n ),\n 0\n ) {\n revert(0, 0)\n }\n }\n }\n emit AccountCreation(proxy, _owner, _index);\n }\n\n /**\n * @notice Deploys account using create and points it to _implementation\n * @param _owner EOA signatory for the account to be deployed\n * @return proxy address of the deployed account\n */\n function deployAccount(address _owner) public returns (address proxy) {\n bytes memory deploymentData = abi.encodePacked(\n type(Proxy).creationCode,\n uint256(uint160(basicImplementation))\n );\n\n \n assembly {\n proxy := create(\n 0x0,\n add(0x20, deploymentData),\n mload(deploymentData)\n )\n }\n require(address(proxy) != address(0), \"Create call failed\");\n\n bytes memory initializer = getInitializer(_owner);\n\n // calldata for init method\n if (initializer.length > 0) {\n \n assembly {\n if eq(\n call(\n gas(),\n proxy,\n 0,\n add(initializer, 0x20),\n mload(initializer),\n 0,\n 0\n ),\n 0\n ) {\n revert(0, 0)\n }\n }\n }\n emit AccountCreationWithoutIndex(proxy, _owner);\n }\n\n /**\n * @dev Allows to retrieve the initializer data for the account.\n * @param _owner EOA signatory for the account to be deployed\n * @return initializer bytes for init method\n */\n function getInitializer(\n address _owner\n ) internal view returns (bytes memory) {\n return\n abi.encodeCall(\n BaseSmartAccount.init,\n (_owner, address(minimalHandler))\n );\n }\n\n /**\n * @notice Allows to find out account address prior to deployment\n * @param _owner EOA signatory for the account to be deployed\n * @param _index extra salt that allows to deploy more accounts if needed for same EOA (default 0)\n */\n function getAddressForCounterFactualAccount(\n address _owner,\n uint256 _index\n ) external view returns (address _account) {\n // create initializer data based on init method, _owner and minimalHandler\n bytes memory initializer = getInitializer(_owner);\n bytes memory code = abi.encodePacked(\n type(Proxy).creationCode,\n uint256(uint160(basicImplementation))\n );\n bytes32 salt = keccak256(\n abi.encodePacked(keccak256(initializer), _index)\n );\n bytes32 hash = keccak256(\n abi.encodePacked(bytes1(0xff), address(this), salt, keccak256(code))\n );\n _account = address(uint160(uint256(hash)));\n }\n // off-chain calculation\n // return ethers.utils.getCreate2Address(<factory address>, <create2 salt>, ethers.utils.keccak256(creationCode + implementation));\n}\n"
},
"contracts/smart-contract-wallet/test/upgrades/v1/SmartAccountV1.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport {BaseSmartAccount, IEntryPoint, Transaction, FeeRefund, Enum, UserOperation} from \"./BaseSmartAccountV1.sol\";\nimport {ModuleManager} from \"./ModuleManagerV1.sol\";\nimport {FallbackManager} from \"../../../base/FallbackManager.sol\";\nimport {SignatureDecoder} from \"../../../common/SignatureDecoder.sol\";\nimport {SecuredTokenTransfer} from \"../../../common/SecuredTokenTransfer.sol\";\nimport {LibAddress} from \"../../../libs/LibAddress.sol\";\nimport {ISignatureValidator} from \"../../../interfaces/ISignatureValidator.sol\";\nimport {Math} from \"../../../libs/Math.sol\";\nimport {IERC165} from \"../../../interfaces/IERC165.sol\";\nimport {ReentrancyGuard} from \"../../../common/ReentrancyGuard.sol\";\nimport {SmartAccountErrors} from \"../../../common/Errors.sol\";\nimport {ECDSA} from \"@openzeppelin/contracts/utils/cryptography/ECDSA.sol\";\nimport {IModule} from \"./IModuleV1.sol\";\n\n/**\n * @title SmartAccount - EIP-4337 compatible smart contract wallet.\n * @dev This contract is the base for the Smart Account functionality.\n * - It provides the functionality to execute both gnosis-style txns and AA (EIP-4337) userOps\n * - It allows to receive and manage assets.\n * - It is responsible for managing the modules and fallbacks.\n * - The Smart Account can be extended with modules, such as Social Recovery, Session Key and others.\n * @author Chirag Titiya - <[email protected]>\n */\ncontract SmartAccountV1 is\n BaseSmartAccount,\n ModuleManager,\n FallbackManager,\n SignatureDecoder,\n SecuredTokenTransfer,\n IERC165,\n ReentrancyGuard,\n SmartAccountErrors,\n ISignatureValidator\n{\n using ECDSA for bytes32;\n using LibAddress for address;\n\n // Storage Version\n string public constant VERSION = \"1.0.0\";\n\n // Domain Seperators keccak256(\"EIP712Domain(uint256 chainId,address verifyingContract)\");\n bytes32 internal constant DOMAIN_SEPARATOR_TYPEHASH =\n 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218;\n\n // keccak256(\n // \"AccountTx(address to,uint256 value,bytes data,uint8 operation,uint256 targetTxGas,uint256 baseGas,uint256 gasPrice,uint256 tokenGasPriceFactor,address gasToken,address refundReceiver,uint256 nonce)\"\n // );\n bytes32 internal constant ACCOUNT_TX_TYPEHASH =\n 0xda033865d68bf4a40a5a7cb4159a99e33dba8569e65ea3e38222eb12d9e66eee;\n\n // Owner storage\n address public owner;\n\n // changed to 2D nonce below\n // @notice there is no _nonce\n mapping(uint256 => uint256) public nonces;\n\n // AA immutable storage\n IEntryPoint private immutable _entryPoint;\n uint256 private immutable _chainId;\n address private immutable _self;\n\n // Events\n\n event ImplementationUpdated(\n address indexed oldImplementation,\n address indexed newImplementation\n );\n event EOAChanged(\n address indexed _scw,\n address indexed _oldEOA,\n address indexed _newEOA\n );\n event AccountHandlePayment(bytes32 indexed txHash, uint256 indexed payment);\n event SmartAccountReceivedNativeToken(\n address indexed sender,\n uint256 indexed value\n );\n\n /**\n * @dev Constructor that sets the owner of the contract and the entry point contract.\n * @param anEntryPoint The address of the entry point contract.\n */\n constructor(IEntryPoint anEntryPoint) {\n _self = address(this);\n // By setting the owner it is not possible to call init anymore,\n // so we create an account with fixed non-zero owner.\n // This is an unusable account, perfect for the singleton\n owner = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);\n if (address(anEntryPoint) == address(0))\n revert EntryPointCannotBeZero();\n _entryPoint = anEntryPoint;\n _chainId = block.chainid;\n }\n\n /// modifiers\n /**\n * @dev Modifier to allow only the owner to call the function.\n * Reverts with CallerIsNotOwner if the caller is not the owner.\n */\n modifier onlyOwner() {\n if (msg.sender != owner) revert CallerIsNotOwner(msg.sender);\n _;\n }\n /**\n * @dev Modifier to allow only the owner or the contract itself to call the function.\n * Reverts with MixedAuthFail if the caller is not the owner or the contract itself.\n */\n modifier mixedAuth() {\n if (msg.sender != owner && msg.sender != address(this))\n revert MixedAuthFail(msg.sender);\n _;\n }\n\n /**\n * @dev This function allows the owner or entry point to execute certain actions.\n * If the caller is not authorized, the function will revert with an error message.\n * @notice This modifier is marked as internal and can only be called within the contract itself.\n */\n function _requireFromEntryPointOrOwner() internal view {\n if (msg.sender != address(entryPoint()) && msg.sender != owner)\n revert CallerIsNotEntryPointOrOwner(msg.sender);\n }\n\n /**\n * @dev Allows to change the owner of the smart account by current owner or self-call (modules)\n * @param _newOwner Address of the new signatory\n */\n function setOwner(address _newOwner) public mixedAuth {\n if (_newOwner == address(0)) revert OwnerCannotBeZero();\n if (_newOwner == address(this)) revert OwnerCanNotBeSelf();\n if (_newOwner == owner) revert OwnerProvidedIsSame();\n address oldOwner = owner;\n assembly {\n sstore(owner.slot, _newOwner)\n }\n emit EOAChanged(address(this), oldOwner, _newOwner);\n }\n\n /**\n * @notice All the new implementations MUST have this method!\n * @notice Updates the implementation of the base wallet\n * @param _implementation New wallet implementation\n */\n function updateImplementation(\n address _implementation\n ) public virtual mixedAuth {\n require(_implementation != address(0), \"Address cannot be zero\");\n if (!_implementation.isContract())\n revert InvalidImplementation(_implementation);\n address oldImplementation;\n \n assembly {\n oldImplementation := sload(address())\n sstore(address(), _implementation)\n }\n emit ImplementationUpdated(oldImplementation, _implementation);\n }\n\n /// Getters\n /**\n * @dev Returns the address of the implementation contract associated with this contract.\n * @notice The implementation address is stored in the contract's storage slot with index 0.\n */\n function getImplementation()\n external\n view\n returns (address _implementation)\n {\n \n assembly {\n _implementation := sload(address())\n }\n }\n\n /**\n * @dev Returns the domain separator for this contract, as defined in the EIP-712 standard.\n * @return bytes32 The domain separator hash.\n */\n function domainSeparator() public view returns (bytes32) {\n return\n keccak256(\n abi.encode(\n DOMAIN_SEPARATOR_TYPEHASH,\n block.chainid,\n address(this)\n )\n );\n }\n\n /**\n * @notice Returns the ID of the chain the contract is currently deployed on.\n * @return _chainId The ID of the current chain as a uint256.\n */\n function getChainId() public view returns (uint256) {\n return _chainId;\n }\n\n /**\n * @dev returns a value from the nonces 2d mapping\n * @param batchId : the key of the user's batch being queried\n * @return nonce : the number of transactions made within said batch\n */\n function getNonce(uint256 batchId) public view virtual returns (uint256) {\n return nonces[batchId];\n }\n\n /**\n * @dev Returns the current entry point used by this account.\n * @return EntryPoint as an `IEntryPoint` interface.\n * @dev This function should be implemented by the subclass to return the current entry point used by this account.\n */\n function entryPoint() public view virtual override returns (IEntryPoint) {\n return _entryPoint;\n }\n\n /**\n * @dev Initialize the Smart Account with required states\n * @param _owner Signatory of the Smart Account\n * @param _handler Default fallback handler provided in Smart Account\n * @notice devs need to make sure it is only callble once by initiazer or state check restrictions\n * @notice any further implementations that introduces a new state must have a reinit method\n * @notice init is prevented here by setting owner in the constructor and checking here for address(0)\n */\n function init(address _owner, address _handler) external virtual override {\n if (owner != address(0)) revert AlreadyInitialized(address(this));\n if (_owner == address(0)) revert OwnerCannotBeZero();\n owner = _owner;\n _setFallbackHandler(_handler);\n _setupModules(address(0), bytes(\"\"));\n }\n\n /**\n * @dev Gnosis style transaction with optional repay in native tokens OR ERC20\n * @dev Allows to execute a transaction confirmed by required signature/s and then pays the account that submitted the transaction.\n * @dev Function name optimized to have hash started with zeros to make this function calls cheaper\n * @notice The fees are always transferred, even if the user transaction fails.\n * @param _tx Smart Account transaction\n * @param refundInfo Required information for gas refunds\n * @param signatures Packed signature/s data ({bytes32 r}{bytes32 s}{uint8 v})\n */\n function execTransaction_S6W(\n Transaction memory _tx,\n FeeRefund memory refundInfo,\n bytes memory signatures\n ) public payable virtual nonReentrant returns (bool success) {\n uint256 startGas = gasleft();\n bytes32 txHash;\n // Use scope here to limit variable lifetime and prevent `stack too deep` errors\n {\n bytes memory txHashData = encodeTransactionData(\n // Transaction info\n _tx,\n // Payment info\n refundInfo,\n // Signature info\n nonces[1]++\n );\n txHash = keccak256(txHashData);\n checkSignatures(txHash, signatures);\n }\n\n // We require some gas to emit the events (at least 2500) after the execution and some to perform code until the execution (500)\n // We also include the 1/64 in the check that is not send along with a call to counteract potential shortings because of EIP-150\n // Bitshift left 6 bits means multiplying by 64, just more gas efficient\n if (\n gasleft() <\n Math.max((_tx.targetTxGas << 6) / 63, _tx.targetTxGas + 2500) + 500\n )\n revert NotEnoughGasLeft(\n gasleft(),\n Math.max((_tx.targetTxGas << 6) / 63, _tx.targetTxGas + 2500) +\n 500\n );\n // Use scope here to limit variable lifetime and prevent `stack too deep` errors\n {\n // If the gasPrice is 0 we assume that nearly all available gas can be used (it is always more than targetTxGas)\n // We only substract 2500 (compared to the 3000 before) to ensure that the amount passed is still higher than targetTxGas\n success = execute(\n _tx.to,\n _tx.value,\n _tx.data,\n _tx.operation,\n refundInfo.gasPrice == 0 ? (gasleft() - 2500) : _tx.targetTxGas\n );\n // If no targetTxGas and no gasPrice was set (e.g. both are 0), then the internal tx is required to be successful\n // This makes it possible to use `estimateGas` without issues, as it searches for the minimum gas where the tx doesn't revert\n if (!success && _tx.targetTxGas == 0 && refundInfo.gasPrice == 0)\n revert CanNotEstimateGas(\n _tx.targetTxGas,\n refundInfo.gasPrice,\n success\n );\n // We transfer the calculated tx costs to the tx.origin to avoid sending it to intermediate contracts that have made calls\n uint256 payment;\n if (refundInfo.gasPrice != 0) {\n payment = handlePayment(\n startGas - gasleft(),\n refundInfo.baseGas,\n refundInfo.gasPrice,\n refundInfo.tokenGasPriceFactor,\n refundInfo.gasToken,\n refundInfo.refundReceiver\n );\n emit AccountHandlePayment(txHash, payment);\n }\n }\n }\n\n /**\n * @dev Interface function with the standard name for execTransaction_S6W\n */\n function execTransaction(\n Transaction memory _tx,\n FeeRefund memory refundInfo,\n bytes memory signatures\n ) external payable virtual override returns (bool) {\n return execTransaction_S6W(_tx, refundInfo, signatures);\n }\n\n /**\n * @dev Handles the payment for a transaction refund from Smart Account to Relayer.\n * @param gasUsed Gas used by the transaction.\n * @param baseGas Gas costs that are independent of the transaction execution\n * (e.g. base transaction fee, signature check, payment of the refund, emitted events).\n * @param gasPrice Gas price / TokenGasPrice (gas price in the context of token using offchain price feeds)\n * that should be used for the payment calculation.\n * @param tokenGasPriceFactor factor by which calculated token gas price is already multiplied.\n * @param gasToken Token address (or 0 if ETH) that is used for the payment.\n * @return payment The amount of payment made in the specified token.\n */\n function handlePayment(\n uint256 gasUsed,\n uint256 baseGas,\n uint256 gasPrice,\n uint256 tokenGasPriceFactor,\n address gasToken,\n address payable refundReceiver\n ) private returns (uint256 payment) {\n if (tokenGasPriceFactor == 0) revert TokenGasPriceFactorCanNotBeZero();\n // solhint-disable-next-line avoid-tx-origin\n address payable receiver = refundReceiver == address(0)\n ? payable(tx.origin)\n : refundReceiver;\n if (gasToken == address(0)) {\n // For ETH we will only adjust the gas price to not be higher than the actual used gas price\n payment =\n (gasUsed + baseGas) *\n (gasPrice < tx.gasprice ? gasPrice : tx.gasprice);\n bool success;\n assembly {\n success := call(gas(), receiver, payment, 0, 0, 0, 0)\n }\n if (!success)\n revert TokenTransferFailed(address(0), receiver, payment);\n } else {\n payment =\n ((gasUsed + baseGas) * (gasPrice)) /\n (tokenGasPriceFactor);\n if (!transferToken(gasToken, receiver, payment))\n revert TokenTransferFailed(gasToken, receiver, payment);\n }\n }\n\n /**\n * @dev Allows to estimate a transaction.\n * @notice This method is only meant for estimation purpose, therefore the call will always revert and encode the result in the revert data.\n * @notice Call this method to get an estimate of the handlePayment costs that are deducted with `execTransaction`\n * @param gasUsed Gas used by the transaction.\n * @param baseGas Gas costs that are independent of the transaction execution\n * (e.g. base transaction fee, signature check, payment of the refund, emitted events).\n * @param gasPrice Gas price / TokenGasPrice (gas price in the context of token using offchain price feeds)\n * that should be used for the payment calculation.\n * @param tokenGasPriceFactor factor by which calculated token gas price is already multiplied.\n * @param gasToken Token address (or 0 if ETH) that is used for the payment.\n * @return requiredGas Estimate of refunds\n */\n function handlePaymentRevert(\n uint256 gasUsed,\n uint256 baseGas,\n uint256 gasPrice,\n uint256 tokenGasPriceFactor,\n address gasToken,\n address payable refundReceiver\n ) external returns (uint256 requiredGas) {\n require(tokenGasPriceFactor != 0, \"invalid tokenGasPriceFactor\");\n uint256 startGas = gasleft();\n // solhint-disable-next-line avoid-tx-origin\n address payable receiver = refundReceiver == address(0)\n ? payable(tx.origin)\n : refundReceiver;\n if (gasToken == address(0)) {\n // For ETH we will only adjust the gas price to not be higher than the actual used gas price\n uint256 payment = (gasUsed + baseGas) *\n (gasPrice < tx.gasprice ? gasPrice : tx.gasprice);\n bool success;\n assembly {\n success := call(gas(), receiver, payment, 0, 0, 0, 0)\n }\n if (!success)\n revert TokenTransferFailed(address(0), receiver, payment);\n } else {\n uint256 payment = ((gasUsed + baseGas) * (gasPrice)) /\n (tokenGasPriceFactor);\n if (!transferToken(gasToken, receiver, payment))\n revert TokenTransferFailed(gasToken, receiver, payment);\n }\n unchecked {\n requiredGas = startGas - gasleft();\n }\n revert(string(abi.encodePacked(requiredGas)));\n }\n\n /**\n * @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise.\n * @param dataHash Hash of the data (could be either a message hash or transaction hash)\n * @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash.\n */\n function checkSignatures(\n bytes32 dataHash,\n bytes memory signatures\n ) public view virtual {\n require(signatures.length >= 65, \"Invalid signatures length\");\n uint8 v;\n bytes32 r;\n bytes32 s;\n address _signer;\n (v, r, s) = signatureSplit(signatures);\n if (v == 0) {\n // If v is 0 then it is a contract signature\n // When handling contract signatures the address of the signer contract is encoded into r\n _signer = address(uint160(uint256(r)));\n\n // Check that signature data pointer (s) is not pointing inside the static part of the signatures bytes\n // Here we check that the pointer is not pointing inside the part that is being processed\n if (uint256(s) < 65)\n revert WrongContractSignatureFormat(uint256(s), 0, 0);\n\n // Check if the contract signature is in bounds: start of data is s + 32 and end is start + signature length\n uint256 contractSignatureLen;\n \n assembly {\n contractSignatureLen := mload(add(add(signatures, s), 0x20))\n }\n if (uint256(s) + 32 + contractSignatureLen > signatures.length)\n revert WrongContractSignatureFormat(\n uint256(s),\n contractSignatureLen,\n signatures.length\n );\n\n // Check signature\n bytes memory contractSignature;\n \n assembly {\n // The signature data for contract signatures is appended to the concatenated signatures and the offset is stored in s\n contractSignature := add(add(signatures, s), 0x20)\n }\n if (\n ISignatureValidator(_signer).isValidSignature(\n dataHash,\n contractSignature\n ) != EIP1271_MAGIC_VALUE\n ) revert WrongContractSignature(contractSignature);\n } else if (v > 30) {\n // If v > 30 then default va (27,28) has been adjusted for eth_sign flow\n // To support eth_sign and similar we adjust v and hash the messageHash with the Ethereum message prefix before applying ecrecover\n (_signer, ) = dataHash.toEthSignedMessageHash().tryRecover(\n v - 4,\n r,\n s\n );\n } else {\n (_signer, ) = dataHash.tryRecover(v, r, s);\n }\n if (_signer != owner) revert InvalidSignature();\n }\n\n /**\n * @dev Allows to estimate a transaction.\n * This method is only meant for estimation purpose, therefore the call will always revert and encode the result in the revert data.\n * Since the `estimateGas` function includes refunds, call this method to get an estimated of the costs that are deducted from the wallet with `execTransaction`\n * @param to Destination address of the transaction.\n * @param value Ether value of transaction.\n * @param data Data payload of transaction.\n * @param operation Operation type of transaction.\n * @return Estimate without refunds and overhead fees (base transaction and payload data gas costs).\n */\n function requiredTxGas(\n address to,\n uint256 value,\n bytes calldata data,\n Enum.Operation operation\n ) external returns (uint256) {\n uint256 startGas = gasleft();\n // We don't provide an error message here, as we use it to return the estimate\n if (!execute(to, value, data, operation, gasleft()))\n revert ExecutionFailed();\n // Convert response to string and return via error message\n unchecked {\n revert(string(abi.encodePacked(startGas - gasleft())));\n }\n }\n\n /**\n * @dev Returns hash to be signed by owner.\n * @param to Destination address.\n * @param value Ether value.\n * @param data Data payload.\n * @param operation Operation type.\n * @param targetTxGas Fas that should be used for the internal Smart Account transaction.\n * @param baseGas Additional Gas costs for data used to trigger the transaction.\n * @param gasPrice Maximum gas price/ token gas price that should be used for this transaction.\n * @param tokenGasPriceFactor factor by which calculated token gas price is already multiplied.\n * @param gasToken Token address (or 0 if ETH) that is used for the payment.\n * @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).\n * @param _nonce Transaction nonce.\n * @return Transaction hash.\n */\n function getTransactionHash(\n address to,\n uint256 value,\n bytes calldata data,\n Enum.Operation operation,\n uint256 targetTxGas,\n uint256 baseGas,\n uint256 gasPrice,\n uint256 tokenGasPriceFactor,\n address gasToken,\n address payable refundReceiver,\n uint256 _nonce\n ) public view returns (bytes32) {\n Transaction memory _tx = Transaction({\n to: to,\n value: value,\n data: data,\n operation: operation,\n targetTxGas: targetTxGas\n });\n FeeRefund memory refundInfo = FeeRefund({\n baseGas: baseGas,\n gasPrice: gasPrice,\n tokenGasPriceFactor: tokenGasPriceFactor,\n gasToken: gasToken,\n refundReceiver: refundReceiver\n });\n return keccak256(encodeTransactionData(_tx, refundInfo, _nonce));\n }\n\n /**\n * @dev Returns the bytes that are hashed to be signed by owner.\n * @param _tx The wallet transaction to be signed.\n * @param refundInfo Required information for gas refunds.\n * @param _nonce Transaction nonce.\n * @return transactionHash bytes that are hashed to be signed by the owner.\n */\n function encodeTransactionData(\n Transaction memory _tx,\n FeeRefund memory refundInfo,\n uint256 _nonce\n ) public view returns (bytes memory) {\n bytes32 accountTxHash = keccak256(\n abi.encode(\n ACCOUNT_TX_TYPEHASH,\n _tx.to,\n _tx.value,\n keccak256(_tx.data),\n _tx.operation,\n _tx.targetTxGas,\n refundInfo.baseGas,\n refundInfo.gasPrice,\n refundInfo.tokenGasPriceFactor,\n refundInfo.gasToken,\n refundInfo.refundReceiver,\n _nonce\n )\n );\n return\n bytes.concat(\n bytes1(0x19),\n bytes1(0x01),\n domainSeparator(),\n accountTxHash\n );\n }\n\n /**\n * @dev Utility method to be able to transfer native tokens out of Smart Account\n * @notice only owner/ signatory of Smart Account with enough gas to spend can call this method\n * @notice While enabling multisig module and renouncing ownership this will not work\n * @param dest Destination address\n * @param amount Amount of native tokens\n */\n function transfer(address payable dest, uint256 amount) external onlyOwner {\n if (dest == address(0)) revert TransferToZeroAddressAttempt();\n bool success;\n assembly {\n success := call(gas(), dest, amount, 0, 0, 0, 0)\n }\n if (!success) revert TokenTransferFailed(address(0), dest, amount);\n }\n\n /**\n * @dev Utility method to be able to transfer ERC20 tokens out of Smart Account\n * @notice only owner/ signatory of Smart Account with enough gas to spend can call this method\n * @notice While enabling multisig module and renouncing ownership this will not work\n * @param token Token address\n * @param dest Destination/ Receiver address\n * @param amount Amount of tokens\n */\n function pullTokens(\n address token,\n address dest,\n uint256 amount\n ) external onlyOwner {\n if (dest == address(0)) revert TransferToZeroAddressAttempt();\n if (!transferToken(token, dest, amount))\n revert TokenTransferFailed(token, dest, amount);\n }\n\n /**\n * @dev Execute a transaction (called directly from owner, or by entryPoint)\n * @notice Name is optimized for this method to be cheaper to be called\n * @param dest Address of the contract to call\n * @param value Amount of native tokens to send along with the transaction\n * @param func Data of the transaction\n */\n function executeCall_s1m(\n address dest,\n uint256 value,\n bytes calldata func\n ) public {\n _requireFromEntryPointOrOwner();\n _call(dest, value, func);\n }\n\n /**\n * @dev Interface function with the standard name for executeCall_s1m\n * @param dest Address of the contract to call\n * @param value Amount of native tokens to send along with the transaction\n * @param func Data of the transaction\n */\n function executeCall(\n address dest,\n uint256 value,\n bytes calldata func\n ) external {\n executeCall_s1m(dest, value, func);\n }\n\n /**\n * @dev Execute a sequence of transactions\n * @notice Name is optimized for this method to be cheaper to be called\n * @param dest Addresses of the contracts to call\n * @param value Amounts of native tokens to send along with the transactions\n * @param func Data of the transactions\n */\n function executeBatchCall_4by(\n address[] calldata dest,\n uint256[] calldata value,\n bytes[] calldata func\n ) public {\n _requireFromEntryPointOrOwner();\n if (\n dest.length == 0 ||\n dest.length != value.length ||\n value.length != func.length\n ) revert WrongBatchProvided(dest.length, value.length, func.length, 0);\n for (uint256 i; i < dest.length; ) {\n _call(dest[i], value[i], func[i]);\n unchecked {\n ++i;\n }\n }\n }\n\n /**\n * @dev Interface function with the standard name for executeBatchCall_4by\n * @param dest Addresses of the contracts to call\n * @param value Amounts of native tokens to send along with the transactions\n * @param func Data of the transactions\n */\n function executeBatchCall(\n address[] calldata dest,\n uint256[] calldata value,\n bytes[] calldata func\n ) external {\n executeBatchCall_4by(dest, value, func);\n }\n\n /**\n * @dev internal method that fecilitates the extenral calls from SmartAccount\n * @dev similar to execute() of Executor.sol\n * @param target destination address contract/non-contract\n * @param value amount of native tokens\n * @param data function singature of destination\n */\n function _call(address target, uint256 value, bytes memory data) internal {\n assembly {\n let success := call(\n gas(),\n target,\n value,\n add(data, 0x20),\n mload(data),\n 0,\n 0\n )\n let ptr := mload(0x40)\n returndatacopy(ptr, 0, returndatasize())\n if iszero(success) {\n revert(ptr, returndatasize())\n }\n }\n }\n\n /**\n * @dev Implements the template method of BaseAccount and validates the user's signature for a given operation.\n * @notice This function is marked as internal and virtual, and it overrides the BaseAccount function of the same name.\n * @param userOp The user operation to be validated, provided as a `UserOperation` calldata struct.\n * @param userOpHash The hashed version of the user operation, provided as a `bytes32` value.\n */\n function _validateSignature(\n UserOperation calldata userOp,\n bytes32 userOpHash\n ) internal virtual override returns (uint256 validationData) {\n // below changes need formal verification.\n bytes calldata userOpData = userOp.callData;\n if (userOpData.length > 0) {\n bytes4 methodSig = bytes4(userOpData[:4]);\n // If method to be called is executeCall then only check for module transaction\n if (methodSig == this.executeCall.selector) {\n (address _to, uint _amount, bytes memory _data) = abi.decode(\n userOpData[4:],\n (address, uint, bytes)\n );\n if (address(modules[_to]) != address(0))\n return IModule(_to).validateSignature(userOp, userOpHash);\n }\n }\n bytes32 hash = userOpHash.toEthSignedMessageHash();\n if (owner != hash.recover(userOp.signature))\n return SIG_VALIDATION_FAILED;\n return 0;\n }\n\n /**\n * Implementation of ISignatureValidator (see `interfaces/ISignatureValidator.sol`)\n * @dev If owner is a smart-contract (other smart contract wallet or module, that controls\n * signature verifications - like multisig), forward isValidSignature request to it.\n * In case of multisig, _signature can be several concatenated signatures\n * If owner is EOA, perform a regular ecrecover.\n * @param _dataHash 32 bytes hash of the data signed on the behalf of address(msg.sender)\n * @param _signature Signature byte array associated with _dataHash\n * @return bytes4 value.\n */\n function isValidSignature(\n bytes32 _dataHash,\n bytes memory _signature\n ) public view override returns (bytes4) {\n if (owner.code.length > 0) {\n return\n ISignatureValidator(owner).isValidSignature(\n _dataHash,\n _signature\n );\n }\n if (owner == _dataHash.recover(_signature)) {\n return EIP1271_MAGIC_VALUE;\n }\n return bytes4(0xffffffff);\n }\n\n /**\n * @dev Check current account deposit in the entryPoint\n */\n function getDeposit() public view returns (uint256) {\n return entryPoint().balanceOf(address(this));\n }\n\n /**\n * @dev Deposit more funds for this account in the entryPoint\n */\n function addDeposit() public payable {\n entryPoint().depositTo{value: msg.value}(address(this));\n }\n\n /**\n * @dev Withdraw value from the account's deposit\n * @param withdrawAddress target to send to\n * @param amount to withdraw\n */\n function withdrawDepositTo(\n address payable withdrawAddress,\n uint256 amount\n ) public payable onlyOwner {\n entryPoint().withdrawTo(withdrawAddress, amount);\n }\n\n /**\n * @notice Query if a contract implements an interface\n * @param _interfaceId The interface identifier, as specified in ERC165\n * @return `true` if the contract implements `_interfaceID`\n */\n function supportsInterface(\n bytes4 _interfaceId\n ) external view virtual override returns (bool) {\n return _interfaceId == type(IERC165).interfaceId; // 0x01ffc9a7\n }\n\n /**\n * @dev This function is a special fallback function that is triggered when the contract receives Ether.\n * It logs an event indicating the amount of Ether received and the sender's address.\n * @notice This function is marked as external and payable, meaning it can be called from external\n * sources and accepts Ether as payment.\n */\n receive() external payable {\n if (address(this) == _self) revert DelegateCallsOnly();\n emit SmartAccountReceivedNativeToken(msg.sender, msg.value);\n }\n}\n"
},
"contracts/smart-contract-wallet/test/WhitelistModule.sol": {
"content": "// SPDX-License-Identifier: Apache-2.0\npragma solidity 0.8.17;\nimport \"../SmartAccount.sol\";\nimport {IModule} from \"../interfaces/IModule.sol\";\n\ncontract WhitelistModule {\n mapping(address => bool) public whitelisted;\n address public moduleOwner;\n uint256 internal constant SIG_VALIDATION_FAILED = 1;\n\n // @review\n // Might as well keep a state to mark seen userOpHashes\n mapping(bytes32 => bool) public opsSeen;\n\n // @todo\n // Notice validateAndUpdateNonce in just skipped in case of modules. To avoid replay of same userOpHash I think it should be done.\n\n constructor(address _owner) {\n moduleOwner = _owner;\n }\n\n modifier onlyOwner() {\n require(msg.sender == moduleOwner, \"sender not authorized\");\n _;\n }\n\n function whitelistDestination(address payable _target) external onlyOwner {\n require(\n _target != address(0),\n \"Destination target can not be zero address\"\n );\n whitelisted[_target] = true;\n }\n\n /**\n * @dev standard validateSignature for modules to validate and mark userOpHash as seen\n * @param userOp the operation that is about to be executed.\n * @param userOpHash hash of the user's request data. can be used as the basis for signature.\n * @return sigValidationResult sigAuthorizer to be passed back to trusting Account, aligns with validationData\n */\n function validateSignature(\n UserOperation calldata userOp,\n bytes32 userOpHash\n ) external virtual returns (uint256 sigValidationResult) {\n if (opsSeen[userOpHash] == true) return SIG_VALIDATION_FAILED;\n opsSeen[userOpHash] = true;\n // can perform it's own access control logic, verify agaisnt expected signer and return SIG_VALIDATION_FAILED\n return 0;\n }\n\n function authCall(\n SmartAccount _account,\n address payable _to,\n uint96 _amount,\n bytes memory _data\n ) external {\n // Could have some access control from here like guardians!\n require(_to != address(0), \"Target can not be zero address\");\n require(\n whitelisted[_to] == true,\n \"Unauthorized :: Target must be whitelised!\"\n );\n require(\n _account.execTransactionFromModule(\n _to,\n _amount,\n _data,\n Enum.Operation.Call\n ),\n \"Could not execute ether transfer\"\n );\n }\n}\n"
},
"contracts/smart-contract-wallet/utils/Decoder.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\ncontract Decoder {\n function decode(\n address to,\n bytes memory data\n ) public returns (bytes memory) {\n (bool success, bytes memory result) = to.call(data);\n require(!success, \"Call failed\");\n return result;\n }\n}\n"
},
"contracts/smart-contract-wallet/utils/GasEstimator.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\n// Generic contract for estimating gas on any target and data\ncontract GasEstimator {\n function estimate(\n address _to,\n bytes calldata _data\n ) external returns (bool success, bytes memory result, uint256 gas) {\n // solhint-disable\n uint256 initialGas = gasleft();\n (success, result) = _to.call(_data);\n gas = initialGas - gasleft();\n // solhint-enable\n }\n}\n"
},
"contracts/smart-contract-wallet/utils/GasEstimatorSmartAccount.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport \"../SmartAccountFactory.sol\";\n\n// Contract for estimating gas on undeployed smart account\n// Deploys a smart account and then calls the appropriate method\ncontract GasEstimatorSmartAccount {\n function estimate(\n address _actualWallet,\n address _factory,\n address _moduleSetupContract,\n bytes calldata _moduleSetupData,\n uint256 _index,\n bytes calldata _data // execTransaction data // counterFactual wallet should have assets if required\n ) external returns (bool success, bytes memory result, uint256 gas) {\n // solhint-disable\n uint256 initialGas = gasleft();\n address _wallet = SmartAccountFactory(_factory)\n .deployCounterFactualAccount(\n _moduleSetupContract,\n _moduleSetupData,\n _index\n );\n (success, result) = _actualWallet.call(_data);\n gas = initialGas - gasleft();\n // solhint-enable\n }\n}\n"
},
"hardhat/console.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity >= 0.4.22 <0.9.0;\n\nlibrary console {\n\taddress constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);\n\n\tfunction _sendLogPayload(bytes memory payload) private view {\n\t\tuint256 payloadLength = payload.length;\n\t\taddress consoleAddress = CONSOLE_ADDRESS;\n\t\tassembly {\n\t\t\tlet payloadStart := add(payload, 32)\n\t\t\tlet r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)\n\t\t}\n\t}\n\n\tfunction log() internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log()\"));\n\t}\n\n\tfunction logInt(int256 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(int256)\", p0));\n\t}\n\n\tfunction logUint(uint256 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256)\", p0));\n\t}\n\n\tfunction logString(string memory p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string)\", p0));\n\t}\n\n\tfunction logBool(bool p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool)\", p0));\n\t}\n\n\tfunction logAddress(address p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address)\", p0));\n\t}\n\n\tfunction logBytes(bytes memory p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes)\", p0));\n\t}\n\n\tfunction logBytes1(bytes1 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes1)\", p0));\n\t}\n\n\tfunction logBytes2(bytes2 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes2)\", p0));\n\t}\n\n\tfunction logBytes3(bytes3 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes3)\", p0));\n\t}\n\n\tfunction logBytes4(bytes4 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes4)\", p0));\n\t}\n\n\tfunction logBytes5(bytes5 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes5)\", p0));\n\t}\n\n\tfunction logBytes6(bytes6 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes6)\", p0));\n\t}\n\n\tfunction logBytes7(bytes7 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes7)\", p0));\n\t}\n\n\tfunction logBytes8(bytes8 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes8)\", p0));\n\t}\n\n\tfunction logBytes9(bytes9 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes9)\", p0));\n\t}\n\n\tfunction logBytes10(bytes10 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes10)\", p0));\n\t}\n\n\tfunction logBytes11(bytes11 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes11)\", p0));\n\t}\n\n\tfunction logBytes12(bytes12 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes12)\", p0));\n\t}\n\n\tfunction logBytes13(bytes13 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes13)\", p0));\n\t}\n\n\tfunction logBytes14(bytes14 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes14)\", p0));\n\t}\n\n\tfunction logBytes15(bytes15 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes15)\", p0));\n\t}\n\n\tfunction logBytes16(bytes16 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes16)\", p0));\n\t}\n\n\tfunction logBytes17(bytes17 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes17)\", p0));\n\t}\n\n\tfunction logBytes18(bytes18 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes18)\", p0));\n\t}\n\n\tfunction logBytes19(bytes19 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes19)\", p0));\n\t}\n\n\tfunction logBytes20(bytes20 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes20)\", p0));\n\t}\n\n\tfunction logBytes21(bytes21 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes21)\", p0));\n\t}\n\n\tfunction logBytes22(bytes22 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes22)\", p0));\n\t}\n\n\tfunction logBytes23(bytes23 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes23)\", p0));\n\t}\n\n\tfunction logBytes24(bytes24 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes24)\", p0));\n\t}\n\n\tfunction logBytes25(bytes25 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes25)\", p0));\n\t}\n\n\tfunction logBytes26(bytes26 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes26)\", p0));\n\t}\n\n\tfunction logBytes27(bytes27 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes27)\", p0));\n\t}\n\n\tfunction logBytes28(bytes28 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes28)\", p0));\n\t}\n\n\tfunction logBytes29(bytes29 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes29)\", p0));\n\t}\n\n\tfunction logBytes30(bytes30 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes30)\", p0));\n\t}\n\n\tfunction logBytes31(bytes31 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes31)\", p0));\n\t}\n\n\tfunction logBytes32(bytes32 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bytes32)\", p0));\n\t}\n\n\tfunction log(uint256 p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256)\", p0));\n\t}\n\n\tfunction log(string memory p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string)\", p0));\n\t}\n\n\tfunction log(bool p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool)\", p0));\n\t}\n\n\tfunction log(address p0) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address)\", p0));\n\t}\n\n\tfunction log(uint256 p0, uint256 p1) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256)\", p0, p1));\n\t}\n\n\tfunction log(uint256 p0, string memory p1) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,string)\", p0, p1));\n\t}\n\n\tfunction log(uint256 p0, bool p1) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool)\", p0, p1));\n\t}\n\n\tfunction log(uint256 p0, address p1) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,address)\", p0, p1));\n\t}\n\n\tfunction log(string memory p0, uint256 p1) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,uint256)\", p0, p1));\n\t}\n\n\tfunction log(string memory p0, string memory p1) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,string)\", p0, p1));\n\t}\n\n\tfunction log(string memory p0, bool p1) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,bool)\", p0, p1));\n\t}\n\n\tfunction log(string memory p0, address p1) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,address)\", p0, p1));\n\t}\n\n\tfunction log(bool p0, uint256 p1) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256)\", p0, p1));\n\t}\n\n\tfunction log(bool p0, string memory p1) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,string)\", p0, p1));\n\t}\n\n\tfunction log(bool p0, bool p1) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,bool)\", p0, p1));\n\t}\n\n\tfunction log(bool p0, address p1) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,address)\", p0, p1));\n\t}\n\n\tfunction log(address p0, uint256 p1) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,uint256)\", p0, p1));\n\t}\n\n\tfunction log(address p0, string memory p1) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,string)\", p0, p1));\n\t}\n\n\tfunction log(address p0, bool p1) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,bool)\", p0, p1));\n\t}\n\n\tfunction log(address p0, address p1) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,address)\", p0, p1));\n\t}\n\n\tfunction log(uint256 p0, uint256 p1, uint256 p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,uint256)\", p0, p1, p2));\n\t}\n\n\tfunction log(uint256 p0, uint256 p1, string memory p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,string)\", p0, p1, p2));\n\t}\n\n\tfunction log(uint256 p0, uint256 p1, bool p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,bool)\", p0, p1, p2));\n\t}\n\n\tfunction log(uint256 p0, uint256 p1, address p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,address)\", p0, p1, p2));\n\t}\n\n\tfunction log(uint256 p0, string memory p1, uint256 p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,uint256)\", p0, p1, p2));\n\t}\n\n\tfunction log(uint256 p0, string memory p1, string memory p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,string)\", p0, p1, p2));\n\t}\n\n\tfunction log(uint256 p0, string memory p1, bool p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,bool)\", p0, p1, p2));\n\t}\n\n\tfunction log(uint256 p0, string memory p1, address p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,address)\", p0, p1, p2));\n\t}\n\n\tfunction log(uint256 p0, bool p1, uint256 p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,uint256)\", p0, p1, p2));\n\t}\n\n\tfunction log(uint256 p0, bool p1, string memory p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,string)\", p0, p1, p2));\n\t}\n\n\tfunction log(uint256 p0, bool p1, bool p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,bool)\", p0, p1, p2));\n\t}\n\n\tfunction log(uint256 p0, bool p1, address p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,address)\", p0, p1, p2));\n\t}\n\n\tfunction log(uint256 p0, address p1, uint256 p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,uint256)\", p0, p1, p2));\n\t}\n\n\tfunction log(uint256 p0, address p1, string memory p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,string)\", p0, p1, p2));\n\t}\n\n\tfunction log(uint256 p0, address p1, bool p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,bool)\", p0, p1, p2));\n\t}\n\n\tfunction log(uint256 p0, address p1, address p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,address)\", p0, p1, p2));\n\t}\n\n\tfunction log(string memory p0, uint256 p1, uint256 p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,uint256)\", p0, p1, p2));\n\t}\n\n\tfunction log(string memory p0, uint256 p1, string memory p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,string)\", p0, p1, p2));\n\t}\n\n\tfunction log(string memory p0, uint256 p1, bool p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,bool)\", p0, p1, p2));\n\t}\n\n\tfunction log(string memory p0, uint256 p1, address p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,address)\", p0, p1, p2));\n\t}\n\n\tfunction log(string memory p0, string memory p1, uint256 p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,string,uint256)\", p0, p1, p2));\n\t}\n\n\tfunction log(string memory p0, string memory p1, string memory p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,string,string)\", p0, p1, p2));\n\t}\n\n\tfunction log(string memory p0, string memory p1, bool p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,string,bool)\", p0, p1, p2));\n\t}\n\n\tfunction log(string memory p0, string memory p1, address p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,string,address)\", p0, p1, p2));\n\t}\n\n\tfunction log(string memory p0, bool p1, uint256 p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,bool,uint256)\", p0, p1, p2));\n\t}\n\n\tfunction log(string memory p0, bool p1, string memory p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,bool,string)\", p0, p1, p2));\n\t}\n\n\tfunction log(string memory p0, bool p1, bool p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,bool,bool)\", p0, p1, p2));\n\t}\n\n\tfunction log(string memory p0, bool p1, address p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,bool,address)\", p0, p1, p2));\n\t}\n\n\tfunction log(string memory p0, address p1, uint256 p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,address,uint256)\", p0, p1, p2));\n\t}\n\n\tfunction log(string memory p0, address p1, string memory p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,address,string)\", p0, p1, p2));\n\t}\n\n\tfunction log(string memory p0, address p1, bool p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,address,bool)\", p0, p1, p2));\n\t}\n\n\tfunction log(string memory p0, address p1, address p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,address,address)\", p0, p1, p2));\n\t}\n\n\tfunction log(bool p0, uint256 p1, uint256 p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,uint256)\", p0, p1, p2));\n\t}\n\n\tfunction log(bool p0, uint256 p1, string memory p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,string)\", p0, p1, p2));\n\t}\n\n\tfunction log(bool p0, uint256 p1, bool p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,bool)\", p0, p1, p2));\n\t}\n\n\tfunction log(bool p0, uint256 p1, address p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,address)\", p0, p1, p2));\n\t}\n\n\tfunction log(bool p0, string memory p1, uint256 p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,string,uint256)\", p0, p1, p2));\n\t}\n\n\tfunction log(bool p0, string memory p1, string memory p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,string,string)\", p0, p1, p2));\n\t}\n\n\tfunction log(bool p0, string memory p1, bool p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,string,bool)\", p0, p1, p2));\n\t}\n\n\tfunction log(bool p0, string memory p1, address p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,string,address)\", p0, p1, p2));\n\t}\n\n\tfunction log(bool p0, bool p1, uint256 p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,uint256)\", p0, p1, p2));\n\t}\n\n\tfunction log(bool p0, bool p1, string memory p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,string)\", p0, p1, p2));\n\t}\n\n\tfunction log(bool p0, bool p1, bool p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,bool)\", p0, p1, p2));\n\t}\n\n\tfunction log(bool p0, bool p1, address p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,address)\", p0, p1, p2));\n\t}\n\n\tfunction log(bool p0, address p1, uint256 p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,address,uint256)\", p0, p1, p2));\n\t}\n\n\tfunction log(bool p0, address p1, string memory p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,address,string)\", p0, p1, p2));\n\t}\n\n\tfunction log(bool p0, address p1, bool p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,address,bool)\", p0, p1, p2));\n\t}\n\n\tfunction log(bool p0, address p1, address p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,address,address)\", p0, p1, p2));\n\t}\n\n\tfunction log(address p0, uint256 p1, uint256 p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,uint256)\", p0, p1, p2));\n\t}\n\n\tfunction log(address p0, uint256 p1, string memory p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,string)\", p0, p1, p2));\n\t}\n\n\tfunction log(address p0, uint256 p1, bool p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,bool)\", p0, p1, p2));\n\t}\n\n\tfunction log(address p0, uint256 p1, address p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,address)\", p0, p1, p2));\n\t}\n\n\tfunction log(address p0, string memory p1, uint256 p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,string,uint256)\", p0, p1, p2));\n\t}\n\n\tfunction log(address p0, string memory p1, string memory p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,string,string)\", p0, p1, p2));\n\t}\n\n\tfunction log(address p0, string memory p1, bool p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,string,bool)\", p0, p1, p2));\n\t}\n\n\tfunction log(address p0, string memory p1, address p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,string,address)\", p0, p1, p2));\n\t}\n\n\tfunction log(address p0, bool p1, uint256 p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,bool,uint256)\", p0, p1, p2));\n\t}\n\n\tfunction log(address p0, bool p1, string memory p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,bool,string)\", p0, p1, p2));\n\t}\n\n\tfunction log(address p0, bool p1, bool p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,bool,bool)\", p0, p1, p2));\n\t}\n\n\tfunction log(address p0, bool p1, address p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,bool,address)\", p0, p1, p2));\n\t}\n\n\tfunction log(address p0, address p1, uint256 p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,address,uint256)\", p0, p1, p2));\n\t}\n\n\tfunction log(address p0, address p1, string memory p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,address,string)\", p0, p1, p2));\n\t}\n\n\tfunction log(address p0, address p1, bool p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,address,bool)\", p0, p1, p2));\n\t}\n\n\tfunction log(address p0, address p1, address p2) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,address,address)\", p0, p1, p2));\n\t}\n\n\tfunction log(uint256 p0, uint256 p1, uint256 p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,uint256,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, uint256 p1, uint256 p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,uint256,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, uint256 p1, uint256 p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,uint256,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, uint256 p1, uint256 p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,uint256,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, uint256 p1, string memory p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,string,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, uint256 p1, string memory p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,string,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, uint256 p1, string memory p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,string,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, uint256 p1, string memory p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,string,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, uint256 p1, bool p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,bool,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, uint256 p1, bool p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,bool,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, uint256 p1, bool p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,bool,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, uint256 p1, bool p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,bool,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, uint256 p1, address p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,address,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, uint256 p1, address p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,address,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, uint256 p1, address p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,address,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, uint256 p1, address p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,address,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, string memory p1, uint256 p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,uint256,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, string memory p1, uint256 p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,uint256,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, string memory p1, uint256 p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,uint256,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, string memory p1, uint256 p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,uint256,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, string memory p1, string memory p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,string,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, string memory p1, string memory p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,string,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, string memory p1, string memory p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,string,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, string memory p1, string memory p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,string,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, string memory p1, bool p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,bool,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, string memory p1, bool p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,bool,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, string memory p1, bool p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,bool,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, string memory p1, bool p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,bool,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, string memory p1, address p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,address,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, string memory p1, address p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,address,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, string memory p1, address p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,address,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, string memory p1, address p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,address,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, bool p1, uint256 p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,uint256,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, bool p1, uint256 p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,uint256,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, bool p1, uint256 p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,uint256,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, bool p1, uint256 p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,uint256,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, bool p1, string memory p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,string,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, bool p1, string memory p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,string,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, bool p1, string memory p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,string,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, bool p1, string memory p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,string,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, bool p1, bool p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,bool,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, bool p1, bool p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,bool,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, bool p1, bool p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,bool,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, bool p1, bool p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,bool,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, bool p1, address p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,address,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, bool p1, address p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,address,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, bool p1, address p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,address,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, bool p1, address p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,address,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, address p1, uint256 p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,uint256,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, address p1, uint256 p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,uint256,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, address p1, uint256 p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,uint256,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, address p1, uint256 p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,uint256,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, address p1, string memory p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,string,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, address p1, string memory p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,string,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, address p1, string memory p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,string,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, address p1, string memory p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,string,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, address p1, bool p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,bool,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, address p1, bool p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,bool,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, address p1, bool p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,bool,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, address p1, bool p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,bool,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, address p1, address p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,address,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, address p1, address p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,address,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, address p1, address p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,address,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(uint256 p0, address p1, address p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,address,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, uint256 p1, uint256 p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,uint256,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, uint256 p1, uint256 p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,uint256,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, uint256 p1, uint256 p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,uint256,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, uint256 p1, uint256 p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,uint256,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, uint256 p1, string memory p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,string,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, uint256 p1, string memory p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,string,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, uint256 p1, string memory p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,string,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, uint256 p1, string memory p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,string,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, uint256 p1, bool p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,bool,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, uint256 p1, bool p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,bool,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, uint256 p1, bool p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,bool,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, uint256 p1, bool p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,bool,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, uint256 p1, address p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,address,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, uint256 p1, address p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,address,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, uint256 p1, address p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,address,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, uint256 p1, address p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,address,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, string memory p1, uint256 p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,string,uint256,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, string memory p1, uint256 p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,string,uint256,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, string memory p1, uint256 p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,string,uint256,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, string memory p1, uint256 p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,string,uint256,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, string memory p1, string memory p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,string,string,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,string,string,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, string memory p1, string memory p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,string,string,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, string memory p1, string memory p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,string,string,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, string memory p1, bool p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,string,bool,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, string memory p1, bool p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,string,bool,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, string memory p1, bool p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,string,bool,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, string memory p1, bool p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,string,bool,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, string memory p1, address p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,string,address,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, string memory p1, address p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,string,address,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, string memory p1, address p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,string,address,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, string memory p1, address p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,string,address,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, bool p1, uint256 p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,bool,uint256,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, bool p1, uint256 p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,bool,uint256,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, bool p1, uint256 p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,bool,uint256,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, bool p1, uint256 p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,bool,uint256,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, bool p1, string memory p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,bool,string,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, bool p1, string memory p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,bool,string,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, bool p1, string memory p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,bool,string,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, bool p1, string memory p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,bool,string,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, bool p1, bool p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,bool,bool,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, bool p1, bool p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,bool,bool,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, bool p1, bool p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,bool,bool,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, bool p1, bool p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,bool,bool,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, bool p1, address p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,bool,address,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, bool p1, address p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,bool,address,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, bool p1, address p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,bool,address,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, bool p1, address p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,bool,address,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, address p1, uint256 p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,address,uint256,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, address p1, uint256 p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,address,uint256,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, address p1, uint256 p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,address,uint256,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, address p1, uint256 p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,address,uint256,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, address p1, string memory p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,address,string,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, address p1, string memory p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,address,string,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, address p1, string memory p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,address,string,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, address p1, string memory p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,address,string,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, address p1, bool p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,address,bool,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, address p1, bool p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,address,bool,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, address p1, bool p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,address,bool,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, address p1, bool p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,address,bool,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, address p1, address p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,address,address,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, address p1, address p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,address,address,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, address p1, address p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,address,address,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(string memory p0, address p1, address p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(string,address,address,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, uint256 p1, uint256 p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,uint256,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, uint256 p1, uint256 p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,uint256,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, uint256 p1, uint256 p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,uint256,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, uint256 p1, uint256 p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,uint256,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, uint256 p1, string memory p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,string,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, uint256 p1, string memory p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,string,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, uint256 p1, string memory p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,string,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, uint256 p1, string memory p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,string,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, uint256 p1, bool p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,bool,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, uint256 p1, bool p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,bool,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, uint256 p1, bool p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,bool,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, uint256 p1, bool p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,bool,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, uint256 p1, address p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,address,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, uint256 p1, address p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,address,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, uint256 p1, address p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,address,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, uint256 p1, address p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,address,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, string memory p1, uint256 p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,string,uint256,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, string memory p1, uint256 p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,string,uint256,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, string memory p1, uint256 p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,string,uint256,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, string memory p1, uint256 p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,string,uint256,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, string memory p1, string memory p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,string,string,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, string memory p1, string memory p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,string,string,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, string memory p1, string memory p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,string,string,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, string memory p1, string memory p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,string,string,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, string memory p1, bool p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,string,bool,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, string memory p1, bool p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,string,bool,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, string memory p1, bool p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,string,bool,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, string memory p1, bool p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,string,bool,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, string memory p1, address p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,string,address,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, string memory p1, address p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,string,address,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, string memory p1, address p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,string,address,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, string memory p1, address p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,string,address,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, bool p1, uint256 p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,uint256,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, bool p1, uint256 p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,uint256,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, bool p1, uint256 p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,uint256,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, bool p1, uint256 p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,uint256,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, bool p1, string memory p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,string,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, bool p1, string memory p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,string,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, bool p1, string memory p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,string,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, bool p1, string memory p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,string,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, bool p1, bool p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,bool,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, bool p1, bool p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,bool,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, bool p1, bool p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,bool,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, bool p1, bool p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,bool,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, bool p1, address p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,address,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, bool p1, address p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,address,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, bool p1, address p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,address,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, bool p1, address p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,address,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, address p1, uint256 p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,address,uint256,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, address p1, uint256 p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,address,uint256,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, address p1, uint256 p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,address,uint256,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, address p1, uint256 p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,address,uint256,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, address p1, string memory p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,address,string,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, address p1, string memory p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,address,string,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, address p1, string memory p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,address,string,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, address p1, string memory p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,address,string,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, address p1, bool p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,address,bool,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, address p1, bool p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,address,bool,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, address p1, bool p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,address,bool,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, address p1, bool p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,address,bool,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, address p1, address p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,address,address,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, address p1, address p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,address,address,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, address p1, address p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,address,address,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(bool p0, address p1, address p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(bool,address,address,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, uint256 p1, uint256 p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,uint256,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, uint256 p1, uint256 p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,uint256,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, uint256 p1, uint256 p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,uint256,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, uint256 p1, uint256 p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,uint256,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, uint256 p1, string memory p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,string,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, uint256 p1, string memory p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,string,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, uint256 p1, string memory p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,string,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, uint256 p1, string memory p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,string,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, uint256 p1, bool p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,bool,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, uint256 p1, bool p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,bool,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, uint256 p1, bool p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,bool,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, uint256 p1, bool p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,bool,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, uint256 p1, address p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,address,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, uint256 p1, address p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,address,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, uint256 p1, address p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,address,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, uint256 p1, address p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,address,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, string memory p1, uint256 p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,string,uint256,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, string memory p1, uint256 p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,string,uint256,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, string memory p1, uint256 p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,string,uint256,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, string memory p1, uint256 p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,string,uint256,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, string memory p1, string memory p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,string,string,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, string memory p1, string memory p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,string,string,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, string memory p1, string memory p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,string,string,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, string memory p1, string memory p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,string,string,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, string memory p1, bool p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,string,bool,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, string memory p1, bool p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,string,bool,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, string memory p1, bool p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,string,bool,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, string memory p1, bool p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,string,bool,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, string memory p1, address p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,string,address,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, string memory p1, address p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,string,address,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, string memory p1, address p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,string,address,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, string memory p1, address p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,string,address,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, bool p1, uint256 p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,bool,uint256,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, bool p1, uint256 p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,bool,uint256,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, bool p1, uint256 p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,bool,uint256,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, bool p1, uint256 p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,bool,uint256,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, bool p1, string memory p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,bool,string,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, bool p1, string memory p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,bool,string,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, bool p1, string memory p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,bool,string,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, bool p1, string memory p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,bool,string,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, bool p1, bool p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,bool,bool,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, bool p1, bool p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,bool,bool,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, bool p1, bool p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,bool,bool,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, bool p1, bool p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,bool,bool,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, bool p1, address p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,bool,address,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, bool p1, address p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,bool,address,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, bool p1, address p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,bool,address,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, bool p1, address p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,bool,address,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, address p1, uint256 p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,address,uint256,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, address p1, uint256 p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,address,uint256,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, address p1, uint256 p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,address,uint256,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, address p1, uint256 p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,address,uint256,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, address p1, string memory p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,address,string,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, address p1, string memory p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,address,string,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, address p1, string memory p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,address,string,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, address p1, string memory p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,address,string,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, address p1, bool p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,address,bool,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, address p1, bool p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,address,bool,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, address p1, bool p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,address,bool,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, address p1, bool p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,address,bool,address)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, address p1, address p2, uint256 p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,address,address,uint256)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, address p1, address p2, string memory p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,address,address,string)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, address p1, address p2, bool p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,address,address,bool)\", p0, p1, p2, p3));\n\t}\n\n\tfunction log(address p0, address p1, address p2, address p3) internal view {\n\t\t_sendLogPayload(abi.encodeWithSignature(\"log(address,address,address,address)\", p0, p1, p2, p3));\n\t}\n\n}\n"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 800
},
"outputSelection": {
"*": {
"*": [
"abi",
"evm.bytecode",
"evm.deployedBytecode",
"evm.methodIdentifiers",
"metadata",
"devdoc",
"userdoc",
"storageLayout",
"evm.gasEstimates"
],
"": [
"ast"
]
}
},
"metadata": {
"useLiteralContent": true
}
}
}