creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "src/accounts/LlamaAccount.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.19;\n\nimport {Initializable} from \"@openzeppelin/proxy/utils/Initializable.sol\";\nimport {IERC20} from \"@openzeppelin/token/ERC20/IERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin/token/ERC20/utils/SafeERC20.sol\";\nimport {IERC721} from \"@openzeppelin/token/ERC721/IERC721.sol\";\nimport {ERC721Holder} from \"@openzeppelin/token/ERC721/utils/ERC721Holder.sol\";\nimport {IERC1155} from \"@openzeppelin/token/ERC1155/IERC1155.sol\";\nimport {ERC1155Holder} from \"@openzeppelin/token/ERC1155/utils/ERC1155Holder.sol\";\nimport {Address} from \"@openzeppelin/utils/Address.sol\";\n\nimport {ILlamaAccount} from \"src/interfaces/ILlamaAccount.sol\";\nimport {LlamaUtils} from \"src/lib/LlamaUtils.sol\";\nimport {LlamaCore} from \"src/LlamaCore.sol\";\n\n/// @title Llama Account\n/// @author Llama (devsdosomething@llama.xyz)\n/// @notice This contract can be used to hold assets for a Llama instance.\ncontract LlamaAccount is ILlamaAccount, ERC721Holder, ERC1155Holder, Initializable {\n  using SafeERC20 for IERC20;\n  using Address for address payable;\n\n  // =========================\n  // ======== Structs ========\n  // =========================\n\n  /// @dev Llama account initialization configuration.\n  struct Config {\n    string name; // Name of the Llama account.\n  }\n\n  /// @dev Data for sending native tokens to recipients.\n  struct NativeTokenData {\n    address payable recipient; // Recipient of the native tokens.\n    uint256 amount; // Amount of native tokens to send.\n  }\n\n  /// @dev Data for sending ERC20 tokens to recipients.\n  struct ERC20Data {\n    IERC20 token; // The ERC20 token to transfer.\n    address recipient; // The address to transfer the token to.\n    uint256 amount; // The amount of tokens to transfer.\n  }\n\n  /// @dev Data for sending ERC721 tokens to recipients.\n  struct ERC721Data {\n    IERC721 token; // The ERC721 token to transfer.\n    address recipient; // The address to transfer the token to.\n    uint256 tokenId; // The tokenId of the token to transfer.\n  }\n\n  /// @dev Data for operator allowance for ERC721 transfers.\n  struct ERC721OperatorData {\n    IERC721 token; // The ERC721 token to transfer.\n    address recipient; // The address to transfer the token to.\n    bool approved; // Whether to approve or revoke allowance.\n  }\n\n  /// @dev Data for sending ERC1155 tokens to recipients.\n  struct ERC1155Data {\n    IERC1155 token; // The ERC1155 token to transfer.\n    address recipient; // The address to transfer the token to.\n    uint256 tokenId; // The tokenId of the token to transfer.\n    uint256 amount; // The amount of tokens to transfer.\n    bytes data; // The data to pass to the ERC1155 token.\n  }\n\n  /// @dev Data for batch sending ERC1155 tokens to recipients.\n  struct ERC1155BatchData {\n    IERC1155 token; // The ERC1155 token to transfer.\n    address recipient; // The address to transfer the token to.\n    uint256[] tokenIds; // The tokenId of the token to transfer.\n    uint256[] amounts; // The amount of tokens to transfer.\n    bytes data; // The data to pass to the ERC1155 token.\n  }\n\n  /// @dev Data for operator allowance for ERC1155 transfers.\n  struct ERC1155OperatorData {\n    IERC1155 token; // The ERC1155 token to transfer.\n    address recipient; // The address to transfer the token to.\n    bool approved; // Whether to approve or revoke allowance.\n  }\n\n  // ======================================\n  // ======== Errors and Modifiers ========\n  // ======================================\n\n  /// @dev Only callable by a Llama instance's executor.\n  error OnlyLlama();\n\n  /// @dev Recipient cannot be the 0 address.\n  error ZeroAddressNotAllowed();\n\n  /// @dev External call failed.\n  /// @param result Data returned by the called function.\n  error FailedExecution(bytes result);\n\n  /// @dev Slot 0 cannot be changed as a result of delegatecalls.\n  error Slot0Changed();\n\n  /// @dev Value cannot be sent with delegatecalls.\n  error CannotDelegatecallWithValue();\n\n  /// @dev Checks that the caller is the Llama executor and reverts if not.\n  modifier onlyLlama() {\n    if (msg.sender != llamaExecutor) revert OnlyLlama();\n    _;\n  }\n\n  // ===================================\n  // ======== Storage Variables ========\n  // ===================================\n\n  /// @notice The Llama instance's executor.\n  /// @dev We intentionally put this before the `name` so it's packed with the `Initializable`\n  /// storage variables, that way we can only check one slot before and after a delegatecall.\n  address public llamaExecutor;\n\n  /// @notice Name of the Llama account.\n  string public name;\n\n  // ======================================================\n  // ======== Contract Creation and Initialization ========\n  // ======================================================\n\n  /// @dev This contract is deployed as a minimal proxy from the core's `_deployAccounts` function. The\n  /// `_disableInitializers` locks the implementation (logic) contract, preventing any future initialization of it.\n  constructor() {\n    _disableInitializers();\n  }\n\n  /// @inheritdoc ILlamaAccount\n  function initialize(bytes memory config) external initializer returns (bool) {\n    llamaExecutor = address(LlamaCore(msg.sender).executor());\n    Config memory accountConfig = abi.decode(config, (Config));\n    name = accountConfig.name;\n\n    return true;\n  }\n\n  // ===========================================\n  // ======== External and Public Logic ========\n  // ===========================================\n\n  // -------- Native Token --------\n\n  /// @notice Enables the Llama account to receive native tokens.\n  receive() external payable {}\n\n  /// @notice Transfer native tokens to a recipient.\n  /// @param nativeTokenData The `amount` and `recipient` of the native token transfer.\n  function transferNativeToken(NativeTokenData calldata nativeTokenData) public onlyLlama {\n    if (nativeTokenData.recipient == address(0)) revert ZeroAddressNotAllowed();\n    nativeTokenData.recipient.sendValue(nativeTokenData.amount);\n  }\n\n  /// @notice Batch transfer native tokens to a recipient.\n  /// @param nativeTokenData The `amounts` and `recipients` for the native token transfers.\n  function batchTransferNativeToken(NativeTokenData[] calldata nativeTokenData) external onlyLlama {\n    uint256 length = nativeTokenData.length;\n    for (uint256 i = 0; i < length; i = LlamaUtils.uncheckedIncrement(i)) {\n      transferNativeToken(nativeTokenData[i]);\n    }\n  }\n\n  // -------- ERC20 Token --------\n\n  /// @notice Transfer ERC20 tokens to a recipient.\n  /// @param erc20Data The `token`, `recipient`, and `amount` for the ERC20 transfer.\n  function transferERC20(ERC20Data calldata erc20Data) public onlyLlama {\n    if (erc20Data.recipient == address(0)) revert ZeroAddressNotAllowed();\n    erc20Data.token.safeTransfer(erc20Data.recipient, erc20Data.amount);\n  }\n\n  /// @notice Batch transfer ERC20 tokens to recipients.\n  /// @param erc20Data The `token`, `recipient`, and `amount` for the ERC20 transfers.\n  function batchTransferERC20(ERC20Data[] calldata erc20Data) external onlyLlama {\n    uint256 length = erc20Data.length;\n    for (uint256 i = 0; i < length; i = LlamaUtils.uncheckedIncrement(i)) {\n      transferERC20(erc20Data[i]);\n    }\n  }\n\n  /// @notice Approve an ERC20 allowance for a recipient.\n  /// @param erc20Data The `token`, `recipient`, and `amount` for the ERC20 approval.\n  function approveERC20(ERC20Data calldata erc20Data) public onlyLlama {\n    erc20Data.token.safeApprove(erc20Data.recipient, erc20Data.amount);\n  }\n\n  /// @notice Batch approve ERC20 allowances for recipients.\n  /// @param erc20Data The `token`, `recipient`, and `amount` for the ERC20 approvals.\n  function batchApproveERC20(ERC20Data[] calldata erc20Data) external onlyLlama {\n    uint256 length = erc20Data.length;\n    for (uint256 i = 0; i < length; i = LlamaUtils.uncheckedIncrement(i)) {\n      approveERC20(erc20Data[i]);\n    }\n  }\n\n  // -------- ERC721 Token --------\n\n  /// @notice Transfer an ERC721 token to a recipient.\n  /// @param erc721Data The `token`, `recipient`, and `tokenId` of the ERC721 transfer.\n  function transferERC721(ERC721Data calldata erc721Data) public onlyLlama {\n    if (erc721Data.recipient == address(0)) revert ZeroAddressNotAllowed();\n    erc721Data.token.transferFrom(address(this), erc721Data.recipient, erc721Data.tokenId);\n  }\n\n  /// @notice Batch transfer ERC721 tokens to recipients.\n  /// @param erc721Data The `token`, `recipient`, and `tokenId` of the ERC721 transfers.\n  function batchTransferERC721(ERC721Data[] calldata erc721Data) external onlyLlama {\n    uint256 length = erc721Data.length;\n    for (uint256 i = 0; i < length; i = LlamaUtils.uncheckedIncrement(i)) {\n      transferERC721(erc721Data[i]);\n    }\n  }\n\n  /// @notice Approve a recipient to transfer an ERC721.\n  /// @param erc721Data The `token`, `recipient`, and `tokenId` of the ERC721 approval.\n  function approveERC721(ERC721Data calldata erc721Data) public onlyLlama {\n    erc721Data.token.approve(erc721Data.recipient, erc721Data.tokenId);\n  }\n\n  /// @notice Batch approve recipients to transfer ERC721s.\n  /// @param erc721Data The `token`, `recipient`, and `tokenId` for the ERC721 approvals.\n  function batchApproveERC721(ERC721Data[] calldata erc721Data) external onlyLlama {\n    uint256 length = erc721Data.length;\n    for (uint256 i = 0; i < length; i = LlamaUtils.uncheckedIncrement(i)) {\n      approveERC721(erc721Data[i]);\n    }\n  }\n\n  /// @notice Approve an operator for ERC721 transfers.\n  /// @param erc721OperatorData The `token`, `recipient`, and `approved` boolean for the ERC721 operator approval.\n  function approveOperatorERC721(ERC721OperatorData calldata erc721OperatorData) public onlyLlama {\n    erc721OperatorData.token.setApprovalForAll(erc721OperatorData.recipient, erc721OperatorData.approved);\n  }\n\n  /// @notice Batch approve operators for ERC721 transfers.\n  /// @param erc721OperatorData The `token`, `recipient`, and `approved` booleans for the ERC721 operator approvals.\n  function batchApproveOperatorERC721(ERC721OperatorData[] calldata erc721OperatorData) external onlyLlama {\n    uint256 length = erc721OperatorData.length;\n    for (uint256 i = 0; i < length; i = LlamaUtils.uncheckedIncrement(i)) {\n      approveOperatorERC721(erc721OperatorData[i]);\n    }\n  }\n\n  // -------- ERC1155 Token --------\n\n  /// @notice Transfer ERC1155 tokens to a recipient.\n  /// @param erc1155Data The data of the ERC1155 transfer.\n  function transferERC1155(ERC1155Data calldata erc1155Data) external onlyLlama {\n    if (erc1155Data.recipient == address(0)) revert ZeroAddressNotAllowed();\n    erc1155Data.token.safeTransferFrom(\n      address(this), erc1155Data.recipient, erc1155Data.tokenId, erc1155Data.amount, erc1155Data.data\n    );\n  }\n\n  /// @notice Batch transfer ERC1155 tokens of a single ERC1155 collection to recipients.\n  /// @param erc1155BatchData The data of the ERC1155 batch transfer.\n  function batchTransferSingleERC1155(ERC1155BatchData calldata erc1155BatchData) public onlyLlama {\n    if (erc1155BatchData.recipient == address(0)) revert ZeroAddressNotAllowed();\n    erc1155BatchData.token.safeBatchTransferFrom(\n      address(this),\n      erc1155BatchData.recipient,\n      erc1155BatchData.tokenIds,\n      erc1155BatchData.amounts,\n      erc1155BatchData.data\n    );\n  }\n\n  /// @notice Batch transfer ERC1155 tokens of multiple ERC1155 collections to recipients.\n  /// @param erc1155BatchData The data of the ERC1155 batch transfers.\n  function batchTransferMultipleERC1155(ERC1155BatchData[] calldata erc1155BatchData) external onlyLlama {\n    uint256 length = erc1155BatchData.length;\n    for (uint256 i = 0; i < length; i = LlamaUtils.uncheckedIncrement(i)) {\n      batchTransferSingleERC1155(erc1155BatchData[i]);\n    }\n  }\n\n  /// @notice Grant an ERC1155 operator allowance to recipients.\n  /// @param erc1155OperatorData The data of the ERC1155 operator allowance.\n  function approveOperatorERC1155(ERC1155OperatorData calldata erc1155OperatorData) public onlyLlama {\n    erc1155OperatorData.token.setApprovalForAll(erc1155OperatorData.recipient, erc1155OperatorData.approved);\n  }\n\n  /// @notice Batch approve ERC1155 operator allowances to recipients.\n  /// @param erc1155OperatorData The data of the ERC1155 operator allowances.\n  function batchApproveOperatorERC1155(ERC1155OperatorData[] calldata erc1155OperatorData) external onlyLlama {\n    uint256 length = erc1155OperatorData.length;\n    for (uint256 i = 0; i < length; i = LlamaUtils.uncheckedIncrement(i)) {\n      approveOperatorERC1155(erc1155OperatorData[i]);\n    }\n  }\n\n  // -------- Generic Execution --------\n\n  /// @notice Execute arbitrary calls from the Llama Account.\n  /// @dev Be careful and intentional while assigning permissions to a policyholder that can create an action to call\n  /// this function, especially while using the delegatecall functionality as it can lead to arbitrary code execution in\n  /// the context of this Llama account.\n  /// @param target The address of the contract to call.\n  /// @param withDelegatecall Whether to use delegatecall or call.\n  /// @param value The amount of ETH to send with the call, taken from the Llama Account.\n  /// @param callData The calldata to pass to the contract.\n  /// @return The result of the call.\n  function execute(address target, bool withDelegatecall, uint256 value, bytes calldata callData)\n    external\n    onlyLlama\n    returns (bytes memory)\n  {\n    bool success;\n    bytes memory result;\n\n    if (withDelegatecall) {\n      if (value > 0) revert CannotDelegatecallWithValue();\n\n      // Whenever we're executing arbitrary code in the context of this account, we want to ensure\n      // that none of the storage in this contract changes, as this could let someone who sneaks in\n      // a malicious (or buggy) target to take ownership of this contract. Slot 0 contains all\n      // relevant storage variables for security, so we check the value before and after execution\n      // to make sure it's unchanged. The contract name starts in slot 1, but it's not as important\n      // if that's changed (and it can be changed back), so to save gas we don't check the name.\n      // The storage layout of this contract is below:\n      //\n      // | Variable Name | Type    | Slot | Offset | Bytes |\n      // |---------------|---------|------|--------|-------|\n      // | _initialized  | uint8   | 0    | 0      | 1     |\n      // | _initializing | bool    | 0    | 1      | 1     |\n      // | llamaExecutor | address | 0    | 2      | 20    |\n      // | name          | string  | 1    | 0      | 32    |\n\n      bytes32 originalStorage = _readSlot0();\n      (success, result) = target.delegatecall(callData);\n      if (originalStorage != _readSlot0()) revert Slot0Changed();\n    } else {\n      (success, result) = target.call{value: value}(callData);\n    }\n\n    if (!success) revert FailedExecution(result);\n    return result;\n  }\n\n  // ================================\n  // ======== Internal Logic ========\n  // ================================\n\n  /// @dev Reads slot 0 from storage, used to check that storage hasn't changed after delegatecall.\n  function _readSlot0() internal view returns (bytes32 slot0) {\n    assembly {\n      slot0 := sload(0)\n    }\n  }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/proxy/utils/Initializable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (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 Internal function that returns the initialized version. Returns `_initialized`\n     */\n    function _getInitializedVersion() internal view returns (uint8) {\n        return _initialized;\n    }\n\n    /**\n     * @dev Internal function that returns the initialized version. Returns `_initializing`\n     */\n    function _isInitializing() internal view returns (bool) {\n        return _initializing;\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/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"
      },
      "lib/openzeppelin-contracts/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"
      },
      "lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n    /**\n     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n    /**\n     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n     */\n    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n    /**\n     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n     */\n    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n    /**\n     * @dev Returns the number of tokens in ``owner``'s account.\n     */\n    function balanceOf(address owner) external view returns (uint256 balance);\n\n    /**\n     * @dev Returns the owner of the `tokenId` token.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     */\n    function ownerOf(uint256 tokenId) external view returns (address owner);\n\n    /**\n     * @dev Safely transfers `tokenId` token from `from` to `to`.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must exist and be owned by `from`.\n     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function safeTransferFrom(\n        address from,\n        address to,\n        uint256 tokenId,\n        bytes calldata data\n    ) external;\n\n    /**\n     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n     * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must exist and be owned by `from`.\n     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function safeTransferFrom(\n        address from,\n        address to,\n        uint256 tokenId\n    ) external;\n\n    /**\n     * @dev Transfers `tokenId` token from `from` to `to`.\n     *\n     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721\n     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must\n     * understand this adds an external call which potentially creates a reentrancy vulnerability.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must be owned by `from`.\n     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(\n        address from,\n        address to,\n        uint256 tokenId\n    ) external;\n\n    /**\n     * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n     * The approval is cleared when the token is transferred.\n     *\n     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n     *\n     * Requirements:\n     *\n     * - The caller must own the token or be an approved operator.\n     * - `tokenId` must exist.\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address to, uint256 tokenId) external;\n\n    /**\n     * @dev Approve or remove `operator` as an operator for the caller.\n     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n     *\n     * Requirements:\n     *\n     * - The `operator` cannot be the caller.\n     *\n     * Emits an {ApprovalForAll} event.\n     */\n    function setApprovalForAll(address operator, bool _approved) external;\n\n    /**\n     * @dev Returns the account approved for `tokenId` token.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     */\n    function getApproved(uint256 tokenId) external view returns (address operator);\n\n    /**\n     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n     *\n     * See {setApprovalForAll}\n     */\n    function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/token/ERC721/utils/ERC721Holder.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/utils/ERC721Holder.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721Receiver.sol\";\n\n/**\n * @dev Implementation of the {IERC721Receiver} interface.\n *\n * Accepts all token transfers.\n * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.\n */\ncontract ERC721Holder is IERC721Receiver {\n    /**\n     * @dev See {IERC721Receiver-onERC721Received}.\n     *\n     * Always returns `IERC721Receiver.onERC721Received.selector`.\n     */\n    function onERC721Received(\n        address,\n        address,\n        uint256,\n        bytes memory\n    ) public virtual override returns (bytes4) {\n        return this.onERC721Received.selector;\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/token/ERC1155/IERC1155.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/IERC1155.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC1155 compliant contract, as defined in the\n * https://eips.ethereum.org/EIPS/eip-1155[EIP].\n *\n * _Available since v3.1._\n */\ninterface IERC1155 is IERC165 {\n    /**\n     * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.\n     */\n    event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);\n\n    /**\n     * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all\n     * transfers.\n     */\n    event TransferBatch(\n        address indexed operator,\n        address indexed from,\n        address indexed to,\n        uint256[] ids,\n        uint256[] values\n    );\n\n    /**\n     * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to\n     * `approved`.\n     */\n    event ApprovalForAll(address indexed account, address indexed operator, bool approved);\n\n    /**\n     * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.\n     *\n     * If an {URI} event was emitted for `id`, the standard\n     * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value\n     * returned by {IERC1155MetadataURI-uri}.\n     */\n    event URI(string value, uint256 indexed id);\n\n    /**\n     * @dev Returns the amount of tokens of token type `id` owned by `account`.\n     *\n     * Requirements:\n     *\n     * - `account` cannot be the zero address.\n     */\n    function balanceOf(address account, uint256 id) external view returns (uint256);\n\n    /**\n     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.\n     *\n     * Requirements:\n     *\n     * - `accounts` and `ids` must have the same length.\n     */\n    function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)\n        external\n        view\n        returns (uint256[] memory);\n\n    /**\n     * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,\n     *\n     * Emits an {ApprovalForAll} event.\n     *\n     * Requirements:\n     *\n     * - `operator` cannot be the caller.\n     */\n    function setApprovalForAll(address operator, bool approved) external;\n\n    /**\n     * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.\n     *\n     * See {setApprovalForAll}.\n     */\n    function isApprovedForAll(address account, address operator) external view returns (bool);\n\n    /**\n     * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.\n     *\n     * Emits a {TransferSingle} event.\n     *\n     * Requirements:\n     *\n     * - `to` cannot be the zero address.\n     * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.\n     * - `from` must have a balance of tokens of type `id` of at least `amount`.\n     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the\n     * acceptance magic value.\n     */\n    function safeTransferFrom(\n        address from,\n        address to,\n        uint256 id,\n        uint256 amount,\n        bytes calldata data\n    ) external;\n\n    /**\n     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.\n     *\n     * Emits a {TransferBatch} event.\n     *\n     * Requirements:\n     *\n     * - `ids` and `amounts` must have the same length.\n     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the\n     * acceptance magic value.\n     */\n    function safeBatchTransferFrom(\n        address from,\n        address to,\n        uint256[] calldata ids,\n        uint256[] calldata amounts,\n        bytes calldata data\n    ) external;\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/token/ERC1155/utils/ERC1155Holder.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/utils/ERC1155Holder.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./ERC1155Receiver.sol\";\n\n/**\n * Simple implementation of `ERC1155Receiver` that will allow a contract to hold ERC1155 tokens.\n *\n * IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be\n * stuck.\n *\n * @dev _Available since v3.1._\n */\ncontract ERC1155Holder is ERC1155Receiver {\n    function onERC1155Received(\n        address,\n        address,\n        uint256,\n        uint256,\n        bytes memory\n    ) public virtual override returns (bytes4) {\n        return this.onERC1155Received.selector;\n    }\n\n    function onERC1155BatchReceived(\n        address,\n        address,\n        uint256[] memory,\n        uint256[] memory,\n        bytes memory\n    ) public virtual override returns (bytes4) {\n        return this.onERC1155BatchReceived.selector;\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/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"
      },
      "src/interfaces/ILlamaAccount.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.19;\n\n/// @title Llama Account Logic Interface\n/// @author Llama (devsdosomething@llama.xyz)\n/// @notice This is the interface for Llama accounts which can be used to hold assets for a Llama instance.\ninterface ILlamaAccount {\n  // -------- For Inspection --------\n\n  /// @notice Returns the address of the Llama instance's executor.\n  function llamaExecutor() external view returns (address);\n\n  // -------- At Account Creation --------\n\n  /// @notice Initializes a new clone of the account.\n  /// @dev This function is called by the `_deployAccounts` function in the `LlamaCore` contract. The `initializer`\n  /// modifier ensures that this function can be invoked at most once.\n  /// @param config The account configuration, encoded as bytes to support differing constructor arguments in\n  /// different account logic contracts.\n  /// @return This return statement must be hardcoded to `true` to ensure that initializing an EOA\n  /// (like the zero address) will revert.\n  function initialize(bytes memory config) external returns (bool);\n}\n"
      },
      "src/lib/LlamaUtils.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.19;\n\nimport {PermissionData} from \"src/lib/Structs.sol\";\n\n/// @dev Shared helper methods for Llama's contracts.\nlibrary LlamaUtils {\n  /// @dev Thrown when a value cannot be safely casted to a smaller type.\n  error UnsafeCast(uint256 n);\n\n  /// @dev Reverts if `n` does not fit in a `uint64`.\n  function toUint64(uint256 n) internal pure returns (uint64) {\n    if (n > type(uint64).max) revert UnsafeCast(n);\n    return uint64(n);\n  }\n\n  /// @dev Reverts if `n` does not fit in a `uint96`.\n  function toUint96(uint256 n) internal pure returns (uint96) {\n    if (n > type(uint96).max) revert UnsafeCast(n);\n    return uint96(n);\n  }\n\n  /// @dev Increments a `uint256` without checking for overflow.\n  function uncheckedIncrement(uint256 i) internal pure returns (uint256) {\n    unchecked {\n      return i + 1;\n    }\n  }\n\n  /// @dev Hashes a permission to return the corresponding permission ID.\n  function computePermissionId(PermissionData memory permission) internal pure returns (bytes32) {\n    return keccak256(abi.encode(permission));\n  }\n}\n"
      },
      "src/LlamaCore.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.19;\n\nimport {Clones} from \"@openzeppelin/proxy/Clones.sol\";\nimport {Initializable} from \"@openzeppelin/proxy/utils/Initializable.sol\";\n\nimport {ILlamaAccount} from \"src/interfaces/ILlamaAccount.sol\";\nimport {ILlamaActionGuard} from \"src/interfaces/ILlamaActionGuard.sol\";\nimport {ILlamaPolicyMetadata} from \"src/interfaces/ILlamaPolicyMetadata.sol\";\nimport {ILlamaStrategy} from \"src/interfaces/ILlamaStrategy.sol\";\nimport {ActionState} from \"src/lib/Enums.sol\";\nimport {LlamaUtils} from \"src/lib/LlamaUtils.sol\";\nimport {\n  Action,\n  ActionInfo,\n  LlamaInstanceConfig,\n  LlamaPolicyConfig,\n  PermissionData,\n  RoleHolderData,\n  RolePermissionData\n} from \"src/lib/Structs.sol\";\nimport {LlamaExecutor} from \"src/LlamaExecutor.sol\";\nimport {LlamaPolicy} from \"src/LlamaPolicy.sol\";\n\n/// @title Llama Core\n/// @author Llama (devsdosomething@llama.xyz)\n/// @notice Manages the action process from creation to execution.\ncontract LlamaCore is Initializable {\n  // =========================\n  // ======== Structs ========\n  // =========================\n\n  /// @dev Stores the two different status values for a strategy.\n  struct StrategyStatus {\n    bool deployed; // Whether or not the strategy has been deployed from this `LlamaCore`.\n    bool authorized; // Whether or not the strategy has been authorized for action creations in this `LlamaCore`.\n  }\n\n  // ======================================\n  // ======== Errors and Modifiers ========\n  // ======================================\n\n  /// @dev Bootstrap strategy must be deployed and authorized during initialization.\n  /// @dev This should never be thrown in production.\n  error BootstrapStrategyNotAuthorized();\n\n  /// @dev Policyholder cannot cast if it has 0 quantity of role.\n  /// @param policyholder Address of policyholder.\n  /// @param role The role being used in the cast.\n  error CannotCastWithZeroQuantity(address policyholder, uint8 role);\n\n  /// @dev Policyholder cannot cast after the minimum execution time.\n  error CannotDisapproveAfterMinExecutionTime();\n\n  /// @dev An action's target contract cannot be the executor.\n  error CannotSetExecutorAsTarget();\n\n  /// @dev Address cannot be used.\n  error RestrictedAddress();\n\n  /// @dev Policyholders can only cast once.\n  error DuplicateCast();\n\n  /// @dev Action execution failed.\n  /// @param reason Data returned by the function called by the action.\n  error FailedActionExecution(bytes reason);\n\n  /// @dev `ActionInfo` does not hash to the correct value.\n  error InfoHashMismatch();\n\n  /// @dev `msg.value` does not equal the action's value.\n  error IncorrectMsgValue();\n\n  /// @dev The action is not in the expected state.\n  /// @param current The current state of the action.\n  error InvalidActionState(ActionState current);\n\n  /// @dev The policyholder does not have the role at action creation time.\n  error InvalidPolicyholder();\n\n  /// @dev The recovered signer does not match the expected policyholder.\n  error InvalidSignature();\n\n  /// @dev An action cannot queue successfully if it's `minExecutionTime` is less than `block.timestamp`.\n  error MinExecutionTimeCannotBeInThePast();\n\n  /// @dev The provided strategy address does not map to a deployed strategy.\n  error NonExistentStrategy();\n\n  /// @dev Only callable by a Llama instance's executor.\n  error OnlyLlama();\n\n  /// @dev Policyholder does not have the permission ID to create the action.\n  error PolicyholderDoesNotHavePermission();\n\n  /// @dev If `block.timestamp` is less than `minExecutionTime`, the action cannot be executed.\n  error MinExecutionTimeNotReached();\n\n  /// @dev Actions can only be created with authorized strategies.\n  error UnauthorizedStrategy();\n\n  /// @dev Strategies can only be created with valid logic contracts.\n  error UnauthorizedStrategyLogic();\n\n  /// @dev Accounts can only be created with valid logic contracts.\n  error UnauthorizedAccountLogic();\n\n  /// @dev Checks that the caller is the Llama Executor and reverts if not.\n  modifier onlyLlama() {\n    if (msg.sender != address(executor)) revert OnlyLlama();\n    _;\n  }\n\n  // ========================\n  // ======== Events ========\n  // ========================\n\n  /// @dev Emitted when an account is created.\n  event AccountCreated(ILlamaAccount account, ILlamaAccount indexed accountLogic, bytes initializationData);\n\n  /// @dev Emitted when a new account implementation (logic) contract is authorized or unauthorized.\n  event AccountLogicAuthorizationSet(ILlamaAccount indexed accountLogic, bool authorized);\n\n  /// @dev Emitted when an action is created.\n  event ActionCreated(\n    uint256 id,\n    address indexed creator,\n    uint8 role,\n    ILlamaStrategy indexed strategy,\n    address indexed target,\n    uint256 value,\n    bytes data,\n    string description\n  );\n\n  /// @dev Emitted when an action is canceled.\n  event ActionCanceled(uint256 id, address indexed caller);\n\n  /// @dev Emitted when an action guard is set.\n  event ActionGuardSet(address indexed target, bytes4 indexed selector, ILlamaActionGuard actionGuard);\n\n  /// @dev Emitted when an action is queued.\n  event ActionQueued(\n    uint256 id,\n    address indexed caller,\n    ILlamaStrategy indexed strategy,\n    address indexed creator,\n    uint256 minExecutionTime\n  );\n\n  /// @dev Emitted when an action is executed.\n  event ActionExecuted(\n    uint256 id, address indexed caller, ILlamaStrategy indexed strategy, address indexed creator, bytes result\n  );\n\n  /// @dev Emitted when an approval is cast.\n  event ApprovalCast(uint256 id, address indexed policyholder, uint8 indexed role, uint256 quantity, string reason);\n\n  /// @dev Emitted when a disapproval is cast.\n  event DisapprovalCast(uint256 id, address indexed policyholder, uint8 indexed role, uint256 quantity, string reason);\n\n  /// @dev Emitted when a deployed strategy is authorized or unauthorized.\n  event StrategyAuthorizationSet(ILlamaStrategy indexed strategy, bool authorized);\n\n  /// @dev Emitted when a strategy is created.\n  event StrategyCreated(ILlamaStrategy strategy, ILlamaStrategy indexed strategyLogic, bytes initializationData);\n\n  /// @dev Emitted when a new strategy implementation (logic) contract is authorized or unauthorized.\n  event StrategyLogicAuthorizationSet(ILlamaStrategy indexed strategyLogic, bool authorized);\n\n  /// @dev Emitted when a script is authorized or unauthorized.\n  event ScriptAuthorizationSet(address indexed script, bool authorized);\n\n  // =================================================\n  // ======== Constants and Storage Variables ========\n  // =================================================\n\n  /// @dev EIP-712 base typehash.\n  bytes32 internal constant EIP712_DOMAIN_TYPEHASH =\n    keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\");\n\n  /// @dev EIP-712 createAction typehash.\n  bytes32 internal constant CREATE_ACTION_TYPEHASH = keccak256(\n    \"CreateAction(address policyholder,uint8 role,address strategy,address target,uint256 value,bytes data,string description,uint256 nonce)\"\n  );\n\n  /// @dev EIP-712 cancelAction typehash.\n  bytes32 internal constant CANCEL_ACTION_TYPEHASH = keccak256(\n    \"CancelAction(address policyholder,ActionInfo actionInfo,uint256 nonce)ActionInfo(uint256 id,address creator,uint8 creatorRole,address strategy,address target,uint256 value,bytes data)\"\n  );\n\n  /// @dev EIP-712 castApproval typehash.\n  bytes32 internal constant CAST_APPROVAL_TYPEHASH = keccak256(\n    \"CastApproval(address policyholder,uint8 role,ActionInfo actionInfo,string reason,uint256 nonce)ActionInfo(uint256 id,address creator,uint8 creatorRole,address strategy,address target,uint256 value,bytes data)\"\n  );\n\n  /// @dev EIP-712 castDisapproval typehash.\n  bytes32 internal constant CAST_DISAPPROVAL_TYPEHASH = keccak256(\n    \"CastDisapproval(address policyholder,uint8 role,ActionInfo actionInfo,string reason,uint256 nonce)ActionInfo(uint256 id,address creator,uint8 creatorRole,address strategy,address target,uint256 value,bytes data)\"\n  );\n\n  /// @dev EIP-712 actionInfo typehash.\n  bytes32 internal constant ACTION_INFO_TYPEHASH = keccak256(\n    \"ActionInfo(uint256 id,address creator,uint8 creatorRole,address strategy,address target,uint256 value,bytes data)\"\n  );\n\n  /// @dev Mapping of actionIds to Actions. This data can be accessed through the `getAction` function.\n  mapping(uint256 actionId => Action) internal actions;\n\n  /// @notice The contract that executes actions for this Llama instance.\n  LlamaExecutor public executor;\n\n  /// @notice The ERC721 contract that defines the policies for this Llama instance.\n  LlamaPolicy public policy;\n\n  /// @notice Name of this Llama instance.\n  string public name;\n\n  /// @notice The current number of actions created.\n  uint256 public actionsCount;\n\n  /// @notice Mapping of actionIds to policyholders to approvals.\n  mapping(uint256 actionId => mapping(address policyholder => bool hasApproved)) public approvals;\n\n  /// @notice Mapping of actionIds to policyholders to disapprovals.\n  mapping(uint256 actionId => mapping(address policyholder => bool hasDisapproved)) public disapprovals;\n\n  /// @notice Mapping of all deployed strategies and their current authorization status.\n  mapping(ILlamaStrategy strategy => StrategyStatus authorizationStatus) public strategies;\n\n  /// @notice Mapping of all authorized scripts.\n  mapping(address script => bool isAuthorized) public authorizedScripts;\n\n  /// @notice Mapping of policyholders to function selectors to current nonces for EIP-712 signatures.\n  /// @dev This is used to prevent replay attacks by incrementing the nonce for each operation (`createAction`,\n  /// `cancelAction`, `castApproval` and `castDisapproval`) signed by the policyholder.\n  mapping(address policyholder => mapping(bytes4 selector => uint256 currentNonce)) public nonces;\n\n  /// @notice Mapping of target to selector to actionGuard address.\n  mapping(address target => mapping(bytes4 selector => ILlamaActionGuard guard)) public actionGuard;\n\n  /// @notice Mapping of all authorized Llama account implementation (logic) contracts.\n  mapping(ILlamaAccount accountLogic => bool isAuthorized) public authorizedAccountLogics;\n\n  /// @notice Mapping of all authorized Llama strategy implementation (logic) contracts.\n  mapping(ILlamaStrategy strategyLogic => bool isAuthorized) public authorizedStrategyLogics;\n\n  // ======================================================\n  // ======== Contract Creation and Initialization ========\n  // ======================================================\n\n  /// @dev This contract is deployed as a minimal proxy from the factory's `deploy` function. The `_disableInitializers`\n  /// locks the implementation (logic) contract, preventing any future initialization of it.\n  constructor() {\n    _disableInitializers();\n  }\n\n  /// @notice Initializes a new `LlamaCore` clone.\n  /// @dev This function is called by the `deploy` function in the `LlamaFactory` contract. The `initializer` modifier\n  /// ensures that this function can be invoked at most once.\n  /// @param config The struct that contains the configuration for this Llama instance. See `Structs.sol` for details on\n  /// the parameters\n  /// @param policyLogic The `LlamaPolicy` implementation (logic) contract\n  /// @param policyMetadataLogic The `LlamaPolicyMetadata` implementation (logic) contract\n  function initialize(\n    LlamaInstanceConfig calldata config,\n    LlamaPolicy policyLogic,\n    ILlamaPolicyMetadata policyMetadataLogic\n  ) external initializer {\n    name = config.name;\n    // Deploy the executor.\n    executor = new LlamaExecutor();\n\n    // Since the `LlamaCore` salt is dependent on the name and deployer, we can use a constant salt of 0 here.\n    // The policy address will still be deterministic and dependent on the name and deployer because with CREATE2\n    // the resulting address is a function of the deployer address (the core address).\n    policy = LlamaPolicy(Clones.cloneDeterministic(address(policyLogic), 0));\n\n    // Calculated from the first strategy configuration passed in.\n    ILlamaStrategy bootstrapStrategy = ILlamaStrategy(\n      Clones.predictDeterministicAddress(\n        address(config.strategyLogic), keccak256(config.initialStrategies[0]), address(this)\n      )\n    );\n    PermissionData memory bootstrapPermissionData =\n      PermissionData(address(policy), LlamaPolicy.setRolePermission.selector, bootstrapStrategy);\n\n    // Initialize `LlamaPolicy` with holders of role ID 1 (Bootstrap Role) given permission to change role\n    // permissions. This is required to reduce the chance that an instance is deployed with an invalid configuration\n    // that results in the instance being unusable.\n    policy.initialize(config.name, config.policyConfig, policyMetadataLogic, address(executor), bootstrapPermissionData);\n\n    // Authorize strategy logic contract and deploy strategies.\n    _setStrategyLogicAuthorization(config.strategyLogic, true);\n    _deployStrategies(config.strategyLogic, config.initialStrategies);\n\n    // Check that the bootstrap strategy was deployed and authorized to the pre-calculated address.\n    // This should never be thrown in production and is just here as an extra safety check.\n    if (!strategies[bootstrapStrategy].authorized) revert BootstrapStrategyNotAuthorized();\n\n    // Authorize account logic contract and deploy accounts.\n    _setAccountLogicAuthorization(config.accountLogic, true);\n    _deployAccounts(config.accountLogic, config.initialAccounts);\n  }\n\n  // ===========================================\n  // ======== External and Public Logic ========\n  // ===========================================\n\n  // -------- Action Lifecycle Management --------\n\n  /// @notice Creates an action. The creator needs to hold a policy with the permission ID of the provided\n  /// `(target, selector, strategy)`.\n  /// @dev Use `\"\"` for `description` if there is no description.\n  /// @param role The role that will be used to determine the permission ID of the policyholder.\n  /// @param strategy The strategy contract that will determine how the action is executed.\n  /// @param target The contract called when the action is executed.\n  /// @param value The value in wei to be sent when the action is executed.\n  /// @param data Data to be called on the target when the action is executed.\n  /// @param description A human readable description of the action and the changes it will enact.\n  /// @return actionId Action ID of the newly created action.\n  function createAction(\n    uint8 role,\n    ILlamaStrategy strategy,\n    address target,\n    uint256 value,\n    bytes calldata data,\n    string memory description\n  ) external returns (uint256 actionId) {\n    actionId = _createAction(msg.sender, role, strategy, target, value, data, description);\n  }\n\n  /// @notice Creates an action via an off-chain signature. The creator needs to hold a policy with the permission ID\n  /// of the provided `(target, selector, strategy)`.\n  /// @dev Use `\"\"` for `description` if there is no description.\n  /// @param policyholder The policyholder that signed the message.\n  /// @param role The role that will be used to determine the permission ID of the policyholder.\n  /// @param strategy The strategy contract that will determine how the action is executed.\n  /// @param target The contract called when the action is executed.\n  /// @param value The value in wei to be sent when the action is executed.\n  /// @param data Data to be called on the target when the action is executed.\n  /// @param description A human readable description of the action and the changes it will enact.\n  /// @param v ECDSA signature component: Parity of the `y` coordinate of point `R`\n  /// @param r ECDSA signature component: x-coordinate of `R`\n  /// @param s ECDSA signature component: `s` value of the signature\n  /// @return actionId Action ID of the newly created action.\n  function createActionBySig(\n    address policyholder,\n    uint8 role,\n    ILlamaStrategy strategy,\n    address target,\n    uint256 value,\n    bytes calldata data,\n    string memory description,\n    uint8 v,\n    bytes32 r,\n    bytes32 s\n  ) external returns (uint256 actionId) {\n    bytes32 digest = _getCreateActionTypedDataHash(policyholder, role, strategy, target, value, data, description);\n    address signer = ecrecover(digest, v, r, s);\n    if (signer == address(0) || signer != policyholder) revert InvalidSignature();\n    actionId = _createAction(signer, role, strategy, target, value, data, description);\n  }\n\n  /// @notice Queue an action by its `actionInfo` struct if it's in Approved state.\n  /// @param actionInfo Data required to create an action.\n  function queueAction(ActionInfo calldata actionInfo) external {\n    Action storage action = actions[actionInfo.id];\n    ActionState currentState = getActionState(actionInfo);\n    if (currentState != ActionState.Approved) revert InvalidActionState(currentState);\n\n    _queueAction(action, actionInfo);\n  }\n\n  /// @notice Execute an action by its `actionInfo` struct if it's in Queued state and `minExecutionTime` has passed.\n  /// @param actionInfo Data required to create an action.\n  function executeAction(ActionInfo calldata actionInfo) external payable {\n    // Initial checks that action is ready to execute.\n    Action storage action = actions[actionInfo.id];\n    ActionState currentState = getActionState(actionInfo);\n\n    if (currentState != ActionState.Queued) revert InvalidActionState(currentState);\n    if (block.timestamp < action.minExecutionTime) revert MinExecutionTimeNotReached();\n    if (msg.value != actionInfo.value) revert IncorrectMsgValue();\n\n    action.executed = true;\n\n    // Check pre-execution action guard.\n    ILlamaActionGuard guard = action.guard;\n    if (guard != ILlamaActionGuard(address(0))) guard.validatePreActionExecution(actionInfo);\n\n    // Execute action.\n    (bool success, bytes memory result) =\n      executor.execute{value: actionInfo.value}(actionInfo.target, action.isScript, actionInfo.data);\n\n    if (!success) revert FailedActionExecution(result);\n\n    // Check post-execution action guard.\n    if (guard != ILlamaActionGuard(address(0))) guard.validatePostActionExecution(actionInfo);\n\n    // Action successfully executed.\n    emit ActionExecuted(actionInfo.id, msg.sender, actionInfo.strategy, actionInfo.creator, result);\n  }\n\n  /// @notice Cancels an action by its `actionInfo` struct.\n  /// @dev Rules for cancelation are defined by the strategy.\n  /// @param actionInfo Data required to create an action.\n  function cancelAction(ActionInfo calldata actionInfo) external {\n    _cancelAction(msg.sender, actionInfo);\n  }\n\n  /// @notice Cancels an action by its `actionInfo` struct via an off-chain signature.\n  /// @dev Rules for cancelation are defined by the strategy.\n  /// @param policyholder The policyholder that signed the message.\n  /// @param actionInfo Data required to create an action.\n  /// @param v ECDSA signature component: Parity of the `y` coordinate of point `R`\n  /// @param r ECDSA signature component: x-coordinate of `R`\n  /// @param s ECDSA signature component: `s` value of the signature\n  function cancelActionBySig(address policyholder, ActionInfo calldata actionInfo, uint8 v, bytes32 r, bytes32 s)\n    external\n  {\n    bytes32 digest = _getCancelActionTypedDataHash(policyholder, actionInfo);\n    address signer = ecrecover(digest, v, r, s);\n    if (signer == address(0) || signer != policyholder) revert InvalidSignature();\n    _cancelAction(signer, actionInfo);\n  }\n\n  /// @notice How policyholders add their support of the approval of an action with a reason.\n  /// @dev Use `\"\"` for `reason` if there is no reason.\n  /// @param role The role the policyholder uses to cast their approval.\n  /// @param actionInfo Data required to create an action.\n  /// @param reason The reason given for the approval by the policyholder.\n  /// @return The quantity of the cast.\n  function castApproval(uint8 role, ActionInfo calldata actionInfo, string calldata reason) external returns (uint96) {\n    return _castApproval(msg.sender, role, actionInfo, reason);\n  }\n\n  /// @notice How policyholders add their support of the approval of an action via an off-chain signature.\n  /// @dev Use `\"\"` for `reason` if there is no reason.\n  /// @param policyholder The policyholder that signed the message.\n  /// @param role The role the policyholder uses to cast their approval.\n  /// @param actionInfo Data required to create an action.\n  /// @param reason The reason given for the approval by the policyholder.\n  /// @param v ECDSA signature component: Parity of the `y` coordinate of point `R`\n  /// @param r ECDSA signature component: x-coordinate of `R`\n  /// @param s ECDSA signature component: `s` value of the signature\n  /// @return The quantity of the cast.\n  function castApprovalBySig(\n    address policyholder,\n    uint8 role,\n    ActionInfo calldata actionInfo,\n    string calldata reason,\n    uint8 v,\n    bytes32 r,\n    bytes32 s\n  ) external returns (uint96) {\n    bytes32 digest = _getCastApprovalTypedDataHash(policyholder, role, actionInfo, reason);\n    address signer = ecrecover(digest, v, r, s);\n    if (signer == address(0) || signer != policyholder) revert InvalidSignature();\n    return _castApproval(signer, role, actionInfo, reason);\n  }\n\n  /// @notice How policyholders add their support of the disapproval of an action with a reason.\n  /// @dev Use `\"\"` for `reason` if there is no reason.\n  /// @param role The role the policyholder uses to cast their disapproval.\n  /// @param actionInfo Data required to create an action.\n  /// @param reason The reason given for the disapproval by the policyholder.\n  /// @return The quantity of the cast.\n  function castDisapproval(uint8 role, ActionInfo calldata actionInfo, string calldata reason)\n    external\n    returns (uint96)\n  {\n    return _castDisapproval(msg.sender, role, actionInfo, reason);\n  }\n\n  /// @notice How policyholders add their support of the disapproval of an action via an off-chain signature.\n  /// @dev Use `\"\"` for `reason` if there is no reason.\n  /// @param policyholder The policyholder that signed the message.\n  /// @param role The role the policyholder uses to cast their disapproval.\n  /// @param actionInfo Data required to create an action.\n  /// @param reason The reason given for the approval by the policyholder.\n  /// @param v ECDSA signature component: Parity of the `y` coordinate of point `R`\n  /// @param r ECDSA signature component: x-coordinate of `R`\n  /// @param s ECDSA signature component: `s` value of the signature\n  /// @return The quantity of the cast.\n  function castDisapprovalBySig(\n    address policyholder,\n    uint8 role,\n    ActionInfo calldata actionInfo,\n    string calldata reason,\n    uint8 v,\n    bytes32 r,\n    bytes32 s\n  ) external returns (uint96) {\n    bytes32 digest = _getCastDisapprovalTypedDataHash(policyholder, role, actionInfo, reason);\n    address signer = ecrecover(digest, v, r, s);\n    if (signer == address(0) || signer != policyholder) revert InvalidSignature();\n    return _castDisapproval(signer, role, actionInfo, reason);\n  }\n\n  // -------- Instance Management --------\n\n  /// @notice Sets `strategyLogic` authorization status, which determines if it can be used to create new strategies.\n  /// @dev Unauthorizing a strategy logic contract will not affect previously deployed strategies.\n  /// @dev Be careful not to conflate this with `setStrategyAuthorization`.\n  /// @param strategyLogic The strategy logic contract to authorize.\n  /// @param authorized `true` to authorize the strategy logic, `false` to unauthorize it.\n  function setStrategyLogicAuthorization(ILlamaStrategy strategyLogic, bool authorized) external onlyLlama {\n    _setStrategyLogicAuthorization(strategyLogic, authorized);\n  }\n\n  /// @notice Deploy new strategies and add them to the mapping of authorized strategies.\n  /// @param llamaStrategyLogic address of the Llama strategy logic contract.\n  /// @param strategyConfigs Array of new strategy configurations.\n  function createStrategies(ILlamaStrategy llamaStrategyLogic, bytes[] calldata strategyConfigs) external onlyLlama {\n    _deployStrategies(llamaStrategyLogic, strategyConfigs);\n  }\n\n  /// @notice Sets `strategy` authorization status, which determines if it can be used to create actions.\n  /// @dev To unauthorize a deployed `strategy`, set `authorized` to `false`.\n  /// @dev Be careful not to conflate this with `setStrategyLogicAuthorization`.\n  /// @param strategy The address of the deployed strategy contract.\n  /// @param authorized `true` to authorize the strategy, `false` to unauthorize it.\n  function setStrategyAuthorization(ILlamaStrategy strategy, bool authorized) external onlyLlama {\n    _setStrategyAuthorization(strategy, authorized);\n  }\n\n  /// @notice Sets `accountLogic` authorization status, which determines if it can be used to create new accounts.\n  /// @dev Unauthorizing an account logic contract will not affect previously deployed accounts.\n  /// @param accountLogic The account logic contract to authorize.\n  /// @param authorized `true` to authorize the account logic, `false` to unauthorize it.\n  function setAccountLogicAuthorization(ILlamaAccount accountLogic, bool authorized) external onlyLlama {\n    _setAccountLogicAuthorization(accountLogic, authorized);\n  }\n\n  /// @notice Deploy new accounts.\n  /// @param llamaAccountLogic address of the Llama account logic contract.\n  /// @param accountConfigs Array of new account configurations.\n  function createAccounts(ILlamaAccount llamaAccountLogic, bytes[] calldata accountConfigs) external onlyLlama {\n    _deployAccounts(llamaAccountLogic, accountConfigs);\n  }\n\n  /// @notice Sets `guard` as the action guard for the given `target` and `selector`.\n  /// @dev To remove a guard, set `guard` to the zero address.\n  /// @param target The target contract where the `guard` will apply.\n  /// @param selector The function selector where the `guard` will apply.\n  function setGuard(address target, bytes4 selector, ILlamaActionGuard guard) external onlyLlama {\n    if (target == address(this) || target == address(policy)) revert RestrictedAddress();\n    actionGuard[target][selector] = guard;\n    emit ActionGuardSet(target, selector, guard);\n  }\n\n  /// @notice Sets `script` authorization status, which determines if it can be delegatecalled from the executor.\n  /// @dev To unauthorize a `script`, set `authorized` to `false`.\n  /// @param script The address of the script contract.\n  /// @param authorized `true` to authorize the script, `false` to unauthorize it.\n  function setScriptAuthorization(address script, bool authorized) external onlyLlama {\n    if (script == address(this) || script == address(policy)) revert RestrictedAddress();\n    authorizedScripts[script] = authorized;\n    emit ScriptAuthorizationSet(script, authorized);\n  }\n\n  // -------- User Nonce Management --------\n\n  /// @notice Increments the caller's nonce for the given `selector`. This is useful for revoking\n  /// signatures that have not been used yet.\n  /// @param selector The function selector to increment the nonce for.\n  function incrementNonce(bytes4 selector) external {\n    // Safety: Can never overflow a uint256 by incrementing.\n    nonces[msg.sender][selector] = LlamaUtils.uncheckedIncrement(nonces[msg.sender][selector]);\n  }\n\n  // -------- Action and State Getters --------\n\n  /// @notice Get an Action struct by `actionId`.\n  /// @param actionId ID of the action.\n  /// @return The Action struct.\n  function getAction(uint256 actionId) external view returns (Action memory) {\n    return actions[actionId];\n  }\n\n  /// @notice Get the current action state of an action by its `actionInfo` struct.\n  /// @param actionInfo Data required to create an action.\n  /// @return The current action state of the action.\n  function getActionState(ActionInfo calldata actionInfo) public view returns (ActionState) {\n    // We don't need an explicit check on the action ID to make sure it exists, because if the\n    // action does not exist, the expected payload hash from storage will be `bytes32(0)`, so\n    // bypassing this check by providing a non-existent actionId would require finding a collision\n    // to get a hash of zero.\n    Action storage action = actions[actionInfo.id];\n    _validateActionInfoHash(action.infoHash, actionInfo);\n\n    if (action.canceled) return ActionState.Canceled;\n\n    if (action.executed) return ActionState.Executed;\n\n    if (actionInfo.strategy.isActionActive(actionInfo)) return ActionState.Active;\n\n    if (!actionInfo.strategy.isActionApproved(actionInfo)) return ActionState.Failed;\n\n    if (action.minExecutionTime == 0) return ActionState.Approved;\n\n    if (actionInfo.strategy.isActionDisapproved(actionInfo)) return ActionState.Failed;\n\n    if (actionInfo.strategy.isActionExpired(actionInfo)) return ActionState.Expired;\n\n    return ActionState.Queued;\n  }\n\n  // ================================\n  // ======== Internal Logic ========\n  // ================================\n\n  /// @dev Creates an action. The creator needs to hold a policy with the permission ID of the provided\n  /// `(target, selector, strategy)`.\n  function _createAction(\n    address policyholder,\n    uint8 role,\n    ILlamaStrategy strategy,\n    address target,\n    uint256 value,\n    bytes calldata data,\n    string memory description\n  ) internal returns (uint256 actionId) {\n    if (target == address(executor)) revert CannotSetExecutorAsTarget();\n    if (!strategies[strategy].authorized) revert UnauthorizedStrategy();\n\n    PermissionData memory permission = PermissionData(target, bytes4(data), strategy);\n    bytes32 permissionId = LlamaUtils.computePermissionId(permission);\n\n    // Typically (such as in Governor contracts) this should check that the caller has permission\n    // at `block.number|timestamp - 1` but here we're just checking if the caller *currently* has\n    // permission. Technically this introduces a race condition if e.g. an action to revoke a role\n    // from someone (or revoke a permission from a role) is ready to be executed at the same time as\n    // an action is created, as the order of transactions in the block then affects if action\n    // creation would succeed. However, we are ok with this tradeoff because it means we don't need\n    // to checkpoint the `canCreateAction` mapping which is simpler and cheaper, and in practice\n    // this race condition is unlikely to matter.\n    if (!policy.hasPermissionId(policyholder, role, permissionId)) revert PolicyholderDoesNotHavePermission();\n\n    // Update `actionsCount` and create `actionInfo` struct.\n    actionId = actionsCount;\n    actionsCount = LlamaUtils.uncheckedIncrement(actionsCount); // Safety: Can never overflow a uint256 by incrementing.\n    ActionInfo memory actionInfo = ActionInfo(actionId, policyholder, role, strategy, target, value, data);\n\n    // Scope to avoid stack too deep\n    {\n      // Save action.\n      Action storage newAction = actions[actionId];\n      newAction.infoHash = _infoHash(actionInfo);\n      newAction.creationTime = LlamaUtils.toUint64(block.timestamp);\n      newAction.isScript = authorizedScripts[target];\n\n      // Validate action creation.\n      strategy.validateActionCreation(actionInfo);\n\n      ILlamaActionGuard guard = actionGuard[target][bytes4(data)];\n      if (guard != ILlamaActionGuard(address(0))) {\n        guard.validateActionCreation(actionInfo);\n        newAction.guard = guard;\n      }\n    }\n\n    emit ActionCreated(actionId, policyholder, role, strategy, target, value, data, description);\n  }\n\n  /// @dev Cancels an action by its `actionInfo` struct.\n  function _cancelAction(address policyholder, ActionInfo calldata actionInfo) internal {\n    Action storage action = actions[actionInfo.id];\n    _validateActionInfoHash(action.infoHash, actionInfo);\n\n    // We don't need an explicit check on action existence because if it doesn't exist the strategy will be the zero\n    // address, and Solidity will revert since there is no code at the zero address.\n    actionInfo.strategy.validateActionCancelation(actionInfo, policyholder);\n\n    action.canceled = true;\n    emit ActionCanceled(actionInfo.id, policyholder);\n  }\n\n  /// @dev How policyholders that have the right role contribute towards the approval of an action with a reason.\n  function _castApproval(address policyholder, uint8 role, ActionInfo calldata actionInfo, string memory reason)\n    internal\n    returns (uint96)\n  {\n    (Action storage action, uint96 quantity) = _preCastAssertions(actionInfo, policyholder, role, ActionState.Active);\n\n    action.totalApprovals = _newCastCount(action.totalApprovals, quantity);\n    approvals[actionInfo.id][policyholder] = true;\n    emit ApprovalCast(actionInfo.id, policyholder, role, quantity, reason);\n\n    // We call `getActionState` here to determine if we should queue the action. This works because the ordering\n    // in `LlamaCore.getActionState` checks `.isActionActive()` first, and if not, then it calls `.isActionApproved`.\n    // If `.isActionActive()` returns `true`, then we don't queue.\n    // If `.isActionApproved()` returns `true`, then we queue.\n    ActionState currentState = getActionState(actionInfo);\n    if (currentState == ActionState.Approved) _queueAction(action, actionInfo);\n\n    return quantity;\n  }\n\n  /// @dev How policyholders that have the right role contribute towards the disapproval of an action with a reason.\n  function _castDisapproval(address policyholder, uint8 role, ActionInfo calldata actionInfo, string memory reason)\n    internal\n    returns (uint96)\n  {\n    (Action storage action, uint96 quantity) = _preCastAssertions(actionInfo, policyholder, role, ActionState.Queued);\n\n    action.totalDisapprovals = _newCastCount(action.totalDisapprovals, quantity);\n    disapprovals[actionInfo.id][policyholder] = true;\n    emit DisapprovalCast(actionInfo.id, policyholder, role, quantity, reason);\n    return quantity;\n  }\n\n  /// @dev Updates state of an action to `ActionState::Queued` and emits an event. Used in `queueAction` and\n  /// `_castApproval`.\n  function _queueAction(Action storage action, ActionInfo calldata actionInfo) internal {\n    uint64 minExecutionTime = actionInfo.strategy.minExecutionTime(actionInfo);\n    if (minExecutionTime < block.timestamp) revert MinExecutionTimeCannotBeInThePast();\n    action.minExecutionTime = minExecutionTime;\n    emit ActionQueued(actionInfo.id, msg.sender, actionInfo.strategy, actionInfo.creator, minExecutionTime);\n  }\n\n  /// @dev The only `expectedState` values allowed to be passed into this method are Active or Queued.\n  function _preCastAssertions(\n    ActionInfo calldata actionInfo,\n    address policyholder,\n    uint8 role,\n    ActionState expectedState\n  ) internal view returns (Action storage action, uint96 quantity) {\n    action = actions[actionInfo.id];\n    ActionState currentState = getActionState(actionInfo);\n    if (currentState != expectedState) revert InvalidActionState(currentState);\n\n    bool isApproval = expectedState == ActionState.Active;\n    bool alreadyCast = isApproval ? approvals[actionInfo.id][policyholder] : disapprovals[actionInfo.id][policyholder];\n    if (alreadyCast) revert DuplicateCast();\n\n    // We look up data at `action.creationTime - 1` to avoid race conditions: A user's role balances\n    // can change after action creation in the same block, so we can't actually know what the\n    // correct values are at the time of action creation.\n    uint256 checkpointTime = action.creationTime - 1;\n    bool hasRole = policy.hasRole(policyholder, role, checkpointTime);\n    if (!hasRole) revert InvalidPolicyholder();\n\n    if (isApproval) {\n      actionInfo.strategy.checkIfApprovalEnabled(actionInfo, policyholder, role);\n      quantity = actionInfo.strategy.getApprovalQuantityAt(policyholder, role, checkpointTime);\n      if (quantity == 0) revert CannotCastWithZeroQuantity(policyholder, role);\n    } else {\n      if (block.timestamp >= action.minExecutionTime) revert CannotDisapproveAfterMinExecutionTime();\n      actionInfo.strategy.checkIfDisapprovalEnabled(actionInfo, policyholder, role);\n      quantity = actionInfo.strategy.getDisapprovalQuantityAt(policyholder, role, checkpointTime);\n      if (quantity == 0) revert CannotCastWithZeroQuantity(policyholder, role);\n    }\n  }\n\n  /// @dev Returns the new total count of approvals or disapprovals.\n  function _newCastCount(uint96 currentCount, uint96 quantity) internal pure returns (uint96) {\n    if (uint256(currentCount) + quantity >= type(uint96).max) return type(uint96).max;\n    return currentCount + quantity;\n  }\n\n  /// @dev Sets the authorization status for a strategy implementation (logic) contract.\n  function _setStrategyLogicAuthorization(ILlamaStrategy strategyLogic, bool authorized) internal {\n    authorizedStrategyLogics[strategyLogic] = authorized;\n    emit StrategyLogicAuthorizationSet(strategyLogic, authorized);\n  }\n\n  /// @dev Deploys new strategies. Takes in the strategy logic contract to be used and an array of configurations to\n  /// initialize the new strategies with.\n  function _deployStrategies(ILlamaStrategy llamaStrategyLogic, bytes[] calldata strategyConfigs) internal {\n    if (!authorizedStrategyLogics[llamaStrategyLogic]) revert UnauthorizedStrategyLogic();\n\n    uint256 strategyLength = strategyConfigs.length;\n    for (uint256 i = 0; i < strategyLength; i = LlamaUtils.uncheckedIncrement(i)) {\n      bytes32 salt = keccak256(strategyConfigs[i]);\n      ILlamaStrategy strategy = ILlamaStrategy(Clones.cloneDeterministic(address(llamaStrategyLogic), salt));\n      strategy.initialize(strategyConfigs[i]);\n      strategies[strategy].deployed = true;\n      _setStrategyAuthorization(strategy, true);\n      emit StrategyCreated(strategy, llamaStrategyLogic, strategyConfigs[i]);\n    }\n  }\n\n  /// @dev Sets the `strategy` authorization status to `authorized`.\n  function _setStrategyAuthorization(ILlamaStrategy strategy, bool authorized) internal {\n    if (!strategies[strategy].deployed) revert NonExistentStrategy();\n    strategies[strategy].authorized = authorized;\n    emit StrategyAuthorizationSet(strategy, authorized);\n  }\n\n  /// @dev Authorizes an account implementation (logic) contract.\n  function _setAccountLogicAuthorization(ILlamaAccount accountLogic, bool authorized) internal {\n    authorizedAccountLogics[accountLogic] = authorized;\n    emit AccountLogicAuthorizationSet(accountLogic, authorized);\n  }\n\n  /// @dev Deploys new accounts. Takes in the account logic contract to be used and an array of configurations to\n  /// initialize the new accounts with.\n  function _deployAccounts(ILlamaAccount llamaAccountLogic, bytes[] calldata accountConfigs) internal {\n    if (!authorizedAccountLogics[llamaAccountLogic]) revert UnauthorizedAccountLogic();\n\n    uint256 accountLength = accountConfigs.length;\n    for (uint256 i = 0; i < accountLength; i = LlamaUtils.uncheckedIncrement(i)) {\n      bytes32 salt = keccak256(accountConfigs[i]);\n      ILlamaAccount account = ILlamaAccount(Clones.cloneDeterministic(address(llamaAccountLogic), salt));\n      account.initialize(accountConfigs[i]);\n      emit AccountCreated(account, llamaAccountLogic, accountConfigs[i]);\n    }\n  }\n\n  /// @dev Returns the hash of the `createAction` parameters using the `actionInfo` struct.\n  function _infoHash(ActionInfo memory actionInfo) internal pure returns (bytes32) {\n    return keccak256(\n      abi.encodePacked(\n        actionInfo.id,\n        actionInfo.creator,\n        actionInfo.creatorRole,\n        actionInfo.strategy,\n        actionInfo.target,\n        actionInfo.value,\n        actionInfo.data\n      )\n    );\n  }\n\n  /// @dev Validates that the hash of the `actionInfo` struct matches the provided hash.\n  function _validateActionInfoHash(bytes32 actualHash, ActionInfo calldata actionInfo) internal pure {\n    bytes32 expectedHash = _infoHash(actionInfo);\n    if (actualHash != expectedHash) revert InfoHashMismatch();\n  }\n\n  /// @dev Returns the current nonce for a given policyholder and selector, and increments it. Used to prevent\n  /// replay attacks.\n  function _useNonce(address policyholder, bytes4 selector) internal returns (uint256 nonce) {\n    nonce = nonces[policyholder][selector];\n    nonces[policyholder][selector] = LlamaUtils.uncheckedIncrement(nonce);\n  }\n\n  // -------- EIP-712 Getters --------\n\n  /// @dev Returns the EIP-712 domain separator.\n  function _getDomainHash() internal view returns (bytes32) {\n    return keccak256(\n      abi.encode(EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(\"1\")), block.chainid, address(this))\n    );\n  }\n\n  /// @dev Returns the hash of the ABI-encoded EIP-712 message for the `CreateAction` domain, which can be used to\n  /// recover the signer.\n  function _getCreateActionTypedDataHash(\n    address policyholder,\n    uint8 role,\n    ILlamaStrategy strategy,\n    address target,\n    uint256 value,\n    bytes calldata data,\n    string memory description\n  ) internal returns (bytes32) {\n    // Calculating and storing nonce in memory and using that below, instead of calculating in place to prevent stack\n    // too deep error.\n    uint256 nonce = _useNonce(policyholder, msg.sig);\n\n    bytes32 createActionHash = keccak256(\n      abi.encode(\n        CREATE_ACTION_TYPEHASH,\n        policyholder,\n        role,\n        address(strategy),\n        target,\n        value,\n        keccak256(data),\n        keccak256(bytes(description)),\n        nonce\n      )\n    );\n\n    return keccak256(abi.encodePacked(\"\\x19\\x01\", _getDomainHash(), createActionHash));\n  }\n\n  /// @dev Returns the hash of the ABI-encoded EIP-712 message for the `CancelAction` domain, which can be used to\n  /// recover the signer.\n  function _getCancelActionTypedDataHash(address policyholder, ActionInfo calldata actionInfo)\n    internal\n    returns (bytes32)\n  {\n    bytes32 cancelActionHash = keccak256(\n      abi.encode(CANCEL_ACTION_TYPEHASH, policyholder, _getActionInfoHash(actionInfo), _useNonce(policyholder, msg.sig))\n    );\n\n    return keccak256(abi.encodePacked(\"\\x19\\x01\", _getDomainHash(), cancelActionHash));\n  }\n\n  /// @dev Returns the hash of the ABI-encoded EIP-712 message for the `CastApproval` domain, which can be used to\n  /// recover the signer.\n  function _getCastApprovalTypedDataHash(\n    address policyholder,\n    uint8 role,\n    ActionInfo calldata actionInfo,\n    string calldata reason\n  ) internal returns (bytes32) {\n    bytes32 castApprovalHash = keccak256(\n      abi.encode(\n        CAST_APPROVAL_TYPEHASH,\n        policyholder,\n        role,\n        _getActionInfoHash(actionInfo),\n        keccak256(bytes(reason)),\n        _useNonce(policyholder, msg.sig)\n      )\n    );\n\n    return keccak256(abi.encodePacked(\"\\x19\\x01\", _getDomainHash(), castApprovalHash));\n  }\n\n  /// @dev Returns the hash of the ABI-encoded EIP-712 message for the `CastDisapproval` domain, which can be used to\n  /// recover the signer.\n  function _getCastDisapprovalTypedDataHash(\n    address policyholder,\n    uint8 role,\n    ActionInfo calldata actionInfo,\n    string calldata reason\n  ) internal returns (bytes32) {\n    bytes32 castDisapprovalHash = keccak256(\n      abi.encode(\n        CAST_DISAPPROVAL_TYPEHASH,\n        policyholder,\n        role,\n        _getActionInfoHash(actionInfo),\n        keccak256(bytes(reason)),\n        _useNonce(policyholder, msg.sig)\n      )\n    );\n\n    return keccak256(abi.encodePacked(\"\\x19\\x01\", _getDomainHash(), castDisapprovalHash));\n  }\n\n  /// @dev Returns the hash of `actionInfo`.\n  function _getActionInfoHash(ActionInfo calldata actionInfo) internal pure returns (bytes32) {\n    return keccak256(\n      abi.encode(\n        ACTION_INFO_TYPEHASH,\n        actionInfo.id,\n        actionInfo.creator,\n        actionInfo.creatorRole,\n        address(actionInfo.strategy),\n        actionInfo.target,\n        actionInfo.value,\n        keccak256(actionInfo.data)\n      )\n    );\n  }\n}\n"
      },
      "lib/openzeppelin-contracts/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"
      },
      "lib/openzeppelin-contracts/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"
      },
      "lib/openzeppelin-contracts/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"
      },
      "lib/openzeppelin-contracts/contracts/token/ERC1155/utils/ERC1155Receiver.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC1155/utils/ERC1155Receiver.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC1155Receiver.sol\";\nimport \"../../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev _Available since v3.1._\n */\nabstract contract ERC1155Receiver is ERC165, IERC1155Receiver {\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n        return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);\n    }\n}\n"
      },
      "src/lib/Structs.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.19;\n\nimport {ILlamaAccount} from \"src/interfaces/ILlamaAccount.sol\";\nimport {ILlamaActionGuard} from \"src/interfaces/ILlamaActionGuard.sol\";\nimport {ILlamaStrategy} from \"src/interfaces/ILlamaStrategy.sol\";\nimport {RoleDescription} from \"src/lib/UDVTs.sol\";\n\n/// @dev Data required to create an action.\nstruct ActionInfo {\n  uint256 id; // ID of the action.\n  address creator; // Address that created the action.\n  uint8 creatorRole; // The role that created the action.\n  ILlamaStrategy strategy; // Strategy used to govern the action.\n  address target; // Contract being called by an action.\n  uint256 value; // Value in wei to be sent when the action is executed.\n  bytes data; // Data to be called on the target when the action is executed.\n}\n\n/// @dev Data that represents an action.\nstruct Action {\n  // Instead of storing all data required to execute an action in storage, we only save the hash to\n  // make action creation cheaper. The hash is computed by taking the keccak256 hash of the concatenation of each\n  // field in the `ActionInfo` struct.\n  bytes32 infoHash;\n  bool executed; // Has action executed.\n  bool canceled; // Is action canceled.\n  bool isScript; // Is the action's target a script.\n  ILlamaActionGuard guard; // The action's guard. This is the address(0) if no guard is set on the action's target and\n    // selector pair.\n  uint64 creationTime; // The timestamp when action was created (used for policy snapshots).\n  uint64 minExecutionTime; // Only set when an action is queued. The timestamp when action execution can begin.\n  uint96 totalApprovals; // The total quantity of policyholder approvals.\n  uint96 totalDisapprovals; // The total quantity of policyholder disapprovals.\n}\n\n/// @dev Data that represents a permission.\nstruct PermissionData {\n  address target; // Contract being called by an action.\n  bytes4 selector; // Selector of the function being called by an action.\n  ILlamaStrategy strategy; // Strategy used to govern the action.\n}\n\n/// @dev Data required to assign/revoke a role to/from a policyholder.\nstruct RoleHolderData {\n  uint8 role; // ID of the role to set (uint8 ensures onchain enumerability when burning policies).\n  address policyholder; // Policyholder to assign the role to.\n  uint96 quantity; // Quantity of the role to assign to the policyholder, i.e. their (dis)approval quantity.\n  uint64 expiration; // When the role expires.\n}\n\n/// @dev Data required to assign/revoke a permission to/from a role.\nstruct RolePermissionData {\n  uint8 role; // ID of the role to set (uint8 ensures onchain enumerability when burning policies).\n  PermissionData permissionData; // The `(target, selector, strategy)` tuple that will be keccak256 hashed to\n    // generate the permission ID to assign or unassign to the role\n  bool hasPermission; // Whether to assign the permission or remove the permission.\n}\n\n/// @dev Configuration of a new Llama instance.\nstruct LlamaInstanceConfig {\n  string name; // The name of the Llama instance.\n  ILlamaStrategy strategyLogic; // The initial strategy implementation (logic) contract.\n  ILlamaAccount accountLogic; // The initial account implementation (logic) contract.\n  bytes[] initialStrategies; // Array of initial strategy configurations.\n  bytes[] initialAccounts; // Array of initial account configurations.\n  LlamaPolicyConfig policyConfig; // Configuration of the instance's policy.\n}\n\n/// @dev Configuration of a new Llama policy.\nstruct LlamaPolicyConfig {\n  RoleDescription[] roleDescriptions; // The initial role descriptions.\n  RoleHolderData[] roleHolders; // The `role`, `policyholder`, `quantity` and `expiration` of the initial role holders.\n  RolePermissionData[] rolePermissions; // The `role`, `permissionData`, and  the `hasPermission` boolean.\n  string color; // The primary color of the SVG representation of the instance's policy (e.g. #00FF00).\n  string logo; // The SVG string representing the logo for the deployed Llama instance's NFT.\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/proxy/Clones.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (proxy/Clones.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for\n * deploying minimal proxy contracts, also known as \"clones\".\n *\n * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies\n * > a minimal bytecode implementation that delegates all calls to a known, fixed address.\n *\n * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`\n * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the\n * deterministic method.\n *\n * _Available since v3.4._\n */\nlibrary Clones {\n    /**\n     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.\n     *\n     * This function uses the create opcode, which should never revert.\n     */\n    function clone(address implementation) internal returns (address instance) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes\n            // of the `implementation` address with the bytecode before the address.\n            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))\n            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.\n            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))\n            instance := create(0, 0x09, 0x37)\n        }\n        require(instance != address(0), \"ERC1167: create failed\");\n    }\n\n    /**\n     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.\n     *\n     * This function uses the create2 opcode and a `salt` to deterministically deploy\n     * the clone. Using the same `implementation` and `salt` multiple time will revert, since\n     * the clones cannot be deployed twice at the same address.\n     */\n    function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes\n            // of the `implementation` address with the bytecode before the address.\n            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))\n            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.\n            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))\n            instance := create2(0, 0x09, 0x37, salt)\n        }\n        require(instance != address(0), \"ERC1167: create2 failed\");\n    }\n\n    /**\n     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.\n     */\n    function predictDeterministicAddress(\n        address implementation,\n        bytes32 salt,\n        address deployer\n    ) internal pure returns (address predicted) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let ptr := mload(0x40)\n            mstore(add(ptr, 0x38), deployer)\n            mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)\n            mstore(add(ptr, 0x14), implementation)\n            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)\n            mstore(add(ptr, 0x58), salt)\n            mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))\n            predicted := keccak256(add(ptr, 0x43), 0x55)\n        }\n    }\n\n    /**\n     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.\n     */\n    function predictDeterministicAddress(address implementation, bytes32 salt)\n        internal\n        view\n        returns (address predicted)\n    {\n        return predictDeterministicAddress(implementation, salt, address(this));\n    }\n}\n"
      },
      "src/interfaces/ILlamaActionGuard.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.19;\n\nimport {ActionInfo} from \"src/lib/Structs.sol\";\n\n/// @title Llama Action Guard Interface\n/// @author Llama (devsdosomething@llama.xyz)\n/// @notice Executes checks on action creation and execution to verify that the action is allowed.\n/// @dev Methods are not `view` because (1) an action guard may write to it's own storage, and (2)\n/// Having `view` methods that can revert isn't great UX. Allowing guards to write to their own\n/// storage is useful to persist state between calls to the various guard methods. For example, a\n/// guard may:\n///   - Store the USD price of a token during action creation in `validateActionCreation`.\n///   - Verify the price has not changed by more than a given amount during `validatePreActionExecution`\n///     and save off the current USD value of an account.\n///   - Verify the USD value of an account has not decreased by more than a certain amount during\n///     execution, i.e. between `validatePreActionExecution` and `validatePostActionExecution`.\ninterface ILlamaActionGuard {\n  /// @notice Reverts if action creation is not allowed.\n  /// @param actionInfo Data required to create an action.\n  function validateActionCreation(ActionInfo calldata actionInfo) external;\n\n  /// @notice Called immediately before action execution, and reverts if the action is not allowed\n  /// to be executed.\n  /// @param actionInfo Data required to create an action.\n  function validatePreActionExecution(ActionInfo calldata actionInfo) external;\n\n  /// @notice Called immediately after action execution, and reverts if the just-executed\n  /// action should not have been allowed to execute.\n  /// @param actionInfo Data required to create an action.\n  function validatePostActionExecution(ActionInfo calldata actionInfo) external;\n}\n"
      },
      "src/interfaces/ILlamaPolicyMetadata.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.19;\n\n/// @title Llama Policy Metadata\n/// @author Llama (devsdosomething@llama.xyz)\n/// @notice Interface for utility contract to compute Llama policy metadata.\ninterface ILlamaPolicyMetadata {\n  /// @notice Initializes a new clone of the policy metadata contract.\n  /// @dev This function is called by the `_setAndInitializePolicyMetadata` function in the `LlamaPolicy` contract. The\n  /// `initializer` modifier ensures that this function can be invoked at most once.\n  /// @param config The policy metadata configuration, encoded as bytes to support differing initialization arguments in\n  /// different policy metadata logic contracts.\n  /// @return This return statement must be hardcoded to `true` to ensure that initializing an EOA\n  /// (like the zero address) will revert.\n  function initialize(bytes memory config) external returns (bool);\n\n  /// @notice Returns the token URI for a given Llama policy ID.\n  /// @param name The name of the Llama instance.\n  /// @param executor The executor of the Llama instance.\n  /// @param tokenId The token ID of the Llama policyholder.\n  function getTokenURI(string memory name, address executor, uint256 tokenId) external view returns (string memory);\n\n  /// @notice Returns the contract URI for a Llama instance's policies.\n  /// @param name The name of the Llama instance.\n  /// @param executor The executor of the Llama instance.\n  function getContractURI(string memory name, address executor) external view returns (string memory);\n}\n"
      },
      "src/interfaces/ILlamaStrategy.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.19;\n\nimport {ActionInfo} from \"src/lib/Structs.sol\";\nimport {LlamaCore} from \"src/LlamaCore.sol\";\nimport {LlamaPolicy} from \"src/LlamaPolicy.sol\";\n\n/// @title Llama Strategy Interface\n/// @author Llama (devsdosomething@llama.xyz)\n/// @notice This is the interface for Llama strategies which determine the rules of an action's process.\n/// @dev The interface is sorted by the stage of the action's lifecycle in which the method's are used.\ninterface ILlamaStrategy {\n  // -------- For Inspection --------\n  // These are not strictly required by the core, but are useful for inspecting a strategy contract.\n\n  /// @notice Returns the address of the Llama core that this strategy is registered to.\n  function llamaCore() external view returns (LlamaCore);\n\n  /// @notice Returns the name of the Llama policy that this strategy is registered to.\n  function policy() external view returns (LlamaPolicy);\n\n  // -------- At Strategy Creation --------\n\n  /// @notice Initializes a new clone of the strategy.\n  /// @dev This function is called by the `_deployStrategies` function in the `LlamaCore` contract. The `initializer`\n  /// modifier ensures that this function can be invoked at most once.\n  /// @param config The strategy configuration, encoded as bytes to support differing constructor arguments in\n  /// different strategies.\n  /// @return This return statement must be hardcoded to `true` to ensure that initializing an EOA\n  /// (like the zero address) will revert.\n  function initialize(bytes memory config) external returns (bool);\n\n  // -------- At Action Creation --------\n\n  /// @notice Reverts if action creation is not allowed.\n  /// @param actionInfo Data required to create an action.\n  function validateActionCreation(ActionInfo calldata actionInfo) external view;\n\n  // -------- When Casting Approval --------\n\n  /// @notice Reverts if approvals are not allowed with this strategy for the given policyholder when approving with\n  /// role.\n  /// @param actionInfo Data required to create an action.\n  /// @param policyholder Address of the policyholder.\n  /// @param role The role of the policyholder being used to cast approval.\n  function checkIfApprovalEnabled(ActionInfo calldata actionInfo, address policyholder, uint8 role) external view;\n\n  /// @notice Get the quantity of an approval of a policyholder at a specific timestamp.\n  /// @param policyholder Address of the policyholder.\n  /// @param role The role to check quantity for.\n  /// @param timestamp The timestamp at which to get the approval quantity.\n  /// @return The quantity of the policyholder's approval.\n  function getApprovalQuantityAt(address policyholder, uint8 role, uint256 timestamp) external view returns (uint96);\n\n  // -------- When Casting Disapproval --------\n\n  /// @notice Reverts if disapprovals are not allowed with this strategy for the given policyholder when disapproving\n  /// with role.\n  /// @param actionInfo Data required to create an action.\n  /// @param policyholder Address of the policyholder.\n  /// @param role The role of the policyholder being used to cast disapproval.\n  function checkIfDisapprovalEnabled(ActionInfo calldata actionInfo, address policyholder, uint8 role) external view;\n\n  /// @notice Get the quantity of a disapproval of a policyholder at a specific timestamp.\n  /// @param policyholder Address of the policyholder.\n  /// @param role The role to check quantity for.\n  /// @param timestamp The timestamp at which to get the disapproval quantity.\n  /// @return The quantity of the policyholder's disapproval.\n  function getDisapprovalQuantityAt(address policyholder, uint8 role, uint256 timestamp) external view returns (uint96);\n\n  // -------- When Queueing --------\n\n  /// @notice Returns the earliest timestamp, in seconds, at which an action can be executed.\n  /// @param actionInfo Data required to create an action.\n  /// @return The earliest timestamp at which an action can be executed.\n  function minExecutionTime(ActionInfo calldata actionInfo) external view returns (uint64);\n\n  // -------- When Canceling --------\n\n  /// @notice Reverts if the action cannot be canceled.\n  /// @param actionInfo Data required to create an action.\n  /// @param caller Policyholder initiating the cancelation.\n  function validateActionCancelation(ActionInfo calldata actionInfo, address caller) external view;\n\n  // -------- When Determining Action State --------\n  // These are used during casting of approvals and disapprovals, when queueing, and when executing.\n\n  /// @notice Get whether an action is currently active.\n  /// @param actionInfo Data required to create an action.\n  /// @return Boolean value that is `true` if the action is currently active, `false` otherwise.\n  function isActionActive(ActionInfo calldata actionInfo) external view returns (bool);\n\n  /// @notice Get whether an action has passed the approval process.\n  /// @param actionInfo Data required to create an action.\n  /// @return Boolean value that is `true` if the action has passed the approval process.\n  function isActionApproved(ActionInfo calldata actionInfo) external view returns (bool);\n\n  /// @notice Get whether an action has been vetoed during the disapproval process.\n  /// @param actionInfo Data required to create an action.\n  /// @return Boolean value that is `true` if the action has been vetoed during the disapproval process.\n  function isActionDisapproved(ActionInfo calldata actionInfo) external view returns (bool);\n\n  /// @notice Returns `true` if the action is expired, `false` otherwise.\n  /// @param actionInfo Data required to create an action.\n  /// @return Boolean value that is `true` if the action is expired.\n  function isActionExpired(ActionInfo calldata actionInfo) external view returns (bool);\n}\n"
      },
      "src/lib/Enums.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.19;\n\n/// @dev Possible states of an action during its lifecycle.\nenum ActionState {\n  Active, // Action created and approval period begins.\n  Canceled, // Action canceled by creator.\n  Failed, // Action approval failed.\n  Approved, // Action approval succeeded and ready to be queued.\n  Queued, // Action queued for queueing duration and disapproval period begins.\n  Expired, // block.timestamp is greater than Action's executionTime + expirationDelay.\n  Executed // Action has executed successfully.\n}\n"
      },
      "src/LlamaExecutor.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.19;\n\n/// @title Llama Executor\n/// @author Llama (devsdosomething@llama.xyz)\n/// @notice The exit point of a Llama instance. It calls the target contract during action execution.\ncontract LlamaExecutor {\n  /// @dev Only callable by a Llama instance's core contract.\n  error OnlyLlamaCore();\n\n  /// @notice The core contract for this Llama instance.\n  address public immutable LLAMA_CORE;\n\n  /// @dev This contract is deployed from the core's `initialize` function.\n  constructor() {\n    LLAMA_CORE = msg.sender;\n  }\n\n  /// @notice Called by `executeAction` in the core contract to make the call described by the action.\n  /// @dev Using a separate executor contract ensures `target` being delegatecalled cannot write to `LlamaCore`'s\n  /// storage. By using a sole executor for calls and delegatecalls,\n  /// a Llama instance is represented by one contract address.\n  /// @param target The contract called when the action is executed.\n  /// @param isScript A boolean that determines if the target is a script and should be delegatecalled.\n  /// @param data Data to be called on the `target` when the action is executed.\n  /// @return success A boolean that indicates if the call succeeded.\n  /// @return result The data returned by the function being called.\n  function execute(address target, bool isScript, bytes calldata data)\n    external\n    payable\n    returns (bool success, bytes memory result)\n  {\n    if (msg.sender != LLAMA_CORE) revert OnlyLlamaCore();\n    (success, result) = isScript ? target.delegatecall(data) : target.call{value: msg.value}(data);\n  }\n}\n"
      },
      "src/LlamaPolicy.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.19;\n\nimport {Clones} from \"@openzeppelin/proxy/Clones.sol\";\n\nimport {LibString} from \"@solady/utils/LibString.sol\";\n\nimport {ILlamaPolicyMetadata} from \"src/interfaces/ILlamaPolicyMetadata.sol\";\nimport {PolicyholderCheckpoints} from \"src/lib/PolicyholderCheckpoints.sol\";\nimport {SupplyCheckpoints} from \"src/lib/SupplyCheckpoints.sol\";\nimport {ERC721NonTransferableMinimalProxy} from \"src/lib/ERC721NonTransferableMinimalProxy.sol\";\nimport {LlamaUtils} from \"src/lib/LlamaUtils.sol\";\nimport {LlamaPolicyConfig, PermissionData} from \"src/lib/Structs.sol\";\nimport {RoleDescription} from \"src/lib/UDVTs.sol\";\nimport {LlamaExecutor} from \"src/LlamaExecutor.sol\";\n\n/// @title Llama Policy\n/// @author Llama (devsdosomething@llama.xyz)\n/// @notice An ERC721 contract where each token is non-transferable, functions as the respective policy for a given\n/// policyholder and has roles assigned to `create`, `approve` and `disapprove` actions.\n/// @dev The roles and permissions determine how the policyholder can interact with the Llama core contract.\ncontract LlamaPolicy is ERC721NonTransferableMinimalProxy {\n  using PolicyholderCheckpoints for PolicyholderCheckpoints.History;\n  using SupplyCheckpoints for SupplyCheckpoints.History;\n\n  // ======================================\n  // ======== Errors and Modifiers ========\n  // ======================================\n\n  /// @dev Roleholder cannot be set at the same timestamp as an action creation.\n  error ActionCreationAtSameTimestamp();\n\n  /// @dev Thrown when revoking a policy from an address without one\n  /// @param userAddress The address of the possible policyholder.\n  error AddressDoesNotHoldPolicy(address userAddress);\n\n  /// @dev Cannot set \"all holders\" role.\n  error AllHoldersRole();\n\n  /// @dev Policy can only be initialized once.\n  error AlreadyInitialized();\n\n  /// @dev The indices would result in `Panic: Index Out of Bounds`.\n  /// @dev Thrown when the `end` index is greater than array length or when the `start` index is greater than the `end`\n  /// index.\n  error InvalidIndices();\n\n  /// @dev Thrown when the provided policyholder and role are not in the expected state for the function.\n  error InvalidRoleHolderInput();\n\n  /// @dev Policy tokens cannot be transferred.\n  error NonTransferableToken();\n\n  /// @dev Only callable by a Llama instance's executor.\n  error OnlyLlama();\n\n  /// @dev Only callable by the Llama Factory.\n  error OnlyLlamaFactory();\n\n  /// @dev Operations can only occur on initialized roles.\n  error RoleNotInitialized(uint8 role);\n\n  /// @dev Checks that the caller is the Llama executor and reverts if not.\n  modifier onlyLlama() {\n    if (msg.sender != llamaExecutor) revert OnlyLlama();\n    _;\n  }\n\n  /// @dev Ensures that none of the ERC721 `transfer` and `approval` functions can be called, so that the policies are\n  /// non-transferable.\n  modifier nonTransferableToken() {\n    _; // We put this ahead of the revert so we don't get an unreachable code warning.\n    revert NonTransferableToken();\n  }\n\n  // ========================\n  // ======== Events ========\n  // ========================\n\n  /// @dev Emitted when a policyholder is assigned a role.\n  event RoleAssigned(address indexed policyholder, uint8 indexed role, uint64 expiration, uint96 quantity);\n\n  /// @dev Emitted when a role is initialized with a description.\n  event RoleInitialized(uint8 indexed role, RoleDescription description);\n\n  /// @dev Emitted when a permission ID is assigned to a role.\n  event RolePermissionAssigned(\n    uint8 indexed role, bytes32 indexed permissionId, PermissionData permissionData, bool hasPermission\n  );\n\n  /// @dev Emitted when a new Llama policy metadata contract is set.\n  event PolicyMetadataSet(\n    ILlamaPolicyMetadata policyMetadata, ILlamaPolicyMetadata indexed policyMetadataLogic, bytes initializationData\n  );\n\n  /// @dev Emitted when an expired role is explicitly revoked from a policyholder.\n  event ExpiredRoleRevoked(address indexed caller, address indexed policyholder, uint8 indexed role);\n\n  // =================================================\n  // ======== Constants and Storage Variables ========\n  // =================================================\n\n  /// @dev A special role used to reference all policyholders.\n  uint8 internal constant ALL_HOLDERS_ROLE = 0;\n\n  /// @dev At deployment, this role is given permission to call the `setRolePermission` function.\n  /// However, this may change depending on how the Llama instance is configured. This is done to mitigate the chances\n  /// of deploying a misconfigured Llama instance that is unusable. See the documentation for more info.\n  uint8 internal constant BOOTSTRAP_ROLE = 1;\n\n  /// @dev Tracks total supplies of a given role. There are two notions of total supply:\n  ///   - The `numberOfHolders` is simply the number of policyholders that hold the role.\n  ///   - The `totalQuantity` is the sum of the quantity of the role for each policyholder that\n  ///     holds the role.\n  /// Both versions of supply are tracked to enable different types of strategies.\n  mapping(uint8 role => SupplyCheckpoints.History) internal roleSupplyCkpts;\n\n  /// @dev Checkpoints a token ID's \"balance\" (quantity) of a given role. The quantity of the\n  /// role is how much quantity the role-holder gets when approving/disapproving (regardless of\n  /// strategy).\n  mapping(uint256 tokenId => mapping(uint8 role => PolicyholderCheckpoints.History)) internal roleBalanceCkpts;\n\n  /// @notice Returns `true` if the role can create actions with the given permission ID.\n  mapping(uint8 role => mapping(bytes32 permissionId => bool hasPermission)) public canCreateAction;\n\n  /// @notice The highest role ID that has been initialized.\n  uint8 public numRoles;\n\n  /// @notice The address of the `LlamaExecutor` of this instance.\n  address public llamaExecutor;\n\n  /// @notice The Llama policy metadata contract.\n  ILlamaPolicyMetadata public llamaPolicyMetadata;\n\n  // ======================================================\n  // ======== Contract Creation and Initialization ========\n  // ======================================================\n\n  /// @dev This contract is deployed as a minimal proxy from the core's `initialize` function. The\n  /// `_disableInitializers` locks the implementation (logic) contract, preventing any future initialization of it.\n  constructor() {\n    _disableInitializers();\n  }\n\n  /// @notice Initializes a new `LlamaPolicy` clone.\n  /// @dev This function is called by the `initialize` function in the `LlamaCore` contract. The `initializer` modifier\n  /// ensures that this function can be invoked at most once.\n  /// @param _name The ERC-721 name of the policy NFT.\n  /// @param config The struct that contains the configuration for this instance's policy.\n  /// @param policyMetadataLogic The `LlamaPolicyMetadata` implementation (logic) contract.\n  /// @param executor The instance's `LlamaExecutor`.\n  /// @param bootstrapPermissionData The permission data that hashes to the permission ID that allows policyholders to\n  /// change role permissions.\n  function initialize(\n    string memory _name,\n    LlamaPolicyConfig calldata config,\n    ILlamaPolicyMetadata policyMetadataLogic,\n    address executor,\n    PermissionData memory bootstrapPermissionData\n  ) external initializer {\n    __initializeERC721MinimalProxy(_name, string.concat(\"LL-\", LibString.replace(LibString.upper(_name), \" \", \"-\")));\n    llamaExecutor = executor;\n\n    // Initialize the roles.\n    emit RoleInitialized(ALL_HOLDERS_ROLE, RoleDescription.wrap(\"All Holders\"));\n    for (uint256 i = 0; i < config.roleDescriptions.length; i = LlamaUtils.uncheckedIncrement(i)) {\n      _initializeRole(config.roleDescriptions[i]);\n    }\n\n    // Assign the role holders.\n    for (uint256 i = 0; i < config.roleHolders.length; i = LlamaUtils.uncheckedIncrement(i)) {\n      _setRoleHolder(\n        config.roleHolders[i].role,\n        config.roleHolders[i].policyholder,\n        config.roleHolders[i].quantity,\n        config.roleHolders[i].expiration\n      );\n    }\n\n    // Assign the role permissions.\n    for (uint256 i = 0; i < config.rolePermissions.length; i = LlamaUtils.uncheckedIncrement(i)) {\n      _setRolePermission(\n        config.rolePermissions[i].role,\n        config.rolePermissions[i].permissionData,\n        config.rolePermissions[i].hasPermission\n      );\n    }\n\n    // Must have assigned roles during initialization, otherwise the system cannot be used. However,\n    // we do not check that roles were assigned \"properly\" as there is no single correct way, so\n    // this is more of a sanity check, not a guarantee that the system will work after initialization.\n    if (numRoles == 0 || getRoleSupplyAsNumberOfHolders(ALL_HOLDERS_ROLE) == 0) revert InvalidRoleHolderInput();\n\n    // Gives holders of role ID 1 permission to change role permissions. This is required to reduce the chance that an\n    // instance is deployed with an invalid configuration that results in the instance being unusable.\n    _setRolePermission(BOOTSTRAP_ROLE, bootstrapPermissionData, true);\n\n    _setAndInitializePolicyMetadata(policyMetadataLogic, abi.encode(config.color, config.logo));\n  }\n\n  // ===========================================\n  // ======== External and Public Logic ========\n  // ===========================================\n\n  // -------- Role and Permission Management --------\n\n  /// @notice Initializes the next unassigned role with the given `description`.\n  /// @param description The description of the role to initialize.\n  function initializeRole(RoleDescription description) external onlyLlama {\n    _initializeRole(description);\n  }\n\n  /// @notice Assigns a role to a policyholder.\n  /// @param role ID of the role to set (uint8 ensures onchain enumerability when burning policies).\n  /// @param policyholder Policyholder to assign the role to.\n  /// @param quantity Quantity of the role to assign to the policyholder, i.e. their (dis)approval quantity.\n  /// @param expiration When the role expires.\n  function setRoleHolder(uint8 role, address policyholder, uint96 quantity, uint64 expiration) external onlyLlama {\n    _setRoleHolder(role, policyholder, quantity, expiration);\n  }\n\n  /// @notice Assigns a permission ID to a role.\n  /// @param role ID of the role to assign permission to.\n  /// @param permissionData The `(target, selector, strategy)` tuple that will be keccak256 hashed to generate the\n  /// permission ID to assign or unassign to the role.\n  /// @param hasPermission Whether to assign the permission or remove the permission.\n  function setRolePermission(uint8 role, PermissionData memory permissionData, bool hasPermission) external onlyLlama {\n    _setRolePermission(role, permissionData, hasPermission);\n  }\n\n  /// @notice Revokes a policyholder's expired role.\n  /// @param role Role that has expired.\n  /// @param policyholder Policyholder that held the role.\n  /// @dev This function needs to be explicitly called to revoke expired roles by monitoring through offchain\n  /// infrastructure, otherwise expired roles can continue to create actions (if they have the right permissions) and\n  /// take part in the approval/disapproval process if the strategy allows it.\n  function revokeExpiredRole(uint8 role, address policyholder) external {\n    // Read the most recent checkpoint for the policyholder's role balance.\n    if (!isRoleExpired(policyholder, role)) revert InvalidRoleHolderInput();\n    _setRoleHolder(role, policyholder, 0, 0);\n    emit ExpiredRoleRevoked(msg.sender, policyholder, role);\n  }\n\n  /// @notice Revokes all roles from the `policyholder` and burns their policy.\n  /// @param policyholder Policyholder to revoke all roles from.\n  function revokePolicy(address policyholder) external onlyLlama {\n    if (balanceOf(policyholder) == 0) revert AddressDoesNotHoldPolicy(policyholder);\n    // We start from i = 1 here because a value of zero is reserved for the \"all holders\" role, and\n    // that will get removed automatically when the token is burned. Similarly, use we `<=` to make sure\n    // the last role is also revoked.\n    for (uint256 i = 1; i <= numRoles; i = LlamaUtils.uncheckedIncrement(i)) {\n      if (hasRole(policyholder, uint8(i))) _setRoleHolder(uint8(i), policyholder, 0, 0);\n    }\n    _burn(policyholder);\n  }\n\n  /// @notice Updates the description of a role.\n  /// @param role ID of the role to update.\n  /// @param description New description of the role.\n  function updateRoleDescription(uint8 role, RoleDescription description) external onlyLlama {\n    if (role > numRoles) revert RoleNotInitialized(role);\n    emit RoleInitialized(role, description);\n  }\n\n  // -------- Metadata --------\n\n  /// @notice Sets the Llama policy metadata contract which contains the function body for `tokenURI()` and\n  /// `contractURI()`.\n  /// @dev This is handled by a separate contract to ensure contract size stays under 24kB.\n  /// @param llamaPolicyMetadataLogic The logic contract address for the Llama policy metadata contract.\n  /// @param config The configuration data used to initialize the Llama policy metadata logic contract.\n  function setAndInitializePolicyMetadata(ILlamaPolicyMetadata llamaPolicyMetadataLogic, bytes memory config)\n    external\n    onlyLlama\n  {\n    _setAndInitializePolicyMetadata(llamaPolicyMetadataLogic, config);\n  }\n\n  // -------- Role and Permission Getters --------\n\n  /// @notice Returns the latest quantity of the `role` for the given `policyholder`. The returned value is the\n  /// quantity of the role when approving/disapproving (regardless of strategy).\n  /// @param policyholder Policyholder to get the role quantity for.\n  /// @param role ID of the role.\n  /// @return The latest quantity of the role for the given policyholder.\n  function getQuantity(address policyholder, uint8 role) external view returns (uint96) {\n    uint256 tokenId = _tokenId(policyholder);\n    return roleBalanceCkpts[tokenId][role].latest();\n  }\n\n  /// @notice Returns the past quantity of the `role` for the given `policyholder` at `timestamp`. The returned\n  /// value is the quantity of the role when approving/disapproving (regardless of strategy).\n  /// @param policyholder Policyholder to get the role quantity for.\n  /// @param role ID of the role.\n  /// @param timestamp Timestamp at which to get the quantity of the role for the given policyholder.\n  /// @return The past quantity of the role for the given policyholder at `timestamp`.\n  function getPastQuantity(address policyholder, uint8 role, uint256 timestamp) external view returns (uint96) {\n    uint256 tokenId = _tokenId(policyholder);\n    return roleBalanceCkpts[tokenId][role].getAtProbablyRecentTimestamp(timestamp);\n  }\n\n  /// @notice Returns the latest total number of role holders for given `role`.\n  /// @param role ID of the role.\n  /// @return numberOfHolders The latest total number of role holders for given `role`.\n  function getRoleSupplyAsNumberOfHolders(uint8 role) public view returns (uint96 numberOfHolders) {\n    (numberOfHolders,) = roleSupplyCkpts[role].latest();\n  }\n\n  /// @notice Returns the past total number of role holders for given `role` at `timestamp`.\n  /// @param role ID of the role.\n  /// @param timestamp Timestamp at which to get the past total number of role holders for given `role`.\n  /// @return numberOfHolders The past total number of role holders for given `role` at `timestamp`.\n  function getPastRoleSupplyAsNumberOfHolders(uint8 role, uint256 timestamp)\n    external\n    view\n    returns (uint96 numberOfHolders)\n  {\n    (numberOfHolders,) = roleSupplyCkpts[role].getAtProbablyRecentTimestamp(timestamp);\n  }\n\n  /// @notice Returns the latest sum of quantity across all role holders for given `role`.\n  /// @param role ID of the role.\n  /// @return totalQuantity The latest sum of quantity across all role holders for given `role`.\n  function getRoleSupplyAsQuantitySum(uint8 role) external view returns (uint96 totalQuantity) {\n    (, totalQuantity) = roleSupplyCkpts[role].latest();\n  }\n\n  /// @notice Returns the sum of quantity across all role holders for given `role` at `timestamp`.\n  /// @param role ID of the role.\n  /// @param timestamp Timestamp at which to get the sum of quantity across all role holders for given `role`.\n  /// @return totalQuantity The past sum of quantity across all role holders for given `role` at `timestamp`.\n  function getPastRoleSupplyAsQuantitySum(uint8 role, uint256 timestamp) external view returns (uint96 totalQuantity) {\n    (, totalQuantity) = roleSupplyCkpts[role].getAtProbablyRecentTimestamp(timestamp);\n  }\n\n  /// @notice Returns all policyholder checkpoints for the given `policyholder` and `role`.\n  /// @param policyholder Policyholder to get the checkpoints for.\n  /// @param role ID of the role.\n  /// @return All policyholder checkpoints for the given `policyholder` and `role`.\n  function roleBalanceCheckpoints(address policyholder, uint8 role)\n    external\n    view\n    returns (PolicyholderCheckpoints.History memory)\n  {\n    uint256 tokenId = _tokenId(policyholder);\n    return roleBalanceCkpts[tokenId][role];\n  }\n\n  /// @notice Returns all supply checkpoints for the given `role`.\n  /// @param role ID of the role.\n  /// @return All supply checkpoints for the given `role`.\n  function roleSupplyCheckpoints(uint8 role) external view returns (SupplyCheckpoints.History memory) {\n    return roleSupplyCkpts[role];\n  }\n\n  /// @notice Returns all policyholder checkpoints for the given policyholder and role between `start` and\n  /// `end`, where `start` is inclusive and `end` is exclusive.\n  /// @param policyholder Policyholder to get the checkpoints for.\n  /// @param role Role held by policyholder to get the checkpoints for.\n  /// @param start Start index of the checkpoints to get from their checkpoint history array. This index is inclusive.\n  /// @param end End index of the checkpoints to get from their checkpoint history array. This index is exclusive.\n  /// @return All policyholder checkpoints for the given policyholder and role between `start` and `end`.\n  function roleBalanceCheckpoints(address policyholder, uint8 role, uint256 start, uint256 end)\n    external\n    view\n    returns (PolicyholderCheckpoints.History memory)\n  {\n    if (start > end) revert InvalidIndices();\n    uint256 checkpointsLength = roleBalanceCkpts[_tokenId(policyholder)][role]._checkpoints.length;\n    if (end > checkpointsLength) revert InvalidIndices();\n\n    uint256 tokenId = _tokenId(policyholder);\n    uint256 sliceLength = end - start;\n    PolicyholderCheckpoints.Checkpoint[] memory checkpoints = new PolicyholderCheckpoints.Checkpoint[](sliceLength);\n    for (uint256 i = start; i < end; i = LlamaUtils.uncheckedIncrement(i)) {\n      checkpoints[i - start] = roleBalanceCkpts[tokenId][role]._checkpoints[i];\n    }\n    return PolicyholderCheckpoints.History(checkpoints);\n  }\n\n  /// @notice Returns all supply checkpoints for the given role between `start` and\n  /// `end`, where `start` is inclusive and `end` is exclusive.\n  /// @param role Role held by policyholder to get the checkpoints for.\n  /// @param start Start index of the checkpoints to get from their checkpoint history array. This index is inclusive.\n  /// @param end End index of the checkpoints to get from their checkpoint history array. This index is exclusive.\n  /// @return All supply checkpoints for the given role between `start` and `end`.\n  function roleSupplyCheckpoints(uint8 role, uint256 start, uint256 end)\n    external\n    view\n    returns (SupplyCheckpoints.History memory)\n  {\n    if (start > end) revert InvalidIndices();\n    uint256 checkpointsLength = roleSupplyCkpts[role]._checkpoints.length;\n    if (end > checkpointsLength) revert InvalidIndices();\n\n    uint256 sliceLength = end - start;\n    SupplyCheckpoints.Checkpoint[] memory checkpoints = new SupplyCheckpoints.Checkpoint[](sliceLength);\n    for (uint256 i = start; i < end; i = LlamaUtils.uncheckedIncrement(i)) {\n      checkpoints[i - start] = roleSupplyCkpts[role]._checkpoints[i];\n    }\n    return SupplyCheckpoints.History(checkpoints);\n  }\n\n  /// @notice Returns the number of policyholder checkpoints for the given `policyholder` and `role`.\n  /// @dev Useful for knowing the max index when requesting a range of checkpoints in `roleBalanceCheckpoints`.\n  /// @param policyholder Policyholder to get the number of checkpoints for.\n  /// @param role ID of the role.\n  /// @return The number of policyholder checkpoints for the given `policyholder` and `role`.\n  function roleBalanceCheckpointsLength(address policyholder, uint8 role) external view returns (uint256) {\n    uint256 tokenId = _tokenId(policyholder);\n    return roleBalanceCkpts[tokenId][role]._checkpoints.length;\n  }\n\n  /// @notice Returns the number of supply checkpoints for the given `role`.\n  /// @dev Useful for knowing the max index when requesting a range of checkpoints in `roleSupplyCheckpoints`.\n  /// @param role ID of the role.\n  /// @return The number of supply checkpoints for the given `role`.\n  function roleSupplyCheckpointsLength(uint8 role) external view returns (uint256) {\n    return roleSupplyCkpts[role]._checkpoints.length;\n  }\n\n  /// @notice Returns `true` if the `policyholder` has the `role`, `false` otherwise.\n  /// @param policyholder Policyholder to check if they have the role.\n  /// @param role ID of the role.\n  /// @return `true` if the `policyholder` has the `role`, `false` otherwise.\n  function hasRole(address policyholder, uint8 role) public view returns (bool) {\n    uint96 quantity = roleBalanceCkpts[_tokenId(policyholder)][role].latest();\n    return quantity > 0;\n  }\n\n  /// @notice Returns `true` if the `policyholder` has the `role` at `timestamp`, `false` otherwise.\n  /// @param policyholder Policyholder to check if they have the role.\n  /// @param role ID of the role.\n  /// @param timestamp Timestamp to check if the role was held at.\n  /// @return `true` if the `policyholder` has the `role` at `timestamp`, `false` otherwise.\n  function hasRole(address policyholder, uint8 role, uint256 timestamp) external view returns (bool) {\n    uint256 quantity = roleBalanceCkpts[_tokenId(policyholder)][role].getAtProbablyRecentTimestamp(timestamp);\n    return quantity > 0;\n  }\n\n  /// @notice Returns `true` if the given `policyholder` has a given `permissionId` under the `role`,\n  /// `false` otherwise.\n  /// @param policyholder Policyholder to check if they have the permission under the role.\n  /// @param role ID of the role.\n  /// @param permissionId ID of the permission.\n  /// @return `true` if the given `policyholder` has a given `permissionId` under the `role`, `false` otherwise.\n  function hasPermissionId(address policyholder, uint8 role, bytes32 permissionId) external view returns (bool) {\n    uint96 quantity = roleBalanceCkpts[_tokenId(policyholder)][role].latest();\n    return quantity > 0 && canCreateAction[role][permissionId];\n  }\n\n  /// @notice Returns `true` if the `role` held by `policyholder` is expired, `false` otherwise.\n  /// @param policyholder Policyholder to check if their role is expired.\n  /// @param role ID of the role.\n  /// @return `true` if the `role` held by `policyholder` is expired, `false` otherwise.\n  function isRoleExpired(address policyholder, uint8 role) public view returns (bool) {\n    (,, uint64 expiration, uint96 quantity) = roleBalanceCkpts[_tokenId(policyholder)][role].latestCheckpoint();\n    return quantity > 0 && block.timestamp > expiration;\n  }\n\n  /// @notice Returns the expiration timestamp of the `role` held by `policyholder`.\n  /// @param policyholder Policyholder to get the expiration timestamp of their role.\n  /// @param role ID of the role.\n  /// @return The expiration timestamp of the `role` held by `policyholder`.\n  function roleExpiration(address policyholder, uint8 role) external view returns (uint64) {\n    (,, uint64 expiration,) = roleBalanceCkpts[_tokenId(policyholder)][role].latestCheckpoint();\n    return expiration;\n  }\n\n  /// @notice Returns the total number of policies in existence.\n  /// @dev This is just an alias for convenience/familiarity.\n  /// @return The total number of policies in existence.\n  function totalSupply() external view returns (uint256) {\n    return getRoleSupplyAsNumberOfHolders(ALL_HOLDERS_ROLE);\n  }\n\n  // -------- ERC-721 Getters --------\n\n  /// @notice Returns the token URI for the given `tokenId` of this Llama instance.\n  /// @param tokenId The ID of the policy token.\n  /// @return The token URI for the given `tokenId` of this Llama instance.\n  function tokenURI(uint256 tokenId) public view override returns (string memory) {\n    ownerOf(tokenId); // ensure token exists, will revert with NOT_MINTED error if not\n    return llamaPolicyMetadata.getTokenURI(name, llamaExecutor, tokenId);\n  }\n\n  /// @notice Returns a URI for the storefront-level metadata for your contract.\n  /// @return The contract URI for the given Llama instance.\n  function contractURI() public view returns (string memory) {\n    return llamaPolicyMetadata.getContractURI(name, llamaExecutor);\n  }\n\n  // -------- ERC-721 Methods --------\n\n  /// @dev overriding `transferFrom` to disable transfers\n  function transferFrom(address, /* from */ address, /* to */ uint256 /* policyId */ )\n    public\n    pure\n    override\n    nonTransferableToken\n  {}\n\n  /// @dev overriding `safeTransferFrom` to disable transfers\n  function safeTransferFrom(address, /* from */ address, /* to */ uint256 /* id */ )\n    public\n    pure\n    override\n    nonTransferableToken\n  {}\n\n  /// @dev overriding `safeTransferFrom` to disable transfers\n  function safeTransferFrom(address, /* from */ address, /* to */ uint256, /* policyId */ bytes calldata /* data */ )\n    public\n    pure\n    override\n    nonTransferableToken\n  {}\n\n  /// @dev overriding `approve` to disable approvals\n  function approve(address, /* spender */ uint256 /* id */ ) public pure override nonTransferableToken {}\n\n  /// @dev overriding `approve` to disable approvals\n  function setApprovalForAll(address, /* operator */ bool /* approved */ ) public pure override nonTransferableToken {}\n\n  // ================================\n  // ======== Internal Logic ========\n  // ================================\n\n  /// @dev Initializes the next unassigned role with the given `description`.\n  function _initializeRole(RoleDescription description) internal {\n    numRoles += 1;\n    emit RoleInitialized(numRoles, description);\n  }\n\n  /// @dev Checks if the conditions are met for a `role` to be updated.\n  function _assertValidRoleHolderUpdate(uint8 role, uint96 quantity, uint64 expiration) internal view {\n    // Ensure role is initialized.\n    if (role > numRoles) revert RoleNotInitialized(role);\n\n    // Cannot set the ALL_HOLDERS_ROLE because this is handled in the _mint / _burn methods and can\n    // create duplicate entries if set here.\n    if (role == ALL_HOLDERS_ROLE) revert AllHoldersRole();\n\n    // An expiration of zero is only allowed if the role is being removed. Roles are removed when\n    // the quantity is zero. In other words, the relationships that are required between the role\n    // quantity and expiration fields are:\n    //   - quantity > 0 && expiration > block.timestamp: This means you are adding a role\n    //   - quantity == 0 && expiration == 0: This means you are removing a role\n    bool case1 = quantity > 0 && expiration > block.timestamp;\n    bool case2 = quantity == 0 && expiration == 0;\n    if (!(case1 || case2)) revert InvalidRoleHolderInput();\n  }\n\n  /// @dev Sets the `role` for the given `policyholder` to the given `quantity` and `expiration`.\n  function _setRoleHolder(uint8 role, address policyholder, uint96 quantity, uint64 expiration) internal {\n    _assertValidRoleHolderUpdate(role, quantity, expiration);\n\n    // Save off whether or not the policyholder has a nonzero quantity of this role. This is used\n    // below when updating the total supply of the role. The policy contract has an invariant that\n    // even when a role is expired, i.e. `block.timestamp > expiration`, that role is still active\n    // until explicitly revoked with `revokeExpiredRole`. Based on the assertions above for\n    // determining valid inputs to this method, this means we know if a user had a role simply by\n    // checking if the quantity is nonzero, and we don't need to check the expiration when setting\n    // the `hadRole` and `willHaveRole` variables.\n    uint256 tokenId = _tokenId(policyholder);\n    uint96 initialQuantity = roleBalanceCkpts[tokenId][role].latest();\n    bool hadRole = initialQuantity > 0;\n    bool willHaveRole = quantity > 0;\n\n    // Now we update the policyholder's role balance checkpoint.\n    roleBalanceCkpts[tokenId][role].push(willHaveRole ? quantity : 0, expiration);\n\n    // If they don't hold a policy, we mint one for them. This means that even if you use 0 quantity\n    // and 0 expiration, a policy is still minted even though they hold no roles. This is because\n    // they do hold the ALL_HOLDERS_ROLE simply by having a policy, so we allow this.\n    if (balanceOf(policyholder) == 0) _mint(policyholder);\n\n    // Lastly we update the total supply of the role. If the expiration is zero, it means the role\n    // was removed. Determining how to update total supply requires knowing if the policyholder currently\n    // has a nonzero quantity of this role. This is strictly a quantity check and ignores the\n    // expiration because this is used to determine whether or not to update the total supply.\n    uint96 quantityDiff;\n    unchecked {\n      // Safety: Can never underflow due to ternary operator check.\n      quantityDiff = initialQuantity > quantity ? initialQuantity - quantity : quantity - initialQuantity;\n    }\n\n    (uint96 numberOfHolders, uint96 totalQuantity) = roleSupplyCkpts[role].latest();\n\n    if (hadRole && !willHaveRole) {\n      roleSupplyCkpts[role].push(numberOfHolders - 1, totalQuantity - quantityDiff);\n    } else if (!hadRole && willHaveRole) {\n      roleSupplyCkpts[role].push(numberOfHolders + 1, totalQuantity + quantityDiff);\n    } else if (hadRole && willHaveRole && initialQuantity > quantity) {\n      roleSupplyCkpts[role].push(numberOfHolders, totalQuantity - quantityDiff);\n    } else if (hadRole && willHaveRole && initialQuantity < quantity) {\n      roleSupplyCkpts[role].push(numberOfHolders, totalQuantity + quantityDiff);\n    } else {\n      // There are two ways to reach this branch, both of which are no-ops:\n      //   1. `hadRole` and `willHaveRole` are both false. We allow this without reverting so you can give\n      //      someone a policy with only the `ALL_HOLDERS_ROLE` by passing in any other role that won't be set.\n      //   2. `hadRole` and `willHaveRole` are both true, and `initialQuantity == quantity`. We allow this without\n      //      reverting so that you can update the expiration of an existing role.\n    }\n    emit RoleAssigned(policyholder, role, expiration, quantity);\n  }\n\n  /// @dev Sets a role's permission along with whether that permission is valid or not.\n  function _setRolePermission(uint8 role, PermissionData memory permissionData, bool hasPermission) internal {\n    if (role > numRoles) revert RoleNotInitialized(role);\n    bytes32 permissionId = LlamaUtils.computePermissionId(permissionData);\n    canCreateAction[role][permissionId] = hasPermission;\n    emit RolePermissionAssigned(role, permissionId, permissionData, hasPermission);\n  }\n\n  /// @dev Mints a policyholder's policy.\n  function _mint(address policyholder) internal {\n    uint256 tokenId = _tokenId(policyholder);\n    ERC721NonTransferableMinimalProxy._mint(policyholder, tokenId);\n\n    (uint96 numberOfHolders, uint96 totalQuantity) = roleSupplyCkpts[ALL_HOLDERS_ROLE].latest();\n    unchecked {\n      // Safety: Can never overflow a uint96 by incrementing.\n      roleSupplyCkpts[ALL_HOLDERS_ROLE].push(numberOfHolders + 1, totalQuantity + 1);\n    }\n\n    roleBalanceCkpts[tokenId][ALL_HOLDERS_ROLE].push(1, type(uint64).max);\n    emit RoleAssigned(policyholder, ALL_HOLDERS_ROLE, type(uint64).max, 1);\n  }\n\n  /// @dev Burns a policyholder's policy.\n  function _burn(address policyholder) internal {\n    uint256 tokenId = _tokenId(policyholder);\n    ERC721NonTransferableMinimalProxy._burn(tokenId);\n\n    (uint96 numberOfHolders, uint96 totalQuantity) = roleSupplyCkpts[ALL_HOLDERS_ROLE].latest();\n    unchecked {\n      // Safety: Can never underflow, since we only burn tokens that currently exist.\n      roleSupplyCkpts[ALL_HOLDERS_ROLE].push(numberOfHolders - 1, totalQuantity - 1);\n    }\n\n    roleBalanceCkpts[tokenId][ALL_HOLDERS_ROLE].push(0, 0);\n    emit RoleAssigned(policyholder, ALL_HOLDERS_ROLE, 0, 0);\n  }\n\n  /// @dev Sets the Llama policy metadata contract.\n  function _setAndInitializePolicyMetadata(ILlamaPolicyMetadata llamaPolicyMetadataLogic, bytes memory config) internal {\n    llamaPolicyMetadata =\n      ILlamaPolicyMetadata(Clones.cloneDeterministic(address(llamaPolicyMetadataLogic), keccak256(config)));\n    llamaPolicyMetadata.initialize(config);\n    emit PolicyMetadataSet(llamaPolicyMetadata, llamaPolicyMetadataLogic, config);\n  }\n\n  /// @dev Returns the token ID for a `policyholder`.\n  function _tokenId(address policyholder) internal pure returns (uint256) {\n    return uint256(uint160(policyholder));\n  }\n}\n"
      },
      "lib/openzeppelin-contracts/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"
      },
      "lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n        return interfaceId == type(IERC165).interfaceId;\n    }\n}\n"
      },
      "src/lib/UDVTs.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.19;\n\n// @dev We use this UDVT for stronger typing of the Role Description.\ntype RoleDescription is bytes32;\n"
      },
      "lib/solady/src/utils/LibString.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.4;\n\n/// @notice Library for converting numbers into strings and other string operations.\n/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibString.sol)\n/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/LibString.sol)\nlibrary LibString {\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                        CUSTOM ERRORS                       */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    /// @dev The `length` of the output is too small to contain all the hex digits.\n    error HexLengthInsufficient();\n\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                         CONSTANTS                          */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    /// @dev The constant returned when the `search` is not found in the string.\n    uint256 internal constant NOT_FOUND = type(uint256).max;\n\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                     DECIMAL OPERATIONS                     */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    /// @dev Returns the base 10 decimal representation of `value`.\n    function toString(uint256 value) internal pure returns (string memory str) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // The maximum value of a uint256 contains 78 digits (1 byte per digit), but\n            // we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.\n            // We will need 1 word for the trailing zeros padding, 1 word for the length,\n            // and 3 words for a maximum of 78 digits.\n            str := add(mload(0x40), 0x80)\n            // Update the free memory pointer to allocate.\n            mstore(0x40, add(str, 0x20))\n            // Zeroize the slot after the string.\n            mstore(str, 0)\n\n            // Cache the end of the memory to calculate the length later.\n            let end := str\n\n            let w := not(0) // Tsk.\n            // We write the string from rightmost digit to leftmost digit.\n            // The following is essentially a do-while loop that also handles the zero case.\n            for { let temp := value } 1 {} {\n                str := add(str, w) // `sub(str, 1)`.\n                // Write the character to the pointer.\n                // The ASCII index of the '0' character is 48.\n                mstore8(str, add(48, mod(temp, 10)))\n                // Keep dividing `temp` until zero.\n                temp := div(temp, 10)\n                if iszero(temp) { break }\n            }\n\n            let length := sub(end, str)\n            // Move the pointer 32 bytes leftwards to make room for the length.\n            str := sub(str, 0x20)\n            // Store the length.\n            mstore(str, length)\n        }\n    }\n\n    /// @dev Returns the base 10 decimal representation of `value`.\n    function toString(int256 value) internal pure returns (string memory str) {\n        if (value >= 0) {\n            return toString(uint256(value));\n        }\n        unchecked {\n            str = toString(uint256(-value));\n        }\n        /// @solidity memory-safe-assembly\n        assembly {\n            // We still have some spare memory space on the left,\n            // as we have allocated 3 words (96 bytes) for up to 78 digits.\n            let length := mload(str) // Load the string length.\n            mstore(str, 0x2d) // Store the '-' character.\n            str := sub(str, 1) // Move back the string pointer by a byte.\n            mstore(str, add(length, 1)) // Update the string length.\n        }\n    }\n\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                   HEXADECIMAL OPERATIONS                   */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    /// @dev Returns the hexadecimal representation of `value`,\n    /// left-padded to an input length of `length` bytes.\n    /// The output is prefixed with \"0x\" encoded using 2 hexadecimal digits per byte,\n    /// giving a total length of `length * 2 + 2` bytes.\n    /// Reverts if `length` is too small for the output to contain all the digits.\n    function toHexString(uint256 value, uint256 length) internal pure returns (string memory str) {\n        str = toHexStringNoPrefix(value, length);\n        /// @solidity memory-safe-assembly\n        assembly {\n            let strLength := add(mload(str), 2) // Compute the length.\n            mstore(str, 0x3078) // Write the \"0x\" prefix.\n            str := sub(str, 2) // Move the pointer.\n            mstore(str, strLength) // Write the length.\n        }\n    }\n\n    /// @dev Returns the hexadecimal representation of `value`,\n    /// left-padded to an input length of `length` bytes.\n    /// The output is prefixed with \"0x\" encoded using 2 hexadecimal digits per byte,\n    /// giving a total length of `length * 2` bytes.\n    /// Reverts if `length` is too small for the output to contain all the digits.\n    function toHexStringNoPrefix(uint256 value, uint256 length)\n        internal\n        pure\n        returns (string memory str)\n    {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // We need 0x20 bytes for the trailing zeros padding, `length * 2` bytes\n            // for the digits, 0x02 bytes for the prefix, and 0x20 bytes for the length.\n            // We add 0x20 to the total and round down to a multiple of 0x20.\n            // (0x20 + 0x20 + 0x02 + 0x20) = 0x62.\n            str := add(mload(0x40), and(add(shl(1, length), 0x42), not(0x1f)))\n            // Allocate the memory.\n            mstore(0x40, add(str, 0x20))\n            // Zeroize the slot after the string.\n            mstore(str, 0)\n\n            // Cache the end to calculate the length later.\n            let end := str\n            // Store \"0123456789abcdef\" in scratch space.\n            mstore(0x0f, 0x30313233343536373839616263646566)\n\n            let start := sub(str, add(length, length))\n            let w := not(1) // Tsk.\n            let temp := value\n            // We write the string from rightmost digit to leftmost digit.\n            // The following is essentially a do-while loop that also handles the zero case.\n            for {} 1 {} {\n                str := add(str, w) // `sub(str, 2)`.\n                mstore8(add(str, 1), mload(and(temp, 15)))\n                mstore8(str, mload(and(shr(4, temp), 15)))\n                temp := shr(8, temp)\n                if iszero(xor(str, start)) { break }\n            }\n\n            if temp {\n                // Store the function selector of `HexLengthInsufficient()`.\n                mstore(0x00, 0x2194895a)\n                // Revert with (offset, size).\n                revert(0x1c, 0x04)\n            }\n\n            // Compute the string's length.\n            let strLength := sub(end, str)\n            // Move the pointer and write the length.\n            str := sub(str, 0x20)\n            mstore(str, strLength)\n        }\n    }\n\n    /// @dev Returns the hexadecimal representation of `value`.\n    /// The output is prefixed with \"0x\" and encoded using 2 hexadecimal digits per byte.\n    /// As address are 20 bytes long, the output will left-padded to have\n    /// a length of `20 * 2 + 2` bytes.\n    function toHexString(uint256 value) internal pure returns (string memory str) {\n        str = toHexStringNoPrefix(value);\n        /// @solidity memory-safe-assembly\n        assembly {\n            let strLength := add(mload(str), 2) // Compute the length.\n            mstore(str, 0x3078) // Write the \"0x\" prefix.\n            str := sub(str, 2) // Move the pointer.\n            mstore(str, strLength) // Write the length.\n        }\n    }\n\n    /// @dev Returns the hexadecimal representation of `value`.\n    /// The output is encoded using 2 hexadecimal digits per byte.\n    /// As address are 20 bytes long, the output will left-padded to have\n    /// a length of `20 * 2` bytes.\n    function toHexStringNoPrefix(uint256 value) internal pure returns (string memory str) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,\n            // 0x02 bytes for the prefix, and 0x40 bytes for the digits.\n            // The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x40) is 0xa0.\n            str := add(mload(0x40), 0x80)\n            // Allocate the memory.\n            mstore(0x40, add(str, 0x20))\n            // Zeroize the slot after the string.\n            mstore(str, 0)\n\n            // Cache the end to calculate the length later.\n            let end := str\n            // Store \"0123456789abcdef\" in scratch space.\n            mstore(0x0f, 0x30313233343536373839616263646566)\n\n            let w := not(1) // Tsk.\n            // We write the string from rightmost digit to leftmost digit.\n            // The following is essentially a do-while loop that also handles the zero case.\n            for { let temp := value } 1 {} {\n                str := add(str, w) // `sub(str, 2)`.\n                mstore8(add(str, 1), mload(and(temp, 15)))\n                mstore8(str, mload(and(shr(4, temp), 15)))\n                temp := shr(8, temp)\n                if iszero(temp) { break }\n            }\n\n            // Compute the string's length.\n            let strLength := sub(end, str)\n            // Move the pointer and write the length.\n            str := sub(str, 0x20)\n            mstore(str, strLength)\n        }\n    }\n\n    /// @dev Returns the hexadecimal representation of `value`.\n    /// The output is prefixed with \"0x\", encoded using 2 hexadecimal digits per byte,\n    /// and the alphabets are capitalized conditionally according to\n    /// https://eips.ethereum.org/EIPS/eip-55\n    function toHexStringChecksumed(address value) internal pure returns (string memory str) {\n        str = toHexString(value);\n        /// @solidity memory-safe-assembly\n        assembly {\n            let mask := shl(6, div(not(0), 255)) // `0b010000000100000000 ...`\n            let o := add(str, 0x22)\n            let hashed := and(keccak256(o, 40), mul(34, mask)) // `0b10001000 ... `\n            let t := shl(240, 136) // `0b10001000 << 240`\n            for { let i := 0 } 1 {} {\n                mstore(add(i, i), mul(t, byte(i, hashed)))\n                i := add(i, 1)\n                if eq(i, 20) { break }\n            }\n            mstore(o, xor(mload(o), shr(1, and(mload(0x00), and(mload(o), mask)))))\n            o := add(o, 0x20)\n            mstore(o, xor(mload(o), shr(1, and(mload(0x20), and(mload(o), mask)))))\n        }\n    }\n\n    /// @dev Returns the hexadecimal representation of `value`.\n    /// The output is prefixed with \"0x\" and encoded using 2 hexadecimal digits per byte.\n    function toHexString(address value) internal pure returns (string memory str) {\n        str = toHexStringNoPrefix(value);\n        /// @solidity memory-safe-assembly\n        assembly {\n            let strLength := add(mload(str), 2) // Compute the length.\n            mstore(str, 0x3078) // Write the \"0x\" prefix.\n            str := sub(str, 2) // Move the pointer.\n            mstore(str, strLength) // Write the length.\n        }\n    }\n\n    /// @dev Returns the hexadecimal representation of `value`.\n    /// The output is encoded using 2 hexadecimal digits per byte.\n    function toHexStringNoPrefix(address value) internal pure returns (string memory str) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            str := mload(0x40)\n\n            // Allocate the memory.\n            // We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,\n            // 0x02 bytes for the prefix, and 0x28 bytes for the digits.\n            // The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x28) is 0x80.\n            mstore(0x40, add(str, 0x80))\n\n            // Store \"0123456789abcdef\" in scratch space.\n            mstore(0x0f, 0x30313233343536373839616263646566)\n\n            str := add(str, 2)\n            mstore(str, 40)\n\n            let o := add(str, 0x20)\n            mstore(add(o, 40), 0)\n\n            value := shl(96, value)\n\n            // We write the string from rightmost digit to leftmost digit.\n            // The following is essentially a do-while loop that also handles the zero case.\n            for { let i := 0 } 1 {} {\n                let p := add(o, add(i, i))\n                let temp := byte(i, value)\n                mstore8(add(p, 1), mload(and(temp, 15)))\n                mstore8(p, mload(shr(4, temp)))\n                i := add(i, 1)\n                if eq(i, 20) { break }\n            }\n        }\n    }\n\n    /// @dev Returns the hex encoded string from the raw bytes.\n    /// The output is encoded using 2 hexadecimal digits per byte.\n    function toHexString(bytes memory raw) internal pure returns (string memory str) {\n        str = toHexStringNoPrefix(raw);\n        /// @solidity memory-safe-assembly\n        assembly {\n            let strLength := add(mload(str), 2) // Compute the length.\n            mstore(str, 0x3078) // Write the \"0x\" prefix.\n            str := sub(str, 2) // Move the pointer.\n            mstore(str, strLength) // Write the length.\n        }\n    }\n\n    /// @dev Returns the hex encoded string from the raw bytes.\n    /// The output is encoded using 2 hexadecimal digits per byte.\n    function toHexStringNoPrefix(bytes memory raw) internal pure returns (string memory str) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let length := mload(raw)\n            str := add(mload(0x40), 2) // Skip 2 bytes for the optional prefix.\n            mstore(str, add(length, length)) // Store the length of the output.\n\n            // Store \"0123456789abcdef\" in scratch space.\n            mstore(0x0f, 0x30313233343536373839616263646566)\n\n            let o := add(str, 0x20)\n            let end := add(raw, length)\n\n            for {} iszero(eq(raw, end)) {} {\n                raw := add(raw, 1)\n                mstore8(add(o, 1), mload(and(mload(raw), 15)))\n                mstore8(o, mload(and(shr(4, mload(raw)), 15)))\n                o := add(o, 2)\n            }\n            mstore(o, 0) // Zeroize the slot after the string.\n            mstore(0x40, and(add(o, 31), not(31))) // Allocate the memory.\n        }\n    }\n\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                   RUNE STRING OPERATIONS                   */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    /// @dev Returns the number of UTF characters in the string.\n    function runeCount(string memory s) internal pure returns (uint256 result) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            if mload(s) {\n                mstore(0x00, div(not(0), 255))\n                mstore(0x20, 0x0202020202020202020202020202020202020202020202020303030304040506)\n                let o := add(s, 0x20)\n                let end := add(o, mload(s))\n                for { result := 1 } 1 { result := add(result, 1) } {\n                    o := add(o, byte(0, mload(shr(250, mload(o)))))\n                    if iszero(lt(o, end)) { break }\n                }\n            }\n        }\n    }\n\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                   BYTE STRING OPERATIONS                   */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    // For performance and bytecode compactness, all indices of the following operations\n    // are byte (ASCII) offsets, not UTF character offsets.\n\n    /// @dev Returns `subject` all occurrences of `search` replaced with `replacement`.\n    function replace(string memory subject, string memory search, string memory replacement)\n        internal\n        pure\n        returns (string memory result)\n    {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let subjectLength := mload(subject)\n            let searchLength := mload(search)\n            let replacementLength := mload(replacement)\n\n            subject := add(subject, 0x20)\n            search := add(search, 0x20)\n            replacement := add(replacement, 0x20)\n            result := add(mload(0x40), 0x20)\n\n            let subjectEnd := add(subject, subjectLength)\n            if iszero(gt(searchLength, subjectLength)) {\n                let subjectSearchEnd := add(sub(subjectEnd, searchLength), 1)\n                let h := 0\n                if iszero(lt(searchLength, 32)) { h := keccak256(search, searchLength) }\n                let m := shl(3, sub(32, and(searchLength, 31)))\n                let s := mload(search)\n                for {} 1 {} {\n                    let t := mload(subject)\n                    // Whether the first `searchLength % 32` bytes of\n                    // `subject` and `search` matches.\n                    if iszero(shr(m, xor(t, s))) {\n                        if h {\n                            if iszero(eq(keccak256(subject, searchLength), h)) {\n                                mstore(result, t)\n                                result := add(result, 1)\n                                subject := add(subject, 1)\n                                if iszero(lt(subject, subjectSearchEnd)) { break }\n                                continue\n                            }\n                        }\n                        // Copy the `replacement` one word at a time.\n                        for { let o := 0 } 1 {} {\n                            mstore(add(result, o), mload(add(replacement, o)))\n                            o := add(o, 0x20)\n                            if iszero(lt(o, replacementLength)) { break }\n                        }\n                        result := add(result, replacementLength)\n                        subject := add(subject, searchLength)\n                        if searchLength {\n                            if iszero(lt(subject, subjectSearchEnd)) { break }\n                            continue\n                        }\n                    }\n                    mstore(result, t)\n                    result := add(result, 1)\n                    subject := add(subject, 1)\n                    if iszero(lt(subject, subjectSearchEnd)) { break }\n                }\n            }\n\n            let resultRemainder := result\n            result := add(mload(0x40), 0x20)\n            let k := add(sub(resultRemainder, result), sub(subjectEnd, subject))\n            // Copy the rest of the string one word at a time.\n            for {} lt(subject, subjectEnd) {} {\n                mstore(resultRemainder, mload(subject))\n                resultRemainder := add(resultRemainder, 0x20)\n                subject := add(subject, 0x20)\n            }\n            result := sub(result, 0x20)\n            // Zeroize the slot after the string.\n            let last := add(add(result, 0x20), k)\n            mstore(last, 0)\n            // Allocate memory for the length and the bytes,\n            // rounded up to a multiple of 32.\n            mstore(0x40, and(add(last, 31), not(31)))\n            // Store the length of the result.\n            mstore(result, k)\n        }\n    }\n\n    /// @dev Returns the byte index of the first location of `search` in `subject`,\n    /// searching from left to right, starting from `from`.\n    /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `search` is not found.\n    function indexOf(string memory subject, string memory search, uint256 from)\n        internal\n        pure\n        returns (uint256 result)\n    {\n        /// @solidity memory-safe-assembly\n        assembly {\n            for { let subjectLength := mload(subject) } 1 {} {\n                if iszero(mload(search)) {\n                    if iszero(gt(from, subjectLength)) {\n                        result := from\n                        break\n                    }\n                    result := subjectLength\n                    break\n                }\n                let searchLength := mload(search)\n                let subjectStart := add(subject, 0x20)\n\n                result := not(0) // Initialize to `NOT_FOUND`.\n\n                subject := add(subjectStart, from)\n                let end := add(sub(add(subjectStart, subjectLength), searchLength), 1)\n\n                let m := shl(3, sub(32, and(searchLength, 31)))\n                let s := mload(add(search, 0x20))\n\n                if iszero(and(lt(subject, end), lt(from, subjectLength))) { break }\n\n                if iszero(lt(searchLength, 32)) {\n                    for { let h := keccak256(add(search, 0x20), searchLength) } 1 {} {\n                        if iszero(shr(m, xor(mload(subject), s))) {\n                            if eq(keccak256(subject, searchLength), h) {\n                                result := sub(subject, subjectStart)\n                                break\n                            }\n                        }\n                        subject := add(subject, 1)\n                        if iszero(lt(subject, end)) { break }\n                    }\n                    break\n                }\n                for {} 1 {} {\n                    if iszero(shr(m, xor(mload(subject), s))) {\n                        result := sub(subject, subjectStart)\n                        break\n                    }\n                    subject := add(subject, 1)\n                    if iszero(lt(subject, end)) { break }\n                }\n                break\n            }\n        }\n    }\n\n    /// @dev Returns the byte index of the first location of `search` in `subject`,\n    /// searching from left to right.\n    /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `search` is not found.\n    function indexOf(string memory subject, string memory search)\n        internal\n        pure\n        returns (uint256 result)\n    {\n        result = indexOf(subject, search, 0);\n    }\n\n    /// @dev Returns the byte index of the first location of `search` in `subject`,\n    /// searching from right to left, starting from `from`.\n    /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `search` is not found.\n    function lastIndexOf(string memory subject, string memory search, uint256 from)\n        internal\n        pure\n        returns (uint256 result)\n    {\n        /// @solidity memory-safe-assembly\n        assembly {\n            for {} 1 {} {\n                result := not(0) // Initialize to `NOT_FOUND`.\n                let searchLength := mload(search)\n                if gt(searchLength, mload(subject)) { break }\n                let w := result\n\n                let fromMax := sub(mload(subject), searchLength)\n                if iszero(gt(fromMax, from)) { from := fromMax }\n\n                let end := add(add(subject, 0x20), w)\n                subject := add(add(subject, 0x20), from)\n                if iszero(gt(subject, end)) { break }\n                // As this function is not too often used,\n                // we shall simply use keccak256 for smaller bytecode size.\n                for { let h := keccak256(add(search, 0x20), searchLength) } 1 {} {\n                    if eq(keccak256(subject, searchLength), h) {\n                        result := sub(subject, add(end, 1))\n                        break\n                    }\n                    subject := add(subject, w) // `sub(subject, 1)`.\n                    if iszero(gt(subject, end)) { break }\n                }\n                break\n            }\n        }\n    }\n\n    /// @dev Returns the byte index of the first location of `search` in `subject`,\n    /// searching from right to left.\n    /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `search` is not found.\n    function lastIndexOf(string memory subject, string memory search)\n        internal\n        pure\n        returns (uint256 result)\n    {\n        result = lastIndexOf(subject, search, uint256(int256(-1)));\n    }\n\n    /// @dev Returns whether `subject` starts with `search`.\n    function startsWith(string memory subject, string memory search)\n        internal\n        pure\n        returns (bool result)\n    {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let searchLength := mload(search)\n            // Just using keccak256 directly is actually cheaper.\n            // forgefmt: disable-next-item\n            result := and(\n                iszero(gt(searchLength, mload(subject))),\n                eq(\n                    keccak256(add(subject, 0x20), searchLength),\n                    keccak256(add(search, 0x20), searchLength)\n                )\n            )\n        }\n    }\n\n    /// @dev Returns whether `subject` ends with `search`.\n    function endsWith(string memory subject, string memory search)\n        internal\n        pure\n        returns (bool result)\n    {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let searchLength := mload(search)\n            let subjectLength := mload(subject)\n            // Whether `search` is not longer than `subject`.\n            let withinRange := iszero(gt(searchLength, subjectLength))\n            // Just using keccak256 directly is actually cheaper.\n            // forgefmt: disable-next-item\n            result := and(\n                withinRange,\n                eq(\n                    keccak256(\n                        // `subject + 0x20 + max(subjectLength - searchLength, 0)`.\n                        add(add(subject, 0x20), mul(withinRange, sub(subjectLength, searchLength))),\n                        searchLength\n                    ),\n                    keccak256(add(search, 0x20), searchLength)\n                )\n            )\n        }\n    }\n\n    /// @dev Returns `subject` repeated `times`.\n    function repeat(string memory subject, uint256 times)\n        internal\n        pure\n        returns (string memory result)\n    {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let subjectLength := mload(subject)\n            if iszero(or(iszero(times), iszero(subjectLength))) {\n                subject := add(subject, 0x20)\n                result := mload(0x40)\n                let output := add(result, 0x20)\n                for {} 1 {} {\n                    // Copy the `subject` one word at a time.\n                    for { let o := 0 } 1 {} {\n                        mstore(add(output, o), mload(add(subject, o)))\n                        o := add(o, 0x20)\n                        if iszero(lt(o, subjectLength)) { break }\n                    }\n                    output := add(output, subjectLength)\n                    times := sub(times, 1)\n                    if iszero(times) { break }\n                }\n                // Zeroize the slot after the string.\n                mstore(output, 0)\n                // Store the length.\n                let resultLength := sub(output, add(result, 0x20))\n                mstore(result, resultLength)\n                // Allocate memory for the length and the bytes,\n                // rounded up to a multiple of 32.\n                mstore(0x40, add(result, and(add(resultLength, 63), not(31))))\n            }\n        }\n    }\n\n    /// @dev Returns a copy of `subject` sliced from `start` to `end` (exclusive).\n    /// `start` and `end` are byte offsets.\n    function slice(string memory subject, uint256 start, uint256 end)\n        internal\n        pure\n        returns (string memory result)\n    {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let subjectLength := mload(subject)\n            if iszero(gt(subjectLength, end)) { end := subjectLength }\n            if iszero(gt(subjectLength, start)) { start := subjectLength }\n            if lt(start, end) {\n                result := mload(0x40)\n                let resultLength := sub(end, start)\n                mstore(result, resultLength)\n                subject := add(subject, start)\n                let w := not(31)\n                // Copy the `subject` one word at a time, backwards.\n                for { let o := and(add(resultLength, 31), w) } 1 {} {\n                    mstore(add(result, o), mload(add(subject, o)))\n                    o := add(o, w) // `sub(o, 0x20)`.\n                    if iszero(o) { break }\n                }\n                // Zeroize the slot after the string.\n                mstore(add(add(result, 0x20), resultLength), 0)\n                // Allocate memory for the length and the bytes,\n                // rounded up to a multiple of 32.\n                mstore(0x40, add(result, and(add(resultLength, 63), w)))\n            }\n        }\n    }\n\n    /// @dev Returns a copy of `subject` sliced from `start` to the end of the string.\n    /// `start` is a byte offset.\n    function slice(string memory subject, uint256 start)\n        internal\n        pure\n        returns (string memory result)\n    {\n        result = slice(subject, start, uint256(int256(-1)));\n    }\n\n    /// @dev Returns all the indices of `search` in `subject`.\n    /// The indices are byte offsets.\n    function indicesOf(string memory subject, string memory search)\n        internal\n        pure\n        returns (uint256[] memory result)\n    {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let subjectLength := mload(subject)\n            let searchLength := mload(search)\n\n            if iszero(gt(searchLength, subjectLength)) {\n                subject := add(subject, 0x20)\n                search := add(search, 0x20)\n                result := add(mload(0x40), 0x20)\n\n                let subjectStart := subject\n                let subjectSearchEnd := add(sub(add(subject, subjectLength), searchLength), 1)\n                let h := 0\n                if iszero(lt(searchLength, 32)) { h := keccak256(search, searchLength) }\n                let m := shl(3, sub(32, and(searchLength, 31)))\n                let s := mload(search)\n                for {} 1 {} {\n                    let t := mload(subject)\n                    // Whether the first `searchLength % 32` bytes of\n                    // `subject` and `search` matches.\n                    if iszero(shr(m, xor(t, s))) {\n                        if h {\n                            if iszero(eq(keccak256(subject, searchLength), h)) {\n                                subject := add(subject, 1)\n                                if iszero(lt(subject, subjectSearchEnd)) { break }\n                                continue\n                            }\n                        }\n                        // Append to `result`.\n                        mstore(result, sub(subject, subjectStart))\n                        result := add(result, 0x20)\n                        // Advance `subject` by `searchLength`.\n                        subject := add(subject, searchLength)\n                        if searchLength {\n                            if iszero(lt(subject, subjectSearchEnd)) { break }\n                            continue\n                        }\n                    }\n                    subject := add(subject, 1)\n                    if iszero(lt(subject, subjectSearchEnd)) { break }\n                }\n                let resultEnd := result\n                // Assign `result` to the free memory pointer.\n                result := mload(0x40)\n                // Store the length of `result`.\n                mstore(result, shr(5, sub(resultEnd, add(result, 0x20))))\n                // Allocate memory for result.\n                // We allocate one more word, so this array can be recycled for {split}.\n                mstore(0x40, add(resultEnd, 0x20))\n            }\n        }\n    }\n\n    /// @dev Returns a arrays of strings based on the `delimiter` inside of the `subject` string.\n    function split(string memory subject, string memory delimiter)\n        internal\n        pure\n        returns (string[] memory result)\n    {\n        uint256[] memory indices = indicesOf(subject, delimiter);\n        /// @solidity memory-safe-assembly\n        assembly {\n            let w := not(31)\n            let indexPtr := add(indices, 0x20)\n            let indicesEnd := add(indexPtr, shl(5, add(mload(indices), 1)))\n            mstore(add(indicesEnd, w), mload(subject))\n            mstore(indices, add(mload(indices), 1))\n            let prevIndex := 0\n            for {} 1 {} {\n                let index := mload(indexPtr)\n                mstore(indexPtr, 0x60)\n                if iszero(eq(index, prevIndex)) {\n                    let element := mload(0x40)\n                    let elementLength := sub(index, prevIndex)\n                    mstore(element, elementLength)\n                    // Copy the `subject` one word at a time, backwards.\n                    for { let o := and(add(elementLength, 31), w) } 1 {} {\n                        mstore(add(element, o), mload(add(add(subject, prevIndex), o)))\n                        o := add(o, w) // `sub(o, 0x20)`.\n                        if iszero(o) { break }\n                    }\n                    // Zeroize the slot after the string.\n                    mstore(add(add(element, 0x20), elementLength), 0)\n                    // Allocate memory for the length and the bytes,\n                    // rounded up to a multiple of 32.\n                    mstore(0x40, add(element, and(add(elementLength, 63), w)))\n                    // Store the `element` into the array.\n                    mstore(indexPtr, element)\n                }\n                prevIndex := add(index, mload(delimiter))\n                indexPtr := add(indexPtr, 0x20)\n                if iszero(lt(indexPtr, indicesEnd)) { break }\n            }\n            result := indices\n            if iszero(mload(delimiter)) {\n                result := add(indices, 0x20)\n                mstore(result, sub(mload(indices), 2))\n            }\n        }\n    }\n\n    /// @dev Returns a concatenated string of `a` and `b`.\n    /// Cheaper than `string.concat()` and does not de-align the free memory pointer.\n    function concat(string memory a, string memory b)\n        internal\n        pure\n        returns (string memory result)\n    {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let w := not(31)\n            result := mload(0x40)\n            let aLength := mload(a)\n            // Copy `a` one word at a time, backwards.\n            for { let o := and(add(mload(a), 32), w) } 1 {} {\n                mstore(add(result, o), mload(add(a, o)))\n                o := add(o, w) // `sub(o, 0x20)`.\n                if iszero(o) { break }\n            }\n            let bLength := mload(b)\n            let output := add(result, mload(a))\n            // Copy `b` one word at a time, backwards.\n            for { let o := and(add(bLength, 32), w) } 1 {} {\n                mstore(add(output, o), mload(add(b, o)))\n                o := add(o, w) // `sub(o, 0x20)`.\n                if iszero(o) { break }\n            }\n            let totalLength := add(aLength, bLength)\n            let last := add(add(result, 0x20), totalLength)\n            // Zeroize the slot after the string.\n            mstore(last, 0)\n            // Stores the length.\n            mstore(result, totalLength)\n            // Allocate memory for the length and the bytes,\n            // rounded up to a multiple of 32.\n            mstore(0x40, and(add(last, 31), w))\n        }\n    }\n\n    /// @dev Returns a copy of the string in either lowercase or UPPERCASE.\n    function toCase(string memory subject, bool toUpper)\n        internal\n        pure\n        returns (string memory result)\n    {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let length := mload(subject)\n            if length {\n                result := add(mload(0x40), 0x20)\n                subject := add(subject, 1)\n                let flags := shl(add(70, shl(5, toUpper)), 67108863)\n                let w := not(0)\n                for { let o := length } 1 {} {\n                    o := add(o, w)\n                    let b := and(0xff, mload(add(subject, o)))\n                    mstore8(add(result, o), xor(b, and(shr(b, flags), 0x20)))\n                    if iszero(o) { break }\n                }\n                // Restore the result.\n                result := mload(0x40)\n                // Stores the string length.\n                mstore(result, length)\n                // Zeroize the slot after the string.\n                let last := add(add(result, 0x20), length)\n                mstore(last, 0)\n                // Allocate memory for the length and the bytes,\n                // rounded up to a multiple of 32.\n                mstore(0x40, and(add(last, 31), not(31)))\n            }\n        }\n    }\n\n    /// @dev Returns a lowercased copy of the string.\n    function lower(string memory subject) internal pure returns (string memory result) {\n        result = toCase(subject, false);\n    }\n\n    /// @dev Returns an UPPERCASED copy of the string.\n    function upper(string memory subject) internal pure returns (string memory result) {\n        result = toCase(subject, true);\n    }\n\n    /// @dev Escapes the string to be used within HTML tags.\n    function escapeHTML(string memory s) internal pure returns (string memory result) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            for {\n                let end := add(s, mload(s))\n                result := add(mload(0x40), 0x20)\n                // Store the bytes of the packed offsets and strides into the scratch space.\n                // `packed = (stride << 5) | offset`. Max offset is 20. Max stride is 6.\n                mstore(0x1f, 0x900094)\n                mstore(0x08, 0xc0000000a6ab)\n                // Store \"&quot;&amp;&#39;&lt;&gt;\" into the scratch space.\n                mstore(0x00, shl(64, 0x2671756f743b26616d703b262333393b266c743b2667743b))\n            } iszero(eq(s, end)) {} {\n                s := add(s, 1)\n                let c := and(mload(s), 0xff)\n                // Not in `[\"\\\"\",\"'\",\"&\",\"<\",\">\"]`.\n                if iszero(and(shl(c, 1), 0x500000c400000000)) {\n                    mstore8(result, c)\n                    result := add(result, 1)\n                    continue\n                }\n                let t := shr(248, mload(c))\n                mstore(result, mload(and(t, 31)))\n                result := add(result, shr(5, t))\n            }\n            let last := result\n            // Zeroize the slot after the string.\n            mstore(last, 0)\n            // Restore the result to the start of the free memory.\n            result := mload(0x40)\n            // Store the length of the result.\n            mstore(result, sub(last, add(result, 0x20)))\n            // Allocate memory for the length and the bytes,\n            // rounded up to a multiple of 32.\n            mstore(0x40, and(add(last, 31), not(31)))\n        }\n    }\n\n    /// @dev Escapes the string to be used within double-quotes in a JSON.\n    function escapeJSON(string memory s) internal pure returns (string memory result) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            for {\n                let end := add(s, mload(s))\n                result := add(mload(0x40), 0x20)\n                // Store \"\\\\u0000\" in scratch space.\n                // Store \"0123456789abcdef\" in scratch space.\n                // Also, store `{0x08:\"b\", 0x09:\"t\", 0x0a:\"n\", 0x0c:\"f\", 0x0d:\"r\"}`.\n                // into the scratch space.\n                mstore(0x15, 0x5c75303030303031323334353637383961626364656662746e006672)\n                // Bitmask for detecting `[\"\\\"\",\"\\\\\"]`.\n                let e := or(shl(0x22, 1), shl(0x5c, 1))\n            } iszero(eq(s, end)) {} {\n                s := add(s, 1)\n                let c := and(mload(s), 0xff)\n                if iszero(lt(c, 0x20)) {\n                    if iszero(and(shl(c, 1), e)) {\n                        // Not in `[\"\\\"\",\"\\\\\"]`.\n                        mstore8(result, c)\n                        result := add(result, 1)\n                        continue\n                    }\n                    mstore8(result, 0x5c) // \"\\\\\".\n                    mstore8(add(result, 1), c)\n                    result := add(result, 2)\n                    continue\n                }\n                if iszero(and(shl(c, 1), 0x3700)) {\n                    // Not in `[\"\\b\",\"\\t\",\"\\n\",\"\\f\",\"\\d\"]`.\n                    mstore8(0x1d, mload(shr(4, c))) // Hex value.\n                    mstore8(0x1e, mload(and(c, 15))) // Hex value.\n                    mstore(result, mload(0x19)) // \"\\\\u00XX\".\n                    result := add(result, 6)\n                    continue\n                }\n                mstore8(result, 0x5c) // \"\\\\\".\n                mstore8(add(result, 1), mload(add(c, 8)))\n                result := add(result, 2)\n            }\n            let last := result\n            // Zeroize the slot after the string.\n            mstore(last, 0)\n            // Restore the result to the start of the free memory.\n            result := mload(0x40)\n            // Store the length of the result.\n            mstore(result, sub(last, add(result, 0x20)))\n            // Allocate memory for the length and the bytes,\n            // rounded up to a multiple of 32.\n            mstore(0x40, and(add(last, 31), not(31)))\n        }\n    }\n\n    /// @dev Returns whether `a` equals `b`.\n    function eq(string memory a, string memory b) internal pure returns (bool result) {\n        assembly {\n            result := eq(keccak256(add(a, 0x20), mload(a)), keccak256(add(b, 0x20), mload(b)))\n        }\n    }\n\n    /// @dev Packs a single string with its length into a single word.\n    /// Returns `bytes32(0)` if the length is zero or greater than 31.\n    function packOne(string memory a) internal pure returns (bytes32 result) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // We don't need to zero right pad the string,\n            // since this is our own custom non-standard packing scheme.\n            result :=\n                mul(\n                    // Load the length and the bytes.\n                    mload(add(a, 0x1f)),\n                    // `length != 0 && length < 32`. Abuses underflow.\n                    // Assumes that the length is valid and within the block gas limit.\n                    lt(sub(mload(a), 1), 0x1f)\n                )\n        }\n    }\n\n    /// @dev Unpacks a string packed using {packOne}.\n    /// Returns the empty string if `packed` is `bytes32(0)`.\n    /// If `packed` is not an output of {packOne}, the output behaviour is undefined.\n    function unpackOne(bytes32 packed) internal pure returns (string memory result) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Grab the free memory pointer.\n            result := mload(0x40)\n            // Allocate 2 words (1 for the length, 1 for the bytes).\n            mstore(0x40, add(result, 0x40))\n            // Zeroize the length slot.\n            mstore(result, 0)\n            // Store the length and bytes.\n            mstore(add(result, 0x1f), packed)\n            // Right pad with zeroes.\n            mstore(add(add(result, 0x20), mload(result)), 0)\n        }\n    }\n\n    /// @dev Packs two strings with their lengths into a single word.\n    /// Returns `bytes32(0)` if combined length is zero or greater than 30.\n    function packTwo(string memory a, string memory b) internal pure returns (bytes32 result) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let aLength := mload(a)\n            // We don't need to zero right pad the strings,\n            // since this is our own custom non-standard packing scheme.\n            result :=\n                mul(\n                    // Load the length and the bytes of `a` and `b`.\n                    or(\n                        shl(shl(3, sub(0x1f, aLength)), mload(add(a, aLength))),\n                        mload(sub(add(b, 0x1e), aLength))\n                    ),\n                    // `totalLength != 0 && totalLength < 31`. Abuses underflow.\n                    // Assumes that the lengths are valid and within the block gas limit.\n                    lt(sub(add(aLength, mload(b)), 1), 0x1e)\n                )\n        }\n    }\n\n    /// @dev Unpacks strings packed using {packTwo}.\n    /// Returns the empty strings if `packed` is `bytes32(0)`.\n    /// If `packed` is not an output of {packTwo}, the output behaviour is undefined.\n    function unpackTwo(bytes32 packed)\n        internal\n        pure\n        returns (string memory resultA, string memory resultB)\n    {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Grab the free memory pointer.\n            resultA := mload(0x40)\n            resultB := add(resultA, 0x40)\n            // Allocate 2 words for each string (1 for the length, 1 for the byte). Total 4 words.\n            mstore(0x40, add(resultB, 0x40))\n            // Zeroize the length slots.\n            mstore(resultA, 0)\n            mstore(resultB, 0)\n            // Store the lengths and bytes.\n            mstore(add(resultA, 0x1f), packed)\n            mstore(add(resultB, 0x1f), mload(add(add(resultA, 0x20), mload(resultA))))\n            // Right pad with zeroes.\n            mstore(add(add(resultA, 0x20), mload(resultA)), 0)\n            mstore(add(add(resultB, 0x20), mload(resultB)), 0)\n        }\n    }\n\n    /// @dev Directly returns `a` without copying.\n    function directReturn(string memory a) internal pure {\n        assembly {\n            // Assumes that the string does not start from the scratch space.\n            let retStart := sub(a, 0x20)\n            let retSize := add(mload(a), 0x40)\n            // Right pad with zeroes. Just in case the string is produced\n            // by a method that doesn't zero right pad.\n            mstore(add(retStart, retSize), 0)\n            // Store the return offset.\n            mstore(retStart, 0x20)\n            // End the transaction, returning the string.\n            return(retStart, retSize)\n        }\n    }\n}\n"
      },
      "src/lib/PolicyholderCheckpoints.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// forgefmt: disable-start\npragma solidity ^0.8.0;\n\nimport {LlamaUtils} from \"src/lib/LlamaUtils.sol\";\n\n/**\n * @dev This library defines the `History` struct, for checkpointing values as they change at different points in\n * time, and later looking up past values by block timestamp.\n *\n * To create a history of checkpoints define a variable type `PolicyholderCheckpoints.History` in your contract, and store a new\n * checkpoint for the current transaction timestamp using the {push} function.\n *\n * @dev This was created by modifying then running the OpenZeppelin `Checkpoints.js` script, which generated a version\n * of this library that uses a 64 bit `timestamp` and 96 bit `quantity` field in the `Checkpoint` struct. The struct\n * was then modified to add a 64 bit `expiration` field. For simplicity, safe cast and math methods were inlined from\n * the OpenZeppelin versions at the same commit. We disable forge-fmt for this file to simplify diffing against the\n * original OpenZeppelin version: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/d00acef4059807535af0bd0dd0ddf619747a044b/contracts/utils/Checkpoints.sol\n */\nlibrary PolicyholderCheckpoints {\n    struct History {\n        Checkpoint[] _checkpoints;\n    }\n\n    struct Checkpoint {\n        uint64 timestamp;\n        uint64 expiration;\n        uint96 quantity;\n    }\n\n    /**\n     * @dev Returns the quantity at a given block timestamp. If a checkpoint is not available at that time, the closest\n     * one before it is returned, or zero otherwise. Similar to {upperLookup} but optimized for the case when the\n     * searched checkpoint is probably \"recent\", defined as being among the last sqrt(N) checkpoints where N is the\n     * timestamp of checkpoints.\n     */\n    function getAtProbablyRecentTimestamp(History storage self, uint256 timestamp) internal view returns (uint96) {\n        require(timestamp < block.timestamp, \"PolicyholderCheckpoints: timestamp is not in the past\");\n        uint64 _timestamp = LlamaUtils.toUint64(timestamp);\n\n        uint256 len = self._checkpoints.length;\n\n        uint256 low = 0;\n        uint256 high = len;\n\n        if (len > 5) {\n            uint256 mid = len - sqrt(len);\n            if (_timestamp < _unsafeAccess(self._checkpoints, mid).timestamp) {\n                high = mid;\n            } else {\n                low = mid + 1;\n            }\n        }\n\n        uint256 pos = _upperBinaryLookup(self._checkpoints, _timestamp, low, high);\n\n        return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1).quantity;\n    }\n\n    /**\n     * @dev Pushes a `quantity` and `expiration` onto a History so that it is stored as the checkpoint for the current\n     * `timestamp`.\n     *\n     * Returns previous quantity and new quantity.\n     *\n     * @dev Note that the order of the `expiration` and `quantity` parameters is reversed from the ordering used\n     * everywhere else in this file. The struct and other methods have the order as `(expiration, quantity)` but this\n     * method has it as `(quantity, expiration)`. As a result, use caution when editing this method to avoid\n     * accidentally introducing a bug or breaking change.\n     */\n    function push(History storage self, uint256 quantity, uint256 expiration) internal returns (uint96, uint96) {\n        return _insert(self._checkpoints, LlamaUtils.toUint64(block.timestamp), LlamaUtils.toUint64(expiration), LlamaUtils.toUint96(quantity));\n    }\n\n    /**\n     * @dev Returns the quantity in the most recent checkpoint, or zero if there are no checkpoints.\n     */\n    function latest(History storage self) internal view returns (uint96) {\n        uint256 pos = self._checkpoints.length;\n        return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1).quantity;\n    }\n\n    /**\n     * @dev Returns whether there is a checkpoint in the structure (i.e. it is not empty), and if so the timestamp and\n     * quantity in the most recent checkpoint.\n     */\n    function latestCheckpoint(History storage self)\n        internal\n        view\n        returns (\n            bool exists,\n            uint64 timestamp,\n            uint64 expiration,\n            uint96 quantity\n        )\n    {\n        uint256 pos = self._checkpoints.length;\n        if (pos == 0) {\n            return (false, 0, 0, 0);\n        } else {\n            Checkpoint memory ckpt = _unsafeAccess(self._checkpoints, pos - 1);\n            return (true, ckpt.timestamp, ckpt.expiration, ckpt.quantity);\n        }\n    }\n\n    /**\n     * @dev Returns the number of checkpoints.\n     */\n    function length(History storage self) internal view returns (uint256) {\n        return self._checkpoints.length;\n    }\n\n    /**\n     * @dev Pushes a (`timestamp`, `expiration`, `quantity`) pair into an ordered list of checkpoints, either by inserting a new\n     * checkpoint, or by updating the last one.\n     */\n    function _insert(\n        Checkpoint[] storage self,\n        uint64 timestamp,\n        uint64 expiration,\n        uint96 quantity\n    ) private returns (uint96, uint96) {\n        uint256 pos = self.length;\n\n        if (pos > 0) {\n            // Copying to memory is important here.\n            Checkpoint memory last = _unsafeAccess(self, pos - 1);\n\n            // Checkpoints timestamps must be increasing.\n            require(last.timestamp <= timestamp, \"Role Checkpoint: invalid timestamp\");\n\n            // Update or push new checkpoint\n            if (last.timestamp == timestamp) {\n                Checkpoint storage ckpt = _unsafeAccess(self, pos - 1);\n                ckpt.quantity = quantity;\n                ckpt.expiration = expiration;\n            } else {\n                self.push(Checkpoint({timestamp: timestamp, expiration: expiration, quantity: quantity}));\n            }\n            return (last.quantity, quantity);\n        } else {\n            self.push(Checkpoint({timestamp: timestamp, expiration: expiration, quantity: quantity}));\n            return (0, quantity);\n        }\n    }\n\n    /**\n     * @dev Return the index of the oldest checkpoint whose timestamp is greater than the search timestamp, or `high`\n     * if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and exclusive\n     * `high`.\n     *\n     * WARNING: `high` should not be greater than the array's length.\n     */\n    function _upperBinaryLookup(\n        Checkpoint[] storage self,\n        uint64 timestamp,\n        uint256 low,\n        uint256 high\n    ) private view returns (uint256) {\n        while (low < high) {\n            uint256 mid = average(low, high);\n            if (_unsafeAccess(self, mid).timestamp > timestamp) {\n                high = mid;\n            } else {\n                low = mid + 1;\n            }\n        }\n        return high;\n    }\n\n    /**\n     * @dev Return the index of the oldest checkpoint whose timestamp is greater or equal than the search timestamp, or\n     * `high` if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and\n     * exclusive `high`.\n     *\n     * WARNING: `high` should not be greater than the array's length.\n     */\n    function _lowerBinaryLookup(\n        Checkpoint[] storage self,\n        uint64 timestamp,\n        uint256 low,\n        uint256 high\n    ) private view returns (uint256) {\n        while (low < high) {\n            uint256 mid = average(low, high);\n            if (_unsafeAccess(self, mid).timestamp < timestamp) {\n                low = mid + 1;\n            } else {\n                high = mid;\n            }\n        }\n        return high;\n    }\n\n    function _unsafeAccess(Checkpoint[] storage self, uint256 pos)\n        private\n        pure\n        returns (Checkpoint storage result)\n    {\n        assembly {\n            mstore(0, self.slot)\n            result.slot := add(keccak256(0, 0x20), pos)\n        }\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) private pure returns (uint256) {\n        return (a & b) + (a ^ b) / 2; // (a + b) / 2 can overflow.\n    }\n\n    /**\n     * @dev This was copied from Solmate v7 https://github.com/transmissions11/solmate/blob/e8f96f25d48fe702117ce76c79228ca4f20206cb/src/utils/FixedPointMathLib.sol\n     * @notice The math utils in solmate v7 were reviewed/audited by spearbit as part of the art gobblers audit, and are more efficient than the v6 versions.\n     */\n    function sqrt(uint256 x) internal pure returns (uint256 z) {\n        assembly {\n            let y := x // We start y at x, which will help us make our initial estimate.\n\n            z := 181 // The \"correct\" value is 1, but this saves a multiplication later.\n\n            // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\n            // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\n\n            // We check y >= 2^(k + 8) but shift right by k bits\n            // each branch to ensure that if x >= 256, then y >= 256.\n            if iszero(lt(y, 0x10000000000000000000000000000000000)) {\n                y := shr(128, y)\n                z := shl(64, z)\n            }\n            if iszero(lt(y, 0x1000000000000000000)) {\n                y := shr(64, y)\n                z := shl(32, z)\n            }\n            if iszero(lt(y, 0x10000000000)) {\n                y := shr(32, y)\n                z := shl(16, z)\n            }\n            if iszero(lt(y, 0x1000000)) {\n                y := shr(16, y)\n                z := shl(8, z)\n            }\n\n            // Goal was to get z*z*y within a small factor of x. More iterations could\n            // get y in a tighter range. Currently, we will have y in [256, 256*2^16).\n            // We ensured y >= 256 so that the relative difference between y and y+1 is small.\n            // That's not possible if x < 256 but we can just verify those cases exhaustively.\n\n            // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.\n            // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.\n            // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.\n\n            // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range\n            // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.\n\n            // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate\n            // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.\n\n            // There is no overflow risk here since y < 2^136 after the first branch above.\n            z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.\n\n            // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n\n            // If x+1 is a perfect square, the Babylonian method cycles between\n            // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.\n            // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\n            // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.\n            // If you don't care whether the floor or ceil square root is returned, you can remove this statement.\n            z := sub(z, lt(div(x, z), z))\n        }\n    }\n}\n"
      },
      "src/lib/SupplyCheckpoints.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// forgefmt: disable-start\npragma solidity ^0.8.0;\n\nimport {LlamaUtils} from \"src/lib/LlamaUtils.sol\";\n\n/**\n * @dev This library defines the `History` struct, for checkpointing values as they change at different points in\n * time, and later looking up past values by block timestamp.\n *\n * To create a history of checkpoints define a variable type `SupplyCheckpoints.History` in your contract, and store a\n * new checkpoint for the current transaction timestamp using the {push} function.\n *\n * @dev This was created by modifying then running the OpenZeppelin `Checkpoints.js` script, which generated a version\n * of this library that uses a 64 bit `timestamp` and 96 bit `quantity` field in the `Checkpoint` struct. The struct\n * was then modified to work with the below `Checkpoint` struct. For simplicity, safe cast and math methods were inlined\n * from the OpenZeppelin versions at the same commit. We disable forge-fmt for this file to simplify diffing against the\n * original OpenZeppelin version: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/d00acef4059807535af0bd0dd0ddf619747a044b/contracts/utils/Checkpoints.sol\n */\nlibrary SupplyCheckpoints {\n    struct History {\n        Checkpoint[] _checkpoints;\n    }\n\n    struct Checkpoint {\n        uint64 timestamp;\n        uint96 numberOfHolders;\n        uint96 totalQuantity;\n    }\n\n    /**\n     * @dev Returns the supply quantities at a given block timestamp. If a checkpoint is not available at that time, the closest\n     * one before it is returned, or zero otherwise. Similar to {upperLookup} but optimized for the case when the\n     * searched checkpoint is probably \"recent\", defined as being among the last sqrt(N) checkpoints where N is the\n     * timestamp of checkpoints.\n     */\n    function getAtProbablyRecentTimestamp(History storage self, uint256 timestamp)\n      internal\n      view\n      returns (uint96 numberOfHolders, uint96 totalQuantity)\n    {\n        require(timestamp < block.timestamp, \"SupplyCheckpoints: timestamp is not in the past\");\n        uint64 _timestamp = LlamaUtils.toUint64(timestamp);\n\n        uint256 len = self._checkpoints.length;\n\n        uint256 low = 0;\n        uint256 high = len;\n\n        if (len > 5) {\n            uint256 mid = len - sqrt(len);\n            if (_timestamp < _unsafeAccess(self._checkpoints, mid).timestamp) {\n                high = mid;\n            } else {\n                low = mid + 1;\n            }\n        }\n\n        uint256 pos = _upperBinaryLookup(self._checkpoints, _timestamp, low, high);\n\n        return pos == 0 ? (0, 0) : _unsafeSupplyAccess(self._checkpoints, pos - 1);\n    }\n\n    /**\n     * @dev Pushes the `numberOfHolders` and `totalQuantity` supplies onto a History so that it is stored as the\n     * checkpoint for the current `timestamp`.\n     *\n     * For simplicity, this method does not return anything, since the return values are not needed by Llama.\n     */\n    function push(History storage self, uint256 numberOfHolders, uint256 totalQuantity) internal {\n        _insert(self._checkpoints, LlamaUtils.toUint64(block.timestamp), LlamaUtils.toUint96(numberOfHolders), LlamaUtils.toUint96(totalQuantity));\n    }\n\n    /**\n     * @dev Returns the supplies in the most recent checkpoint, or zeros if there are no checkpoints.\n     */\n    function latest(History storage self) internal view returns (uint96 numberOfHolders, uint96 totalQuantity) {\n        uint256 pos = self._checkpoints.length;\n        return pos == 0 ? (0, 0) : _unsafeSupplyAccess(self._checkpoints, pos - 1);\n    }\n\n    /**\n     * @dev Returns whether there is a checkpoint in the structure (i.e. it is not empty), and if so the timestamp and\n     * supplies in the most recent checkpoint.\n     */\n    function latestCheckpoint(History storage self)\n        internal\n        view\n        returns (\n            bool exists,\n            uint64 timestamp,\n            uint96 numberOfHolders,\n            uint96 totalQuantity\n        )\n    {\n        uint256 pos = self._checkpoints.length;\n        if (pos == 0) {\n            return (false, 0, 0, 0);\n        } else {\n            Checkpoint memory ckpt = _unsafeAccess(self._checkpoints, pos - 1);\n            return (true, ckpt.timestamp, ckpt.numberOfHolders, ckpt.totalQuantity);\n        }\n    }\n\n    /**\n     * @dev Returns the number of checkpoints.\n     */\n    function length(History storage self) internal view returns (uint256) {\n        return self._checkpoints.length;\n    }\n\n    /**\n     * @dev Pushes a (`timestamp`, `numberOfHolders`, `totalQuantity`) pair into an ordered list of checkpoints, either\n     * by inserting a new checkpoint, or by updating the last one.\n     *\n     * For simplicity, this method does not return anything, since the return values are not needed by Llama.\n     */\n    function _insert(\n        Checkpoint[] storage self,\n        uint64 timestamp,\n        uint96 numberOfHolders,\n        uint96 totalQuantity\n    ) private {\n        uint256 pos = self.length;\n\n        if (pos > 0) {\n            // Copying to memory is important here.\n            Checkpoint memory last = _unsafeAccess(self, pos - 1);\n\n            // Checkpoints timestamps must be increasing.\n            require(last.timestamp <= timestamp, \"Supply Checkpoint: invalid timestamp\");\n\n            // Update or push new checkpoint\n            if (last.timestamp == timestamp) {\n                Checkpoint storage ckpt = _unsafeAccess(self, pos - 1);\n                ckpt.numberOfHolders = numberOfHolders;\n                ckpt.totalQuantity = totalQuantity;\n            } else {\n                self.push(Checkpoint({timestamp: timestamp, numberOfHolders: numberOfHolders, totalQuantity: totalQuantity}));\n            }\n        } else {\n            self.push(Checkpoint({timestamp: timestamp, numberOfHolders: numberOfHolders, totalQuantity: totalQuantity}));\n        }\n    }\n\n    /**\n     * @dev Return the index of the oldest checkpoint whose timestamp is greater than the search timestamp, or `high`\n     * if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and exclusive\n     * `high`.\n     *\n     * WARNING: `high` should not be greater than the array's length.\n     */\n    function _upperBinaryLookup(\n        Checkpoint[] storage self,\n        uint64 timestamp,\n        uint256 low,\n        uint256 high\n    ) private view returns (uint256) {\n        while (low < high) {\n            uint256 mid = average(low, high);\n            if (_unsafeAccess(self, mid).timestamp > timestamp) {\n                high = mid;\n            } else {\n                low = mid + 1;\n            }\n        }\n        return high;\n    }\n\n    /**\n     * @dev Return the index of the oldest checkpoint whose timestamp is greater or equal than the search timestamp, or\n     * `high` if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and\n     * exclusive `high`.\n     *\n     * WARNING: `high` should not be greater than the array's length.\n     */\n    function _lowerBinaryLookup(\n        Checkpoint[] storage self,\n        uint64 timestamp,\n        uint256 low,\n        uint256 high\n    ) private view returns (uint256) {\n        while (low < high) {\n            uint256 mid = average(low, high);\n            if (_unsafeAccess(self, mid).timestamp < timestamp) {\n                low = mid + 1;\n            } else {\n                high = mid;\n            }\n        }\n        return high;\n    }\n\n    function _unsafeAccess(Checkpoint[] storage self, uint256 pos)\n        private\n        pure\n        returns (Checkpoint storage result)\n    {\n        assembly {\n            mstore(0, self.slot)\n            result.slot := add(keccak256(0, 0x20), pos)\n        }\n    }\n\n    function _unsafeSupplyAccess(Checkpoint[] storage self, uint256 pos)\n        private\n        view\n        returns (uint96 numberOfHolders, uint96 totalQuantity)\n    {\n        Checkpoint storage result;\n        assembly {\n            mstore(0, self.slot)\n            result.slot := add(keccak256(0, 0x20), pos)\n        }\n        numberOfHolders = result.numberOfHolders;\n        totalQuantity = result.totalQuantity;\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) private pure returns (uint256) {\n        return (a & b) + (a ^ b) / 2; // (a + b) / 2 can overflow.\n    }\n\n    /**\n     * @dev This was copied from Solmate v7 https://github.com/transmissions11/solmate/blob/e8f96f25d48fe702117ce76c79228ca4f20206cb/src/utils/FixedPointMathLib.sol\n     * @notice The math utils in solmate v7 were reviewed/audited by spearbit as part of the art gobblers audit, and are more efficient than the v6 versions.\n     */\n    function sqrt(uint256 x) internal pure returns (uint256 z) {\n        assembly {\n            let y := x // We start y at x, which will help us make our initial estimate.\n\n            z := 181 // The \"correct\" value is 1, but this saves a multiplication later.\n\n            // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\n            // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\n\n            // We check y >= 2^(k + 8) but shift right by k bits\n            // each branch to ensure that if x >= 256, then y >= 256.\n            if iszero(lt(y, 0x10000000000000000000000000000000000)) {\n                y := shr(128, y)\n                z := shl(64, z)\n            }\n            if iszero(lt(y, 0x1000000000000000000)) {\n                y := shr(64, y)\n                z := shl(32, z)\n            }\n            if iszero(lt(y, 0x10000000000)) {\n                y := shr(32, y)\n                z := shl(16, z)\n            }\n            if iszero(lt(y, 0x1000000)) {\n                y := shr(16, y)\n                z := shl(8, z)\n            }\n\n            // Goal was to get z*z*y within a small factor of x. More iterations could\n            // get y in a tighter range. Currently, we will have y in [256, 256*2^16).\n            // We ensured y >= 256 so that the relative difference between y and y+1 is small.\n            // That's not possible if x < 256 but we can just verify those cases exhaustively.\n\n            // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.\n            // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.\n            // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.\n\n            // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range\n            // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.\n\n            // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate\n            // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.\n\n            // There is no overflow risk here since y < 2^136 after the first branch above.\n            z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.\n\n            // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n\n            // If x+1 is a perfect square, the Babylonian method cycles between\n            // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.\n            // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\n            // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.\n            // If you don't care whether the floor or ceil square root is returned, you can remove this statement.\n            z := sub(z, lt(div(x, z), z))\n        }\n    }\n}\n"
      },
      "src/lib/ERC721NonTransferableMinimalProxy.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\n// forgefmt: disable-start\npragma solidity ^0.8.0;\n\nimport {Initializable} from \"@openzeppelin/proxy/utils/Initializable.sol\";\n\n/// @title ERC721 Non-Transferable Minimal Proxy\n/// @notice This contract is a modified version of Solmate's ERC721 contract\n/// @notice Modern, minimalist, and gas efficient ERC-721 implementation as a minimal proxy.\n/// @author Solmate / Llama (https://github.com/transmissions11/solmate/blob/34d20fc027fe8d50da71428687024a29dc01748b/src/tokens/ERC721.sol)\nabstract contract ERC721NonTransferableMinimalProxy is Initializable {\n  /*//////////////////////////////////////////////////////////////\n                                 EVENTS\n    //////////////////////////////////////////////////////////////*/\n\n  event Transfer(address indexed from, address indexed to, uint256 indexed id);\n\n  event Approval(address indexed owner, address indexed spender, uint256 indexed id);\n\n  event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n  /*//////////////////////////////////////////////////////////////\n                         METADATA STORAGE/LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n  string public name;\n\n  string public symbol;\n\n  function tokenURI(uint256 id) public view virtual returns (string memory);\n\n  /*//////////////////////////////////////////////////////////////\n                      ERC721 BALANCE/OWNER STORAGE\n    //////////////////////////////////////////////////////////////*/\n\n  mapping(uint256 => address) internal _ownerOf;\n\n  mapping(address => uint256) internal _balanceOf;\n\n  function ownerOf(uint256 id) public view virtual returns (address owner) {\n    require((owner = _ownerOf[id]) != address(0), \"NOT_MINTED\");\n  }\n\n  function balanceOf(address owner) public view virtual returns (uint256) {\n    require(owner != address(0), \"ZERO_ADDRESS\");\n\n    return _balanceOf[owner];\n  }\n\n  /*//////////////////////////////////////////////////////////////\n                         ERC721 APPROVAL STORAGE\n    //////////////////////////////////////////////////////////////*/\n\n  mapping(uint256 => address) public getApproved;\n\n  mapping(address => mapping(address => bool)) public isApprovedForAll;\n\n  /*//////////////////////////////////////////////////////////////\n                               CONSTRUCTOR\n    //////////////////////////////////////////////////////////////*/\n\n  function __initializeERC721MinimalProxy (string memory _name, string memory _symbol) internal {\n    name = _name;\n    symbol = _symbol;\n  }\n\n  /*//////////////////////////////////////////////////////////////\n                              ERC721 LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n  function approve(address spender, uint256 id) public virtual {\n    address owner = _ownerOf[id];\n\n    require(msg.sender == owner || isApprovedForAll[owner][msg.sender], \"NOT_AUTHORIZED\");\n\n    getApproved[id] = spender;\n\n    emit Approval(owner, spender, id);\n  }\n\n  function setApprovalForAll(address operator, bool approved) public virtual {\n    isApprovedForAll[msg.sender][operator] = approved;\n\n    emit ApprovalForAll(msg.sender, operator, approved);\n  }\n\n  function transferFrom(address from, address to, uint256 id) public virtual {\n    require(from == _ownerOf[id], \"WRONG_FROM\");\n\n    require(to != address(0), \"INVALID_RECIPIENT\");\n\n    require(msg.sender == from || isApprovedForAll[from][msg.sender] || msg.sender == getApproved[id], \"NOT_AUTHORIZED\");\n\n    // Underflow of the sender's balance is impossible because we check for\n    // ownership above and the recipient's balance can't realistically overflow.\n    unchecked {\n      _balanceOf[from]--;\n\n      _balanceOf[to]++;\n    }\n\n    _ownerOf[id] = to;\n\n    delete getApproved[id];\n\n    emit Transfer(from, to, id);\n  }\n\n  function safeTransferFrom(address from, address to, uint256 id) public virtual;\n\n  function safeTransferFrom(address from, address to, uint256 id, bytes calldata data) public virtual;\n\n  /*//////////////////////////////////////////////////////////////\n                              ERC165 LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n  function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {\n    return interfaceId == 0x01ffc9a7 // ERC165 Interface ID for ERC165\n      || interfaceId == 0x80ac58cd // ERC165 Interface ID for ERC721\n      || interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC721Metadata\n  }\n\n  /*//////////////////////////////////////////////////////////////\n                        INTERNAL MINT/BURN LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n  function _mint(address to, uint256 id) internal virtual {\n    require(to != address(0), \"INVALID_RECIPIENT\");\n\n    require(_ownerOf[id] == address(0), \"ALREADY_MINTED\");\n\n    // Counter overflow is incredibly unrealistic.\n    unchecked {\n      _balanceOf[to]++;\n    }\n\n    _ownerOf[id] = to;\n\n    emit Transfer(address(0), to, id);\n  }\n\n  function _burn(uint256 id) internal virtual {\n    address owner = _ownerOf[id];\n\n    require(owner != address(0), \"NOT_MINTED\");\n\n    // Ownership check above ensures no underflow.\n    unchecked {\n      _balanceOf[owner]--;\n    }\n\n    delete _ownerOf[id];\n\n    delete getApproved[id];\n\n    emit Transfer(owner, address(0), id);\n  }\n\n  /*//////////////////////////////////////////////////////////////\n                        INTERNAL SAFE MINT LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n  function _safeMint(address to, uint256 id) internal virtual {\n    _mint(to, id);\n\n    require(\n      to.code.length == 0\n        || ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, \"\")\n          == ERC721TokenReceiver.onERC721Received.selector,\n      \"UNSAFE_RECIPIENT\"\n    );\n  }\n\n  function _safeMint(address to, uint256 id, bytes memory data) internal virtual {\n    _mint(to, id);\n\n    require(\n      to.code.length == 0\n        || ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, data)\n          == ERC721TokenReceiver.onERC721Received.selector,\n      \"UNSAFE_RECIPIENT\"\n    );\n  }\n}\n\n/// @notice A generic interface for a contract which properly accepts ERC721 tokens.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC721.sol)\nabstract contract ERC721TokenReceiver {\n  function onERC721Received(address, address, uint256, bytes calldata) external virtual returns (bytes4) {\n    return ERC721TokenReceiver.onERC721Received.selector;\n  }\n}\n"
      }
    },
    "settings": {
      "remappings": [
        "@openzeppelin/=lib/openzeppelin-contracts/contracts/",
        "@solmate/=lib/solmate/src/",
        "@solady/=lib/solady/src/",
        "ds-test/=lib/forge-std/lib/ds-test/src/",
        "forge-std/=lib/forge-std/src/",
        "openzeppelin-contracts/=lib/openzeppelin-contracts/",
        "solady/=lib/solady/src/",
        "solmate/=lib/solmate/src/"
      ],
      "optimizer": {
        "enabled": true,
        "runs": 10000000
      },
      "metadata": {
        "useLiteralContent": false,
        "bytecodeHash": "none",
        "appendCBOR": true
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "evmVersion": "paris",
      "libraries": {}
    }
  }}