UNPKG

@levxdao/ve

Version:

VE and Gauge Voting for NFTs

38 lines 229 kB
{ "language": "Solidity", "sources": { "contracts/base/CloneFactory.sol": { "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.15;\n\n// Reference: https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol\nabstract contract CloneFactory {\n function _createClone(address target) internal returns (address result) {\n bytes20 targetBytes = bytes20(target);\n assembly {\n let clone := mload(0x40)\n mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)\n mstore(add(clone, 0x14), targetBytes)\n mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)\n result := create(0, clone, 0x37)\n }\n }\n\n function _isClone(address target, address query) internal view returns (bool result) {\n bytes20 targetBytes = bytes20(target);\n assembly {\n let clone := mload(0x40)\n mstore(clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000)\n mstore(add(clone, 0xa), targetBytes)\n mstore(add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)\n\n let other := add(clone, 0x40)\n extcodecopy(query, other, 0, 0x2d)\n result := and(eq(mload(clone), mload(other)), eq(mload(add(clone, 0xd)), mload(add(other, 0xd))))\n }\n }\n}\n" }, "contracts/NFTGaugeFactory.sol": { "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.15;\n\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\n\nimport \"./base/CloneFactory.sol\";\nimport \"./interfaces/INFTGaugeFactory.sol\";\nimport \"./libraries/Integers.sol\";\nimport \"./libraries/Tokens.sol\";\nimport \"./NFTGauge.sol\";\n\ncontract NFTGaugeFactory is CloneFactory, Ownable, INFTGaugeFactory {\n using SafeERC20 for IERC20;\n using Integers for int128;\n using Integers for uint256;\n\n struct Fee {\n uint64 timestamp;\n uint192 amountPerShare;\n }\n\n address public immutable override tokenURIRenderer;\n address public immutable override minter;\n address public immutable override votingEscrow;\n\n address public override target;\n uint256 public override targetVersion;\n\n uint256 public override feeRatio;\n mapping(address => address) public override currencyConverter;\n mapping(address => address) public override gauges;\n mapping(address => bool) public override isGauge;\n\n mapping(address => Fee[]) public override fees;\n mapping(address => mapping(address => uint256)) public override lastFeeClaimed;\n\n constructor(\n address _tokenURIRenderer,\n address _minter,\n uint256 _feeRatio\n ) {\n tokenURIRenderer = _tokenURIRenderer;\n minter = _minter;\n votingEscrow = IGaugeController(IMinter(_minter).controller()).votingEscrow();\n feeRatio = _feeRatio;\n\n emit UpdateFeeRatio(_feeRatio);\n\n NFTGauge gauge = new NFTGauge();\n gauge.initialize(address(0), address(0), address(0));\n target = address(gauge);\n }\n\n function feesLength(address token) external view override returns (uint256) {\n return fees[token].length;\n }\n\n function upgradeTarget(address _target) external override onlyOwner {\n target = _target;\n\n uint256 version = targetVersion + 1;\n targetVersion = version;\n\n emit UpgradeTarget(_target, version);\n }\n\n function updateCurrencyConverter(address token, address converter) external override onlyOwner {\n currencyConverter[token] = converter;\n\n emit UpdateCurrencyConverter(token, converter);\n }\n\n function updateFeeRatio(uint256 _feeRatio) external override onlyOwner {\n feeRatio = _feeRatio;\n\n emit UpdateFeeRatio(_feeRatio);\n }\n\n function createNFTGauge(address nftContract) external override returns (address gauge) {\n require(gauges[nftContract] == address(0), \"NFTGF: GAUGE_CREATED\");\n\n gauge = _createClone(target);\n INFTGauge(gauge).initialize(nftContract, tokenURIRenderer, minter);\n\n gauges[nftContract] = gauge;\n isGauge[gauge] = true;\n\n emit CreateNFTGauge(nftContract, gauge);\n }\n\n function executePayment(\n address currency,\n address from,\n uint256 amount\n ) external override {\n require(isGauge[msg.sender], \"NFTGF: FORBIDDEN\");\n require(currencyConverter[currency] != address(0), \"NFTGF: INVALID_TOKEN\");\n\n IERC20(currency).safeTransferFrom(from, msg.sender, amount);\n }\n\n function distributeFeesETH() external payable override returns (uint256 amountFee) {\n amountFee = (msg.value * feeRatio) / 10000;\n _distributeFees(address(0), amountFee);\n }\n\n function distributeFees(address token, uint256 amount) external override returns (uint256 amountFee) {\n amountFee = (amount * feeRatio) / 10000;\n _distributeFees(token, amountFee);\n }\n\n function _distributeFees(address token, uint256 amount) internal {\n require(isGauge[msg.sender], \"NFTGF: FORBIDDEN\");\n\n fees[token].push(\n Fee(uint64(block.timestamp), uint192((amount * 1e18) / IVotingEscrow(votingEscrow).totalSupply()))\n );\n\n emit DistributeFees(token, fees[token].length - 1, amount);\n }\n\n /**\n * @notice Claim accumulated fees\n * @param token In which currency fees were paid\n * @param to the last index of the fee (exclusive)\n */\n function claimFees(address token, uint256 to) external override {\n uint256 from = lastFeeClaimed[token][msg.sender];\n\n (int128 value, , uint256 start, ) = IVotingEscrow(votingEscrow).locked(msg.sender);\n require(value > 0, \"NFTGF: LOCK_NOT_FOUND\");\n\n uint256 epoch = IVotingEscrow(votingEscrow).userPointEpoch(msg.sender);\n (int128 bias, int128 slope, uint256 ts, ) = IVotingEscrow(votingEscrow).userPointHistory(msg.sender, epoch);\n\n uint256 amount;\n for (uint256 i = from; i < to; ) {\n Fee memory fee = fees[token][i];\n if (start < fee.timestamp) {\n int128 balance = bias - slope * (uint256(fee.timestamp) - ts).toInt128();\n if (balance > 0) {\n amount += (balance.toUint256() * uint256(fee.amountPerShare)) / 1e18;\n }\n }\n unchecked {\n ++i;\n }\n }\n lastFeeClaimed[token][msg.sender] = to;\n\n emit ClaimFees(token, amount, msg.sender);\n Tokens.transfer(token, msg.sender, amount);\n }\n}\n" }, "@openzeppelin/contracts/access/Ownable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n constructor() {\n _transferOwnership(_msgSender());\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n _;\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n _transferOwnership(address(0));\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n _transferOwnership(newOwner);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Internal function without access restriction.\n */\n function _transferOwnership(address newOwner) internal virtual {\n address oldOwner = _owner;\n _owner = newOwner;\n emit OwnershipTransferred(oldOwner, newOwner);\n }\n}\n" }, "contracts/interfaces/INFTGaugeFactory.sol": { "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\ninterface INFTGaugeFactory {\n event UpgradeTarget(address target, uint256 indexed version);\n event UpdateCurrencyConverter(address indexed token, address indexed converter);\n event CreateNFTGauge(address indexed nftContract, address indexed gauge);\n event UpdateFeeRatio(uint256 feeRatio);\n event DistributeFees(address indexed token, uint256 indexed id, uint256 amount);\n event ClaimFees(address indexed token, uint256 amount, address indexed to);\n\n function tokenURIRenderer() external view returns (address);\n\n function minter() external view returns (address);\n\n function votingEscrow() external view returns (address);\n\n function target() external view returns (address);\n\n function targetVersion() external view returns (uint256);\n\n function feeRatio() external view returns (uint256);\n\n function currencyConverter(address currency) external view returns (address);\n\n function gauges(address nftContract) external view returns (address);\n\n function isGauge(address addr) external view returns (bool);\n\n function fees(address token, uint256 id) external view returns (uint64 timestamp, uint192 amountPerShare);\n\n function lastFeeClaimed(address token, address user) external view returns (uint256);\n\n function feesLength(address token) external view returns (uint256);\n\n function upgradeTarget(address target) external;\n\n function updateCurrencyConverter(address token, address converter) external;\n\n function updateFeeRatio(uint256 feeRatio) external;\n\n function createNFTGauge(address nftContract) external returns (address gauge);\n\n function executePayment(\n address currency,\n address from,\n uint256 amount\n ) external;\n\n function distributeFeesETH() external payable returns (uint256 amountFee);\n\n function distributeFees(address token, uint256 amount) external returns (uint256 amountFee);\n\n function claimFees(address token, uint256 to) external;\n}\n" }, "contracts/libraries/Integers.sol": { "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.15;\n\nlibrary Integers {\n function toInt128(uint256 u) internal pure returns (int128) {\n return int128(int256(u));\n }\n\n function toUint256(int128 i) internal pure returns (uint256) {\n return uint256(uint128(i));\n }\n}\n" }, "contracts/libraries/Tokens.sol": { "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.15;\n\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\nlibrary Tokens {\n using SafeERC20 for IERC20;\n\n function transfer(\n address token,\n address to,\n uint256 amount\n ) internal {\n if (token == address(0)) {\n (bool success, ) = payable(to).call{value: amount}(\"\");\n require(success, \"LEVX: FAILED_TO_TRANSFER_ETH\");\n } else {\n IERC20(token).safeTransfer(to, amount);\n }\n }\n}\n" }, "contracts/NFTGauge.sol": { "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.15;\n\nimport \"./base/WrappedERC721.sol\";\nimport \"./interfaces/INFTGauge.sol\";\nimport \"./interfaces/IGaugeController.sol\";\nimport \"./interfaces/IMinter.sol\";\nimport \"./interfaces/IVotingEscrow.sol\";\nimport \"./interfaces/ICurrencyConverter.sol\";\nimport \"./libraries/Tokens.sol\";\nimport \"./libraries/Math.sol\";\nimport \"./libraries/NFTs.sol\";\n\ncontract NFTGauge is WrappedERC721, INFTGauge {\n struct Snapshot {\n uint64 timestamp;\n uint192 value;\n }\n\n address public override minter;\n address public override controller;\n address public override votingEscrow;\n uint256 public override futureEpochTime;\n\n mapping(uint256 => uint256) public override dividendRatios;\n mapping(address => mapping(uint256 => Snapshot[])) public override dividends; // currency -> tokenId -> Snapshot\n mapping(address => mapping(uint256 => mapping(address => uint256))) public override lastDividendClaimed; // currency -> tokenId -> user -> index\n\n int128 public override period;\n mapping(int128 => uint256) public override periodTimestamp;\n mapping(int128 => uint256) public override integrateInvSupply; // bump epoch when rate() changes\n\n mapping(uint256 => mapping(address => int128)) public override periodOf; // tokenId -> user -> period\n mapping(uint256 => mapping(address => uint256)) public override integrateFraction; // tokenId -> user -> fraction\n\n uint256 public override inflationRate;\n\n bool public override isKilled;\n\n mapping(address => mapping(uint256 => uint256)) public override userWeight;\n mapping(address => uint256) public override userWeightSum;\n\n uint256 internal _interval;\n\n mapping(uint256 => uint256) internal _nonces; // tokenId -> nonce\n mapping(uint256 => mapping(uint256 => mapping(address => Snapshot[]))) internal _points; // tokenId -> nonce -> user -> Snapshot\n mapping(uint256 => mapping(uint256 => Snapshot[])) internal _pointsSum; // tokenId -> nonce -> Snapshot\n Snapshot[] internal _pointsTotal;\n\n function initialize(\n address _nftContract,\n address _tokenURIRenderer,\n address _minter\n ) external override initializer {\n __WrappedERC721_init(_nftContract, _tokenURIRenderer);\n\n minter = _minter;\n address _controller = IMinter(_minter).controller();\n controller = _controller;\n votingEscrow = IGaugeController(_controller).votingEscrow();\n periodTimestamp[0] = block.timestamp;\n inflationRate = IMinter(_minter).rate();\n futureEpochTime = IMinter(_minter).futureEpochTimeWrite();\n _interval = IGaugeController(_controller).interval();\n }\n\n function integrateCheckpoint() external view override returns (uint256) {\n return periodTimestamp[period];\n }\n\n function points(uint256 tokenId, address user) public view override returns (uint256) {\n return _lastValue(_points[tokenId][_nonces[tokenId]][user]);\n }\n\n function pointsAt(\n uint256 tokenId,\n address user,\n uint256 timestamp\n ) public view override returns (uint256) {\n return _getValueAt(_points[tokenId][_nonces[tokenId]][user], timestamp);\n }\n\n function pointsSum(uint256 tokenId) external view override returns (uint256) {\n return _lastValue(_pointsSum[tokenId][_nonces[tokenId]]);\n }\n\n function pointsSumAt(uint256 tokenId, uint256 timestamp) public view override returns (uint256) {\n return _getValueAt(_pointsSum[tokenId][_nonces[tokenId]], timestamp);\n }\n\n function pointsTotal() external view override returns (uint256) {\n return _lastValue(_pointsTotal);\n }\n\n function pointsTotalAt(uint256 timestamp) external view override returns (uint256) {\n return _getValueAt(_pointsTotal, timestamp);\n }\n\n function dividendsLength(address token, uint256 tokenId) external view override returns (uint256) {\n return dividends[token][tokenId].length;\n }\n\n /**\n * @notice Toggle the killed status of the gauge\n */\n function killMe() external override {\n require(msg.sender == controller, \"NFTG: FORBIDDDEN\");\n isKilled = !isKilled;\n }\n\n function _checkpoint() internal returns (int128 _period, uint256 _integrateInvSupply) {\n address _minter = minter;\n address _controller = controller;\n _period = period;\n uint256 _periodTime = periodTimestamp[_period];\n _integrateInvSupply = integrateInvSupply[_period];\n uint256 rate = inflationRate;\n uint256 newRate = rate;\n uint256 prevFutureEpoch = futureEpochTime;\n if (prevFutureEpoch >= _periodTime) {\n futureEpochTime = IMinter(_minter).futureEpochTimeWrite();\n newRate = IMinter(_minter).rate();\n inflationRate = newRate;\n }\n IGaugeController(_controller).checkpointGauge(address(this));\n\n uint256 total = _lastValue(_pointsTotal);\n\n if (isKilled) rate = 0; // Stop distributing inflation as soon as killed\n\n // Update integral of 1/total\n if (block.timestamp > _periodTime) {\n uint256 interval = _interval;\n uint256 prevWeekTime = _periodTime;\n uint256 weekTime = Math.min(((_periodTime + interval) / interval) * interval, block.timestamp);\n for (uint256 i; i < 250; ) {\n uint256 dt = weekTime - prevWeekTime;\n uint256 w = IGaugeController(_controller).gaugeRelativeWeight(\n address(this),\n (prevWeekTime / interval) * interval\n );\n\n if (total > 0) {\n if (prevFutureEpoch >= prevWeekTime && prevFutureEpoch < weekTime) {\n // If we went across one or multiple epochs, apply the rate\n // of the first epoch until it ends, and then the rate of\n // the last epoch.\n // If more than one epoch is crossed - the gauge gets less,\n // but that'd meen it wasn't called for more than 1 year\n _integrateInvSupply += (rate * w * (prevFutureEpoch - prevWeekTime)) / total;\n rate = newRate;\n _integrateInvSupply += (rate * w * (weekTime - prevFutureEpoch)) / total;\n } else {\n _integrateInvSupply += (rate * w * dt) / total;\n }\n }\n\n if (weekTime == block.timestamp) break;\n prevWeekTime = weekTime;\n weekTime = Math.min(weekTime + interval, block.timestamp);\n\n unchecked {\n ++i;\n }\n }\n }\n\n ++_period;\n period = _period;\n periodTimestamp[_period] = block.timestamp;\n integrateInvSupply[_period] = _integrateInvSupply;\n }\n\n /**\n * @notice Checkpoint for a user for a specific token\n * @param tokenId Token Id\n * @param user User address\n */\n function userCheckpoint(uint256 tokenId, address user) public override {\n require(msg.sender == user || user == minter, \"NFTG: FORBIDDEN\");\n (int128 _period, uint256 _integrateInvSupply) = _checkpoint();\n\n // Update user-specific integrals\n int128 userPeriod = periodOf[tokenId][user];\n uint256 oldIntegrateInvSupply = integrateInvSupply[userPeriod];\n uint256 dIntegrate = _integrateInvSupply - oldIntegrateInvSupply;\n if (dIntegrate > 0) {\n uint256 nonce = _nonces[tokenId];\n uint256 sum = _lastValue(_pointsSum[tokenId][nonce]);\n uint256 pt = _lastValue(_points[tokenId][nonce][user]);\n integrateFraction[tokenId][user] += (pt * dIntegrate * 2) / 3 / 1e18; // 67% goes to voters\n if (ownerOf(tokenId) == user) {\n integrateFraction[tokenId][user] += (sum * dIntegrate) / 3 / 1e18; // 33% goes to the owner\n }\n }\n periodOf[tokenId][user] = _period;\n }\n\n /**\n * @notice Mint a wrapped NFT and commit gauge voting to this tokenId\n * @param tokenId Token Id to deposit\n * @param dividendRatio Dividend ratio for the voters in bps (units of 0.01%)\n * @param to The owner of the newly minted wrapped NFT\n * @param _userWeight Weight for a gauge in bps (units of 0.01%). Minimal is 0.01%. Ignored if 0\n */\n function wrap(\n uint256 tokenId,\n uint256 dividendRatio,\n address to,\n uint256 _userWeight\n ) public override {\n require(dividendRatio <= 10000, \"NFTG: INVALID_RATIO\");\n\n dividendRatios[tokenId] = dividendRatio;\n\n _mint(to, tokenId);\n\n vote(tokenId, _userWeight);\n\n emit Wrap(tokenId, to);\n\n NFTs.safeTransferFrom(nftContract, msg.sender, address(this), tokenId);\n }\n\n function unwrap(uint256 tokenId, address to) public override {\n require(ownerOf(tokenId) == msg.sender, \"NFTG: FORBIDDEN\");\n\n dividendRatios[tokenId] = 0;\n\n _burn(tokenId);\n\n uint256 nonce = _nonces[tokenId];\n _updateValueAtNow(_pointsTotal, _lastValue(_pointsTotal) - _lastValue(_pointsSum[tokenId][nonce]));\n _nonces[tokenId] = nonce + 1;\n\n emit Unwrap(tokenId, to);\n\n NFTs.safeTransferFrom(nftContract, address(this), to, tokenId);\n }\n\n function vote(uint256 tokenId, uint256 _userWeight) public override {\n require(_exists(tokenId), \"NFTG: NON_EXISTENT\");\n\n userCheckpoint(tokenId, msg.sender);\n\n uint256 balance = IVotingEscrow(votingEscrow).balanceOf(msg.sender);\n uint256 pointNew = (balance * _userWeight) / 10000;\n uint256 pointOld = points(tokenId, msg.sender);\n\n uint256 nonce = _nonces[tokenId];\n _updateValueAtNow(_points[tokenId][nonce][msg.sender], pointNew);\n _updateValueAtNow(_pointsSum[tokenId][nonce], _lastValue(_pointsSum[tokenId][nonce]) + pointNew - pointOld);\n _updateValueAtNow(_pointsTotal, _lastValue(_pointsTotal) + pointNew - pointOld);\n\n uint256 userWeightOld = userWeight[msg.sender][tokenId];\n uint256 _userWeightSum = userWeightSum[msg.sender] + _userWeight - userWeightOld;\n userWeight[msg.sender][tokenId] = _userWeight;\n userWeightSum[msg.sender] = _userWeightSum;\n\n IGaugeController(controller).voteForGaugeWeights(msg.sender, _userWeightSum);\n\n emit Vote(tokenId, msg.sender, _userWeight);\n }\n\n function claimDividends(address token, uint256 tokenId) external override {\n uint256 amount;\n uint256 _last = lastDividendClaimed[token][tokenId][msg.sender];\n uint256 i;\n while (i < 250) {\n uint256 id = _last + i;\n if (id >= dividends[token][tokenId].length) break;\n\n Snapshot memory dividend = dividends[token][tokenId][id];\n uint256 pt = _getValueAt(_points[tokenId][_nonces[tokenId]][msg.sender], dividend.timestamp);\n if (pt > 0) {\n amount += (pt * uint256(dividend.value)) / 1e18;\n }\n\n unchecked {\n ++i;\n }\n }\n\n require(i > 0, \"NFTG: NO_AMOUNT_TO_CLAIM\");\n lastDividendClaimed[token][tokenId][msg.sender] = _last + i;\n\n emit ClaimDividends(token, tokenId, amount, msg.sender);\n Tokens.transfer(token, msg.sender, amount);\n }\n\n /**\n * @dev `_getValueAt` retrieves the number of tokens at a given time\n * @param snapshots The history of values being queried\n * @param timestamp The block timestamp to retrieve the value at\n * @return The weight at `timestamp`\n */\n function _getValueAt(Snapshot[] storage snapshots, uint256 timestamp) internal view returns (uint256) {\n if (snapshots.length == 0) return 0;\n\n // Shortcut for the actual value\n Snapshot storage last = snapshots[snapshots.length - 1];\n if (timestamp >= last.timestamp) return last.value;\n if (timestamp < snapshots[0].timestamp) return 0;\n\n // Binary search of the value in the array\n uint256 min = 0;\n uint256 max = snapshots.length - 1;\n while (max > min) {\n uint256 mid = (max + min + 1) / 2;\n if (snapshots[mid].timestamp <= timestamp) {\n min = mid;\n } else {\n max = mid - 1;\n }\n }\n return snapshots[min].value;\n }\n\n function _lastValue(Snapshot[] storage snapshots) internal view returns (uint256) {\n uint256 length = snapshots.length;\n return length > 0 ? uint256(snapshots[length - 1].value) : 0;\n }\n\n /**\n * @dev `_updateValueAtNow` is used to update snapshots\n * @param snapshots The history of data being updated\n * @param _value The new number of weight\n */\n function _updateValueAtNow(Snapshot[] storage snapshots, uint256 _value) internal {\n if ((snapshots.length == 0) || (snapshots[snapshots.length - 1].timestamp < block.timestamp)) {\n Snapshot storage newCheckPoint = snapshots.push();\n newCheckPoint.timestamp = uint64(block.timestamp);\n newCheckPoint.value = uint192(_value);\n } else {\n Snapshot storage oldCheckPoint = snapshots[snapshots.length - 1];\n oldCheckPoint.value = uint192(_value);\n }\n }\n\n function _settle(\n uint256 tokenId,\n address currency,\n address to,\n uint256 amount\n ) internal override {\n address _factory = factory;\n address converter = INFTGaugeFactory(_factory).currencyConverter(currency);\n uint256 amountETH = ICurrencyConverter(converter).getAmountETH(amount);\n if (amountETH >= 1e18) {\n IGaugeController(controller).increaseGaugeWeight(amountETH / 1e18);\n }\n\n uint256 fee;\n if (currency == address(0)) {\n fee = INFTGaugeFactory(_factory).distributeFeesETH{value: amount}();\n } else {\n fee = INFTGaugeFactory(_factory).distributeFees(currency, amount);\n }\n\n uint256 dividend;\n uint256 sum = _lastValue(_pointsSum[tokenId][_nonces[tokenId]]);\n if (sum > 0) {\n dividend = ((amount - fee) * dividendRatios[tokenId]) / 10000;\n dividends[currency][tokenId].push(Snapshot(uint64(block.timestamp), uint192((dividend * 1e18) / sum)));\n emit DistributeDividend(currency, tokenId, dividend);\n }\n Tokens.transfer(currency, to, amount - fee - dividend);\n }\n\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal override {\n super._beforeTokenTransfer(from, to, tokenId);\n\n userCheckpoint(tokenId, from);\n }\n}\n" }, "@openzeppelin/contracts/utils/Context.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n" }, "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using Address for address;\n\n function safeTransfer(\n IERC20 token,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(\n IERC20 token,\n address from,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n uint256 newAllowance = token.allowance(address(this), spender) + value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n uint256 newAllowance = oldAllowance - value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) {\n // Return data is optional\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n" }, "@openzeppelin/contracts/token/ERC20/IERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n" }, "@openzeppelin/contracts/utils/Address.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // 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\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n" }, "contracts/base/WrappedERC721.sol": { "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.15;\n\nimport \"@openzeppelin/contracts/security/ReentrancyGuard.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\n\nimport \"../base/ERC721Initializable.sol\";\nimport \"../interfaces/IWrappedERC721.sol\";\nimport \"../interfaces/ITokenURIRenderer.sol\";\nimport \"../interfaces/INFTGaugeFactory.sol\";\nimport \"../libraries/Signature.sol\";\nimport \"../libraries/Tokens.sol\";\nimport \"../libraries/Math.sol\";\n\nabstract contract WrappedERC721 is ERC721Initializable, ReentrancyGuard, IWrappedERC721 {\n using Strings for uint256;\n\n struct Order {\n uint256 price;\n address currency;\n uint64 deadline;\n bool auction;\n }\n\n struct Bid_ {\n uint256 price;\n address bidder;\n uint64 timestamp;\n }\n\n address public override nftContract;\n address public override tokenURIRenderer;\n address public override factory;\n\n mapping(uint256 => mapping(address => Order)) public override sales;\n mapping(uint256 => mapping(address => Bid_)) public override currentBids;\n mapping(uint256 => mapping(address => Order)) public override offers;\n\n function __WrappedERC721_init(address _nftContract, address _tokenURIRenderer) internal initializer {\n nftContract = _nftContract;\n tokenURIRenderer = _tokenURIRenderer;\n factory = msg.sender;\n\n string memory name;\n string memory symbol;\n try IERC721Metadata(_nftContract).name() returns (string memory _name) {\n name = _name;\n } catch {\n name = uint256(uint160(nftContract)).toHexString(20);\n }\n try IERC721Metadata(_nftContract).symbol() returns (string memory _symbol) {\n symbol = string(abi.encodePacked(\"W\", _symbol));\n } catch {\n symbol = \"WNFT\";\n }\n __ERC721_init(string(abi.encodePacked(\"Wrapped \", name)), symbol);\n }\n\n function tokenURI(uint256 tokenId)\n public\n view\n override(ERC721Initializable, IERC721Metadata)\n returns (string memory output)\n {\n require(_exists(tokenId), \"WERC721: TOKEN_NON_EXISTENT\");\n\n return ITokenURIRenderer(tokenURIRenderer).render(nftContract, tokenId);\n }\n\n function listForSale(\n uint256 tokenId,\n uint256 price,\n address currency,\n uint64 deadline,\n bool auction\n ) external override {\n require(block.timestamp < deadline, \"WERC721: INVALID_DEADLINE\");\n require(ownerOf(tokenId) == msg.sender, \"WERC721: FORBIDDEN\");\n require(currency == address(0), \"WERC721: INVALID_CURRENCY\");\n\n sales[tokenId][msg.sender] = Order(price, currency, deadline, auction);\n\n emit ListForSale(tokenId, msg.sender, price, currency, deadline, auction);\n }\n\n function cancelListing(uint256 tokenId) external override {\n require(ownerOf(tokenId) == msg.sender, \"WERC721: FORBIDDEN\");\n\n delete sales[tokenId][msg.sender];\n delete currentBids[tokenId][msg.sender];\n\n emit CancelListing(tokenId, msg.sender);\n }\n\n function buyETH(uint256 tokenId, address owner) external payable override {\n address currency = _buy(tokenId, owner, msg.value);\n require(currency == address(0), \"WERC721: ETH_UNACCEPTABLE\");\n\n _settle(tokenId, address(0), owner, msg.value);\n }\n\n function buy(\n uint256 tokenId,\n address owner,\n uint256 price\n ) external override nonReentrant {\n address currency = _buy(tokenId, owner, price);\n require(currency != address(0), \"WERC721: ONLY_ETH_ACCEPTABLE\");\n\n INFTGaugeFactory(factory).executePayment(currency, msg.sender, price);\n\n _settle(tokenId, currency, owner, price);\n }\n\n function _buy(\n uint256 tokenId,\n address owner,\n uint256 price\n ) internal returns (address currency) {\n Order memory sale = sales[tokenId][owner];\n require(sale.deadline > 0, \"WERC721: NOT_LISTED_FOR_SALE\");\n require(block.timestamp <= sale.deadline, \"WERC721: EXPIRED\");\n require(sale.price == price, \"WERC721: INVALID_PRICE\");\n require(!sale.auction, \"WERC721: BID_REQUIRED\");\n\n _safeTransfer(owner, msg.sender, tokenId, \"0x\");\n\n currency = sale.currency;\n emit Buy(tokenId, owner, msg.sender, price, currency);\n }\n\n function bidETH(uint256 tokenId, address owner) external payable override {\n address currency = _bid(tokenId, owner, msg.value);\n require(currency == address(0), \"WERC721: ETH_UNACCEPTABLE\");\n }\n\n function bid(\n uint256 tokenId,\n address owner,\n uint256 price\n ) external override nonReentrant {\n address currency = _bid(tokenId, owner, price);\n require(currency != address(0), \"WERC721: ONLY_ETH_ACCEPTABLE\");\n\n INFTGaugeFactory(factory).executePayment(currency, msg.sender, price);\n }\n\n function _bid(\n uint256 tokenId,\n address owner,\n uint256 price\n ) internal returns (address currency) {\n Order memory sale = sales[tokenId][owner];\n uint256 deadline = sale.deadline;\n require(deadline > 0, \"WERC721: NOT_LISTED_FOR_SALE\");\n require(sale.auction, \"WERC721: NOT_BIDDABLE\");\n\n curren