{ "language": "Solidity", "sources": { "@balancer-labs/v2-interfaces/contracts/solidity-utils/openzeppelin/IERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\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 `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address recipient, 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 `sender` to `recipient` 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 sender,\n address recipient,\n uint256 amount\n ) external returns (bool);\n\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" }, "@balancer-labs/v2-interfaces/contracts/solidity-utils/misc/IWETH.sol": { "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see .\n\npragma solidity ^0.7.0;\n\nimport \"../openzeppelin/IERC20.sol\";\n\n/**\n * @dev Interface for WETH9.\n * See https://github.com/gnosis/canonical-weth/blob/0dd1ea3e295eef916d0c6223ec63141137d22d67/contracts/WETH9.sol\n */\ninterface IWETH is IERC20 {\n function deposit() external payable;\n\n function withdraw(uint256 amount) external;\n}\n" }, "@balancer-labs/v2-interfaces/contracts/vault/IAsset.sol": { "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see .\n\npragma solidity ^0.7.0;\n\n/**\n * @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero\n * address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like\n * types.\n *\n * This concept is unrelated to a Pool's Asset Managers.\n */\ninterface IAsset {\n // solhint-disable-previous-line no-empty-blocks\n}\n" }, "@balancer-labs/v2-interfaces/contracts/solidity-utils/helpers/BalancerErrors.sol": { "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see .\n\npragma solidity ^0.7.0;\n\n// solhint-disable\n\n/**\n * @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are\n * supported.\n */\nfunction _require(bool condition, uint256 errorCode) pure {\n if (!condition) _revert(errorCode);\n}\n\n/**\n * @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported.\n */\nfunction _revert(uint256 errorCode) pure {\n // We're going to dynamically create a revert string based on the error code, with the following format:\n // 'BAL#{errorCode}'\n // where the code is left-padded with zeroes to three digits (so they range from 000 to 999).\n //\n // We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a\n // number (8 to 16 bits) than the individual string characters.\n //\n // The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a\n // much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a\n // safe place to rely on it without worrying about how its usage might affect e.g. memory contents.\n assembly {\n // First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999\n // range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for\n // the '0' character.\n\n let units := add(mod(errorCode, 10), 0x30)\n\n errorCode := div(errorCode, 10)\n let tenths := add(mod(errorCode, 10), 0x30)\n\n errorCode := div(errorCode, 10)\n let hundreds := add(mod(errorCode, 10), 0x30)\n\n // With the individual characters, we can now construct the full string. The \"BAL#\" part is a known constant\n // (0x42414c23): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the\n // characters to it, each shifted by a multiple of 8.\n // The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits\n // per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte\n // array).\n\n let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds))))\n\n // We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded\n // message will have the following layout:\n // [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ]\n\n // The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We\n // also write zeroes to the next 28 bytes of memory, but those are about to be overwritten.\n mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000)\n // Next is the offset to the location of the string, which will be placed immediately after (20 bytes away).\n mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020)\n // The string length is fixed: 7 characters.\n mstore(0x24, 7)\n // Finally, the string itself is stored.\n mstore(0x44, revertReason)\n\n // Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of\n // the encoded message is therefore 4 + 32 + 32 + 32 = 100.\n revert(0, 100)\n }\n}\n\nlibrary Errors {\n // Math\n uint256 internal constant ADD_OVERFLOW = 0;\n uint256 internal constant SUB_OVERFLOW = 1;\n uint256 internal constant SUB_UNDERFLOW = 2;\n uint256 internal constant MUL_OVERFLOW = 3;\n uint256 internal constant ZERO_DIVISION = 4;\n uint256 internal constant DIV_INTERNAL = 5;\n uint256 internal constant X_OUT_OF_BOUNDS = 6;\n uint256 internal constant Y_OUT_OF_BOUNDS = 7;\n uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8;\n uint256 internal constant INVALID_EXPONENT = 9;\n\n // Input\n uint256 internal constant OUT_OF_BOUNDS = 100;\n uint256 internal constant UNSORTED_ARRAY = 101;\n uint256 internal constant UNSORTED_TOKENS = 102;\n uint256 internal constant INPUT_LENGTH_MISMATCH = 103;\n uint256 internal constant ZERO_TOKEN = 104;\n\n // Shared pools\n uint256 internal constant MIN_TOKENS = 200;\n uint256 internal constant MAX_TOKENS = 201;\n uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202;\n uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203;\n uint256 internal constant MINIMUM_BPT = 204;\n uint256 internal constant CALLER_NOT_VAULT = 205;\n uint256 internal constant UNINITIALIZED = 206;\n uint256 internal constant BPT_IN_MAX_AMOUNT = 207;\n uint256 internal constant BPT_OUT_MIN_AMOUNT = 208;\n uint256 internal constant EXPIRED_PERMIT = 209;\n uint256 internal constant NOT_TWO_TOKENS = 210;\n uint256 internal constant DISABLED = 211;\n\n // Pools\n uint256 internal constant MIN_AMP = 300;\n uint256 internal constant MAX_AMP = 301;\n uint256 internal constant MIN_WEIGHT = 302;\n uint256 internal constant MAX_STABLE_TOKENS = 303;\n uint256 internal constant MAX_IN_RATIO = 304;\n uint256 internal constant MAX_OUT_RATIO = 305;\n uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306;\n uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307;\n uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308;\n uint256 internal constant INVALID_TOKEN = 309;\n uint256 internal constant UNHANDLED_JOIN_KIND = 310;\n uint256 internal constant ZERO_INVARIANT = 311;\n uint256 internal constant ORACLE_INVALID_SECONDS_QUERY = 312;\n uint256 internal constant ORACLE_NOT_INITIALIZED = 313;\n uint256 internal constant ORACLE_QUERY_TOO_OLD = 314;\n uint256 internal constant ORACLE_INVALID_INDEX = 315;\n uint256 internal constant ORACLE_BAD_SECS = 316;\n uint256 internal constant AMP_END_TIME_TOO_CLOSE = 317;\n uint256 internal constant AMP_ONGOING_UPDATE = 318;\n uint256 internal constant AMP_RATE_TOO_HIGH = 319;\n uint256 internal constant AMP_NO_ONGOING_UPDATE = 320;\n uint256 internal constant STABLE_INVARIANT_DIDNT_CONVERGE = 321;\n uint256 internal constant STABLE_GET_BALANCE_DIDNT_CONVERGE = 322;\n uint256 internal constant RELAYER_NOT_CONTRACT = 323;\n uint256 internal constant BASE_POOL_RELAYER_NOT_CALLED = 324;\n uint256 internal constant REBALANCING_RELAYER_REENTERED = 325;\n uint256 internal constant GRADUAL_UPDATE_TIME_TRAVEL = 326;\n uint256 internal constant SWAPS_DISABLED = 327;\n uint256 internal constant CALLER_IS_NOT_LBP_OWNER = 328;\n uint256 internal constant PRICE_RATE_OVERFLOW = 329;\n uint256 internal constant INVALID_JOIN_EXIT_KIND_WHILE_SWAPS_DISABLED = 330;\n uint256 internal constant WEIGHT_CHANGE_TOO_FAST = 331;\n uint256 internal constant LOWER_GREATER_THAN_UPPER_TARGET = 332;\n uint256 internal constant UPPER_TARGET_TOO_HIGH = 333;\n uint256 internal constant UNHANDLED_BY_LINEAR_POOL = 334;\n uint256 internal constant OUT_OF_TARGET_RANGE = 335;\n uint256 internal constant UNHANDLED_EXIT_KIND = 336;\n uint256 internal constant UNAUTHORIZED_EXIT = 337;\n uint256 internal constant MAX_MANAGEMENT_SWAP_FEE_PERCENTAGE = 338;\n uint256 internal constant UNHANDLED_BY_MANAGED_POOL = 339;\n uint256 internal constant UNHANDLED_BY_PHANTOM_POOL = 340;\n uint256 internal constant TOKEN_DOES_NOT_HAVE_RATE_PROVIDER = 341;\n uint256 internal constant INVALID_INITIALIZATION = 342;\n uint256 internal constant OUT_OF_NEW_TARGET_RANGE = 343;\n uint256 internal constant FEATURE_DISABLED = 344;\n uint256 internal constant UNINITIALIZED_POOL_CONTROLLER = 345;\n uint256 internal constant SET_SWAP_FEE_DURING_FEE_CHANGE = 346;\n uint256 internal constant SET_SWAP_FEE_PENDING_FEE_CHANGE = 347;\n uint256 internal constant CHANGE_TOKENS_DURING_WEIGHT_CHANGE = 348;\n uint256 internal constant CHANGE_TOKENS_PENDING_WEIGHT_CHANGE = 349;\n uint256 internal constant MAX_WEIGHT = 350;\n uint256 internal constant UNAUTHORIZED_JOIN = 351;\n uint256 internal constant MAX_MANAGEMENT_AUM_FEE_PERCENTAGE = 352;\n\n // Lib\n uint256 internal constant REENTRANCY = 400;\n uint256 internal constant SENDER_NOT_ALLOWED = 401;\n uint256 internal constant PAUSED = 402;\n uint256 internal constant PAUSE_WINDOW_EXPIRED = 403;\n uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404;\n uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405;\n uint256 internal constant INSUFFICIENT_BALANCE = 406;\n uint256 internal constant INSUFFICIENT_ALLOWANCE = 407;\n uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408;\n uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409;\n uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410;\n uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411;\n uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412;\n uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413;\n uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414;\n uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415;\n uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416;\n uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417;\n uint256 internal constant SAFE_ERC20_CALL_FAILED = 418;\n uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419;\n uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420;\n uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421;\n uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422;\n uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423;\n uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424;\n uint256 internal constant BUFFER_PERIOD_EXPIRED = 425;\n uint256 internal constant CALLER_IS_NOT_OWNER = 426;\n uint256 internal constant NEW_OWNER_IS_ZERO = 427;\n uint256 internal constant CODE_DEPLOYMENT_FAILED = 428;\n uint256 internal constant CALL_TO_NON_CONTRACT = 429;\n uint256 internal constant LOW_LEVEL_CALL_FAILED = 430;\n uint256 internal constant NOT_PAUSED = 431;\n uint256 internal constant ADDRESS_ALREADY_ALLOWLISTED = 432;\n uint256 internal constant ADDRESS_NOT_ALLOWLISTED = 433;\n uint256 internal constant ERC20_BURN_EXCEEDS_BALANCE = 434;\n uint256 internal constant INVALID_OPERATION = 435;\n uint256 internal constant CODEC_OVERFLOW = 436;\n uint256 internal constant IN_RECOVERY_MODE = 437;\n uint256 internal constant NOT_IN_RECOVERY_MODE = 438;\n uint256 internal constant INDUCED_FAILURE = 439;\n uint256 internal constant EXPIRED_SIGNATURE = 440;\n uint256 internal constant MALFORMED_SIGNATURE = 441;\n uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_UINT64 = 442;\n uint256 internal constant UNHANDLED_FEE_TYPE = 443;\n\n // Vault\n uint256 internal constant INVALID_POOL_ID = 500;\n uint256 internal constant CALLER_NOT_POOL = 501;\n uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502;\n uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503;\n uint256 internal constant INVALID_SIGNATURE = 504;\n uint256 internal constant EXIT_BELOW_MIN = 505;\n uint256 internal constant JOIN_ABOVE_MAX = 506;\n uint256 internal constant SWAP_LIMIT = 507;\n uint256 internal constant SWAP_DEADLINE = 508;\n uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509;\n uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510;\n uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511;\n uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512;\n uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513;\n uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514;\n uint256 internal constant INVALID_POST_LOAN_BALANCE = 515;\n uint256 internal constant INSUFFICIENT_ETH = 516;\n uint256 internal constant UNALLOCATED_ETH = 517;\n uint256 internal constant ETH_TRANSFER = 518;\n uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519;\n uint256 internal constant TOKENS_MISMATCH = 520;\n uint256 internal constant TOKEN_NOT_REGISTERED = 521;\n uint256 internal constant TOKEN_ALREADY_REGISTERED = 522;\n uint256 internal constant TOKENS_ALREADY_SET = 523;\n uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524;\n uint256 internal constant NONZERO_TOKEN_BALANCE = 525;\n uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526;\n uint256 internal constant POOL_NO_TOKENS = 527;\n uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528;\n\n // Fees\n uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600;\n uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601;\n uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602;\n uint256 internal constant AUM_FEE_PERCENTAGE_TOO_HIGH = 603;\n\n // Misc\n uint256 internal constant SHOULD_NOT_HAPPEN = 999;\n}\n" }, "@balancer-labs/v2-interfaces/contracts/vault/IVault.sol": { "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see .\n\npragma experimental ABIEncoderV2;\n\nimport \"../solidity-utils/openzeppelin/IERC20.sol\";\nimport \"../solidity-utils/helpers/IAuthentication.sol\";\nimport \"../solidity-utils/helpers/ISignaturesValidator.sol\";\nimport \"../solidity-utils/helpers/ITemporarilyPausable.sol\";\nimport \"../solidity-utils/misc/IWETH.sol\";\n\nimport \"./IAsset.sol\";\nimport \"./IAuthorizer.sol\";\nimport \"./IFlashLoanRecipient.sol\";\nimport \"./IProtocolFeesCollector.sol\";\n\npragma solidity ^0.7.0;\n\n/**\n * @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that\n * don't override one of these declarations.\n */\ninterface IVault is ISignaturesValidator, ITemporarilyPausable, IAuthentication {\n // Generalities about the Vault:\n //\n // - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are\n // transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling\n // `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by\n // calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning\n // a boolean value: in these scenarios, a non-reverting call is assumed to be successful.\n //\n // - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g.\n // while execution control is transferred to a token contract during a swap) will result in a revert. View\n // functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results.\n // Contracts calling view functions in the Vault must make sure the Vault has not already been entered.\n //\n // - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools.\n\n // Authorizer\n //\n // Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists\n // outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller\n // can perform a given action.\n\n /**\n * @dev Returns the Vault's Authorizer.\n */\n function getAuthorizer() external view returns (IAuthorizer);\n\n /**\n * @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this.\n *\n * Emits an `AuthorizerChanged` event.\n */\n function setAuthorizer(IAuthorizer newAuthorizer) external;\n\n /**\n * @dev Emitted when a new authorizer is set by `setAuthorizer`.\n */\n event AuthorizerChanged(IAuthorizer indexed newAuthorizer);\n\n // Relayers\n //\n // Additionally, it is possible for an account to perform certain actions on behalf of another one, using their\n // Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions,\n // and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield\n // this power, two things must occur:\n // - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This\n // means that Balancer governance must approve each individual contract to act as a relayer for the intended\n // functions.\n // - Each user must approve the relayer to act on their behalf.\n // This double protection means users cannot be tricked into approving malicious relayers (because they will not\n // have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised\n // Authorizer or governance drain user funds, since they would also need to be approved by each individual user.\n\n /**\n * @dev Returns true if `user` has approved `relayer` to act as a relayer for them.\n */\n function hasApprovedRelayer(address user, address relayer) external view returns (bool);\n\n /**\n * @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise.\n *\n * Emits a `RelayerApprovalChanged` event.\n */\n function setRelayerApproval(\n address sender,\n address relayer,\n bool approved\n ) external;\n\n /**\n * @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`.\n */\n event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved);\n\n // Internal Balance\n //\n // Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later\n // transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination\n // when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced\n // gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users.\n //\n // Internal Balance management features batching, which means a single contract call can be used to perform multiple\n // operations of different kinds, with different senders and recipients, at once.\n\n /**\n * @dev Returns `user`'s Internal Balance for a set of tokens.\n */\n function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory);\n\n /**\n * @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer)\n * and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as\n * it lets integrators reuse a user's Vault allowance.\n *\n * For each operation, if the caller is not `sender`, it must be an authorized relayer for them.\n */\n function manageUserBalance(UserBalanceOp[] memory ops) external payable;\n\n /**\n * @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received\n without manual WETH wrapping or unwrapping.\n */\n struct UserBalanceOp {\n UserBalanceOpKind kind;\n IAsset asset;\n uint256 amount;\n address sender;\n address payable recipient;\n }\n\n // There are four possible operations in `manageUserBalance`:\n //\n // - DEPOSIT_INTERNAL\n // Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding\n // `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`.\n //\n // ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped\n // and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is\n // relevant for relayers).\n //\n // Emits an `InternalBalanceChanged` event.\n //\n //\n // - WITHDRAW_INTERNAL\n // Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`.\n //\n // ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send\n // it to the recipient as ETH.\n //\n // Emits an `InternalBalanceChanged` event.\n //\n //\n // - TRANSFER_INTERNAL\n // Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`.\n //\n // Reverts if the ETH sentinel value is passed.\n //\n // Emits an `InternalBalanceChanged` event.\n //\n //\n // - TRANSFER_EXTERNAL\n // Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by\n // relayers, as it lets them reuse a user's Vault allowance.\n //\n // Reverts if the ETH sentinel value is passed.\n //\n // Emits an `ExternalBalanceTransfer` event.\n\n enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL }\n\n /**\n * @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through\n * interacting with Pools using Internal Balance.\n *\n * Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH\n * address.\n */\n event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta);\n\n /**\n * @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account.\n */\n event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount);\n\n // Pools\n //\n // There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced\n // functionality:\n //\n // - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the\n // balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads),\n // which increase with the number of registered tokens.\n //\n // - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the\n // balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted\n // constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are\n // independent of the number of registered tokens.\n //\n // - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like\n // minimal swap info Pools, these are called via IMinimalSwapInfoPool.\n\n enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN }\n\n /**\n * @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which\n * is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be\n * changed.\n *\n * The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`,\n * depending on the chosen specialization setting. This contract is known as the Pool's contract.\n *\n * Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words,\n * multiple Pools may share the same contract.\n *\n * Emits a `PoolRegistered` event.\n */\n function registerPool(PoolSpecialization specialization) external returns (bytes32);\n\n /**\n * @dev Emitted when a Pool is registered by calling `registerPool`.\n */\n event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization);\n\n /**\n * @dev Returns a Pool's contract address and specialization setting.\n */\n function getPool(bytes32 poolId) external view returns (address, PoolSpecialization);\n\n /**\n * @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract.\n *\n * Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens,\n * exit by receiving registered tokens, and can only swap registered tokens.\n *\n * Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length\n * of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in\n * ascending order.\n *\n * The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset\n * Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`,\n * depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore\n * expected to be highly secured smart contracts with sound design principles, and the decision to register an\n * Asset Manager should not be made lightly.\n *\n * Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset\n * Manager is set, it cannot be changed except by deregistering the associated token and registering again with a\n * different Asset Manager.\n *\n * Emits a `TokensRegistered` event.\n */\n function registerTokens(\n bytes32 poolId,\n IERC20[] memory tokens,\n address[] memory assetManagers\n ) external;\n\n /**\n * @dev Emitted when a Pool registers tokens by calling `registerTokens`.\n */\n event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers);\n\n /**\n * @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract.\n *\n * Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total\n * balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens\n * must be deregistered in the same `deregisterTokens` call.\n *\n * A deregistered token can be re-registered later on, possibly with a different Asset Manager.\n *\n * Emits a `TokensDeregistered` event.\n */\n function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external;\n\n /**\n * @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`.\n */\n event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens);\n\n /**\n * @dev Returns detailed information for a Pool's registered token.\n *\n * `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens\n * withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token`\n * equals the sum of `cash` and `managed`.\n *\n * Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`,\n * `managed` or `total` balance to be greater than 2^112 - 1.\n *\n * `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a\n * join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for\n * example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a\n * change for this purpose, and will update `lastChangeBlock`.\n *\n * `assetManager` is the Pool's token Asset Manager.\n */\n function getPoolTokenInfo(bytes32 poolId, IERC20 token)\n external\n view\n returns (\n uint256 cash,\n uint256 managed,\n uint256 lastChangeBlock,\n address assetManager\n );\n\n /**\n * @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of\n * the tokens' `balances` changed.\n *\n * The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all\n * Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order.\n *\n * If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same\n * order as passed to `registerTokens`.\n *\n * Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are\n * the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo`\n * instead.\n */\n function getPoolTokens(bytes32 poolId)\n external\n view\n returns (\n IERC20[] memory tokens,\n uint256[] memory balances,\n uint256 lastChangeBlock\n );\n\n /**\n * @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will\n * trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized\n * Pool shares.\n *\n * If the caller is not `sender`, it must be an authorized relayer for them.\n *\n * The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount\n * to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces\n * these maximums.\n *\n * If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable\n * this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the\n * WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent\n * back to the caller (not the sender, which is important for relayers).\n *\n * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when\n * interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be\n * sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final\n * `assets` array might not be sorted. Pools with no registered tokens cannot be joined.\n *\n * If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only\n * be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be\n * withdrawn from Internal Balance: attempting to do so will trigger a revert.\n *\n * This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement\n * their own custom logic. This typically requires additional information from the user (such as the expected number\n * of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed\n * directly to the Pool's contract, as is `recipient`.\n *\n * Emits a `PoolBalanceChanged` event.\n */\n function joinPool(\n bytes32 poolId,\n address sender,\n address recipient,\n JoinPoolRequest memory request\n ) external payable;\n\n struct JoinPoolRequest {\n IAsset[] assets;\n uint256[] maxAmountsIn;\n bytes userData;\n bool fromInternalBalance;\n }\n\n /**\n * @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will\n * trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized\n * Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see\n * `getPoolTokenInfo`).\n *\n * If the caller is not `sender`, it must be an authorized relayer for them.\n *\n * The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum\n * token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault:\n * it just enforces these minimums.\n *\n * If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To\n * enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead\n * of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit.\n *\n * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when\n * interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must\n * be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the\n * final `assets` array might not be sorted. Pools with no registered tokens cannot be exited.\n *\n * If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise,\n * an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to\n * do so will trigger a revert.\n *\n * `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the\n * `tokens` array. This array must match the Pool's registered tokens.\n *\n * This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement\n * their own custom logic. This typically requires additional information from the user (such as the expected number\n * of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and\n * passed directly to the Pool's contract.\n *\n * Emits a `PoolBalanceChanged` event.\n */\n function exitPool(\n bytes32 poolId,\n address sender,\n address payable recipient,\n ExitPoolRequest memory request\n ) external;\n\n struct ExitPoolRequest {\n IAsset[] assets;\n uint256[] minAmountsOut;\n bytes userData;\n bool toInternalBalance;\n }\n\n /**\n * @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively.\n */\n event PoolBalanceChanged(\n bytes32 indexed poolId,\n address indexed liquidityProvider,\n IERC20[] tokens,\n int256[] deltas,\n uint256[] protocolFeeAmounts\n );\n\n enum PoolBalanceChangeKind { JOIN, EXIT }\n\n // Swaps\n //\n // Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this,\n // they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be\n // aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote.\n //\n // The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence.\n // In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'),\n // and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out').\n // More complex swaps, such as one token in to multiple tokens out can be achieved by batching together\n // individual swaps.\n //\n // There are two swap kinds:\n // - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the\n // `onSwap` hook) the amount of tokens out (to send to the recipient).\n // - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines\n // (via the `onSwap` hook) the amount of tokens in (to receive from the sender).\n //\n // Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with\n // the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated\n // tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended\n // swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at\n // the final intended token.\n //\n // In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal\n // Balance) after all individual swaps have been completed, and the net token balance change computed. This makes\n // certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost\n // much less gas than they would otherwise.\n //\n // It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple\n // Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only\n // updating the Pool's internal accounting).\n //\n // To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token\n // involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the\n // minimum amount of tokens to receive (by passing a negative value) is specified.\n //\n // Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after\n // this point in time (e.g. if the transaction failed to be included in a block promptly).\n //\n // If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do\n // the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be\n // passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the\n // same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers).\n //\n // Finally, Internal Balance can be used when either sending or receiving tokens.\n\n enum SwapKind { GIVEN_IN, GIVEN_OUT }\n\n /**\n * @dev Performs a swap with a single Pool.\n *\n * If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens\n * taken from the Pool, which must be greater than or equal to `limit`.\n *\n * If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens\n * sent to the Pool, which must be less than or equal to `limit`.\n *\n * Internal Balance usage and the recipient are determined by the `funds` struct.\n *\n * Emits a `Swap` event.\n */\n function swap(\n SingleSwap memory singleSwap,\n FundManagement memory funds,\n uint256 limit,\n uint256 deadline\n ) external payable returns (uint256);\n\n /**\n * @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on\n * the `kind` value.\n *\n * `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address).\n * Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault.\n *\n * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be\n * used to extend swap behavior.\n */\n struct SingleSwap {\n bytes32 poolId;\n SwapKind kind;\n IAsset assetIn;\n IAsset assetOut;\n uint256 amount;\n bytes userData;\n }\n\n /**\n * @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either\n * the amount of tokens sent to or received from the Pool, depending on the `kind` value.\n *\n * Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the\n * Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at\n * the same index in the `assets` array.\n *\n * Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a\n * Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or\n * `amountOut` depending on the swap kind.\n *\n * Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out\n * of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal\n * the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`.\n *\n * The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses,\n * or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and\n * out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to\n * or unwrapped from WETH by the Vault.\n *\n * Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies\n * the minimum or maximum amount of each token the vault is allowed to transfer.\n *\n * `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the\n * equivalent `swap` call.\n *\n * Emits `Swap` events.\n */\n function batchSwap(\n SwapKind kind,\n BatchSwapStep[] memory swaps,\n IAsset[] memory assets,\n FundManagement memory funds,\n int256[] memory limits,\n uint256 deadline\n ) external payable returns (int256[] memory);\n\n /**\n * @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the\n * `assets` array passed to that function, and ETH assets are converted to WETH.\n *\n * If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out\n * from the previous swap, depending on the swap kind.\n *\n * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be\n * used to extend swap behavior.\n */\n struct BatchSwapStep {\n bytes32 poolId;\n uint256 assetInIndex;\n uint256 assetOutIndex;\n uint256 amount;\n bytes userData;\n }\n\n /**\n * @dev Emitted for each individual swap performed by `swap` or `batchSwap`.\n */\n event Swap(\n bytes32 indexed poolId,\n IERC20 indexed tokenIn,\n IERC20 indexed tokenOut,\n uint256 amountIn,\n uint256 amountOut\n );\n\n /**\n * @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the\n * `recipient` account.\n *\n * If the caller is not `sender`, it must be an authorized relayer for them.\n *\n * If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20\n * transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender`\n * must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of\n * `joinPool`.\n *\n * If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of\n * transferred. This matches the behavior of `exitPool`.\n *\n * Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a\n * revert.\n */\n struct FundManagement {\n address sender;\n bool fromInternalBalance;\n address payable recipient;\n bool toInternalBalance;\n }\n\n /**\n * @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be\n * simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result.\n *\n * Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH)\n * the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it\n * receives are the same that an equivalent `batchSwap` call would receive.\n *\n * Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct.\n * This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens,\n * approve them for the Vault, or even know a user's address.\n *\n * Note that this function is not 'view' (due to implementation details): the client code must explicitly execute\n * eth_call instead of eth_sendTransaction.\n */\n function queryBatchSwap(\n SwapKind kind,\n BatchSwapStep[] memory swaps,\n IAsset[] memory assets,\n FundManagement memory funds\n ) external returns (int256[] memory assetDeltas);\n\n // Flash Loans\n\n /**\n * @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it,\n * and then reverting unless the tokens plus a proportional protocol fee have been returned.\n *\n * The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount\n * for each token contract. `tokens` must be sorted in ascending order.\n *\n * The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the\n * `receiveFlashLoan` call.\n *\n * Emits `FlashLoan` events.\n */\n function flashLoan(\n IFlashLoanRecipient recipient,\n IERC20[] memory tokens,\n uint256[] memory amounts,\n bytes memory userData\n ) external;\n\n /**\n * @dev Emitted for each individual flash loan performed by `flashLoan`.\n */\n event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount);\n\n // Asset Management\n //\n // Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's\n // tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see\n // `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly\n // controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the\n // prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore\n // not constrained to the tokens they are managing, but extends to the entire Pool's holdings.\n //\n // However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit,\n // for example by lending unused tokens out for interest, or using them to participate in voting protocols.\n //\n // This concept is unrelated to the IAsset interface.\n\n /**\n * @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates.\n *\n * Pool Balance management features batching, which means a single contract call can be used to perform multiple\n * operations of different kinds, with different Pools and tokens, at once.\n *\n * For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`.\n */\n function managePoolBalance(PoolBalanceOp[] memory ops) external;\n\n struct PoolBalanceOp {\n PoolBalanceOpKind kind;\n bytes32 poolId;\n IERC20 token;\n uint256 amount;\n }\n\n /**\n * Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged.\n *\n * Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged.\n *\n * Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total.\n * The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss).\n */\n enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE }\n\n /**\n * @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`.\n */\n event PoolBalanceManaged(\n bytes32 indexed poolId,\n address indexed assetManager,\n IERC20 indexed token,\n int256 cashDelta,\n int256 managedDelta\n );\n\n // Protocol Fees\n //\n // Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by\n // permissioned accounts.\n //\n // There are two kinds of protocol fees:\n //\n // - flash loan fees: charged on all flash loans, as a percentage of the amounts lent.\n //\n // - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including\n // swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather,\n // Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the\n // Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as\n // exiting a Pool in debt without first paying their share.\n\n /**\n * @dev Returns the current protocol fee module.\n */\n function getProtocolFeesCollector() external view returns (IProtocolFeesCollector);\n\n /**\n * @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an\n * error in some part of the system.\n *\n * The Vault can only be paused during an initial time period, after which pausing is forever disabled.\n *\n * While the contract is paused, the following features are disabled:\n * - depositing and transferring internal balance\n * - transferring external balance (using the Vault's allowance)\n * - swaps\n * - joining Pools\n * - Asset Manager interactions\n *\n * Internal Balance can still be withdrawn, and Pools exited.\n */\n function setPaused(bool paused) external;\n\n /**\n * @dev Returns the Vault's WETH instance.\n */\n function WETH() external view returns (IWETH);\n // solhint-disable-previous-line func-name-mixedcase\n}\n" }, "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/Address.sol": { "content": "// SPDX-License-Identifier: MIT\n\n// Based on the Address library from OpenZeppelin Contracts, altered by removing the `isContract` checks on\n// `functionCall` and `functionDelegateCall` in order to save gas, as the recipients are known to be contracts.\n\npragma solidity ^0.7.0;\n\nimport \"@balancer-labs/v2-interfaces/contracts/solidity-utils/helpers/BalancerErrors.sol\";\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 function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize, which returns 0 for contracts in\n // construction, since the code is only stored at the end of the\n // constructor execution.\n\n uint256 size;\n // solhint-disable-next-line no-inline-assembly\n assembly {\n size := extcodesize(account)\n }\n return size > 0;\n }\n\n // solhint-disable max-line-length\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, Errors.ADDRESS_INSUFFICIENT_BALANCE);\n\n // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\n (bool success, ) = recipient.call{ value: amount }(\"\");\n _require(success, Errors.ADDRESS_CANNOT_SEND_VALUE);\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 * - 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 // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.call(data);\n return verifyCallResult(success, returndata);\n }\n\n // solhint-enable max-line-length\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but passing some native ETH as msg.value to the call.\n *\n * _Available since v3.4._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.call{ value: value }(data);\n return verifyCallResult(success, returndata);\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 // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata);\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling up the\n * revert reason or using the one provided.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\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 // solhint-disable-next-line no-inline-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n _revert(Errors.LOW_LEVEL_CALL_FAILED);\n }\n }\n }\n}\n" }, "@balancer-labs/v2-solidity-utils/contracts/math/Math.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.0;\n\nimport \"@balancer-labs/v2-interfaces/contracts/solidity-utils/helpers/BalancerErrors.sol\";\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations with added overflow checks.\n * Adapted from OpenZeppelin's SafeMath library.\n */\nlibrary Math {\n /**\n * @dev Returns the absolute value of a signed integer.\n */\n function abs(int256 a) internal pure returns (uint256) {\n return a > 0 ? uint256(a) : uint256(-a);\n }\n\n /**\n * @dev Returns the addition of two unsigned integers of 256 bits, reverting on overflow.\n */\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 c = a + b;\n _require(c >= a, Errors.ADD_OVERFLOW);\n return c;\n }\n\n /**\n * @dev Returns the addition of two signed integers, reverting on overflow.\n */\n function add(int256 a, int256 b) internal pure returns (int256) {\n int256 c = a + b;\n _require((b >= 0 && c >= a) || (b < 0 && c < a), Errors.ADD_OVERFLOW);\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers of 256 bits, reverting on overflow.\n */\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n _require(b <= a, Errors.SUB_OVERFLOW);\n uint256 c = a - b;\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two signed integers, reverting on overflow.\n */\n function sub(int256 a, int256 b) internal pure returns (int256) {\n int256 c = a - b;\n _require((b >= 0 && c <= a) || (b < 0 && c > a), Errors.SUB_OVERFLOW);\n return c;\n }\n\n /**\n * @dev Returns the largest of two numbers of 256 bits.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a >= b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers of 256 bits.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 c = a * b;\n _require(a == 0 || c / a == b, Errors.MUL_OVERFLOW);\n return c;\n }\n\n function div(\n uint256 a,\n uint256 b,\n bool roundUp\n ) internal pure returns (uint256) {\n return roundUp ? divUp(a, b) : divDown(a, b);\n }\n\n function divDown(uint256 a, uint256 b) internal pure returns (uint256) {\n _require(b != 0, Errors.ZERO_DIVISION);\n return a / b;\n }\n\n function divUp(uint256 a, uint256 b) internal pure returns (uint256) {\n _require(b != 0, Errors.ZERO_DIVISION);\n\n if (a == 0) {\n return 0;\n } else {\n return 1 + (a - 1) / b;\n }\n }\n}\n" }, "@balancer-labs/v2-interfaces/contracts/solidity-utils/helpers/IAuthentication.sol": { "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see .\n\npragma solidity ^0.7.0;\n\ninterface IAuthentication {\n /**\n * @dev Returns the action identifier associated with the external function described by `selector`.\n */\n function getActionId(bytes4 selector) external view returns (bytes32);\n}\n" }, "@balancer-labs/v2-interfaces/contracts/solidity-utils/helpers/ISignaturesValidator.sol": { "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see .\n\npragma solidity ^0.7.0;\n\n/**\n * @dev Interface for the SignatureValidator helper, used to support meta-transactions.\n */\ninterface ISignaturesValidator {\n /**\n * @dev Returns the EIP712 domain separator.\n */\n function getDomainSeparator() external view returns (bytes32);\n\n /**\n * @dev Returns the next nonce used by an address to sign messages.\n */\n function getNextNonce(address user) external view returns (uint256);\n}\n" }, "@balancer-labs/v2-interfaces/contracts/solidity-utils/helpers/ITemporarilyPausable.sol": { "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see .\n\npragma solidity ^0.7.0;\n\n/**\n * @dev Interface for the TemporarilyPausable helper.\n */\ninterface ITemporarilyPausable {\n /**\n * @dev Emitted every time the pause state changes by `_setPaused`.\n */\n event PausedStateChanged(bool paused);\n\n /**\n * @dev Returns the current paused state.\n */\n function getPausedState()\n external\n view\n returns (\n bool paused,\n uint256 pauseWindowEndTime,\n uint256 bufferPeriodEndTime\n );\n}\n" }, "@balancer-labs/v2-interfaces/contracts/vault/IAuthorizer.sol": { "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see .\n\npragma solidity ^0.7.0;\n\ninterface IAuthorizer {\n /**\n * @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`.\n */\n function canPerform(\n bytes32 actionId,\n address account,\n address where\n ) external view returns (bool);\n}\n" }, "@balancer-labs/v2-interfaces/contracts/vault/IFlashLoanRecipient.sol": { "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see .\n\npragma solidity ^0.7.0;\n\n// Inspired by Aave Protocol's IFlashLoanReceiver.\n\nimport \"../solidity-utils/openzeppelin/IERC20.sol\";\n\ninterface IFlashLoanRecipient {\n /**\n * @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient.\n *\n * At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this\n * call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the\n * Vault, or else the entire flash loan will revert.\n *\n * `userData` is the same value passed in the `IVault.flashLoan` call.\n */\n function receiveFlashLoan(\n IERC20[] memory tokens,\n uint256[] memory amounts,\n uint256[] memory feeAmounts,\n bytes memory userData\n ) external;\n}\n" }, "@balancer-labs/v2-interfaces/contracts/vault/IProtocolFeesCollector.sol": { "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see .\n\npragma solidity ^0.7.0;\npragma experimental ABIEncoderV2;\n\nimport \"../solidity-utils/openzeppelin/IERC20.sol\";\n\nimport \"./IVault.sol\";\nimport \"./IAuthorizer.sol\";\n\ninterface IProtocolFeesCollector {\n event SwapFeePercentageChanged(uint256 newSwapFeePercentage);\n event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage);\n\n function withdrawCollectedFees(\n IERC20[] calldata tokens,\n uint256[] calldata amounts,\n address recipient\n ) external;\n\n function setSwapFeePercentage(uint256 newSwapFeePercentage) external;\n\n function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external;\n\n function getSwapFeePercentage() external view returns (uint256);\n\n function getFlashLoanFeePercentage() external view returns (uint256);\n\n function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts);\n\n function getAuthorizer() external view returns (IAuthorizer);\n\n function vault() external view returns (IVault);\n}\n" }, "@balancer-labs/v2-solidity-utils/contracts/helpers/InputHelpers.sol": { "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see .\n\npragma solidity ^0.7.0;\n\nimport \"@balancer-labs/v2-interfaces/contracts/solidity-utils/openzeppelin/IERC20.sol\";\nimport \"@balancer-labs/v2-interfaces/contracts/solidity-utils/helpers/BalancerErrors.sol\";\n\nlibrary InputHelpers {\n function ensureInputLengthMatch(uint256 a, uint256 b) internal pure {\n _require(a == b, Errors.INPUT_LENGTH_MISMATCH);\n }\n\n function ensureInputLengthMatch(\n uint256 a,\n uint256 b,\n uint256 c\n ) internal pure {\n _require(a == b && b == c, Errors.INPUT_LENGTH_MISMATCH);\n }\n\n function ensureArrayIsSorted(IERC20[] memory array) internal pure {\n address[] memory addressArray;\n // solhint-disable-next-line no-inline-assembly\n assembly {\n addressArray := array\n }\n ensureArrayIsSorted(addressArray);\n }\n\n function ensureArrayIsSorted(address[] memory array) internal pure {\n if (array.length < 2) {\n return;\n }\n\n address previous = array[0];\n for (uint256 i = 1; i < array.length; ++i) {\n address current = array[i];\n _require(previous < current, Errors.UNSORTED_ARRAY);\n previous = current;\n }\n }\n}\n" }, "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ReentrancyGuard.sol": { "content": "// SPDX-License-Identifier: MIT\n\n// Based on the ReentrancyGuard library from OpenZeppelin Contracts, altered to reduce bytecode size.\n// Modifier code is inlined by the compiler, which causes its code to appear multiple times in the codebase. By using\n// private functions, we achieve the same end result with slightly higher runtime gas costs, but reduced bytecode size.\n\npragma solidity ^0.7.0;\n\nimport \"@balancer-labs/v2-interfaces/contracts/solidity-utils/helpers/BalancerErrors.sol\";\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n // Booleans are more expensive than uint256 or any type that takes up a full\n // word because each write operation emits an extra SLOAD to first read the\n // slot's contents, replace the bits taken up by the boolean, and then write\n // back. This is the compiler's defense against contract upgrades and\n // pointer aliasing, and it cannot be disabled.\n\n // The values being non-zero value makes deployment a bit more expensive,\n // but in exchange the refund on every call to nonReentrant will be lower in\n // amount. Since refunds are capped to a percentage of the total\n // transaction's gas, it is best to keep them low in cases like this one, to\n // increase the likelihood of the full refund coming into effect.\n uint256 private constant _NOT_ENTERED = 1;\n uint256 private constant _ENTERED = 2;\n\n uint256 private _status;\n\n constructor() {\n _status = _NOT_ENTERED;\n }\n\n /**\n * @dev Prevents a contract from calling itself, directly or indirectly.\n * Calling a `nonReentrant` function from another `nonReentrant`\n * function is not supported. It is possible to prevent this from happening\n * by making the `nonReentrant` function external, and make it call a\n * `private` function that does the actual work.\n */\n modifier nonReentrant() {\n _enterNonReentrant();\n _;\n _exitNonReentrant();\n }\n\n function _enterNonReentrant() private {\n // On the first call to nonReentrant, _status will be _NOT_ENTERED\n _require(_status != _ENTERED, Errors.REENTRANCY);\n\n // Any calls to nonReentrant after this point will fail\n _status = _ENTERED;\n }\n\n function _exitNonReentrant() private {\n // By storing the original value once again, a refund is triggered (see\n // https://eips.ethereum.org/EIPS/eip-2200)\n _status = _NOT_ENTERED;\n }\n}\n" }, "contracts/authorizer/TimelockAuthorizer.sol": { "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see .\n\npragma solidity ^0.7.0;\npragma experimental ABIEncoderV2;\n\nimport \"@balancer-labs/v2-interfaces/contracts/solidity-utils/helpers/BalancerErrors.sol\";\nimport \"@balancer-labs/v2-interfaces/contracts/solidity-utils/helpers/IAuthentication.sol\";\nimport \"@balancer-labs/v2-interfaces/contracts/vault/IVault.sol\";\nimport \"@balancer-labs/v2-interfaces/contracts/vault/IAuthorizer.sol\";\n\nimport \"@balancer-labs/v2-solidity-utils/contracts/helpers/InputHelpers.sol\";\nimport \"@balancer-labs/v2-solidity-utils/contracts/math/Math.sol\";\nimport \"@balancer-labs/v2-solidity-utils/contracts/openzeppelin/Address.sol\";\nimport \"@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ReentrancyGuard.sol\";\nimport \"./TimelockExecutor.sol\";\n\n/**\n * @title Timelock Authorizer\n * @author Balancer Labs\n * @dev Authorizer with timelocks (delays).\n *\n * Users are allowed to perform actions if they have the permission to do so.\n *\n * This Authorizer implementation allows defining a delay per action identifier. If a delay is set for an action, users\n * are instead allowed to schedule an execution that will be run in the future by the Authorizer instead of executing it\n * directly themselves.\n *\n * Glossary:\n * - Action: Operation that can be performed to a target contract. These are identified by a unique bytes32 `actionId`\n * defined by each target contract following `IAuthentication.getActionId`.\n * - Scheduled execution: The Authorizer can define different delays per `actionId` in order to determine that a\n * specific time window must pass before these can be executed. When a delay is set for an `actionId`, executions\n * must be scheduled. These executions are identified with an unsigned integer called `scheduledExecutionId`.\n * - Permission: Unique identifier to refer to a user (who) that is allowed to perform an action (what) in a specific\n * target contract (where). This identifier is called `permissionId` and is computed as\n * `keccak256(actionId, account, where)`.\n *\n * Permission granularity:\n * In addition to the who/what/where of a permission, an extra notion of a \"specifier\" is introduced to enable more\n * granular configuration. This concept is used within the Authorizer to provide clarity among four ambiguous actions:\n * granting/revoking permissions, executing scheduled actions, and setting action delays. For example, in managing\n * the permission to set action delays, it is desirable to delineate whether an account can set delays for all\n * actions indiscriminately or only for a specific action ID. In this case, the permission's \"baseActionId\" is the\n * action ID for scheduling a delay change, and the \"specifier\" is the action ID for which the delay will be changed.\n * The \"baseActionId\" and \"specifier\" of a permission are combined into a single \"extended\" `actionId`\n * by calling `getExtendedActionId(baseActionId, specifier)`.\n *\n * Note that the TimelockAuthorizer doesn't make use of reentrancy guards on the majority of external functions.\n * The only function which makes an external non-view call (and so could initate a reentrancy attack) is `execute`\n * which executes a scheduled execution and so this is the only protected function.\n * In fact a number of the TimelockAuthorizer's functions may only be called through a scheduled execution so reentrancy\n * is necessary in order to be able to call these.\n */\ncontract TimelockAuthorizer is IAuthorizer, IAuthentication, ReentrancyGuard {\n using Address for address;\n\n /**\n * @notice An action specifier which grants a general permission to perform all variants of the base action.\n */\n bytes32\n public constant GENERAL_PERMISSION_SPECIFIER = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;\n // solhint-disable-previous-line max-line-length\n\n /**\n * @notice A sentinel value for `where` that will match any address.\n */\n address public constant EVERYWHERE = address(-1);\n\n // We institute a maximum delay to ensure that actions cannot be accidentally/maliciously disabled through setting\n // an arbitrarily long delay.\n uint256 public constant MAX_DELAY = 2 * (365 days);\n // We need a minimum delay period to ensure that scheduled actions may be properly scrutinised.\n uint256 public constant MIN_DELAY = 5 days;\n\n struct ScheduledExecution {\n address where;\n bytes data;\n bool executed;\n bool cancelled;\n bool protected;\n uint256 executableAt;\n }\n\n // solhint-disable var-name-mixedcase\n bytes32 public immutable GRANT_ACTION_ID;\n bytes32 public immutable REVOKE_ACTION_ID;\n bytes32 public immutable EXECUTE_ACTION_ID;\n bytes32 public immutable SCHEDULE_DELAY_ACTION_ID;\n\n // These action ids do not need to be used by external actors as the action ids above do.\n // Instead they're saved just for gas savings so we can keep them private.\n bytes32 private immutable _GENERAL_GRANT_ACTION_ID;\n bytes32 private immutable _GENERAL_REVOKE_ACTION_ID;\n\n TimelockExecutor private immutable _executor;\n IAuthentication private immutable _vault;\n uint256 private immutable _rootTransferDelay;\n\n address private _root;\n address private _pendingRoot;\n ScheduledExecution[] private _scheduledExecutions;\n mapping(bytes32 => bool) private _isPermissionGranted;\n mapping(bytes32 => uint256) private _delaysPerActionId;\n\n /**\n * @notice Emitted when a new execution `scheduledExecutionId` is scheduled.\n */\n event ExecutionScheduled(bytes32 indexed actionId, uint256 indexed scheduledExecutionId);\n\n /**\n * @notice Emitted when an execution `scheduledExecutionId` is executed.\n */\n event ExecutionExecuted(uint256 indexed scheduledExecutionId);\n\n /**\n * @notice Emitted when an execution `scheduledExecutionId` is cancelled.\n */\n event ExecutionCancelled(uint256 indexed scheduledExecutionId);\n\n /**\n * @notice Emitted when a new `delay` is set in order to perform action `actionId`.\n */\n event ActionDelaySet(bytes32 indexed actionId, uint256 delay);\n\n /**\n * @notice Emitted when `account` is granted permission to perform action `actionId` in target `where`.\n */\n event PermissionGranted(bytes32 indexed actionId, address indexed account, address indexed where);\n\n /**\n * @notice Emitted when `account`'s permission to perform action `actionId` in target `where` is revoked.\n */\n event PermissionRevoked(bytes32 indexed actionId, address indexed account, address indexed where);\n\n /**\n * @notice Emitted when a new `root` is set.\n */\n event RootSet(address indexed root);\n\n /**\n * @notice Emitted when a new `pendingRoot` is set. The new account must claim ownership for it to take effect.\n */\n event PendingRootSet(address indexed pendingRoot);\n\n modifier onlyExecutor() {\n _require(msg.sender == address(_executor), Errors.SENDER_NOT_ALLOWED);\n _;\n }\n\n constructor(\n address admin,\n IAuthentication vault,\n uint256 rootTransferDelay\n ) {\n _setRoot(admin);\n _vault = vault;\n _executor = new TimelockExecutor();\n _rootTransferDelay = rootTransferDelay;\n\n bytes32 grantActionId = getActionId(TimelockAuthorizer.grantPermissions.selector);\n bytes32 revokeActionId = getActionId(TimelockAuthorizer.revokePermissions.selector);\n bytes32 generalGrantActionId = getExtendedActionId(grantActionId, GENERAL_PERMISSION_SPECIFIER);\n bytes32 generalRevokeActionId = getExtendedActionId(revokeActionId, GENERAL_PERMISSION_SPECIFIER);\n\n // These don't technically need to be granted as `admin` will be the new root, and can grant these permissions\n // directly to themselves. By granting here improves ergonomics, especially in testing, as the admin is now\n // ready to grant any permission.\n _grantPermission(generalGrantActionId, admin, EVERYWHERE);\n _grantPermission(generalRevokeActionId, admin, EVERYWHERE);\n\n GRANT_ACTION_ID = grantActionId;\n REVOKE_ACTION_ID = revokeActionId;\n EXECUTE_ACTION_ID = getActionId(TimelockAuthorizer.execute.selector);\n SCHEDULE_DELAY_ACTION_ID = getActionId(TimelockAuthorizer.scheduleDelayChange.selector);\n _GENERAL_GRANT_ACTION_ID = generalGrantActionId;\n _GENERAL_REVOKE_ACTION_ID = generalRevokeActionId;\n }\n\n /**\n * @notice Returns true if `account` is the root.\n */\n function isRoot(address account) public view returns (bool) {\n return account == _root;\n }\n\n /**\n * @notice Returns true if `account` is the pending root.\n */\n function isPendingRoot(address account) public view returns (bool) {\n return account == _pendingRoot;\n }\n\n /**\n * @notice Returns the delay required to transfer the root address.\n */\n function getRootTransferDelay() public view returns (uint256) {\n return _rootTransferDelay;\n }\n\n /**\n * @notice Returns the vault address.\n */\n function getVault() external view returns (address) {\n return address(_vault);\n }\n\n /**\n * @notice Returns the executor address.\n */\n function getExecutor() external view returns (address) {\n return address(_executor);\n }\n\n /**\n * @notice Returns the root address.\n */\n function getRoot() external view returns (address) {\n return _root;\n }\n\n /**\n * @notice Returns the currently pending new root address.\n */\n function getPendingRoot() external view returns (address) {\n return _pendingRoot;\n }\n\n /**\n * @notice Returns the action ID for function selector `selector`.\n */\n function getActionId(bytes4 selector) public view override returns (bytes32) {\n return keccak256(abi.encodePacked(bytes32(uint256(address(this))), selector));\n }\n\n /**\n * @notice Returns the action ID for granting a permission for action `actionId`.\n */\n function getGrantPermissionActionId(bytes32 actionId) public view returns (bytes32) {\n return getExtendedActionId(GRANT_ACTION_ID, actionId);\n }\n\n /**\n * @notice Returns the action ID for revoking a permission for action `actionId`.\n */\n function getRevokePermissionActionId(bytes32 actionId) public view returns (bytes32) {\n return getExtendedActionId(REVOKE_ACTION_ID, actionId);\n }\n\n /**\n * @notice Returns the action ID for executing the scheduled action with execution ID `executionId`.\n */\n function getExecuteExecutionActionId(uint256 executionId) public view returns (bytes32) {\n return getExtendedActionId(EXECUTE_ACTION_ID, bytes32(executionId));\n }\n\n /**\n * @notice Returns the action ID for scheduling setting a new delay for action `actionId`.\n */\n function getScheduleDelayActionId(bytes32 actionId) public view returns (bytes32) {\n return getExtendedActionId(SCHEDULE_DELAY_ACTION_ID, actionId);\n }\n\n /**\n * @notice Returns the extended action ID for base action ID `baseActionId` with specific params `specifier`.\n */\n function getExtendedActionId(bytes32 baseActionId, bytes32 specifier) public pure returns (bytes32) {\n return keccak256(abi.encodePacked(baseActionId, specifier));\n }\n\n /**\n * @notice Returns the execution delay for action `actionId`.\n */\n function getActionIdDelay(bytes32 actionId) external view returns (uint256) {\n return _delaysPerActionId[actionId];\n }\n\n /**\n * @notice Returns the permission ID for action `actionId`, account `account` and target `where`.\n */\n function getPermissionId(\n bytes32 actionId,\n address account,\n address where\n ) public pure returns (bytes32) {\n return keccak256(abi.encodePacked(actionId, account, where));\n }\n\n /**\n * @notice Returns true if `account` has the permission defined by action `actionId` and target `where`.\n * @dev This function is specific for the strict permission defined by the tuple `(actionId, where)`: `account` may\n * instead hold the global permission for the action `actionId`, also granting them permission on `where`, but this\n * function would return false regardless.\n *\n * For this reason, it's recommended to use `hasPermission` if checking whether `account` is allowed to perform\n * a given action.\n */\n function isPermissionGrantedOnTarget(\n bytes32 actionId,\n address account,\n address where\n ) external view returns (bool) {\n return _isPermissionGranted[getPermissionId(actionId, account, where)];\n }\n\n /**\n * @notice Returns true if `account` has permission over the action `actionId` in target `where`.\n */\n function hasPermission(\n bytes32 actionId,\n address account,\n address where\n ) public view returns (bool) {\n return\n _isPermissionGranted[getPermissionId(actionId, account, where)] ||\n _isPermissionGranted[getPermissionId(actionId, account, EVERYWHERE)];\n }\n\n /**\n * @notice Returns true if `account` is allowed to grant permissions for action `actionId` in target `where`.\n */\n function isGranter(\n bytes32 actionId,\n address account,\n address where\n ) public view returns (bool) {\n return _hasPermissionSpecificallyOrGenerally(GRANT_ACTION_ID, account, where, actionId);\n }\n\n /**\n * @notice Returns true if `account` is allowed to revoke permissions for action `actionId` in target `where`.\n */\n function isRevoker(\n bytes32 actionId,\n address account,\n address where\n ) public view returns (bool) {\n return _hasPermissionSpecificallyOrGenerally(REVOKE_ACTION_ID, account, where, actionId);\n }\n\n /**\n * @notice Returns true if `account` can perform action `actionId` in target `where`.\n */\n function canPerform(\n bytes32 actionId,\n address account,\n address where\n ) public view override returns (bool) {\n return\n _delaysPerActionId[actionId] > 0 ? account == address(_executor) : hasPermission(actionId, account, where);\n }\n\n /**\n * @notice Returns true if `account` can grant permissions for action `actionId` in target `where`.\n */\n function canGrant(\n bytes32 actionId,\n address account,\n address where\n ) public view returns (bool) {\n return _canPerformSpecificallyOrGenerally(GRANT_ACTION_ID, account, where, actionId);\n }\n\n /**\n * @notice Returns true if `account` can revoke permissions for action `actionId` in target `where`.\n */\n function canRevoke(\n bytes32 actionId,\n address account,\n address where\n ) public view returns (bool) {\n return _canPerformSpecificallyOrGenerally(REVOKE_ACTION_ID, account, where, actionId);\n }\n\n /**\n * @notice Returns the scheduled execution `scheduledExecutionId`.\n */\n function getScheduledExecution(uint256 scheduledExecutionId) external view returns (ScheduledExecution memory) {\n return _scheduledExecutions[scheduledExecutionId];\n }\n\n /**\n * @notice Returns true if execution `scheduledExecutionId` can be executed.\n * Only true if it is not already executed or cancelled, and if the execution delay has passed.\n */\n function canExecute(uint256 scheduledExecutionId) external view returns (bool) {\n require(scheduledExecutionId < _scheduledExecutions.length, \"ACTION_DOES_NOT_EXIST\");\n ScheduledExecution storage scheduledExecution = _scheduledExecutions[scheduledExecutionId];\n return\n !scheduledExecution.executed &&\n !scheduledExecution.cancelled &&\n block.timestamp >= scheduledExecution.executableAt;\n // solhint-disable-previous-line not-rely-on-time\n }\n\n /**\n * @notice Schedules an execution to change the root address to `newRoot`.\n */\n function scheduleRootChange(address newRoot, address[] memory executors)\n external\n returns (uint256 scheduledExecutionId)\n {\n _require(isRoot(msg.sender), Errors.SENDER_NOT_ALLOWED);\n bytes32 actionId = getActionId(this.setPendingRoot.selector);\n bytes memory data = abi.encodeWithSelector(this.setPendingRoot.selector, newRoot);\n return _scheduleWithDelay(actionId, address(this), data, getRootTransferDelay(), executors);\n }\n\n /**\n * @notice Sets the pending root address to `pendingRoot`.\n * @dev This function can never be called directly - it is only ever called as part of a scheduled execution by\n * the TimelockExecutor after after calling `scheduleRootChange`.\n *\n * Once set as the pending root, `pendingRoot` may then call `claimRoot` to become the new root.\n */\n function setPendingRoot(address pendingRoot) external onlyExecutor {\n _setPendingRoot(pendingRoot);\n }\n\n /**\n * @notice Transfers root powers from the current to the pending root address.\n * @dev This function prevents accidentally transferring root to an invalid address.\n * To become root, the pending root must call this function to ensure that it's able to interact with this contract.\n */\n function claimRoot() external {\n address currentRoot = _root;\n address pendingRoot = _pendingRoot;\n _require(msg.sender == pendingRoot, Errors.SENDER_NOT_ALLOWED);\n\n // Grant powers to new root to grant or revoke any permission over any contract.\n _grantPermission(_GENERAL_GRANT_ACTION_ID, pendingRoot, EVERYWHERE);\n _grantPermission(_GENERAL_REVOKE_ACTION_ID, pendingRoot, EVERYWHERE);\n\n // Revoke these powers from the outgoing root.\n _revokePermission(_GENERAL_GRANT_ACTION_ID, currentRoot, EVERYWHERE);\n _revokePermission(_GENERAL_REVOKE_ACTION_ID, currentRoot, EVERYWHERE);\n\n // Complete the root transfer and reset the pending root.\n _setRoot(pendingRoot);\n _setPendingRoot(address(0));\n }\n\n /**\n * @notice Sets a new delay `delay` for action `actionId`.\n * @dev This function can never be called directly - it is only ever called as part of a scheduled execution by\n * the TimelockExecutor after after calling `scheduleDelayChange`.\n */\n function setDelay(bytes32 actionId, uint256 delay) external onlyExecutor {\n bytes32 setAuthorizerActionId = _vault.getActionId(IVault.setAuthorizer.selector);\n bool isAllowed = actionId == setAuthorizerActionId || delay <= _delaysPerActionId[setAuthorizerActionId];\n require(isAllowed, \"DELAY_EXCEEDS_SET_AUTHORIZER\");\n\n _delaysPerActionId[actionId] = delay;\n emit ActionDelaySet(actionId, delay);\n }\n\n /**\n * @notice Schedules an execution to set action `actionId`'s delay to `newDelay`.\n */\n function scheduleDelayChange(\n bytes32 actionId,\n uint256 newDelay,\n address[] memory executors\n ) external returns (uint256 scheduledExecutionId) {\n require(newDelay <= MAX_DELAY, \"DELAY_TOO_LARGE\");\n _require(isRoot(msg.sender), Errors.SENDER_NOT_ALLOWED);\n\n // The delay change is scheduled so that it's never possible to execute an action in a shorter time than the\n // current delay.\n //\n // If we're reducing the action's delay then we must first wait for the difference between the two delays.\n // This means that if we immediately schedule the action for execution once the delay is reduced, then\n // these two delays combined will result in the original delay.\n //\n // If we're increasing the delay on an action, we could execute this change immediately as it's impossible to\n // perform an action sooner by increasing its delay. Requiring a potentially long delay before increasing the\n // delay just adds unnecessary friction to increasing security for sensitive actions.\n //\n // We also enforce a minimum delay period to allow proper scrutiny of the change of the action's delay.\n\n uint256 actionDelay = _delaysPerActionId[actionId];\n uint256 executionDelay = newDelay < actionDelay ? Math.max(actionDelay - newDelay, MIN_DELAY) : MIN_DELAY;\n\n bytes32 scheduleDelayActionId = getScheduleDelayActionId(actionId);\n bytes memory data = abi.encodeWithSelector(this.setDelay.selector, actionId, newDelay);\n return _scheduleWithDelay(scheduleDelayActionId, address(this), data, executionDelay, executors);\n }\n\n /**\n * @notice Schedules an arbitrary execution of `data` in target `where`.\n */\n function schedule(\n address where,\n bytes memory data,\n address[] memory executors\n ) external returns (uint256 scheduledExecutionId) {\n // Allowing scheduling arbitrary calls into the TimelockAuthorizer is dangerous.\n //\n // It is expected that only the `root` account can initiate a root transfer as this condition is enforced\n // by the `scheduleRootChange` function which is the expected method of scheduling a call to `setPendingRoot`.\n // If a call to `setPendingRoot` could be scheduled using this function as well as `scheduleRootChange` then\n // accounts other than `root` could initiate a root transfer (provided they had the necessary permission).\n // Similarly, `setDelay` can only be called if scheduled via `scheduleDelayChange`.\n //\n // For this reason we disallow this function from scheduling calls to functions on the Authorizer to ensure that\n // these actions can only be scheduled through specialised functions.\n require(where != address(this), \"CANNOT_SCHEDULE_AUTHORIZER_ACTIONS\");\n\n // We also disallow the TimelockExecutor from attempting to call into itself. Otherwise the above protection\n // could be bypassed by wrapping a call to `setPendingRoot` inside of a call causing the TimelockExecutor to\n // reenter itself, essentially hiding the fact that `where == address(this)` inside `data`.\n //\n // Note: The TimelockExecutor only accepts calls from the TimelockAuthorizer (i.e. not from itself) so this\n // scenario should be impossible but this check is cheap so we enforce it here as well anyway.\n require(where != address(_executor), \"ATTEMPTING_EXECUTOR_REENTRANCY\");\n\n bytes32 actionId = IAuthentication(where).getActionId(_decodeSelector(data));\n _require(hasPermission(actionId, msg.sender, where), Errors.SENDER_NOT_ALLOWED);\n return _schedule(actionId, where, data, executors);\n }\n\n /**\n * @notice Executes a scheduled action `scheduledExecutionId`.\n */\n function execute(uint256 scheduledExecutionId) external nonReentrant returns (bytes memory result) {\n require(scheduledExecutionId < _scheduledExecutions.length, \"ACTION_DOES_NOT_EXIST\");\n ScheduledExecution storage scheduledExecution = _scheduledExecutions[scheduledExecutionId];\n require(!scheduledExecution.executed, \"ACTION_ALREADY_EXECUTED\");\n require(!scheduledExecution.cancelled, \"ACTION_ALREADY_CANCELLED\");\n\n // solhint-disable-next-line not-rely-on-time\n require(block.timestamp >= scheduledExecution.executableAt, \"ACTION_NOT_EXECUTABLE\");\n if (scheduledExecution.protected) {\n bytes32 executeScheduledActionId = getExecuteExecutionActionId(scheduledExecutionId);\n bool isAllowed = hasPermission(executeScheduledActionId, msg.sender, address(this));\n _require(isAllowed, Errors.SENDER_NOT_ALLOWED);\n }\n\n scheduledExecution.executed = true;\n // Note that this is the only place in the entire contract we perform a non-view call to an external contract.\n result = _executor.execute(scheduledExecution.where, scheduledExecution.data);\n emit ExecutionExecuted(scheduledExecutionId);\n }\n\n /**\n * @notice Cancels a scheduled action `scheduledExecutionId`.\n * @dev The permission to cancel a scheduled action is the same one used to schedule it.\n *\n * Note that in the case of cancelling a malicious granting or revocation of permissions to an address,\n * we must assume that the granter/revoker status of all non-malicious addresses will be revoked as calls to\n * manageGranter/manageRevoker have no delays associated with them.\n */\n function cancel(uint256 scheduledExecutionId) external {\n require(scheduledExecutionId < _scheduledExecutions.length, \"ACTION_DOES_NOT_EXIST\");\n ScheduledExecution storage scheduledExecution = _scheduledExecutions[scheduledExecutionId];\n\n require(!scheduledExecution.executed, \"ACTION_ALREADY_EXECUTED\");\n require(!scheduledExecution.cancelled, \"ACTION_ALREADY_CANCELLED\");\n\n // The permission to cancel a scheduled action is the same one used to schedule it.\n // The root address may cancel any action even without this permission.\n IAuthentication target = IAuthentication(scheduledExecution.where);\n bytes32 actionId = target.getActionId(_decodeSelector(scheduledExecution.data));\n _require(\n hasPermission(actionId, msg.sender, scheduledExecution.where) || isRoot(msg.sender),\n Errors.SENDER_NOT_ALLOWED\n );\n\n scheduledExecution.cancelled = true;\n emit ExecutionCancelled(scheduledExecutionId);\n }\n\n /**\n * @notice Sets `account`'s granter status to `allowed` for action `actionId` in target `where`.\n * @dev Note that granters can revoke the granter status of other granters, even removing the root.\n * However the root can always rejoin, and then remove any malicious granters.\n *\n * Note that there are no delays associated with adding or removing granters. This is based on the assumption that\n * any action which a malicous user could exploit to damage the protocol will have a sufficiently long delay\n * associated with either granting permission for or exercising that permission such that the root will be able to\n * reestablish control and cancel the action before it can be executed.\n */\n function manageGranter(\n bytes32 actionId,\n address account,\n address where,\n bool allowed\n ) external {\n // Root may grant or revoke granter status from any address.\n // Granters may only revoke a granter status from any address.\n bool isAllowed = isRoot(msg.sender) || (!allowed && isGranter(actionId, msg.sender, where));\n _require(isAllowed, Errors.SENDER_NOT_ALLOWED);\n\n bytes32 grantPermissionsActionId = getGrantPermissionActionId(actionId);\n (allowed ? _grantPermission : _revokePermission)(grantPermissionsActionId, account, where);\n }\n\n /**\n * @notice Grants multiple permissions to a single `account`.\n * @dev This function can only be used for actions that have no grant delay. For those that do, use\n * `scheduleGrantPermission` instead.\n */\n function grantPermissions(\n bytes32[] memory actionIds,\n address account,\n address[] memory where\n ) external {\n InputHelpers.ensureInputLengthMatch(actionIds.length, where.length);\n for (uint256 i = 0; i < actionIds.length; i++) {\n // For permissions that have a delay when granting, `canGrant` will return false. `scheduleGrantPermission`\n // will succeed as it checks `isGranter` instead.\n // Note that `canGrant` will return true for the executor if the permission has a delay.\n _require(canGrant(actionIds[i], msg.sender, where[i]), Errors.SENDER_NOT_ALLOWED);\n _grantPermission(actionIds[i], account, where[i]);\n }\n }\n\n /**\n * @notice Schedules a grant permission to `account` for action `actionId` in target `where`.\n */\n function scheduleGrantPermission(\n bytes32 actionId,\n address account,\n address where,\n address[] memory executors\n ) external returns (uint256 scheduledExecutionId) {\n _require(isGranter(actionId, msg.sender, where), Errors.SENDER_NOT_ALLOWED);\n bytes memory data = abi.encodeWithSelector(this.grantPermissions.selector, _ar(actionId), account, _ar(where));\n bytes32 grantPermissionId = getGrantPermissionActionId(actionId);\n return _schedule(grantPermissionId, address(this), data, executors);\n }\n\n /**\n * @notice Sets `account`'s revoker status to `allowed` for action `actionId` in target `where`.\n * @dev Note that revokers can revoke the revoker status of other revokers, even banning the root.\n * However the root can always rejoin, and then remove any malicious revokers.\n *\n * Note that there are no delays associated with adding or removing revokers. This is based on the assumption that\n * any permissions for which revocation from key addresses would be dangerous (e.g. preventing the BalancerMinter\n * from minting BAL) have sufficiently long delays associated with revoking them that the root will be able to\n * reestablish control and cancel the revocation before the scheduled revocation can be executed.\n */\n function manageRevoker(\n bytes32 actionId,\n address account,\n address where,\n bool allowed\n ) external {\n // Root may grant or revoke revoker status from any address.\n // Revokers may only revoke a revoker status from any address.\n bool isAllowed = isRoot(msg.sender) || (!allowed && isRevoker(actionId, msg.sender, where));\n _require(isAllowed, Errors.SENDER_NOT_ALLOWED);\n\n bytes32 revokePermissionsActionId = getRevokePermissionActionId(actionId);\n (allowed ? _grantPermission : _revokePermission)(revokePermissionsActionId, account, where);\n }\n\n /**\n * @notice Revokes multiple permissions from a single `account`.\n * @dev This function can only be used for actions that have no revoke delay. For those that do, use\n * `scheduleRevokePermission` instead.\n */\n function revokePermissions(\n bytes32[] memory actionIds,\n address account,\n address[] memory where\n ) external {\n InputHelpers.ensureInputLengthMatch(actionIds.length, where.length);\n for (uint256 i = 0; i < actionIds.length; i++) {\n // For permissions that have a delay when granting, `canRevoke` will return false.\n // `scheduleRevokePermission` will succeed as it checks `isRevoker` instead.\n // Note that `canRevoke` will return true for the executor if the permission has a delay.\n _require(canRevoke(actionIds[i], msg.sender, where[i]), Errors.SENDER_NOT_ALLOWED);\n _revokePermission(actionIds[i], account, where[i]);\n }\n }\n\n /**\n * @notice Schedules a revoke permission from `account` for action `actionId` in target `where`.\n */\n function scheduleRevokePermission(\n bytes32 actionId,\n address account,\n address where,\n address[] memory executors\n ) external returns (uint256 scheduledExecutionId) {\n _require(isRevoker(actionId, msg.sender, where), Errors.SENDER_NOT_ALLOWED);\n bytes memory data = abi.encodeWithSelector(this.revokePermissions.selector, _ar(actionId), account, _ar(where));\n bytes32 revokePermissionId = getRevokePermissionActionId(actionId);\n return _schedule(revokePermissionId, address(this), data, executors);\n }\n\n /**\n * @notice Revokes multiple permissions from the caller.\n * @dev Note that the caller can always renounce permissions, even if revoking them would typically be\n * subject to a delay.\n */\n function renouncePermissions(bytes32[] memory actionIds, address[] memory where) external {\n InputHelpers.ensureInputLengthMatch(actionIds.length, where.length);\n for (uint256 i = 0; i < actionIds.length; i++) {\n _revokePermission(actionIds[i], msg.sender, where[i]);\n }\n }\n\n function _grantPermission(\n bytes32 actionId,\n address account,\n address where\n ) private {\n bytes32 permission = getPermissionId(actionId, account, where);\n if (!_isPermissionGranted[permission]) {\n _isPermissionGranted[permission] = true;\n emit PermissionGranted(actionId, account, where);\n }\n }\n\n function _revokePermission(\n bytes32 actionId,\n address account,\n address where\n ) private {\n bytes32 permission = getPermissionId(actionId, account, where);\n if (_isPermissionGranted[permission]) {\n _isPermissionGranted[permission] = false;\n emit PermissionRevoked(actionId, account, where);\n }\n }\n\n function _schedule(\n bytes32 actionId,\n address where,\n bytes memory data,\n address[] memory executors\n ) private returns (uint256 scheduledExecutionId) {\n uint256 delay = _delaysPerActionId[actionId];\n require(delay > 0, \"CANNOT_SCHEDULE_ACTION\");\n return _scheduleWithDelay(actionId, where, data, delay, executors);\n }\n\n function _scheduleWithDelay(\n bytes32 actionId,\n address where,\n bytes memory data,\n uint256 delay,\n address[] memory executors\n ) private returns (uint256 scheduledExecutionId) {\n scheduledExecutionId = _scheduledExecutions.length;\n emit ExecutionScheduled(actionId, scheduledExecutionId);\n\n // solhint-disable-next-line not-rely-on-time\n uint256 executableAt = block.timestamp + delay;\n bool protected = executors.length > 0;\n\n _scheduledExecutions.push(\n ScheduledExecution({\n where: where,\n data: data,\n executed: false,\n cancelled: false,\n protected: protected,\n executableAt: executableAt\n })\n );\n\n bytes32 executeActionId = getExecuteExecutionActionId(scheduledExecutionId);\n for (uint256 i = 0; i < executors.length; i++) {\n _grantPermission(executeActionId, executors[i], address(this));\n }\n }\n\n /**\n * @notice Returns if `account` has permission to perform the action `(baseActionId, specifier)` on target `where`.\n * @dev This function differs from `_canPerformSpecificallyOrGenerally` as it *doesn't* take into account whether\n * there is a delay for the action associated with the permission being checked.\n *\n * The address `account` may have the permission associated with the provided action but that doesn't necessarily\n * mean that it may perform that action. If there is no delay associated with this action, `account` may perform the\n * action directly. If there is a delay, then `account` is instead able to schedule that action to be performed\n * at a later date.\n *\n * This function returns true in both cases.\n */\n function _hasPermissionSpecificallyOrGenerally(\n bytes32 baseActionId,\n address account,\n address where,\n bytes32 specifier\n ) internal view returns (bool) {\n bytes32 specificActionId = getExtendedActionId(baseActionId, specifier);\n bytes32 generalActionId = getExtendedActionId(baseActionId, GENERAL_PERMISSION_SPECIFIER);\n return hasPermission(specificActionId, account, where) || hasPermission(generalActionId, account, where);\n }\n\n /**\n * @notice Returns if `account` can perform the action `(baseActionId, specifier)` on target `where`.\n * @dev This function differs from `_hasPermissionSpecificallyOrGenerally` as it *does* take into account whether\n * there is a delay for the action associated with the permission being checked.\n *\n * The address `account` may have the permission associated with the provided action but that doesn't necessarily\n * mean that it may perform that action. If there is no delay associated with this action, `account` may perform the\n * action directly. If there is a delay, then `account` is instead able to schedule that action to be performed\n * at a later date.\n *\n * This function only returns true only in the first case (except for actions performed by the authorizer timelock).\n */\n function _canPerformSpecificallyOrGenerally(\n bytes32 baseActionId,\n address account,\n address where,\n bytes32 specifier\n ) internal view returns (bool) {\n // If there is a delay defined for the specific action ID, then the sender must be the authorizer (scheduled\n // execution)\n bytes32 specificActionId = getExtendedActionId(baseActionId, specifier);\n if (_delaysPerActionId[specificActionId] > 0) {\n return account == address(_executor);\n }\n\n // If there is no delay, we check if the account has that permission\n if (hasPermission(specificActionId, account, where)) {\n return true;\n }\n\n // If the account doesn't have the explicit permission, we repeat for the general permission\n bytes32 generalActionId = getExtendedActionId(baseActionId, GENERAL_PERMISSION_SPECIFIER);\n return canPerform(generalActionId, account, where);\n }\n\n /**\n * @dev Sets the root address to `root`.\n */\n function _setRoot(address root) internal {\n _root = root;\n emit RootSet(root);\n }\n\n /**\n * @dev Sets the pending root address to `pendingRoot`.\n */\n function _setPendingRoot(address pendingRoot) internal {\n _pendingRoot = pendingRoot;\n emit PendingRootSet(pendingRoot);\n }\n\n function _decodeSelector(bytes memory data) internal pure returns (bytes4) {\n // The bytes4 type is left-aligned and padded with zeros: we make use of that property to build the selector\n if (data.length < 4) return bytes4(0);\n return bytes4(data[0]) | (bytes4(data[1]) >> 8) | (bytes4(data[2]) >> 16) | (bytes4(data[3]) >> 24);\n }\n\n function _ar(bytes32 item) private pure returns (bytes32[] memory result) {\n result = new bytes32[](1);\n result[0] = item;\n }\n\n function _ar(address item) private pure returns (address[] memory result) {\n result = new address[](1);\n result[0] = item;\n }\n}\n" }, "contracts/authorizer/TimelockExecutor.sol": { "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see .\n\npragma solidity ^0.7.0;\n\nimport \"@balancer-labs/v2-solidity-utils/contracts/openzeppelin/Address.sol\";\nimport \"@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ReentrancyGuard.sol\";\n\nimport \"./TimelockAuthorizer.sol\";\n\ncontract TimelockExecutor is ReentrancyGuard {\n TimelockAuthorizer public immutable authorizer;\n\n constructor() {\n authorizer = TimelockAuthorizer(msg.sender);\n }\n\n function execute(address target, bytes memory data) external nonReentrant returns (bytes memory result) {\n require(msg.sender == address(authorizer), \"ERR_SENDER_NOT_AUTHORIZER\");\n return Address.functionCall(target, data);\n }\n}\n" } }, "settings": { "optimizer": { "enabled": true, "runs": 9999 }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "libraries": {} } }