{ "language": "Solidity", "sources": { "lib/solmate/src/auth/Owned.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Simple single owner authorization mixin.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Owned.sol)\nabstract contract Owned {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event OwnershipTransferred(address indexed user, address indexed newOwner);\n\n /*//////////////////////////////////////////////////////////////\n OWNERSHIP STORAGE\n //////////////////////////////////////////////////////////////*/\n\n address public owner;\n\n modifier onlyOwner() virtual {\n require(msg.sender == owner, \"UNAUTHORIZED\");\n\n _;\n }\n\n /*//////////////////////////////////////////////////////////////\n CONSTRUCTOR\n //////////////////////////////////////////////////////////////*/\n\n constructor(address _owner) {\n owner = _owner;\n\n emit OwnershipTransferred(address(0), _owner);\n }\n\n /*//////////////////////////////////////////////////////////////\n OWNERSHIP LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function transferOwnership(address newOwner) public virtual onlyOwner {\n owner = newOwner;\n\n emit OwnershipTransferred(msg.sender, newOwner);\n }\n}\n" }, "lib/solmate/src/tokens/ERC20.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)\n/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)\n/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.\nabstract contract ERC20 {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event Transfer(address indexed from, address indexed to, uint256 amount);\n\n event Approval(address indexed owner, address indexed spender, uint256 amount);\n\n /*//////////////////////////////////////////////////////////////\n METADATA STORAGE\n //////////////////////////////////////////////////////////////*/\n\n string public name;\n\n string public symbol;\n\n uint8 public immutable decimals;\n\n /*//////////////////////////////////////////////////////////////\n ERC20 STORAGE\n //////////////////////////////////////////////////////////////*/\n\n uint256 public totalSupply;\n\n mapping(address => uint256) public balanceOf;\n\n mapping(address => mapping(address => uint256)) public allowance;\n\n /*//////////////////////////////////////////////////////////////\n EIP-2612 STORAGE\n //////////////////////////////////////////////////////////////*/\n\n uint256 internal immutable INITIAL_CHAIN_ID;\n\n bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;\n\n mapping(address => uint256) public nonces;\n\n /*//////////////////////////////////////////////////////////////\n CONSTRUCTOR\n //////////////////////////////////////////////////////////////*/\n\n constructor(\n string memory _name,\n string memory _symbol,\n uint8 _decimals\n ) {\n name = _name;\n symbol = _symbol;\n decimals = _decimals;\n\n INITIAL_CHAIN_ID = block.chainid;\n INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();\n }\n\n /*//////////////////////////////////////////////////////////////\n ERC20 LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function approve(address spender, uint256 amount) public virtual returns (bool) {\n allowance[msg.sender][spender] = amount;\n\n emit Approval(msg.sender, spender, amount);\n\n return true;\n }\n\n function transfer(address to, uint256 amount) public virtual returns (bool) {\n balanceOf[msg.sender] -= amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(msg.sender, to, amount);\n\n return true;\n }\n\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual returns (bool) {\n uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;\n\n balanceOf[from] -= amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(from, to, amount);\n\n return true;\n }\n\n /*//////////////////////////////////////////////////////////////\n EIP-2612 LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) public virtual {\n require(deadline >= block.timestamp, \"PERMIT_DEADLINE_EXPIRED\");\n\n // Unchecked because the only math done is incrementing\n // the owner's nonce which cannot realistically overflow.\n unchecked {\n address recoveredAddress = ecrecover(\n keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR(),\n keccak256(\n abi.encode(\n keccak256(\n \"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\"\n ),\n owner,\n spender,\n value,\n nonces[owner]++,\n deadline\n )\n )\n )\n ),\n v,\n r,\n s\n );\n\n require(recoveredAddress != address(0) && recoveredAddress == owner, \"INVALID_SIGNER\");\n\n allowance[recoveredAddress][spender] = value;\n }\n\n emit Approval(owner, spender, value);\n }\n\n function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {\n return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();\n }\n\n function computeDomainSeparator() internal view virtual returns (bytes32) {\n return\n keccak256(\n abi.encode(\n keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"),\n keccak256(bytes(name)),\n keccak256(\"1\"),\n block.chainid,\n address(this)\n )\n );\n }\n\n /*//////////////////////////////////////////////////////////////\n INTERNAL MINT/BURN LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function _mint(address to, uint256 amount) internal virtual {\n totalSupply += amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(address(0), to, amount);\n }\n\n function _burn(address from, uint256 amount) internal virtual {\n balanceOf[from] -= amount;\n\n // Cannot underflow because a user's balance\n // will never be larger than the total supply.\n unchecked {\n totalSupply -= amount;\n }\n\n emit Transfer(from, address(0), amount);\n }\n}\n" }, "lib/solmate/src/utils/Bytes32AddressLib.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Library for converting between addresses and bytes32 values.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/Bytes32AddressLib.sol)\nlibrary Bytes32AddressLib {\n function fromLast20Bytes(bytes32 bytesValue) internal pure returns (address) {\n return address(uint160(uint256(bytesValue)));\n }\n\n function fillLast12Bytes(address addressValue) internal pure returns (bytes32) {\n return bytes32(bytes20(addressValue));\n }\n}\n" }, "lib/solmate/src/utils/FixedPointMathLib.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Arithmetic library with operations for fixed-point numbers.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)\n/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)\nlibrary FixedPointMathLib {\n /*//////////////////////////////////////////////////////////////\n SIMPLIFIED FIXED POINT OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n uint256 internal constant MAX_UINT256 = 2**256 - 1;\n\n uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.\n\n function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.\n }\n\n function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.\n }\n\n function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.\n }\n\n function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.\n }\n\n /*//////////////////////////////////////////////////////////////\n LOW LEVEL FIXED POINT OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n function mulDivDown(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\n revert(0, 0)\n }\n\n // Divide x * y by the denominator.\n z := div(mul(x, y), denominator)\n }\n }\n\n function mulDivUp(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\n revert(0, 0)\n }\n\n // If x * y modulo the denominator is strictly greater than 0,\n // 1 is added to round up the division of x * y by the denominator.\n z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))\n }\n }\n\n function rpow(\n uint256 x,\n uint256 n,\n uint256 scalar\n ) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n switch x\n case 0 {\n switch n\n case 0 {\n // 0 ** 0 = 1\n z := scalar\n }\n default {\n // 0 ** n = 0\n z := 0\n }\n }\n default {\n switch mod(n, 2)\n case 0 {\n // If n is even, store scalar in z for now.\n z := scalar\n }\n default {\n // If n is odd, store x in z for now.\n z := x\n }\n\n // Shifting right by 1 is like dividing by 2.\n let half := shr(1, scalar)\n\n for {\n // Shift n right by 1 before looping to halve it.\n n := shr(1, n)\n } n {\n // Shift n right by 1 each iteration to halve it.\n n := shr(1, n)\n } {\n // Revert immediately if x ** 2 would overflow.\n // Equivalent to iszero(eq(div(xx, x), x)) here.\n if shr(128, x) {\n revert(0, 0)\n }\n\n // Store x squared.\n let xx := mul(x, x)\n\n // Round to the nearest number.\n let xxRound := add(xx, half)\n\n // Revert if xx + half overflowed.\n if lt(xxRound, xx) {\n revert(0, 0)\n }\n\n // Set x to scaled xxRound.\n x := div(xxRound, scalar)\n\n // If n is even:\n if mod(n, 2) {\n // Compute z * x.\n let zx := mul(z, x)\n\n // If z * x overflowed:\n if iszero(eq(div(zx, x), z)) {\n // Revert if x is non-zero.\n if iszero(iszero(x)) {\n revert(0, 0)\n }\n }\n\n // Round to the nearest number.\n let zxRound := add(zx, half)\n\n // Revert if zx + half overflowed.\n if lt(zxRound, zx) {\n revert(0, 0)\n }\n\n // Return properly scaled zxRound.\n z := div(zxRound, scalar)\n }\n }\n }\n }\n }\n\n /*//////////////////////////////////////////////////////////////\n GENERAL NUMBER UTILITIES\n //////////////////////////////////////////////////////////////*/\n\n function sqrt(uint256 x) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n let y := x // We start y at x, which will help us make our initial estimate.\n\n z := 181 // The \"correct\" value is 1, but this saves a multiplication later.\n\n // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\n // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\n\n // We check y >= 2^(k + 8) but shift right by k bits\n // each branch to ensure that if x >= 256, then y >= 256.\n if iszero(lt(y, 0x10000000000000000000000000000000000)) {\n y := shr(128, y)\n z := shl(64, z)\n }\n if iszero(lt(y, 0x1000000000000000000)) {\n y := shr(64, y)\n z := shl(32, z)\n }\n if iszero(lt(y, 0x10000000000)) {\n y := shr(32, y)\n z := shl(16, z)\n }\n if iszero(lt(y, 0x1000000)) {\n y := shr(16, y)\n z := shl(8, z)\n }\n\n // Goal was to get z*z*y within a small factor of x. More iterations could\n // get y in a tighter range. Currently, we will have y in [256, 256*2^16).\n // We ensured y >= 256 so that the relative difference between y and y+1 is small.\n // That's not possible if x < 256 but we can just verify those cases exhaustively.\n\n // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.\n // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.\n // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.\n\n // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range\n // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.\n\n // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate\n // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.\n\n // There is no overflow risk here since y < 2^136 after the first branch above.\n z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.\n\n // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n\n // If x+1 is a perfect square, the Babylonian method cycles between\n // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.\n // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\n // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.\n // If you don't care whether the floor or ceil square root is returned, you can remove this statement.\n z := sub(z, lt(div(x, z), z))\n }\n }\n\n function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Mod x by y. Note this will return\n // 0 instead of reverting if y is zero.\n z := mod(x, y)\n }\n }\n\n function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {\n /// @solidity memory-safe-assembly\n assembly {\n // Divide x by y. Note this will return\n // 0 instead of reverting if y is zero.\n r := div(x, y)\n }\n }\n\n function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n /// @solidity memory-safe-assembly\n assembly {\n // Add 1 to x * y if x % y > 0. Note this will\n // return 0 instead of reverting if y is zero.\n z := add(gt(mod(x, y), 0), div(x, y))\n }\n }\n}\n" }, "lib/solmate/src/utils/ReentrancyGuard.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Gas optimized reentrancy protection for smart contracts.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/ReentrancyGuard.sol)\n/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol)\nabstract contract ReentrancyGuard {\n uint256 private locked = 1;\n\n modifier nonReentrant() virtual {\n require(locked == 1, \"REENTRANCY\");\n\n locked = 2;\n\n _;\n\n locked = 1;\n }\n}\n" }, "lib/solmate/src/utils/SafeTransferLib.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\nimport {ERC20} from \"../tokens/ERC20.sol\";\n\n/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)\n/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.\n/// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.\nlibrary SafeTransferLib {\n /*//////////////////////////////////////////////////////////////\n ETH OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n function safeTransferETH(address to, uint256 amount) internal {\n bool success;\n\n /// @solidity memory-safe-assembly\n assembly {\n // Transfer the ETH and store if it succeeded or not.\n success := call(gas(), to, amount, 0, 0, 0, 0)\n }\n\n require(success, \"ETH_TRANSFER_FAILED\");\n }\n\n /*//////////////////////////////////////////////////////////////\n ERC20 OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n function safeTransferFrom(\n ERC20 token,\n address from,\n address to,\n uint256 amount\n ) internal {\n bool success;\n\n /// @solidity memory-safe-assembly\n assembly {\n // Get a pointer to some free memory.\n let freeMemoryPointer := mload(0x40)\n\n // Write the abi-encoded calldata into memory, beginning with the function selector.\n mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)\n mstore(add(freeMemoryPointer, 4), from) // Append the \"from\" argument.\n mstore(add(freeMemoryPointer, 36), to) // Append the \"to\" argument.\n mstore(add(freeMemoryPointer, 68), amount) // Append the \"amount\" argument.\n\n success := and(\n // Set success to whether the call reverted, if not we check it either\n // returned exactly 1 (can't just be non-zero data), or had no return data.\n or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n // We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.\n // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n // Counterintuitively, this call must be positioned second to the or() call in the\n // surrounding and() call or else returndatasize() will be zero during the computation.\n call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)\n )\n }\n\n require(success, \"TRANSFER_FROM_FAILED\");\n }\n\n function safeTransfer(\n ERC20 token,\n address to,\n uint256 amount\n ) internal {\n bool success;\n\n /// @solidity memory-safe-assembly\n assembly {\n // Get a pointer to some free memory.\n let freeMemoryPointer := mload(0x40)\n\n // Write the abi-encoded calldata into memory, beginning with the function selector.\n mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)\n mstore(add(freeMemoryPointer, 4), to) // Append the \"to\" argument.\n mstore(add(freeMemoryPointer, 36), amount) // Append the \"amount\" argument.\n\n success := and(\n // Set success to whether the call reverted, if not we check it either\n // returned exactly 1 (can't just be non-zero data), or had no return data.\n or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.\n // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n // Counterintuitively, this call must be positioned second to the or() call in the\n // surrounding and() call or else returndatasize() will be zero during the computation.\n call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)\n )\n }\n\n require(success, \"TRANSFER_FAILED\");\n }\n\n function safeApprove(\n ERC20 token,\n address to,\n uint256 amount\n ) internal {\n bool success;\n\n /// @solidity memory-safe-assembly\n assembly {\n // Get a pointer to some free memory.\n let freeMemoryPointer := mload(0x40)\n\n // Write the abi-encoded calldata into memory, beginning with the function selector.\n mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)\n mstore(add(freeMemoryPointer, 4), to) // Append the \"to\" argument.\n mstore(add(freeMemoryPointer, 36), amount) // Append the \"amount\" argument.\n\n success := and(\n // Set success to whether the call reverted, if not we check it either\n // returned exactly 1 (can't just be non-zero data), or had no return data.\n or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.\n // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n // Counterintuitively, this call must be positioned second to the or() call in the\n // surrounding and() call or else returndatasize() will be zero during the computation.\n call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)\n )\n }\n\n require(success, \"APPROVE_FAILED\");\n }\n}\n" }, "src/Platform.sol": { "content": "// SPDX-License-Identifier: Unlicense\npragma solidity 0.8.17;\n/*\n▄▄▄█████▓ ██░ ██ ▓█████ ██░ ██ ▓█████ ██▀███ ▓█████▄ \n▓ ██▒ ▓▒▓██░ ██▒▓█ ▀ ▓██░ ██▒▓█ ▀ ▓██ ▒ ██▒▒██▀ ██▌\n▒ ▓██░ ▒░▒██▀▀██░▒███ ▒██▀▀██░▒███ ▓██ ░▄█ ▒░██ █▌\n░ ▓██▓ ░ ░▓█ ░██ ▒▓█ ▄ ░▓█ ░██ ▒▓█ ▄ ▒██▀▀█▄ ░▓█▄ ▌\n ▒██▒ ░ ░▓█▒░██▓░▒████▒ ░▓█▒░██▓░▒████▒░██▓ ▒██▒░▒████▓ \n ▒ ░░ ▒ ░░▒░▒░░ ▒░ ░ ▒ ░░▒░▒░░ ▒░ ░░ ▒▓ ░▒▓░ ▒▒▓ ▒ \n ░ ▒ ░▒░ ░ ░ ░ ░ ▒ ░▒░ ░ ░ ░ ░ ░▒ ░ ▒░ ░ ▒ ▒ \n ░ ░ ░░ ░ ░ ░ ░░ ░ ░ ░░ ░ ░ ░ ░ \n ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ \n ░ \n .,;>>%%%%%>>;,.\n .>%%%%%%%%%%%%%%%%%%%%>,.\n .>%%%%%%%%%%%%%%%%%%>>,%%%%%%;,.\n .>>>>%%%%%%%%%%%%%>>,%%%%%%%%%%%%,>>%%,.\n .>>%>>>>%%%%%%%%%>>,%%%%%%%%%%%%%%%%%,>>%%%%%,.\n .>>%%%%%>>%%%%>>,%%>>%%%%%%%%%%%%%%%%%%%%,>>%%%%%%%,\n .>>%%%%%%%%%%>>,%%%%%%>>%%%%%%%%%%%%%%%%%%,>>%%%%%%%%%%.\n .>>%%%%%%%%%%>>,>>>>%%%%%%%%%%'..`%%%%%%%%,;>>%%%%%%%%%>%%.\n.>>%%%>>>%%%%%>,%%%%%%%%%%%%%%.%%%,`%%%%%%,;>>%%%%%%%%>>>%%%%.\n>>%%>%>>>%>%%%>,%%%%%>>%%%%%%%%%%%%%`%%%%%%,>%%%%%%%>>>>%%%%%%%.\n>>%>>>%%>>>%%%%>,%>>>%%%%%%%%%%%%%%%%`%%%%%%%%%%%%%%%%%%%%%%%%%%.\n>>%%%%%%%%%%%%%%,>%%%%%%%%%%%%%%%%%%%'%%%,>>%%%%%%%%%%%%%%%%%%%%%.\n>>%%%%%%%%%%%%%%%,>%%%>>>%%%%%%%%%%%%%%%,>>%%%%%%%%>>>>%%%%%%%%%%%.\n>>%%%%%%%%;%;%;%%;,%>>>>%%%%%%%%%%%%%%%,>>>%%%%%%>>;\";>>%%%%%%%%%%%%.\n`>%%%%%%%%%;%;;;%;%,>%%%%%%%%%>>%%%%%%%%,>>>%%%%%%%%%%%%%%%%%%%%%%%%%%.\n >>%%%%%%%%%,;;;;;%%>,%%%%%%%%>>>>%%%%%%%%,>>%%%%%%%%%%%%%%%%%%%%%%%%%%%.\n `>>%%%%%%%%%,%;;;;%%%>,%%%%%%%%>>>>%%%%%%%%,>%%%%%%'%%%%%%%%%%%%%%%%%%%>>.\n `>>%%%%%%%%%%>,;;%%%%%>>,%%%%%%%%>>%%%%%%';;;>%%%%%,`%%%%%%%%%%%%%%%>>%%>.\n >>>%%%%%%%%%%>> %%%%%%%%>>,%%%%>>>%%%%%';;;;;;>>,%%%,`% `;>%%%%%%>>%%\n `>>%%%%%%%%%%>> %%%%%%%%%>>>>>>>>;;;;'.;;;;;>>%%' `%%' ;>%%%%%>\n >>%%%%%%%%%>>; %%%%%%%%>>;;;;;;'' ;;;;;>>%%% ;>%%%%\n `>>%%%%%%%>>>, %%%%%%%%%>>;;' ;;;;>>%%%' ;>%%%\n >>%%%%%%>>>':.%%%%%%%%%%>>; .;;;>>%%%% ;>%%%'\n `>>%%%%%>>> ::`%%%%%%%%%%>>;. ;;;>>%%%%' ;>%%%'\n `>>%%%%>>> `:::`%%%%%%%%%%>;. ;;>>%%%%% ;>%%'\n `>>%%%%>>, `::::`%%%%%%%%%%>, .;>>%%%%%' ;>%'\n `>>%%%%>>, `:::::`%%%%%%%%%>>. ;;>%%%%%% ;>%,\n `>>%%%%>>, :::::::`>>>%%%%>>> ;;>%%%%%' ;>%,\n `>>%%%%>>,::::::,>>>>>>>>>>' ;;>%%%%% ;%%,\n >>%%%%>>,:::,%%>>>>>>>>' ;>%%%%%. ;%%\n >>%%%%>>``%%%%%>>>>>' `>%%%%%%.\n >>%%%%>> `@@a%%%%%%' .%%%%%%%%%.\n `a@@a%@' `%a@@' `a@@a%a@@a\n */\n\nimport {Factory} from \"src/interfaces/Factory.sol\";\nimport {GaugeController} from \"src/interfaces/GaugeController.sol\";\nimport {ReentrancyGuard} from \"solmate/utils/ReentrancyGuard.sol\";\nimport {FixedPointMathLib} from \"solmate/utils/FixedPointMathLib.sol\";\nimport {ERC20, SafeTransferLib} from \"solmate/utils/SafeTransferLib.sol\";\n\n/// version 1.0.2\n/// @title Platform\n/// @author Stake DAO\ncontract Platform is ReentrancyGuard {\n using SafeTransferLib for ERC20;\n using FixedPointMathLib for uint256;\n\n ////////////////////////////////////////////////////////////////\n /// --- EMERGENCY SHUTDOWN\n ///////////////////////////////////////////////////////////////\n\n /// @notice Emergency shutdown flag\n bool public isKilled;\n\n ////////////////////////////////////////////////////////////////\n /// --- STRUCTS\n ///////////////////////////////////////////////////////////////\n\n /// @notice Bribe struct requirements.\n struct Bribe {\n // Address of the target gauge.\n address gauge;\n // Manager.\n address manager;\n // Address of the ERC20 used for rewards.\n address rewardToken;\n // Number of periods.\n uint8 numberOfPeriods;\n // Timestamp where the bribe become unclaimable.\n uint256 endTimestamp;\n // Max Price per vote.\n uint256 maxRewardPerVote;\n // Total Reward Added.\n uint256 totalRewardAmount;\n // Blacklisted addresses.\n address[] blacklist;\n }\n\n /// @notice Period struct.\n struct Period {\n // Period id.\n // Eg: 0 is the first period, 1 is the second period, etc.\n uint8 id;\n // Timestamp of the period start.\n uint256 timestamp;\n // Reward amount distributed during the period.\n uint256 rewardPerPeriod;\n }\n\n struct Upgrade {\n // Number of periods after increase.\n uint8 numberOfPeriods;\n // Total reward amount after increase.\n uint256 totalRewardAmount;\n // New max reward per vote after increase.\n uint256 maxRewardPerVote;\n // New end timestamp after increase.\n uint256 endTimestamp;\n }\n\n ////////////////////////////////////////////////////////////////\n /// --- CONSTANTS & IMMUTABLES\n ///////////////////////////////////////////////////////////////\n\n /// @notice Week in seconds.\n uint256 private constant _WEEK = 1 weeks;\n\n /// @notice Base unit for fixed point compute.\n uint256 private constant _BASE_UNIT = 1e18;\n\n /// @notice Minimum duration a Bribe.\n uint8 public constant MINIMUM_PERIOD = 2;\n\n /// @notice Factory contract.\n Factory public immutable factory;\n\n /// @notice Gauge Controller.\n GaugeController public immutable gaugeController;\n\n ////////////////////////////////////////////////////////////////\n /// --- STORAGE VARS\n ///////////////////////////////////////////////////////////////\n\n /// @notice Bribe ID Counter.\n uint256 public nextID;\n\n /// @notice ID => Bribe.\n mapping(uint256 => Bribe) public bribes;\n\n /// @notice ID => Bribe In Queue to be upgraded.\n mapping(uint256 => Upgrade) public upgradeBribeQueue;\n\n /// @notice ID => Period running.\n mapping(uint256 => Period) public activePeriod;\n\n /// @notice BribeId => isUpgradeable. If true, the bribe can be upgraded.\n mapping(uint256 => bool) public isUpgradeable;\n\n /// @notice ID => Amount Claimed per Bribe.\n mapping(uint256 => uint256) public amountClaimed;\n\n /// @notice ID => Amount of reward per token distributed.\n mapping(uint256 => uint256) public rewardPerToken;\n\n /// @notice Blacklisted addresses per bribe that aren't counted for rewards arithmetics.\n mapping(uint256 => mapping(address => bool)) public isBlacklisted;\n\n /// @notice Last time a user claimed\n mapping(address => mapping(uint256 => uint256)) public lastUserClaim;\n\n ////////////////////////////////////////////////////////////////\n /// --- MODIFIERS\n ///////////////////////////////////////////////////////////////\n\n modifier onlyManager(uint256 _id) {\n if (msg.sender != bribes[_id].manager) revert AUTH_MANAGER_ONLY();\n _;\n }\n\n modifier notKilled() {\n if (isKilled) revert KILLED();\n _;\n }\n\n ////////////////////////////////////////////////////////////////\n /// --- EVENTS\n ///////////////////////////////////////////////////////////////\n\n /// @notice Emitted when a new bribe is created.\n event BribeCreated(\n uint256 indexed id,\n address indexed gauge,\n address manager,\n address indexed rewardToken,\n uint8 numberOfPeriods,\n uint256 maxRewardPerVote,\n uint256 rewardPerPeriod,\n uint256 totalRewardAmount,\n bool isUpgradeable\n );\n\n /// @notice Emitted when a bribe is closed.\n event BribeClosed(uint256 id, uint256 remainingReward);\n\n /// @notice Emitted when a bribe period is rolled over.\n event PeriodRolledOver(uint256 id, uint256 periodId, uint256 timestamp, uint256 rewardPerPeriod);\n\n /// @notice Emitted on claim.\n event Claimed(\n address indexed user, address indexed rewardToken, uint256 indexed bribeId, uint256 amount, uint256 period\n );\n\n /// @notice Emitted when a bribe is queued to upgrade.\n event BribeDurationIncreaseQueued(\n uint256 id, uint8 numberOfPeriods, uint256 totalRewardAmount, uint256 maxRewardPerVote\n );\n\n /// @notice Emitted when a bribe is upgraded.\n event BribeDurationIncreased(\n uint256 id, uint8 numberOfPeriods, uint256 totalRewardAmount, uint256 maxRewardPerVote\n );\n\n /// @notice Emitted when a bribe manager is updated.\n event ManagerUpdated(uint256 id, address indexed manager);\n\n ////////////////////////////////////////////////////////////////\n /// --- ERRORS\n ///////////////////////////////////////////////////////////////\n\n error KILLED();\n error WRONG_INPUT();\n error ZERO_ADDRESS();\n error INVALID_GAUGE();\n error NO_PERIODS_LEFT();\n error NOT_UPGRADEABLE();\n error AUTH_MANAGER_ONLY();\n error ALREADY_INCREASED();\n error NOT_ALLOWED_OPERATION();\n error INVALID_NUMBER_OF_PERIODS();\n\n ////////////////////////////////////////////////////////////////\n /// --- CONSTRUCTOR\n ///////////////////////////////////////////////////////////////\n\n /// @notice Create Bribe platform.\n /// @param _gaugeController Address of the gauge controller.\n constructor(address _gaugeController, address _factory) {\n gaugeController = GaugeController(_gaugeController);\n factory = Factory(_factory);\n }\n\n ////////////////////////////////////////////////////////////////\n /// --- BRIBE CREATION LOGIC\n ///////////////////////////////////////////////////////////////\n\n /// @notice Create a new bribe.\n /// @param gauge Address of the target gauge.\n /// @param rewardToken Address of the ERC20 used or rewards.\n /// @param numberOfPeriods Number of periods.\n /// @param maxRewardPerVote Target Bias for the Gauge.\n /// @param totalRewardAmount Total Reward Added.\n /// @param blacklist Array of addresses to blacklist.\n /// @return newBribeID of the bribe created.\n function createBribe(\n address gauge,\n address manager,\n address rewardToken,\n uint8 numberOfPeriods,\n uint256 maxRewardPerVote,\n uint256 totalRewardAmount,\n address[] calldata blacklist,\n bool upgradeable\n ) external nonReentrant notKilled returns (uint256 newBribeID) {\n if (rewardToken == address(0)) revert ZERO_ADDRESS();\n if (gaugeController.gauge_types(gauge) < 0) return newBribeID;\n if (numberOfPeriods < MINIMUM_PERIOD) revert INVALID_NUMBER_OF_PERIODS();\n if (totalRewardAmount == 0 || maxRewardPerVote == 0) revert WRONG_INPUT();\n\n // Transfer the rewards to the contracts.\n ERC20(rewardToken).safeTransferFrom(msg.sender, address(this), totalRewardAmount);\n\n unchecked {\n // Get the ID for that new Bribe and increment the nextID counter.\n newBribeID = nextID;\n\n ++nextID;\n }\n\n uint256 rewardPerPeriod = totalRewardAmount.mulDivDown(1, numberOfPeriods);\n\n bribes[newBribeID] = Bribe({\n gauge: gauge,\n manager: manager,\n rewardToken: rewardToken,\n numberOfPeriods: numberOfPeriods,\n endTimestamp: getCurrentPeriod() + ((numberOfPeriods + 1) * _WEEK),\n maxRewardPerVote: maxRewardPerVote,\n totalRewardAmount: totalRewardAmount,\n blacklist: blacklist\n });\n\n emit BribeCreated(\n newBribeID,\n gauge,\n manager,\n rewardToken,\n numberOfPeriods,\n maxRewardPerVote,\n rewardPerPeriod,\n totalRewardAmount,\n upgradeable\n );\n\n // Set Upgradeable status.\n isUpgradeable[newBribeID] = upgradeable;\n // Starting from next period.\n activePeriod[newBribeID] = Period(0, getCurrentPeriod() + _WEEK, rewardPerPeriod);\n\n // Add the addresses to the blacklist.\n uint256 length = blacklist.length;\n for (uint256 i = 0; i < length;) {\n isBlacklisted[newBribeID][blacklist[i]] = true;\n unchecked {\n ++i;\n }\n }\n }\n\n /// @notice Claim rewards for a given bribe.\n /// @param bribeId ID of the bribe.\n /// @return Amount of rewards claimed.\n function claim(uint256 bribeId) external returns (uint256) {\n return _claim(msg.sender, bribeId);\n }\n\n /// @notice Update Bribe for a given id.\n /// @param bribeId ID of the bribe.\n function updateBribePeriod(uint256 bribeId) external nonReentrant {\n _updateBribePeriod(bribeId);\n }\n\n /// @notice Update multiple bribes for given ids.\n /// @param ids Array of Bribe IDs.\n function updateBribePeriods(uint256[] calldata ids) external nonReentrant {\n uint256 length = ids.length;\n for (uint256 i = 0; i < length;) {\n _updateBribePeriod(ids[i]);\n unchecked {\n ++i;\n }\n }\n }\n\n /// @notice Claim all rewards for multiple bribes.\n /// @param ids Array of bribe IDs to claim.\n function claimAll(uint256[] calldata ids) external {\n uint256 length = ids.length;\n\n for (uint256 i = 0; i < length;) {\n uint256 id = ids[i];\n _claim(msg.sender, id);\n\n unchecked {\n ++i;\n }\n }\n }\n\n ////////////////////////////////////////////////////////////////\n /// --- INTERNAL LOGIC\n ///////////////////////////////////////////////////////////////\n\n /// @notice Claim rewards for a given bribe.\n /// @param user Address of the user.\n /// @param bribeId ID of the bribe.\n /// @return amount of rewards claimed.\n function _claim(address user, uint256 bribeId) internal nonReentrant notKilled returns (uint256 amount) {\n if (isBlacklisted[bribeId][user]) return 0;\n // Update if needed the current period.\n uint256 currentPeriod = _updateBribePeriod(bribeId);\n\n Bribe storage bribe = bribes[bribeId];\n\n // Address of the target gauge.\n address gauge = bribe.gauge;\n // End timestamp of the bribe.\n uint256 endTimestamp = bribe.endTimestamp;\n // Get the last_vote timestamp.\n uint256 lastVote = gaugeController.last_user_vote(user, gauge);\n // Get the end lock date to compute dt.\n uint256 end = gaugeController.vote_user_slopes(user, gauge).end;\n // Get the voting power user slope.\n uint256 userSlope = gaugeController.vote_user_slopes(user, gauge).slope;\n\n if (\n userSlope == 0 || lastUserClaim[user][bribeId] >= currentPeriod || currentPeriod >= end\n || currentPeriod <= lastVote || currentPeriod >= endTimestamp || currentPeriod != getCurrentPeriod()\n || amountClaimed[bribeId] == bribe.totalRewardAmount\n ) return 0;\n\n // Update User last claim period.\n lastUserClaim[user][bribeId] = currentPeriod;\n\n // Voting Power = userSlope * dt\n // with dt = lock_end - period.\n uint256 _bias = _getAddrBias(userSlope, end, currentPeriod);\n // Compute the reward amount based on\n // Reward / Total Votes.\n amount = _bias.mulWadDown(rewardPerToken[bribeId]);\n // Compute the reward amount based on\n // the max price to pay.\n uint256 _amountWithMaxPrice = _bias.mulWadDown(bribe.maxRewardPerVote);\n // Distribute the _min between the amount based on votes, and price.\n amount = _min(amount, _amountWithMaxPrice);\n\n // Update the amount claimed.\n uint256 _amountClaimed = amountClaimed[bribeId];\n if (amount + _amountClaimed > bribe.totalRewardAmount) {\n amount = bribe.totalRewardAmount - _amountClaimed;\n }\n\n amountClaimed[bribeId] += amount;\n\n uint256 platformFee = factory.platformFee(address(gaugeController));\n if (platformFee != 0) {\n uint256 feeAmount = amount.mulWadDown(platformFee);\n amount -= feeAmount;\n\n // Transfer fees.\n ERC20(bribe.rewardToken).safeTransfer(factory.feeCollector(), feeAmount);\n }\n // Transfer to user.\n ERC20(bribe.rewardToken).safeTransfer(user, amount);\n\n emit Claimed(user, bribe.rewardToken, bribeId, amount, currentPeriod);\n }\n\n /// @notice Update the current period for a given bribe.\n /// @param bribeId Bribe ID.\n /// @return current/updated period.\n function _updateBribePeriod(uint256 bribeId) internal returns (uint256) {\n Period storage _activePeriod = activePeriod[bribeId];\n\n uint256 currentPeriod = getCurrentPeriod();\n\n if (_activePeriod.id == 0 && currentPeriod == _activePeriod.timestamp) {\n // Initialize reward per token.\n // Only for the first period, and if not already initialized.\n _updateRewardPerToken(bribeId, currentPeriod);\n }\n\n // Increase Period\n if (block.timestamp >= _activePeriod.timestamp + _WEEK) {\n // Checkpoint gauge to have up to date gauge weight.\n gaugeController.checkpoint_gauge(bribes[bribeId].gauge);\n // Roll to next period.\n _rollOverToNextPeriod(bribeId, currentPeriod);\n\n return currentPeriod;\n }\n\n return _activePeriod.timestamp;\n }\n\n /// @notice Roll over to next period.\n /// @param bribeId Bribe ID.\n /// @param currentPeriod Next period timestamp.\n function _rollOverToNextPeriod(uint256 bribeId, uint256 currentPeriod) internal {\n uint8 index = getActivePeriodPerBribe(bribeId);\n\n Upgrade storage upgradedBribe = upgradeBribeQueue[bribeId];\n\n // Check if there is an upgrade in queue.\n if (upgradedBribe.totalRewardAmount != 0) {\n // Save new values.\n bribes[bribeId].numberOfPeriods = upgradedBribe.numberOfPeriods;\n bribes[bribeId].totalRewardAmount = upgradedBribe.totalRewardAmount;\n bribes[bribeId].maxRewardPerVote = upgradedBribe.maxRewardPerVote;\n bribes[bribeId].endTimestamp = upgradedBribe.endTimestamp;\n\n emit BribeDurationIncreased(\n bribeId, upgradedBribe.numberOfPeriods, upgradedBribe.totalRewardAmount, upgradedBribe.maxRewardPerVote\n );\n\n // Reset the next values.\n delete upgradeBribeQueue[bribeId];\n }\n\n Bribe storage bribe = bribes[bribeId];\n\n uint256 periodsLeft = getPeriodsLeft(bribeId);\n uint256 rewardPerPeriod;\n rewardPerPeriod = bribe.totalRewardAmount - amountClaimed[bribeId];\n\n if (bribe.endTimestamp > currentPeriod + _WEEK && periodsLeft > 1) {\n rewardPerPeriod = rewardPerPeriod.mulDivDown(1, periodsLeft);\n }\n\n // Get adjusted slope without blacklisted addresses.\n uint256 gaugeBias = _getAdjustedBias(bribe.gauge, bribe.blacklist, currentPeriod);\n\n rewardPerToken[bribeId] = rewardPerPeriod.mulDivDown(_BASE_UNIT, gaugeBias);\n activePeriod[bribeId] = Period(index, currentPeriod, rewardPerPeriod);\n\n emit PeriodRolledOver(bribeId, index, currentPeriod, rewardPerPeriod);\n }\n\n /// @notice Update the amount of reward per token for a given bribe.\n /// @dev This function is only called once per Bribe.\n function _updateRewardPerToken(uint256 bribeId, uint256 currentPeriod) internal {\n if (rewardPerToken[bribeId] == 0) {\n uint256 gaugeBias = _getAdjustedBias(bribes[bribeId].gauge, bribes[bribeId].blacklist, currentPeriod);\n if (gaugeBias != 0) {\n rewardPerToken[bribeId] = activePeriod[bribeId].rewardPerPeriod.mulDivDown(_BASE_UNIT, gaugeBias);\n }\n }\n }\n\n ////////////////////////////////////////////////////////////////\n /// --- VIEWS\n ///////////////////////////////////////////////////////////////\n\n /// @notice Get an estimate of the reward amount for a given user.\n /// @param user Address of the user.\n /// @param bribeId ID of the bribe.\n /// @return amount of rewards.\n /// Mainly used for UI.\n function claimable(address user, uint256 bribeId) external view returns (uint256 amount) {\n if (isBlacklisted[bribeId][user]) return 0;\n\n Bribe memory bribe = bribes[bribeId];\n\n // Update if needed the current period.\n uint256 currentPeriod = getCurrentPeriod();\n // End timestamp of the bribe.\n uint256 endTimestamp = bribe.endTimestamp;\n // Get the last_vote timestamp.\n uint256 lastVote = gaugeController.last_user_vote(user, bribe.gauge);\n // Get the end lock date to compute dt.\n uint256 end = gaugeController.vote_user_slopes(user, bribe.gauge).end;\n // Get the voting power user slope.\n uint256 userSlope = gaugeController.vote_user_slopes(user, bribe.gauge).slope;\n\n if (\n userSlope == 0 || lastUserClaim[user][bribeId] >= currentPeriod || currentPeriod >= end\n || currentPeriod <= lastVote || currentPeriod >= endTimestamp\n || currentPeriod < getActivePeriod(bribeId).timestamp || amountClaimed[bribeId] >= bribe.totalRewardAmount\n ) return 0;\n\n uint256 _rewardPerToken = rewardPerToken[bribeId];\n // If period updated.\n if (_rewardPerToken == 0 || (_rewardPerToken > 0 && getActivePeriod(bribeId).timestamp != currentPeriod)) {\n uint256 _rewardPerPeriod;\n // If there is an upgrade in progress but period hasn't been rolled over yet.\n Upgrade memory upgradedBribe = upgradeBribeQueue[bribeId];\n\n if (upgradedBribe.numberOfPeriods != 0) {\n // Update max reward per vote.\n bribe.maxRewardPerVote = upgradedBribe.maxRewardPerVote;\n bribe.totalRewardAmount = upgradedBribe.totalRewardAmount;\n // Update end timestamp.\n endTimestamp = upgradedBribe.endTimestamp;\n }\n\n uint256 periodsLeft = endTimestamp > currentPeriod ? (endTimestamp - currentPeriod) / _WEEK : 0;\n _rewardPerPeriod = bribe.totalRewardAmount - amountClaimed[bribeId];\n\n if (endTimestamp > currentPeriod + _WEEK && periodsLeft > 1) {\n _rewardPerPeriod = _rewardPerPeriod.mulDivDown(1, periodsLeft);\n }\n\n // Get Adjusted Slope without blacklisted addresses weight.\n uint256 gaugeBias = _getAdjustedBias(bribe.gauge, bribe.blacklist, currentPeriod);\n _rewardPerToken = _rewardPerPeriod.mulDivDown(_BASE_UNIT, gaugeBias);\n }\n // Get user voting power.\n uint256 _bias = _getAddrBias(userSlope, end, currentPeriod);\n // Estimation of the amount of rewards.\n amount = _bias.mulWadDown(_rewardPerToken);\n // Compute the reward amount based on\n // the max price to pay.\n uint256 _amountWithMaxPrice = _bias.mulWadDown(bribe.maxRewardPerVote);\n // Distribute the _min between the amount based on votes, and price.\n amount = _min(amount, _amountWithMaxPrice);\n\n uint256 _amountClaimed = amountClaimed[bribeId];\n // Update the amount claimed.\n if (amount + _amountClaimed > bribe.totalRewardAmount) {\n amount = bribe.totalRewardAmount - _amountClaimed;\n }\n // Substract fees.\n uint256 platformFee = factory.platformFee(address(gaugeController));\n if (platformFee != 0) {\n amount = amount.mulWadDown(_BASE_UNIT - platformFee);\n }\n }\n\n ////////////////////////////////////////////////////////////////\n /// --- INTERNAL VIEWS\n ///////////////////////////////////////////////////////////////\n\n /// @notice Get adjusted slope from Gauge Controller for a given gauge address.\n /// Remove the weight of blacklisted addresses.\n /// @param gauge Address of the gauge.\n /// @param _addressesBlacklisted Array of blacklisted addresses.\n /// @param period Timestamp to check vote weight.\n function _getAdjustedBias(address gauge, address[] memory _addressesBlacklisted, uint256 period)\n internal\n view\n returns (uint256 gaugeBias)\n {\n // Cache the user slope.\n GaugeController.VotedSlope memory userSlope;\n // Bias\n uint256 _bias;\n // Last Vote\n uint256 _lastVote;\n // Cache the length of the array.\n uint256 length = _addressesBlacklisted.length;\n // Cache blacklist.\n // Get the gauge slope.\n gaugeBias = gaugeController.points_weight(gauge, period).bias;\n\n for (uint256 i = 0; i < length;) {\n // Get the user slope.\n userSlope = gaugeController.vote_user_slopes(_addressesBlacklisted[i], gauge);\n _lastVote = gaugeController.last_user_vote(_addressesBlacklisted[i], gauge);\n if (period > _lastVote) {\n _bias = _getAddrBias(userSlope.slope, userSlope.end, period);\n gaugeBias -= _bias;\n }\n // Increment i.\n unchecked {\n ++i;\n }\n }\n }\n\n ////////////////////////////////////////////////////////////////\n /// --- MANAGEMENT LOGIC\n ///////////////////////////////////////////////////////////////\n\n /// @notice Increase Bribe duration.\n /// @param _bribeId ID of the bribe.\n /// @param _additionnalPeriods Number of periods to add.\n /// @param _increasedAmount Total reward amount to add.\n /// @param _newMaxPricePerVote Total reward amount to add.\n function increaseBribeDuration(\n uint256 _bribeId,\n uint8 _additionnalPeriods,\n uint256 _increasedAmount,\n uint256 _newMaxPricePerVote\n ) external nonReentrant notKilled onlyManager(_bribeId) {\n if (!isUpgradeable[_bribeId]) revert NOT_UPGRADEABLE();\n if (getPeriodsLeft(_bribeId) < 1) revert NO_PERIODS_LEFT();\n if (_increasedAmount == 0 || _newMaxPricePerVote == 0) revert WRONG_INPUT();\n\n Bribe storage bribe = bribes[_bribeId];\n Upgrade memory upgradedBribe = upgradeBribeQueue[_bribeId];\n\n ERC20(bribe.rewardToken).safeTransferFrom(msg.sender, address(this), _increasedAmount);\n\n if (upgradedBribe.totalRewardAmount != 0) {\n upgradedBribe = Upgrade({\n numberOfPeriods: upgradedBribe.numberOfPeriods + _additionnalPeriods,\n totalRewardAmount: upgradedBribe.totalRewardAmount + _increasedAmount,\n maxRewardPerVote: _newMaxPricePerVote,\n endTimestamp: upgradedBribe.endTimestamp + (_additionnalPeriods * _WEEK)\n });\n } else {\n upgradedBribe = Upgrade({\n numberOfPeriods: bribe.numberOfPeriods + _additionnalPeriods,\n totalRewardAmount: bribe.totalRewardAmount + _increasedAmount,\n maxRewardPerVote: _newMaxPricePerVote,\n endTimestamp: bribe.endTimestamp + (_additionnalPeriods * _WEEK)\n });\n }\n\n upgradeBribeQueue[_bribeId] = upgradedBribe;\n\n emit BribeDurationIncreaseQueued(\n _bribeId, upgradedBribe.numberOfPeriods, upgradedBribe.totalRewardAmount, _newMaxPricePerVote\n );\n }\n\n /// @notice Close Bribe if there is remaining.\n /// @param bribeId ID of the bribe to close.\n function closeBribe(uint256 bribeId) external nonReentrant onlyManager(bribeId) {\n // Check if the currentPeriod is the last one.\n // If not, we can increase the duration.\n Bribe storage bribe = bribes[bribeId];\n\n if (getCurrentPeriod() >= bribe.endTimestamp || isKilled) {\n uint256 leftOver;\n Upgrade memory upgradedBribe = upgradeBribeQueue[bribeId];\n if (upgradedBribe.totalRewardAmount != 0) {\n leftOver = upgradedBribe.totalRewardAmount - amountClaimed[bribeId];\n delete upgradeBribeQueue[bribeId];\n } else {\n leftOver = bribes[bribeId].totalRewardAmount - amountClaimed[bribeId];\n }\n // Transfer the left over to the owner.\n ERC20(bribe.rewardToken).safeTransfer(bribe.manager, leftOver);\n delete bribes[bribeId].manager;\n\n emit BribeClosed(bribeId, leftOver);\n }\n }\n\n /// @notice Update Bribe Manager.\n /// @param bribeId ID of the bribe.\n /// @param newManager Address of the new manager.\n function updateManager(uint256 bribeId, address newManager) external nonReentrant onlyManager(bribeId) {\n emit ManagerUpdated(bribeId, bribes[bribeId].manager = newManager);\n }\n\n function kill() external {\n if (msg.sender != address(factory)) revert NOT_ALLOWED_OPERATION();\n isKilled = true;\n }\n\n function unKill() external {\n if (msg.sender != address(factory)) revert NOT_ALLOWED_OPERATION();\n isKilled = false;\n }\n\n ////////////////////////////////////////////////////////////////\n /// --- UTILS FUNCTIONS\n ///////////////////////////////////////////////////////////////\n\n /// @notice Returns the number of periods left for a given bribe.\n /// @param bribeId ID of the bribe.\n function getPeriodsLeft(uint256 bribeId) public view returns (uint256 periodsLeft) {\n Bribe memory bribe = bribes[bribeId];\n uint256 endTimestamp = bribe.endTimestamp;\n\n periodsLeft = endTimestamp > getCurrentPeriod() ? (endTimestamp - getCurrentPeriod()) / _WEEK : 0;\n }\n\n /// @notice Return the bribe object for a given ID.\n /// @param bribeId ID of the bribe.\n function getBribe(uint256 bribeId) external view returns (Bribe memory) {\n return bribes[bribeId];\n }\n\n /// @notice Return the bribe in queue for a given ID.\n /// @dev Can return an empty bribe if there is no upgrade.\n /// @param bribeId ID of the bribe.\n function getUpgradedBribeQueued(uint256 bribeId) external view returns (Upgrade memory) {\n return upgradeBribeQueue[bribeId];\n }\n\n /// @notice Return the blacklisted addresses of a bribe for a given ID.\n /// @param bribeId ID of the bribe.\n function getBlacklistedAddressesForBribe(uint256 bribeId) external view returns (address[] memory) {\n return bribes[bribeId].blacklist;\n }\n\n /// @notice Return the active period running of bribe given an ID.\n /// @param bribeId ID of the bribe.\n function getActivePeriod(uint256 bribeId) public view returns (Period memory) {\n return activePeriod[bribeId];\n }\n\n /// @notice Return the expected current period id.\n /// @param bribeId ID of the bribe.\n function getActivePeriodPerBribe(uint256 bribeId) public view returns (uint8) {\n Bribe memory bribe = bribes[bribeId];\n\n uint256 endTimestamp = bribe.endTimestamp;\n uint256 numberOfPeriods = bribe.numberOfPeriods;\n uint256 periodsLeft = endTimestamp > getCurrentPeriod() ? (endTimestamp - getCurrentPeriod()) / _WEEK : 0;\n\n // If periodsLeft is superior, then the bribe didn't start yet.\n return uint8(periodsLeft > numberOfPeriods ? 0 : numberOfPeriods - periodsLeft);\n }\n\n /// @notice Return the current period based on Gauge Controller rounding.\n function getCurrentPeriod() public view returns (uint256) {\n return block.timestamp / _WEEK * _WEEK;\n }\n\n /// @notice Return the minimum between two numbers.\n /// @param a First number.\n /// @param b Second number.\n function _min(uint256 a, uint256 b) private pure returns (uint256 min) {\n min = a < b ? a : b;\n }\n\n /// @notice Return the bias of a given address based on its lock end date and the current period.\n /// @param userSlope User slope.\n /// @param endLockTime Lock end date of the address.\n /// @param currentPeriod Current period.\n function _getAddrBias(uint256 userSlope, uint256 endLockTime, uint256 currentPeriod)\n internal\n pure\n returns (uint256)\n {\n if (currentPeriod + _WEEK >= endLockTime) return 0;\n return userSlope * (endLockTime - currentPeriod);\n }\n}\n" }, "src/PlatformFactory.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity 0.8.17;\n\nimport {Owned} from \"solmate/auth/Owned.sol\";\nimport {ERC20} from \"solmate/tokens/ERC20.sol\";\nimport {Platform, Factory} from \"./Platform.sol\";\nimport {Bytes32AddressLib} from \"solmate/utils/Bytes32AddressLib.sol\";\n\ncontract PlatformFactory is Owned, Factory {\n using Bytes32AddressLib for address;\n using Bytes32AddressLib for bytes32;\n\n uint256 internal constant _DEFAULT_FEE = 2e16; // 2%\n\n /// @notice Fee recipient.\n address public feeCollector;\n\n /// @notice Fee percentage per gaugeController.\n mapping(address => uint256) public customFeesPerGaugeController;\n\n /// @notice Emitted when a new platform is deployed.\n event PlatformDeployed(Platform indexed platform, address indexed gaugeController);\n\n /// @notice Emitted when a new fee is set.\n event PlatformFeeUpdated(address indexed gaugeController, uint256 fee);\n\n /// @notice Emitted when a platform is killed.\n event PlatformKilled(Platform indexed platform, address indexed gaugeController);\n\n /// @notice Emitted when a platform is revived.\n event PlatformRevived(Platform indexed platform, address indexed gaugeController);\n\n /// @notice Thrown if the fee percentage is invalid.\n error INCORRECT_FEE();\n\n ////////////////////////////////////////////////////////////////\n /// --- CONSTRUCTOR\n ///////////////////////////////////////////////////////////////\n\n /// @notice Creates a Platform factory.\n /// @param _owner The owner of the factory.\n constructor(address _owner, address _feeCollector) Owned(_owner) {\n feeCollector = _feeCollector;\n }\n\n function deploy(address _gaugeController) external returns (Platform platform) {\n // Deploy the platform.\n platform = new Platform{salt: address(_gaugeController).fillLast12Bytes()}(_gaugeController, address(this));\n customFeesPerGaugeController[_gaugeController] = _DEFAULT_FEE;\n\n emit PlatformDeployed(platform, _gaugeController);\n }\n\n /// @notice Computes a Platform address from its gauge controller.\n function getPlatformFromGaugeController(address gaugeController) external view returns (Platform) {\n return Platform(\n payable(\n keccak256(\n abi.encodePacked(\n bytes1(0xFF),\n address(this),\n address(gaugeController).fillLast12Bytes(),\n keccak256(\n abi.encodePacked(type(Platform).creationCode, abi.encode(gaugeController, address(this)))\n )\n )\n ).fromLast20Bytes() // Convert the CREATE2 hash into an address.\n )\n );\n }\n\n function platformFee(address _gaugeController) external view returns (uint256) {\n return customFeesPerGaugeController[_gaugeController];\n }\n\n function setPlatformFee(address _gaugeController, uint256 _newCustomFee) external onlyOwner {\n if (_newCustomFee > 1e18) revert INCORRECT_FEE();\n emit PlatformFeeUpdated(_gaugeController, customFeesPerGaugeController[_gaugeController] = _newCustomFee);\n }\n\n function setFeeCollector(address _feeCollector) external onlyOwner {\n feeCollector = _feeCollector;\n }\n\n function kill(address platform) external onlyOwner {\n Platform(platform).kill();\n emit PlatformKilled(Platform(platform), address(Platform(platform).gaugeController()));\n }\n\n function unKill(address platform) external onlyOwner {\n Platform(platform).unKill();\n emit PlatformRevived(Platform(platform), address(Platform(platform).gaugeController()));\n }\n}\n" }, "src/interfaces/Factory.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\ninterface Factory {\n function feeCollector() external view returns (address);\n\n function platformFee(address) external view returns (uint256);\n}\n" }, "src/interfaces/GaugeController.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\ninterface GaugeController {\n struct VotedSlope {\n uint256 slope;\n uint256 power;\n uint256 end;\n }\n\n struct Point {\n uint256 bias;\n uint256 slope;\n }\n\n function vote_user_slopes(address, address) external view returns (VotedSlope memory);\n\n function add_gauge(address, int128) external;\n\n function WEIGHT_VOTE_DELAY() external view returns (uint256);\n\n function last_user_vote(address, address) external view returns (uint256);\n\n function points_weight(address, uint256) external view returns (Point memory);\n\n function checkpoint_gauge(address) external;\n\n //solhint-disable-next-line\n function gauge_types(address addr) external view returns (int128);\n\n //solhint-disable-next-line\n function gauge_relative_weight_write(address addr, uint256 timestamp) external returns (uint256);\n\n //solhint-disable-next-line\n function gauge_relative_weight(address addr) external view returns (uint256);\n\n //solhint-disable-next-line\n function gauge_relative_weight(address addr, uint256 timestamp) external view returns (uint256);\n\n //solhint-disable-next-line\n function get_total_weight() external view returns (uint256);\n\n //solhint-disable-next-line\n function get_gauge_weight(address addr) external view returns (uint256);\n\n function vote_for_gauge_weights(address, uint256) external;\n\n function add_type(string memory, uint256) external;\n\n function admin() external view returns (address);\n}\n" } }, "settings": { "remappings": [ "ds-test/=lib/forge-std/lib/ds-test/src/", "forge-std/=lib/forge-std/src/", "solmate/=lib/solmate/src/" ], "optimizer": { "enabled": true, "runs": 200 }, "metadata": { "bytecodeHash": "ipfs" }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "evmVersion": "london", "libraries": {} } }