From ec63535c148e12526b6b7aa439e4a19545bc51d2 Mon Sep 17 00:00:00 2001 From: echo Date: Mon, 23 Sep 2024 14:22:26 +0800 Subject: [PATCH] Audit part2 (#27) * Audit part2 * clean * fix tests * deploy & verify * fix ci * add log and inf * fix loss of precision in votes * fmt * verify * deposit nft metadata * fix * fix * defined collator sorting order * redeploy * fix ci * fix tests --- Makefile | 3 +- README.md | 9 +- foundry.toml | 8 +- ipfs/deposit/metadata.json | 5 + script/Deploy.s.sol | 47 ++++++- script/Migrate.s.sol | 26 ++++ src/collator/CollatorSet.sol | 24 ++-- src/collator/CollatorStakingHub.sol | 153 ++++++++++++++------- src/collator/CollatorStakingHubStorage.sol | 8 +- src/collator/NominationPool.sol | 10 +- src/deposit/Deposit.sol | 2 +- test/collator/CollatorSet.t.sol | 4 +- test/collator/CollatorStakingHub.t.sol | 83 +++++++---- test/collator/NominationPool.t.sol | 15 +- test/deposit/Deposit.t.sol | 2 +- verify/CollatorStakingHub.json | 2 +- verify/Deposit.json | 2 +- verify/NominationPool.json | 1 + 18 files changed, 273 insertions(+), 131 deletions(-) create mode 100644 ipfs/deposit/metadata.json create mode 100644 script/Migrate.s.sol create mode 100644 verify/NominationPool.json diff --git a/Makefile b/Makefile index 4d8327b..a235d74 100644 --- a/Makefile +++ b/Makefile @@ -8,7 +8,8 @@ fmt :; @forge fmt clean :; @forge clean test :; @forge test dry-run:; @forge script script/Deploy.s.sol:DeployScript -deploy :; @forge script script/Deploy.s.sol:DeployScript --broadcast --verify +deploy :; @forge script script/Deploy.s.sol:DeployScript --broadcast --verify --verifier blockscout +migrate:; @forge script script/Migrate.s.sol:MigrateScript --broadcast --verify --verifier blockscout sync :; @git submodule update --recursive diff --git a/README.md b/README.md index f10f158..3966951 100644 --- a/README.md +++ b/README.md @@ -2,12 +2,9 @@ ## Deployments ```sh - Depoist: 0x7FAcDaFB282028E4B3264fB08cd633A9142514df - Depoist_Logic: 0x545391AA3cd0f8795000D790dE2734822c255305 - gRING: 0x87BD07263D0Ed5687407B80FEB16F2E32C2BA44f - gRING_Logic: 0x6d275b13bD83B08BF203155AeC1319FCC81d83b9 - Hub: 0x279a1aaDb6eC9d213350f95C3Da1A9580FB3326B - Hub_Logic: 0xA6331C23f12c8Fb19ED427e94044156D45A432AF + Depoist: 0x46275d29113f065c2aac262f34C7a3d8a8B7377D + gRING: 0xdafa555e2785DC8834F4Ea9D1ED88B6049142999 + Hub: 0xa4fFAC7A5Da311D724eD47393848f694Baee7930 ``` diff --git a/foundry.toml b/foundry.toml index 8640fb8..27a4286 100644 --- a/foundry.toml +++ b/foundry.toml @@ -2,7 +2,7 @@ src = "src" out = "out" libs = ["lib"] -sender = "0x0f14341A7f464320319025540E8Fe48Ad0fe5aec" +sender = "0x5d3c814F82Ef2b22101635f8C6A3e7C8E09E7DD6" force = true ffi = true ast = true @@ -15,13 +15,15 @@ bytecode_hash = "ipfs" extra_output = ["storageLayout"] extra_output_files = ["metadata"] fs_permissions = [{ access = "read", path = "out" }] -eth_rpc_url = "https://koi-rpc.darwinia.network" -etherscan_api_key = "xxx" +# eth_rpc_url = "https://rpc.darwinia.network" +# etherscan_api_key = "xxx" [rpc_endpoints] koi = "https://koi-rpc.darwinia.network" crab = "https://crab-rpc.darwinia.network" +darwinia = "https://rpc.darwinia.network" [etherscan] koi = { key = "xxx", url = "https://koi-scan.darwinia.network/api", chain = 701 } crab = { key = "xxx", url = "https://crab-scan.darwinia.network/api", chain = 44 } +darwinia = { key = "xxx", url = "https://explorer.darwinia.network/api", chain = 46 } diff --git a/ipfs/deposit/metadata.json b/ipfs/deposit/metadata.json new file mode 100644 index 0000000..95a77d2 --- /dev/null +++ b/ipfs/deposit/metadata.json @@ -0,0 +1,5 @@ +{ + "name": "Deposit NFT", + "description": "Deposit NFT is generated through Deposit contract collateralized RING, It is a voucher for Deposited RING.", + "image": "ipfs://bafybeih57kauz6npkbafh2x3cv3hyljcakdccuckb4huwnwxxxrtqr5pqe" +} diff --git a/script/Deploy.s.sol b/script/Deploy.s.sol index 13967ef..1c5dee1 100644 --- a/script/Deploy.s.sol +++ b/script/Deploy.s.sol @@ -11,10 +11,42 @@ import {Deposit} from "../src/deposit/Deposit.sol"; import {GovernanceRing} from "../src/governance/GovernanceRing.sol"; contract DeployScript is Script { - address deployer = 0x0f14341A7f464320319025540E8Fe48Ad0fe5aec; - address deposit = 0x7FAcDaFB282028E4B3264fB08cd633A9142514df; - address gRING = 0x87BD07263D0Ed5687407B80FEB16F2E32C2BA44f; - address hub = 0x279a1aaDb6eC9d213350f95C3Da1A9580FB3326B; + address deployer = 0x5d3c814F82Ef2b22101635f8C6A3e7C8E09E7DD6; + address deposit = 0x46275d29113f065c2aac262f34C7a3d8a8B7377D; + address gRING = 0xdafa555e2785DC8834F4Ea9D1ED88B6049142999; + address hub = 0xa4fFAC7A5Da311D724eD47393848f694Baee7930; + + struct Settings { + string depositName; + string depositSymbol; + string gringName; + string gringSymbol; + } + + function getSettings(uint256 chainId) public pure returns (Settings memory) { + if (chainId == 701) { + return Settings({ + depositName: "KRING Deposit NFT", + depositSymbol: "KDPS", + gringName: "Governance KRING", + gringSymbol: "gKRING" + }); + } else if (chainId == 44) { + return Settings({ + depositName: "CRAB Deposit NFT", + depositSymbol: "CDPS", + gringName: "Governance CRAB", + gringSymbol: "gCRAB" + }); + } else if (chainId == 46) { + return Settings({ + depositName: "RING Deposit NFT", + depositSymbol: "RDPS", + gringName: "Governance RING", + gringSymbol: "gRING" + }); + } + } function setUp() public {} @@ -23,8 +55,11 @@ contract DeployScript is Script { require(msg.sender == deployer, "!deployer"); + safeconsole.log("Chain Id: ", block.chainid); + Settings memory s = getSettings(block.chainid); + address deposit_PROXY = Upgrades.deployTransparentProxy( - "Deposit.sol:Deposit", deployer, abi.encodeCall(Deposit.initialize, ("RING Deposit NFT", "RDPS")) + "Deposit.sol:Deposit", deployer, abi.encodeCall(Deposit.initialize, (s.depositName, s.depositSymbol)) ); safeconsole.log("Depoist: ", deposit_PROXY); safeconsole.log("Depoist_Logic: ", Upgrades.getImplementationAddress(deposit_PROXY)); @@ -32,7 +67,7 @@ contract DeployScript is Script { address gRING_PROXY = Upgrades.deployTransparentProxy( "GovernanceRing.sol:GovernanceRing", deployer, - abi.encodeCall(GovernanceRing.initialize, (deployer, hub, deposit, "Governance RING", "gRING")) + abi.encodeCall(GovernanceRing.initialize, (deployer, hub, deposit, s.gringName, s.gringSymbol)) ); safeconsole.log("gRING: ", gRING_PROXY); safeconsole.log("gRING_Logic: ", Upgrades.getImplementationAddress(gRING_PROXY)); diff --git a/script/Migrate.s.sol b/script/Migrate.s.sol new file mode 100644 index 0000000..c4c4bc1 --- /dev/null +++ b/script/Migrate.s.sol @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import {Script} from "forge-std/Script.sol"; +import {safeconsole} from "forge-std/safeconsole.sol"; +import {Upgrades} from "openzeppelin-foundry-upgrades/Upgrades.sol"; +import {Core} from "openzeppelin-foundry-upgrades/internal/Core.sol"; + +import {CollatorStakingHub} from "../src/collator/CollatorStakingHub.sol"; +import {Deposit} from "../src/deposit/Deposit.sol"; + +contract MigrateScript is Script { + address proxy = 0xDeC9cD45e921F2AedE72f694743265af37d47Fa7; + + function run() public { + vm.startBroadcast(); + + // address logic = address(new CollatorStakingHub()); + address logic = address(new Deposit()); + // Core.upgradeProxyTo(proxy, logic, ""); + // require(logic == Upgrades.getImplementationAddress(proxy)); + safeconsole.log("logic: ", logic); + + vm.stopBroadcast(); + } +} diff --git a/src/collator/CollatorSet.sol b/src/collator/CollatorSet.sol index 5034383..141f34d 100644 --- a/src/collator/CollatorSet.sol +++ b/src/collator/CollatorSet.sol @@ -5,8 +5,8 @@ import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./CollatorStakingHubStorage.sol"; abstract contract CollatorSet is Initializable, CollatorStakingHubStorage { - address internal constant HEAD = address(0x1); - address internal constant TAIL = address(0x2); + address internal constant HEAD = address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF); + address internal constant TAIL = address(0x1); event AddCollator(address indexed cur, uint256 votes, address prev); event RemoveCollator(address indexed cur, address prev); @@ -47,7 +47,7 @@ abstract contract CollatorSet is Initializable, CollatorStakingHubStorage { require(collators[cur] == address(0), "!cur"); // Next collator must in the list. require(next != address(0), "!prev"); - require(_verifyIndex(prev, votes, next), "!votes"); + require(_verifyIndex(prev, votes, next, cur), "!votes"); collators[cur] = next; collators[prev] = cur; votesOf[cur] = votes; @@ -66,14 +66,6 @@ abstract contract CollatorSet is Initializable, CollatorStakingHubStorage { emit RemoveCollator(cur, prev); } - function _increaseVotes(address cur, uint256 votes, address oldPrev, address newPrev) internal { - _updateVotes(cur, votesOf[cur] + votes, oldPrev, newPrev); - } - - function _reduceVotes(address cur, uint256 votes, address oldPrev, address newPrev) internal { - _updateVotes(cur, votesOf[cur] - votes, oldPrev, newPrev); - } - function _updateVotes(address cur, uint256 newVotes, address oldPrev, address newPrev) internal { require(_isValid(cur), "!valid"); require(collators[cur] != address(0), "!cur"); @@ -81,7 +73,7 @@ abstract contract CollatorSet is Initializable, CollatorStakingHubStorage { require(collators[newPrev] != address(0), "!newPrev"); if (oldPrev == newPrev) { require(_isPrevCollator(cur, oldPrev), "!oldPrev2"); - require(_verifyIndex(newPrev, newVotes, collators[cur]), "!votes"); + require(_verifyIndex(newPrev, newVotes, collators[cur], cur), "!votes"); votesOf[cur] = newVotes; } else { _removeCollator(cur, oldPrev); @@ -90,9 +82,11 @@ abstract contract CollatorSet is Initializable, CollatorStakingHubStorage { emit UpdateCollator(cur, newVotes, oldPrev, newPrev); } - // prev >= cur >= next - function _verifyIndex(address prev, uint256 newValue, address next) internal view returns (bool) { - return votesOf[prev] >= newValue && newValue >= votesOf[next]; + // 1. votes(prev) >= votes(cur) >= votes(next) + // 2. addr(prev) > addr(cur) > addr(next) + function _verifyIndex(address prev, uint256 newValue, address next, address cur) internal view returns (bool) { + return ((votesOf[prev] > newValue) || (votesOf[prev] == newValue && prev > cur)) + && ((newValue > votesOf[next]) || (newValue == votesOf[next] && cur > next)); } function _isPrevCollator(address c, address prev) internal view returns (bool) { diff --git a/src/collator/CollatorStakingHub.sol b/src/collator/CollatorStakingHub.sol index 2b03567..17451b8 100644 --- a/src/collator/CollatorStakingHub.sol +++ b/src/collator/CollatorStakingHub.sol @@ -28,8 +28,9 @@ contract CollatorStakingHub is ReentrancyGuardUpgradeable, CollatorSet { event Staked(address indexed pool, address collator, address account, uint256 assets); event Unstaked(address indexed pool, address collator, address account, uint256 assets); - event NominationPoolCreated(address indexed stRING, address collator, address prev); + event NominationPoolCreated(address indexed pool, address collator); event CommissionUpdated(address indexed collator, uint256 commission); + event RewardDistributed(address indexed collator, uint256 reward); modifier onlySystem() { require(msg.sender == SYSTEM_PALLET, "!system"); @@ -48,28 +49,79 @@ contract CollatorStakingHub is ReentrancyGuardUpgradeable, CollatorSet { _disableInitializers(); } - function createNominationPool(address prev, uint256 commission) public returns (address pool) { + /// 1. Create nomination pool + /// 2. Join collator set + /// 3. Set commsission + function createAndCollate(address prev, uint256 commission) public returns (address pool) { + address collator = msg.sender; + pool = createNominationPool(); + _updateCommissionAndLock(collator, commission); + _addCollator(collator, 0, prev); + } + + /// 1. Join collator set + /// 2. Set commission + function collate(address prev, uint256 commission) public { + address collator = msg.sender; + require(poolOf[collator] != address(0), "!pool"); + _updateCommissionAndLock(collator, commission); + _addCollator(collator, _assetsToVotes(commission, stakedOf(collator)), prev); + } + + /// 1. Exit collator set + /// 2. Clear commission + function stopCollation(address prev) public { + address collator = msg.sender; + require(poolOf[collator] != address(0), "!pool"); + _setCommisson(collator, 0); + _removeCollator(collator, prev); + } + + function createNominationPool() public returns (address pool) { address collator = msg.sender; require(poolOf[collator] == address(0), "created"); - uint256 index = count; bytes memory bytecode = type(NominationPool).creationCode; - bytes memory initCode = bytes.concat(bytecode, abi.encode(collator, index)); + bytes memory initCode = bytes.concat(bytecode, abi.encode(collator)); assembly { pool := create2(0, add(initCode, 32), mload(initCode), 0) } require(pool != address(0), "!create2"); - poolOf[collator] = pool; - _addCollator(collator, 0, prev); - _collate(collator, commission); - emit NominationPoolCreated(pool, collator, prev); + emit NominationPoolCreated(pool, collator); + } + + function updateCommission(uint256 commission, address oldPrev, address newPrev) public nonReentrant { + address collator = msg.sender; + require(poolOf[collator] != address(0), "!pool"); + require(commissionOf[collator] != commission, "same"); + _removeCollator(collator, oldPrev); + _updateCommissionAndLock(collator, commission); + _addCollator(collator, _assetsToVotes(commission, stakedOf(collator)), newPrev); + } + + function _updateCommissionAndLock(address collator, uint256 commission) internal { + require(commissionLocks[collator] < block.timestamp, "!locked"); + _setCommisson(collator, commission); + commissionLocks[collator] = COMMISSION_LOCK_PERIOD + block.timestamp; + } + + function _setCommisson(address collator, uint256 commission) internal { + require(commission <= COMMISSION_BASE, "!commission"); + commissionOf[collator] = commission; + emit CommissionUpdated(collator, commission); + } + + function _updateCollatorVotes(address collator, address oldPrev, address newPrev) internal { + uint256 assets = stakedOf(collator); + uint256 newVotes = _assetsToVotes(commissionOf[collator], assets); + _updateVotes(collator, newVotes, oldPrev, newPrev); } function _stake(address collator, address account, uint256 assets) internal { stakingLocks[collator][account] = STAKING_LOCK_PERIOD + block.timestamp; address pool = poolOf[collator]; - require(pool != address(0), "!collator"); + require(pool != address(0), "!pool"); INominationPool(pool).stake(account, assets); IGRING(gRING).mint(account, assets); emit Staked(pool, collator, account, assets); @@ -78,7 +130,7 @@ contract CollatorStakingHub is ReentrancyGuardUpgradeable, CollatorSet { function _unstake(address collator, address account, uint256 assets) internal { require(stakingLocks[collator][account] < block.timestamp, "!locked"); address pool = poolOf[collator]; - require(pool != address(0), "!collator"); + require(pool != address(0), "!pool"); IGRING(gRING).burn(account, assets); INominationPool(pool).withdraw(account, assets); emit Unstaked(pool, collator, account, assets); @@ -92,49 +144,55 @@ contract CollatorStakingHub is ReentrancyGuardUpgradeable, CollatorSet { function stakeRING(address collator, address oldPrev, address newPrev) public payable nonReentrant { _stake(collator, msg.sender, msg.value); - _increaseVotes(collator, _assetsToVotes(commissionOf[collator], msg.value), oldPrev, newPrev); + _updateCollatorVotes(collator, oldPrev, newPrev); stakedRINGOf[collator][msg.sender] += msg.value; } function unstakeRING(address collator, uint256 assets, address oldPrev, address newPrev) public nonReentrant { _unstake(collator, msg.sender, assets); - payable(msg.sender).sendValue(assets); - _reduceVotes(collator, _assetsToVotes(commissionOf[collator], assets), oldPrev, newPrev); + _updateCollatorVotes(collator, oldPrev, newPrev); stakedRINGOf[collator][msg.sender] -= assets; + payable(msg.sender).sendValue(assets); } - function stakeDeposit(address collator, uint256 depositId, address oldPrev, address newPrev) public nonReentrant { + function stakeDeposits(address collator, uint256[] calldata depositIds, address oldPrev, address newPrev) + public + nonReentrant + { + require(depositIds.length > 0, "!len"); address account = msg.sender; - IDeposit(DEPOSIT).transferFrom(account, address(this), depositId); - uint256 assets = IDeposit(DEPOSIT).assetsOf(depositId); - depositInfos[depositId] = DepositInfo(account, assets, collator); - - _stake(collator, account, assets); - _increaseVotes(collator, _assetsToVotes(commissionOf[collator], assets), oldPrev, newPrev); - require(_stakedDeposits[account].add(depositId), "!add"); + uint256 totalAssets; + for (uint256 i = 0; i < depositIds.length; i++) { + uint256 depositId = depositIds[i]; + IDeposit(DEPOSIT).transferFrom(account, address(this), depositId); + uint256 assets = IDeposit(DEPOSIT).assetsOf(depositId); + depositInfos[depositId] = DepositInfo(account, assets, collator); + require(_stakedDeposits[account].add(depositId), "!add"); + totalAssets += assets; + } + _stake(collator, account, totalAssets); + _updateCollatorVotes(collator, oldPrev, newPrev); } - function unstakeDeposit(uint256 depositId, address oldPrev, address newPrev) public nonReentrant { + function unstakeDeposits(address collator, uint256[] calldata depositIds, address oldPrev, address newPrev) + public + nonReentrant + { + require(depositIds.length > 0, "!len"); address account = msg.sender; - DepositInfo memory info = depositInfos[depositId]; - require(info.account == account); - IDeposit(DEPOSIT).transferFrom(address(this), account, depositId); - delete depositInfos[depositId]; - - _unstake(info.collator, info.account, info.assets); - _reduceVotes(info.collator, _assetsToVotes(commissionOf[info.collator], info.assets), oldPrev, newPrev); - require(_stakedDeposits[account].remove(depositId), "!remove"); - } - - function collate(uint256 commission, address oldPrev, address newPrev) public nonReentrant { - address collator = msg.sender; - require(poolOf[collator] != address(0), "!collator"); - require(commissionLocks[collator] < block.timestamp, "!locked"); - require(commissionOf[collator] != commission, "same"); - _removeCollator(collator, oldPrev); - _collate(collator, commission); - _addCollator(collator, _assetsToVotes(commission, stakedOf(collator)), newPrev); - commissionLocks[collator] = COMMISSION_LOCK_PERIOD + block.timestamp; + uint256 totalAssets; + for (uint256 i = 0; i < depositIds.length; i++) { + uint256 depositId = depositIds[i]; + DepositInfo memory info = depositInfos[depositId]; + require(info.account == account, "!account"); + require(info.collator == collator, "!collator"); + IDeposit(DEPOSIT).transferFrom(address(this), account, depositId); + require(_stakedDeposits[account].remove(depositId), "!remove"); + delete depositInfos[depositId]; + totalAssets += info.assets; + } + _unstake(collator, account, totalAssets); + _updateCollatorVotes(collator, oldPrev, newPrev); } /// @dev Distribute collator reward from Staking Pallet Account. @@ -143,27 +201,26 @@ contract CollatorStakingHub is ReentrancyGuardUpgradeable, CollatorSet { /// @param collator The collator address to distribute reward. function distributeReward(address collator) public payable onlySystem nonReentrant { address pool = poolOf[collator]; - require(pool != address(0), "!collator"); + require(pool != address(0), "!pool"); uint256 rewards = msg.value; uint256 commission_ = rewards * commissionOf[collator] / COMMISSION_BASE; payable(collator).sendValue(commission_); INominationPool(pool).notifyRewardAmount{value: rewards - commission_}(); + emit RewardDistributed(collator, rewards); } function stakedOf(address collator) public view returns (uint256) { address pool = poolOf[collator]; - require(pool != address(0), "!collator"); + require(pool != address(0), "!pool"); return INominationPool(pool).totalSupply(); } - function _collate(address collator, uint256 commission) internal { - require(commission <= COMMISSION_BASE, "!commission"); - commissionOf[collator] = commission; - emit CommissionUpdated(collator, commission); + function assetsToVotes(uint256 commission, uint256 assets) public pure returns (uint256) { + return _assetsToVotes(commission, assets); } function _assetsToVotes(uint256 commission, uint256 assets) internal pure returns (uint256) { - return assets * (100 - commission) / 100; + return assets * (COMMISSION_BASE - commission) / COMMISSION_BASE; } function stakedDepositsOf(address account) public view returns (uint256[] memory) { diff --git a/src/collator/CollatorStakingHubStorage.sol b/src/collator/CollatorStakingHubStorage.sol index a4c850e..dcc3e8e 100644 --- a/src/collator/CollatorStakingHubStorage.sol +++ b/src/collator/CollatorStakingHubStorage.sol @@ -5,9 +5,9 @@ import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; contract CollatorStakingHubStorage { // ---------------------- CollatorSetStorage ---------------------------- - // collator count; + // collator count uint256 public count; - // ordered collators. + // ordered collators mapping(address => address) public collators; // collator => votes = staked_ring * (1 - commission) mapping(address => uint256) public votesOf; @@ -15,7 +15,7 @@ contract CollatorStakingHubStorage { // ---------------------- CollatorStakingHubStorage --------------------- // Governance RING address public gRING; - // Deposit NFT. + // Deposit NFT address public DEPOSIT; // collator => nomination pool mapping(address => address) public poolOf; @@ -25,7 +25,7 @@ contract CollatorStakingHubStorage { mapping(address => mapping(address => uint256)) public stakingLocks; // collator => commissonLockTime mapping(address => uint256) public commissionLocks; - // user => collator => staked ring + // collator => user => staked ring mapping(address => mapping(address => uint256)) public stakedRINGOf; // user => staked depositIds mapping(address => EnumerableSet.UintSet) internal _stakedDeposits; diff --git a/src/collator/NominationPool.sol b/src/collator/NominationPool.sol index 1b92258..b2031e2 100644 --- a/src/collator/NominationPool.sol +++ b/src/collator/NominationPool.sol @@ -9,7 +9,6 @@ contract NominationPool { /* ========== STATE VARIABLES ========== */ - uint256 public id; address public hub; address public collator; uint256 public periodFinish = 0; @@ -31,10 +30,9 @@ contract NominationPool { /* ========== CONSTRUCTOR ========== */ - constructor(address collator_, uint256 index) { + constructor(address collator_) { hub = msg.sender; collator = collator_; - id = index; } /* ========== VIEWS ========== */ @@ -56,16 +54,10 @@ contract NominationPool { return rewardPerTokenStored; } return rewardPerTokenStored + (lastTimeRewardApplicable() - lastUpdateTime) * rewardRate * 1e18 / _totalSupply; - // return rewardPerTokenStored.add( - // lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(_totalSupply) - // ); } function earned(address account) public view returns (uint256) { return _balances[account] * (rewardPerToken() - userRewardPerTokenPaid[account]) / 1e18 + rewards[account]; - // return _balances[account].mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add( - // rewards[account] - // ); } function getRewardForDuration() external view returns (uint256) { diff --git a/src/deposit/Deposit.sol b/src/deposit/Deposit.sol index 7151d9f..9761f13 100644 --- a/src/deposit/Deposit.sol +++ b/src/deposit/Deposit.sol @@ -230,7 +230,7 @@ contract Deposit is override(ERC721Upgradeable, ERC721URIStorageUpgradeable) returns (string memory) { - return "ipfs://bafybeih57kauz6npkbafh2x3cv3hyljcakdccuckb4huwnwxxxrtqr5pqe"; + return "ipfs://bafybeifyt273t4ns4f5c4u57uvtbbh5cuv5uxtpt6x3kn32mfecgltjeh4"; } function supportsInterface(bytes4 interfaceId) diff --git a/test/collator/CollatorSet.t.sol b/test/collator/CollatorSet.t.sol index 0d78666..699d511 100644 --- a/test/collator/CollatorSet.t.sol +++ b/test/collator/CollatorSet.t.sol @@ -113,11 +113,11 @@ contract CollatorSetTest is Test, CollatorSet { } function perform_increase(address cur, uint256 votes, address oldPrev, address newPrev) public { - _increaseVotes(cur, votes, oldPrev, newPrev); + _updateVotes(cur, votesOf[cur] + votes, oldPrev, newPrev); } function perform_reduce(address cur, uint256 votes, address oldPrev, address newPrev) public { - _reduceVotes(cur, votes, oldPrev, newPrev); + _updateVotes(cur, votesOf[cur] - votes, oldPrev, newPrev); } function checkCount(uint256 cnt) public view { diff --git a/test/collator/CollatorStakingHub.t.sol b/test/collator/CollatorStakingHub.t.sol index 712ecd3..e4eb322 100644 --- a/test/collator/CollatorStakingHub.t.sol +++ b/test/collator/CollatorStakingHub.t.sol @@ -14,8 +14,8 @@ contract CollatorStakingHubTest is Test { address deposit; CollatorStakingHub hub; - address HEAD = address(0x1); - address TAIL = address(0x2); + address internal constant HEAD = address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF); + address internal constant TAIL = address(0x1); address alith = address(0x0a); address baltathar = address(0x0b); address charleth = address(0xc); @@ -45,50 +45,49 @@ contract CollatorStakingHubTest is Test { assertEq(deposit, hub.DEPOSIT()); } - function test_createNominationPool() public { + function test_createAndCollate() public { vm.prank(alith); - address a = hub.createNominationPool(HEAD, 1); - assertEq(NominationPool(a).id(), 0); + address a = hub.createAndCollate(HEAD, 1); assertEq(NominationPool(a).hub(), address(hub)); assertEq(NominationPool(a).collator(), alith); vm.prank(baltathar); - address b = hub.createNominationPool(HEAD, 2); - assertEq(NominationPool(b).id(), 1); + address b = hub.createAndCollate(HEAD, 2); assertEq(NominationPool(b).hub(), address(hub)); assertEq(NominationPool(b).collator(), baltathar); vm.prank(charleth); - address c = hub.createNominationPool(baltathar, 3); - assertEq(NominationPool(c).id(), 2); + address c = hub.createAndCollate(HEAD, 3); assertEq(NominationPool(c).hub(), address(hub)); assertEq(NominationPool(c).collator(), charleth); - assertEq(hub.collators(HEAD), baltathar); - assertEq(hub.collators(baltathar), charleth); - assertEq(hub.collators(charleth), alith); + assertEq(hub.collators(HEAD), charleth); + assertEq(hub.collators(charleth), baltathar); + assertEq(hub.collators(baltathar), alith); assertEq(hub.collators(alith), TAIL); assertEq(hub.stakedOf(alith), 0); assertEq(hub.stakedOf(baltathar), 0); assertEq(hub.stakedOf(charleth), 0); } - function test_collect() public { + function test_updateCommission() public { vm.prank(alith); - address a = hub.createNominationPool(HEAD, 1); + address a = hub.createAndCollate(HEAD, 1); + + vm.warp(block.timestamp + hub.COMMISSION_LOCK_PERIOD() + 1); vm.prank(alith); vm.expectRevert(bytes("same")); - hub.collate(1, HEAD, HEAD); + hub.updateCommission(1, HEAD, HEAD); vm.prank(alith); - hub.collate(2, HEAD, HEAD); + hub.updateCommission(2, HEAD, HEAD); assertEq(hub.commissionOf(alith), 2); vm.prank(alith); vm.expectRevert("!locked"); - hub.collate(3, HEAD, HEAD); + hub.updateCommission(3, HEAD, HEAD); vm.warp(block.timestamp + hub.COMMISSION_LOCK_PERIOD() + 1); vm.prank(alith); - hub.collate(3, HEAD, HEAD); + hub.updateCommission(3, HEAD, HEAD); assertEq(hub.commissionOf(alith), 3); } @@ -96,7 +95,7 @@ contract CollatorStakingHubTest is Test { uint256 stake = 1 ether; vm.prank(alith); uint256 commissoin = 1; - address a = hub.createNominationPool(HEAD, commissoin); + address a = hub.createAndCollate(HEAD, commissoin); vm.deal(alice, stake); vm.prank(alice); hub.stakeRING{value: stake}(alith, HEAD, HEAD); @@ -111,7 +110,7 @@ contract CollatorStakingHubTest is Test { uint256 stake = 1 ether; uint256 commissoin = 1; vm.prank(alith); - address a = hub.createNominationPool(HEAD, commissoin); + address a = hub.createAndCollate(HEAD, commissoin); vm.deal(alice, stake); vm.prank(alice); @@ -134,7 +133,7 @@ contract CollatorStakingHubTest is Test { uint256 stake = 1 ether; uint256 commissoin = 1; vm.prank(alith); - address a = hub.createNominationPool(HEAD, commissoin); + address a = hub.createAndCollate(HEAD, commissoin); vm.deal(alice, stake); vm.prank(alice); @@ -158,12 +157,14 @@ contract CollatorStakingHubTest is Test { uint256 commissoin = 1; vm.prank(alith); - address a = hub.createNominationPool(HEAD, commissoin); + address a = hub.createAndCollate(HEAD, commissoin); vm.prank(alice); Deposit(deposit).approve(address(hub), id); vm.prank(alice); - hub.stakeDeposit(alith, id, HEAD, HEAD); + uint256[] memory ids = new uint256[](1); + ids[0] = id; + hub.stakeDeposits(alith, ids, HEAD, HEAD); assertEq(hub.stakingLocks(alith, alice), hub.STAKING_LOCK_PERIOD() + block.timestamp); (address account, uint256 assets, address collator) = hub.depositInfos(id); assertEq(account, alice); @@ -189,17 +190,19 @@ contract CollatorStakingHubTest is Test { uint256 commissoin = 1; vm.prank(alith); - address a = hub.createNominationPool(HEAD, commissoin); + address a = hub.createAndCollate(HEAD, commissoin); vm.prank(alice); Deposit(deposit).approve(address(hub), id); vm.prank(alice); - hub.stakeDeposit(alith, id, HEAD, HEAD); + uint256[] memory ids = new uint256[](1); + ids[0] = id; + hub.stakeDeposits(alith, ids, HEAD, HEAD); vm.warp(block.timestamp + hub.STAKING_LOCK_PERIOD() + 1); vm.prank(alice); - hub.unstakeDeposit(id, HEAD, HEAD); + hub.unstakeDeposits(alith, ids, HEAD, HEAD); (address account, uint256 assets, address collator) = hub.depositInfos(id); assertEq(account, address(0)); @@ -214,6 +217,34 @@ contract CollatorStakingHubTest is Test { assertEq(hub.stakedOf(alith), 0); assertEq(IERC20(gring).balanceOf(alice), 0); } + + function test_lossOfPrecision() public { + uint256 stake = 1; + uint256 total = 3; + uint256 commissoin = 30; + vm.prank(alith); + address a = hub.createAndCollate(HEAD, commissoin); + + vm.deal(alice, total); + vm.prank(alice); + hub.stakeRING{value: stake}(alith, HEAD, HEAD); + assertEq(hub.votesOf(alith), 0); + + vm.prank(alice); + hub.stakeRING{value: stake}(alith, HEAD, HEAD); + assertEq(hub.votesOf(alith), 1); + + vm.prank(alice); + hub.stakeRING{value: stake}(alith, HEAD, HEAD); + assertEq(hub.votesOf(alith), 2); + + vm.warp(block.timestamp + hub.STAKING_LOCK_PERIOD() + 1); + + vm.prank(alice); + hub.unstakeRING(alith, total, HEAD, HEAD); + assertEq(hub.stakedOf(alith), 0); + assertEq(hub.votesOf(alith), 0); + } } contract GRINGMock is ERC20 { diff --git a/test/collator/NominationPool.t.sol b/test/collator/NominationPool.t.sol index e3b451f..7cff94f 100644 --- a/test/collator/NominationPool.t.sol +++ b/test/collator/NominationPool.t.sol @@ -3,6 +3,8 @@ pragma solidity ^0.8.0; import "forge-std/Test.sol"; +import {safeconsole} from "forge-std/safeconsole.sol"; + import "../../src/collator/NominationPool.sol"; contract NominationPoolTest is Test { @@ -16,7 +18,7 @@ contract NominationPoolTest is Test { address bob = address(new Guy()); function setUp() public { - pool = new NominationPool(self, 0); + pool = new NominationPool(self); assertEq(pool.rewardsDuration(), REWARDS_DURATION); } @@ -27,13 +29,12 @@ contract NominationPoolTest is Test { assertEq(endTime, startTime + REWARDS_DURATION); } - function invariant_hub() public view { - assertEq(pool.hub(), self); - } + // function invariant_hub() public view { + // assertEq(pool.hub(), self); + // } function test_constructor() public view { assertEq(pool.totalSupply(), 0); - assertEq(pool.id(), 0); assertEq(pool.hub(), self); assertEq(pool.collator(), self); } @@ -58,7 +59,7 @@ contract NominationPoolTest is Test { function test_notifyRewardAmount_half() public { start(); - vm.warp((endTime - startTime) / 2 + 1); + vm.warp(startTime + (endTime - startTime) / 2); pool.stake(alice, 2 ether); uint256 stakeStartTime = pool.lastUpdateTime(); @@ -81,7 +82,7 @@ contract NominationPoolTest is Test { start(); - vm.warp((endTime - startTime) / 2 + 1); + vm.warp(startTime + (endTime - startTime) / 2); pool.stake(bob, 2 ether); diff --git a/test/deposit/Deposit.t.sol b/test/deposit/Deposit.t.sol index 928db01..f114d6e 100644 --- a/test/deposit/Deposit.t.sol +++ b/test/deposit/Deposit.t.sol @@ -39,7 +39,7 @@ contract DepositTest is Test, ERC721Holder { assertEq(IERC721(deposit).balanceOf(self), 1); assertEq(IERC721(deposit).ownerOf(id), self); assertEq( - IERC721Metadata(deposit).tokenURI(id), "ipfs://bafybeih57kauz6npkbafh2x3cv3hyljcakdccuckb4huwnwxxxrtqr5pqe" + IERC721Metadata(deposit).tokenURI(id), "ipfs://bafybeifyt273t4ns4f5c4u57uvtbbh5cuv5uxtpt6x3kn32mfecgltjeh4" ); assertEq(IERC721Enumerable(deposit).tokenOfOwnerByIndex(self, 0), id); assertEq(IERC721Enumerable(deposit).tokenByIndex(0), id); diff --git a/verify/CollatorStakingHub.json b/verify/CollatorStakingHub.json index 3f7da0f..eec72ed 100644 --- a/verify/CollatorStakingHub.json +++ b/verify/CollatorStakingHub.json @@ -1 +1 @@ -{"language":"Solidity","sources":{"src/collator/CollatorStakingHub.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.20;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@openzeppelin/contracts/utils/Address.sol\";\nimport \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\nimport \"@openzeppelin/contracts/token/ERC721/IERC721.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol\";\nimport \"./interfaces/INominationPool.sol\";\nimport \"./interfaces/IGRING.sol\";\nimport \"../deposit/interfaces/IDeposit.sol\";\nimport \"./NominationPool.sol\";\nimport \"./CollatorSet.sol\";\n\ncontract CollatorStakingHub is ReentrancyGuardUpgradeable, CollatorSet {\n using Strings for uint256;\n using Address for address payable;\n using EnumerableSet for EnumerableSet.UintSet;\n\n // The lock-up period starts with the stake or inscrease stake.\n uint256 public constant STAKING_LOCK_PERIOD = 1 days;\n // The lock-up period starts with the collator commsission update;\n uint256 public constant COMMISSION_LOCK_PERIOD = 7 days;\n // System Account.\n address public constant SYSTEM_PALLET = 0x6D6f646c64612f74727372790000000000000000;\n // 0 ~ 100\n uint256 private constant COMMISSION_BASE = 100;\n\n event Staked(address indexed pool, address collator, address account, uint256 assets);\n event Unstaked(address indexed pool, address collator, address account, uint256 assets);\n event NominationPoolCreated(address indexed stRING, address collator, address prev);\n event CommissionUpdated(address indexed collator, uint256 commission);\n\n modifier onlySystem() {\n require(msg.sender == SYSTEM_PALLET, \"!system\");\n _;\n }\n\n function initialize(address gring, address dps) public initializer {\n gRING = gring;\n DEPOSIT = dps;\n __ReentrancyGuard_init();\n __CollatorSet_init();\n }\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor() {\n _disableInitializers();\n }\n\n function createNominationPool(address prev, uint256 commission) public returns (address pool) {\n address collator = msg.sender;\n require(poolOf[collator] == address(0), \"created\");\n\n uint256 index = count;\n bytes memory bytecode = type(NominationPool).creationCode;\n bytes memory initCode = bytes.concat(bytecode, abi.encode(collator, index));\n assembly {\n pool := create2(0, add(initCode, 32), mload(initCode), 0)\n }\n require(pool != address(0), \"!create2\");\n\n poolOf[collator] = pool;\n _addCollator(collator, 0, prev);\n _collate(collator, commission);\n emit NominationPoolCreated(pool, collator, prev);\n }\n\n function _stake(address collator, address account, uint256 assets) internal {\n stakingLocks[collator][account] = STAKING_LOCK_PERIOD + block.timestamp;\n address pool = poolOf[collator];\n require(pool != address(0), \"!collator\");\n INominationPool(pool).stake(account, assets);\n IGRING(gRING).mint(account, assets);\n emit Staked(pool, collator, account, assets);\n }\n\n function _unstake(address collator, address account, uint256 assets) internal {\n require(stakingLocks[collator][account] < block.timestamp, \"!locked\");\n address pool = poolOf[collator];\n require(pool != address(0), \"!collator\");\n IGRING(gRING).burn(account, assets);\n INominationPool(pool).withdraw(account, assets);\n emit Unstaked(pool, collator, account, assets);\n }\n\n function claim(address collator) public nonReentrant {\n address pool = poolOf[collator];\n require(pool != address(0), \"!collator\");\n INominationPool(pool).getReward(msg.sender);\n }\n\n function stakeRING(address collator, address oldPrev, address newPrev) public payable nonReentrant {\n _stake(collator, msg.sender, msg.value);\n _increaseVotes(collator, _assetsToVotes(commissionOf[collator], msg.value), oldPrev, newPrev);\n stakedRINGOf[collator][msg.sender] += msg.value;\n }\n\n function unstakeRING(address collator, uint256 assets, address oldPrev, address newPrev) public nonReentrant {\n _unstake(collator, msg.sender, assets);\n payable(msg.sender).sendValue(assets);\n _reduceVotes(collator, _assetsToVotes(commissionOf[collator], assets), oldPrev, newPrev);\n stakedRINGOf[collator][msg.sender] -= assets;\n }\n\n function stakeDeposit(address collator, uint256 depositId, address oldPrev, address newPrev) public nonReentrant {\n address account = msg.sender;\n IDeposit(DEPOSIT).transferFrom(account, address(this), depositId);\n uint256 assets = IDeposit(DEPOSIT).assetsOf(depositId);\n depositInfos[depositId] = DepositInfo(account, assets, collator);\n\n _stake(collator, account, assets);\n _increaseVotes(collator, _assetsToVotes(commissionOf[collator], assets), oldPrev, newPrev);\n require(_stakedDeposits[account].add(depositId), \"!add\");\n }\n\n function unstakeDeposit(uint256 depositId, address oldPrev, address newPrev) public nonReentrant {\n address account = msg.sender;\n DepositInfo memory info = depositInfos[depositId];\n require(info.account == account);\n IDeposit(DEPOSIT).transferFrom(address(this), account, depositId);\n delete depositInfos[depositId];\n\n _unstake(info.collator, info.account, info.assets);\n _reduceVotes(info.collator, _assetsToVotes(commissionOf[info.collator], info.assets), oldPrev, newPrev);\n require(_stakedDeposits[account].remove(depositId), \"!remove\");\n }\n\n function collate(uint256 commission, address oldPrev, address newPrev) public nonReentrant {\n address collator = msg.sender;\n require(poolOf[collator] != address(0), \"!collator\");\n require(commissionLocks[collator] < block.timestamp, \"!locked\");\n require(commissionOf[collator] != commission, \"same\");\n _removeCollator(collator, oldPrev);\n _collate(collator, commission);\n _addCollator(collator, _assetsToVotes(commission, stakedOf(collator)), newPrev);\n commissionLocks[collator] = COMMISSION_LOCK_PERIOD + block.timestamp;\n }\n\n /// @dev Distribute collator reward from Staking Pallet Account.\n /// The amount of the reward must be passed in via msg.value.\n /// @notice Only Staking Pallet Account could call this function.\n /// @param collator The collator address to distribute reward.\n function distributeReward(address collator) public payable onlySystem nonReentrant {\n address pool = poolOf[collator];\n require(pool != address(0), \"!collator\");\n uint256 rewards = msg.value;\n uint256 commission_ = rewards * commissionOf[collator] / COMMISSION_BASE;\n payable(collator).sendValue(commission_);\n INominationPool(pool).notifyRewardAmount{value: rewards - commission_}();\n }\n\n function stakedOf(address collator) public view returns (uint256) {\n address pool = poolOf[collator];\n require(pool != address(0), \"!collator\");\n return INominationPool(pool).totalSupply();\n }\n\n function _collate(address collator, uint256 commission) internal {\n require(commission <= COMMISSION_BASE, \"!commission\");\n commissionOf[collator] = commission;\n emit CommissionUpdated(collator, commission);\n }\n\n function _assetsToVotes(uint256 commission, uint256 assets) internal pure returns (uint256) {\n return assets * (100 - commission) / 100;\n }\n\n function stakedDepositsOf(address account) public view returns (uint256[] memory) {\n return _stakedDeposits[account].values();\n }\n\n function stakedDepositsLength(address account) public view returns (uint256) {\n return _stakedDeposits[account].length();\n }\n\n function stakedDepositsAt(address account, uint256 index) public view returns (uint256) {\n return _stakedDeposits[account].at(index);\n }\n\n function stakedDepositsContains(address account, uint256 depositId) public view returns (bool) {\n return _stakedDeposits[account].contains(depositId);\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Strings.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)\n\npragma solidity ^0.8.20;\n\nimport {Math} from \"./math/Math.sol\";\nimport {SignedMath} from \"./math/SignedMath.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant HEX_DIGITS = \"0123456789abcdef\";\n uint8 private constant ADDRESS_LENGTH = 20;\n\n /**\n * @dev The `value` string doesn't fit in the specified `length`.\n */\n error StringsInsufficientHexLength(uint256 value, uint256 length);\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n unchecked {\n uint256 length = Math.log10(value) + 1;\n string memory buffer = new string(length);\n uint256 ptr;\n /// @solidity memory-safe-assembly\n assembly {\n ptr := add(buffer, add(32, length))\n }\n while (true) {\n ptr--;\n /// @solidity memory-safe-assembly\n assembly {\n mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))\n }\n value /= 10;\n if (value == 0) break;\n }\n return buffer;\n }\n }\n\n /**\n * @dev Converts a `int256` to its ASCII `string` decimal representation.\n */\n function toStringSigned(int256 value) internal pure returns (string memory) {\n return string.concat(value < 0 ? \"-\" : \"\", toString(SignedMath.abs(value)));\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n unchecked {\n return toHexString(value, Math.log256(value) + 1);\n }\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n uint256 localValue = value;\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = HEX_DIGITS[localValue & 0xf];\n localValue >>= 4;\n }\n if (localValue != 0) {\n revert StringsInsufficientHexLength(value, length);\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal\n * representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);\n }\n\n /**\n * @dev Returns true if the two strings are equal.\n */\n function equal(string memory a, string memory b) internal pure returns (bool) {\n return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Address.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev The ETH balance of the account is not enough to perform the operation.\n */\n error AddressInsufficientBalance(address account);\n\n /**\n * @dev There's no code at `target` (it is not a contract).\n */\n error AddressEmptyCode(address target);\n\n /**\n * @dev A call to an address target failed. The target may have reverted.\n */\n error FailedInnerCall();\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://consensys.net/diligence/blog/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.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n if (address(this).balance < amount) {\n revert AddressInsufficientBalance(address(this));\n }\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n if (!success) {\n revert FailedInnerCall();\n }\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 or custom error, it is bubbled\n * up by this function (like regular Solidity function calls). However, if\n * the call reverted with no returned reason, this function reverts with a\n * {FailedInnerCall} error.\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 function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0);\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 function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n if (address(this).balance < value) {\n revert AddressInsufficientBalance(address(this));\n }\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an\n * unsuccessful call.\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata\n ) internal view returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n // only check if target is a contract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n if (returndata.length == 0 && target.code.length == 0) {\n revert AddressEmptyCode(target);\n }\n return returndata;\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n * revert reason or with a default {FailedInnerCall} error.\n */\n function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n return returndata;\n }\n }\n\n /**\n * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.\n */\n function _revert(bytes memory returndata) private pure {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert FailedInnerCall();\n }\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol)\n// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```solidity\n * contract Example {\n * // Add the library methods\n * using EnumerableSet for EnumerableSet.AddressSet;\n *\n * // Declare a set state variable\n * EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n *\n * [WARNING]\n * ====\n * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure\n * unusable.\n * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.\n *\n * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an\n * array of EnumerableSet.\n * ====\n */\nlibrary EnumerableSet {\n // To implement this library for multiple types with as little code\n // repetition as possible, we write it in terms of a generic Set type with\n // bytes32 values.\n // The Set implementation uses private functions, and user-facing\n // implementations (such as AddressSet) are just wrappers around the\n // underlying Set.\n // This means that we can only create new EnumerableSets for types that fit\n // in bytes32.\n\n struct Set {\n // Storage of set values\n bytes32[] _values;\n // Position is the index of the value in the `values` array plus 1.\n // Position 0 is used to mean a value is not in the set.\n mapping(bytes32 value => uint256) _positions;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function _add(Set storage set, bytes32 value) private returns (bool) {\n if (!_contains(set, value)) {\n set._values.push(value);\n // The value is stored at length-1, but we add 1 to all indexes\n // and use 0 as a sentinel value\n set._positions[value] = set._values.length;\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function _remove(Set storage set, bytes32 value) private returns (bool) {\n // We cache the value's position to prevent multiple reads from the same storage slot\n uint256 position = set._positions[value];\n\n if (position != 0) {\n // Equivalent to contains(set, value)\n // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n // the array, and then remove the last element (sometimes called as 'swap and pop').\n // This modifies the order of the array, as noted in {at}.\n\n uint256 valueIndex = position - 1;\n uint256 lastIndex = set._values.length - 1;\n\n if (valueIndex != lastIndex) {\n bytes32 lastValue = set._values[lastIndex];\n\n // Move the lastValue to the index where the value to delete is\n set._values[valueIndex] = lastValue;\n // Update the tracked position of the lastValue (that was just moved)\n set._positions[lastValue] = position;\n }\n\n // Delete the slot where the moved value was stored\n set._values.pop();\n\n // Delete the tracked position for the deleted slot\n delete set._positions[value];\n\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function _contains(Set storage set, bytes32 value) private view returns (bool) {\n return set._positions[value] != 0;\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function _length(Set storage set) private view returns (uint256) {\n return set._values.length;\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function _at(Set storage set, uint256 index) private view returns (bytes32) {\n return set._values[index];\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function _values(Set storage set) private view returns (bytes32[] memory) {\n return set._values;\n }\n\n // Bytes32Set\n\n struct Bytes32Set {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _add(set._inner, value);\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _remove(set._inner, value);\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n return _contains(set._inner, value);\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(Bytes32Set storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n return _at(set._inner, index);\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {\n bytes32[] memory store = _values(set._inner);\n bytes32[] memory result;\n\n /// @solidity memory-safe-assembly\n assembly {\n result := store\n }\n\n return result;\n }\n\n // AddressSet\n\n struct AddressSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(AddressSet storage set, address value) internal returns (bool) {\n return _add(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(AddressSet storage set, address value) internal returns (bool) {\n return _remove(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(AddressSet storage set, address value) internal view returns (bool) {\n return _contains(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(AddressSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(AddressSet storage set, uint256 index) internal view returns (address) {\n return address(uint160(uint256(_at(set._inner, index))));\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function values(AddressSet storage set) internal view returns (address[] memory) {\n bytes32[] memory store = _values(set._inner);\n address[] memory result;\n\n /// @solidity memory-safe-assembly\n assembly {\n result := store\n }\n\n return result;\n }\n\n // UintSet\n\n struct UintSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(UintSet storage set, uint256 value) internal returns (bool) {\n return _add(set._inner, bytes32(value));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(UintSet storage set, uint256 value) internal returns (bool) {\n return _remove(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n return _contains(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(UintSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n return uint256(_at(set._inner, index));\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function values(UintSet storage set) internal view returns (uint256[] memory) {\n bytes32[] memory store = _values(set._inner);\n uint256[] memory result;\n\n /// @solidity memory-safe-assembly\n assembly {\n result := store\n }\n\n return result;\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon\n * a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or\n * {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon\n * a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721\n * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must\n * understand this adds an external call which potentially creates a reentrancy vulnerability.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address from, address to, uint256 tokenId) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the address zero.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)\n\npragma solidity ^0.8.20;\nimport {Initializable} from \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuardUpgradeable is Initializable {\n // Booleans are more expensive than uint256 or any type that takes up a full\n // word because each write operation emits an extra SLOAD to first read the\n // slot's contents, replace the bits taken up by the boolean, and then write\n // back. This is the compiler's defense against contract upgrades and\n // pointer aliasing, and it cannot be disabled.\n\n // The values being non-zero value makes deployment a bit more expensive,\n // but in exchange the refund on every call to nonReentrant will be lower in\n // amount. Since refunds are capped to a percentage of the total\n // transaction's gas, it is best to keep them low in cases like this one, to\n // increase the likelihood of the full refund coming into effect.\n uint256 private constant NOT_ENTERED = 1;\n uint256 private constant ENTERED = 2;\n\n /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard\n struct ReentrancyGuardStorage {\n uint256 _status;\n }\n\n // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ReentrancyGuard\")) - 1)) & ~bytes32(uint256(0xff))\n bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;\n\n function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {\n assembly {\n $.slot := ReentrancyGuardStorageLocation\n }\n }\n\n /**\n * @dev Unauthorized reentrant call.\n */\n error ReentrancyGuardReentrantCall();\n\n function __ReentrancyGuard_init() internal onlyInitializing {\n __ReentrancyGuard_init_unchained();\n }\n\n function __ReentrancyGuard_init_unchained() internal onlyInitializing {\n ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n $._status = NOT_ENTERED;\n }\n\n /**\n * @dev Prevents a contract from calling itself, directly or indirectly.\n * Calling a `nonReentrant` function from another `nonReentrant`\n * function is not supported. It is possible to prevent this from happening\n * by making the `nonReentrant` function external, and making it call a\n * `private` function that does the actual work.\n */\n modifier nonReentrant() {\n _nonReentrantBefore();\n _;\n _nonReentrantAfter();\n }\n\n function _nonReentrantBefore() private {\n ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n // On the first call to nonReentrant, _status will be NOT_ENTERED\n if ($._status == ENTERED) {\n revert ReentrancyGuardReentrantCall();\n }\n\n // Any calls to nonReentrant after this point will fail\n $._status = ENTERED;\n }\n\n function _nonReentrantAfter() private {\n ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n // By storing the original value once again, a refund is triggered (see\n // https://eips.ethereum.org/EIPS/eip-2200)\n $._status = NOT_ENTERED;\n }\n\n /**\n * @dev Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n * `nonReentrant` function in the call stack.\n */\n function _reentrancyGuardEntered() internal view returns (bool) {\n ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n return $._status == ENTERED;\n }\n}\n"},"src/collator/interfaces/INominationPool.sol":{"content":"pragma solidity >=0.4.24;\n\ninterface INominationPool {\n // Views\n function lastTimeRewardApplicable() external view returns (uint256);\n\n function rewardPerToken() external view returns (uint256);\n\n function earned(address account) external view returns (uint256);\n\n function getRewardForDuration() external view returns (uint256);\n\n function totalSupply() external view returns (uint256);\n\n function balanceOf(address account) external view returns (uint256);\n\n // Mutative\n\n function stake(address account, uint256 assets) external;\n\n function withdraw(address account, uint256 assets) external;\n\n function getReward(address account) external;\n\n function notifyRewardAmount() external payable;\n}\n"},"src/collator/interfaces/IGRING.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity >=0.4.24;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\ninterface IGRING is IERC20 {\n function burn(address from, uint256 amount) external;\n function mint(address to, uint256 amount) external;\n}\n"},"src/deposit/interfaces/IDeposit.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity >=0.4.24;\n\nimport \"@openzeppelin/contracts/token/ERC721/IERC721.sol\";\n\ninterface IDeposit is IERC721 {\n function assetsOf(uint256 id) external view returns (uint256);\n}\n"},"src/collator/NominationPool.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.20;\n\nimport \"@openzeppelin/contracts/utils/Address.sol\";\nimport \"@openzeppelin/contracts/utils/math/Math.sol\";\n\ncontract NominationPool {\n using Address for address payable;\n\n /* ========== STATE VARIABLES ========== */\n\n uint256 public id;\n address public hub;\n address public collator;\n uint256 public periodFinish = 0;\n uint256 public rewardRate = 0;\n uint256 public rewardsDuration = 7 days;\n uint256 public lastUpdateTime;\n uint256 public rewardPerTokenStored;\n\n mapping(address => uint256) public userRewardPerTokenPaid;\n mapping(address => uint256) public rewards;\n\n uint256 private _totalSupply;\n mapping(address => uint256) private _balances;\n\n modifier onlyHub() {\n require(msg.sender == hub);\n _;\n }\n\n /* ========== CONSTRUCTOR ========== */\n\n constructor(address collator_, uint256 index) {\n hub = msg.sender;\n collator = collator_;\n id = index;\n }\n\n /* ========== VIEWS ========== */\n\n function totalSupply() external view returns (uint256) {\n return _totalSupply;\n }\n\n function balanceOf(address account) external view returns (uint256) {\n return _balances[account];\n }\n\n function lastTimeRewardApplicable() public view returns (uint256) {\n return Math.min(block.timestamp, periodFinish);\n }\n\n function rewardPerToken() public view returns (uint256) {\n if (_totalSupply == 0) {\n return rewardPerTokenStored;\n }\n return rewardPerTokenStored + (lastTimeRewardApplicable() - lastUpdateTime) * rewardRate * 1e18 / _totalSupply;\n // return rewardPerTokenStored.add(\n // lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(_totalSupply)\n // );\n }\n\n function earned(address account) public view returns (uint256) {\n return _balances[account] * (rewardPerToken() - userRewardPerTokenPaid[account]) / 1e18 + rewards[account];\n // return _balances[account].mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(\n // rewards[account]\n // );\n }\n\n function getRewardForDuration() external view returns (uint256) {\n return rewardRate * rewardsDuration;\n }\n\n /* ========== MUTATIVE FUNCTIONS ========== */\n\n function stake(address account, uint256 amount) external onlyHub updateReward(account) {\n require(amount > 0, \"Cannot stake 0\");\n _totalSupply += amount;\n _balances[account] += amount;\n emit Staked(account, amount);\n }\n\n function withdraw(address account, uint256 amount) public onlyHub updateReward(account) {\n require(amount > 0, \"Cannot withdraw 0\");\n _totalSupply -= amount;\n _balances[account] -= amount;\n emit Withdrawn(account, amount);\n }\n\n function getReward(address account) public onlyHub updateReward(account) {\n uint256 reward = rewards[account];\n if (reward > 0) {\n rewards[account] = 0;\n payable(account).sendValue(reward);\n emit RewardPaid(account, reward);\n }\n }\n\n /* ========== RESTRICTED FUNCTIONS ========== */\n\n function notifyRewardAmount() external payable onlyHub updateReward(address(0)) {\n uint256 reward = msg.value;\n if (block.timestamp >= periodFinish) {\n rewardRate = reward / rewardsDuration;\n } else {\n uint256 remaining = periodFinish - block.timestamp;\n uint256 leftover = remaining * rewardRate;\n rewardRate = (reward + leftover) / rewardsDuration;\n }\n\n // Ensure the provided reward amount is not more than the balance in the contract.\n // This keeps the reward rate in the right range, preventing overflows due to\n // very high values of rewardRate in the earned and rewardsPerToken functions;\n // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.\n uint256 balance = address(this).balance;\n require(rewardRate <= balance / rewardsDuration, \"Provided reward too high\");\n\n lastUpdateTime = block.timestamp;\n periodFinish = block.timestamp + rewardsDuration;\n emit RewardAdded(reward);\n }\n\n /* ========== MODIFIERS ========== */\n\n modifier updateReward(address account) {\n rewardPerTokenStored = rewardPerToken();\n lastUpdateTime = lastTimeRewardApplicable();\n if (account != address(0)) {\n rewards[account] = earned(account);\n userRewardPerTokenPaid[account] = rewardPerTokenStored;\n }\n _;\n }\n\n /* ========== EVENTS ========== */\n\n event RewardAdded(uint256 reward);\n event Staked(address indexed user, uint256 amount);\n event Withdrawn(address indexed user, uint256 amount);\n event RewardPaid(address indexed user, uint256 reward);\n}\n"},"src/collator/CollatorSet.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.20;\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"./CollatorStakingHubStorage.sol\";\n\nabstract contract CollatorSet is Initializable, CollatorStakingHubStorage {\n address internal constant HEAD = address(0x1);\n address internal constant TAIL = address(0x2);\n\n event AddCollator(address indexed cur, uint256 votes, address prev);\n event RemoveCollator(address indexed cur, address prev);\n event UpdateCollator(address indexed cur, uint256 votes, address oldPrev, address newPrev);\n\n function __CollatorSet_init() internal onlyInitializing {\n collators[HEAD] = TAIL;\n votesOf[HEAD] = type(uint256).max;\n }\n\n /// @dev Fetch top k collators in ordered collator set.\n /// @param `k` Count of top collators.\n /// @return The `k` top collators.\n /// *Note* The result of top collators length is always be `k`.\n /// If the length of collator set `len` is less than `k`,\n /// the array result of first `len` is filled by nomal collators\n /// and the rest of `len - k` collators is filled by address(0)\n function getTopCollators(uint256 k) public view returns (address[] memory) {\n address[] memory topCollators = new address[](k);\n uint256 len = count;\n if (len > k) len = k;\n address cur = collators[HEAD];\n for (uint256 i = 0; i < len; i++) {\n topCollators[i] = cur;\n cur = collators[cur];\n }\n return topCollators;\n }\n\n function _isValid(address c) internal pure returns (bool) {\n return c != address(0) && c != HEAD && c != TAIL;\n }\n\n function _addCollator(address cur, uint256 votes, address prev) internal {\n require(_isValid(cur), \"!valid\");\n address next = collators[prev];\n // No duplicate collator allowed.\n require(collators[cur] == address(0), \"!cur\");\n // Next collator must in the list.\n require(next != address(0), \"!prev\");\n require(_verifyIndex(prev, votes, next), \"!votes\");\n collators[cur] = next;\n collators[prev] = cur;\n votesOf[cur] = votes;\n count++;\n emit AddCollator(cur, votes, prev);\n }\n\n function _removeCollator(address cur, address prev) internal {\n require(_isValid(cur), \"!valid\");\n require(collators[cur] != address(0), \"!cur\");\n require(_isPrevCollator(cur, prev), \"!prev\");\n collators[prev] = collators[cur];\n collators[cur] = address(0);\n votesOf[cur] = 0;\n count--;\n emit RemoveCollator(cur, prev);\n }\n\n function _increaseVotes(address cur, uint256 votes, address oldPrev, address newPrev) internal {\n _updateVotes(cur, votesOf[cur] + votes, oldPrev, newPrev);\n }\n\n function _reduceVotes(address cur, uint256 votes, address oldPrev, address newPrev) internal {\n _updateVotes(cur, votesOf[cur] - votes, oldPrev, newPrev);\n }\n\n function _updateVotes(address cur, uint256 newVotes, address oldPrev, address newPrev) internal {\n require(_isValid(cur), \"!valid\");\n require(collators[cur] != address(0), \"!cur\");\n require(collators[oldPrev] != address(0), \"!oldPrev1\");\n require(collators[newPrev] != address(0), \"!newPrev\");\n if (oldPrev == newPrev) {\n require(_isPrevCollator(cur, oldPrev), \"!oldPrev2\");\n require(_verifyIndex(newPrev, newVotes, collators[cur]), \"!votes\");\n votesOf[cur] = newVotes;\n } else {\n _removeCollator(cur, oldPrev);\n _addCollator(cur, newVotes, newPrev);\n }\n emit UpdateCollator(cur, newVotes, oldPrev, newPrev);\n }\n\n // prev >= cur >= next\n function _verifyIndex(address prev, uint256 newValue, address next) internal view returns (bool) {\n return votesOf[prev] >= newValue && newValue >= votesOf[next];\n }\n\n function _isPrevCollator(address c, address prev) internal view returns (bool) {\n return collators[prev] == c;\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/Math.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n /**\n * @dev Muldiv operation overflow.\n */\n error MathOverflowedMulDiv();\n\n enum Rounding {\n Floor, // Toward negative infinity\n Ceil, // Toward positive infinity\n Trunc, // Toward zero\n Expand // Away from zero\n }\n\n /**\n * @dev Returns the addition of two unsigned integers, with an overflow flag.\n */\n function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n uint256 c = a + b;\n if (c < a) return (false, 0);\n return (true, c);\n }\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, with an overflow flag.\n */\n function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b > a) return (false, 0);\n return (true, a - b);\n }\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n */\n function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) return (true, 0);\n uint256 c = a * b;\n if (c / a != b) return (false, 0);\n return (true, c);\n }\n }\n\n /**\n * @dev Returns the division of two unsigned integers, with a division by zero flag.\n */\n function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b == 0) return (false, 0);\n return (true, a / b);\n }\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n */\n function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b == 0) return (false, 0);\n return (true, a % b);\n }\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds towards infinity instead\n * of rounding towards zero.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n if (b == 0) {\n // Guarantee the same behavior as in a regular Solidity division.\n return a / b;\n }\n\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or\n * denominator == 0.\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by\n * Uniswap Labs also under MIT license.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0 = x * y; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n // The surrounding unchecked block does not change this fact.\n // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n if (denominator <= prod1) {\n revert MathOverflowedMulDiv();\n }\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator.\n // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.\n\n uint256 twos = denominator & (0 - denominator);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also\n // works in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded\n * towards zero.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n //\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n //\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n //\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1 << (log2(a) >> 1);\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = sqrt(a);\n return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 2 of a positive value rounded towards zero.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 128;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 64;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 32;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 16;\n }\n if (value >> 8 > 0) {\n value >>= 8;\n result += 8;\n }\n if (value >> 4 > 0) {\n value >>= 4;\n result += 4;\n }\n if (value >> 2 > 0) {\n value >>= 2;\n result += 2;\n }\n if (value >> 1 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 10 of a positive value rounded towards zero.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10 ** 64) {\n value /= 10 ** 64;\n result += 64;\n }\n if (value >= 10 ** 32) {\n value /= 10 ** 32;\n result += 32;\n }\n if (value >= 10 ** 16) {\n value /= 10 ** 16;\n result += 16;\n }\n if (value >= 10 ** 8) {\n value /= 10 ** 8;\n result += 8;\n }\n if (value >= 10 ** 4) {\n value /= 10 ** 4;\n result += 4;\n }\n if (value >= 10 ** 2) {\n value /= 10 ** 2;\n result += 2;\n }\n if (value >= 10 ** 1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 256 of a positive value rounded towards zero.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 16;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 8;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 4;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 2;\n }\n if (value >> 8 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.\n */\n function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {\n return uint8(rounding) % 2 == 1;\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard signed math utilities missing in the Solidity language.\n */\nlibrary SignedMath {\n /**\n * @dev Returns the largest of two signed numbers.\n */\n function max(int256 a, int256 b) internal pure returns (int256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two signed numbers.\n */\n function min(int256 a, int256 b) internal pure returns (int256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two signed numbers without overflow.\n * The result is rounded towards zero.\n */\n function average(int256 a, int256 b) internal pure returns (int256) {\n // Formula from the book \"Hacker's Delight\"\n int256 x = (a & b) + ((a ^ b) >> 1);\n return x + (int256(uint256(x) >> 255) & (a ^ b));\n }\n\n /**\n * @dev Returns the absolute unsigned value of a signed value.\n */\n function abs(int256 n) internal pure returns (uint256) {\n unchecked {\n // must be unchecked in order to support `n = type(int256).min`\n return uint256(n >= 0 ? n : -n);\n }\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```solidity\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n *\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Storage of the initializable contract.\n *\n * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions\n * when using with upgradeable contracts.\n *\n * @custom:storage-location erc7201:openzeppelin.storage.Initializable\n */\n struct InitializableStorage {\n /**\n * @dev Indicates that the contract has been initialized.\n */\n uint64 _initialized;\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool _initializing;\n }\n\n // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.Initializable\")) - 1)) & ~bytes32(uint256(0xff))\n bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;\n\n /**\n * @dev The contract is already initialized.\n */\n error InvalidInitialization();\n\n /**\n * @dev The contract is not initializing.\n */\n error NotInitializing();\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint64 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts.\n *\n * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any\n * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in\n * production.\n *\n * Emits an {Initialized} event.\n */\n modifier initializer() {\n // solhint-disable-next-line var-name-mixedcase\n InitializableStorage storage $ = _getInitializableStorage();\n\n // Cache values to avoid duplicated sloads\n bool isTopLevelCall = !$._initializing;\n uint64 initialized = $._initialized;\n\n // Allowed calls:\n // - initialSetup: the contract is not in the initializing state and no previous version was\n // initialized\n // - construction: the contract is initialized at version 1 (no reininitialization) and the\n // current contract is just being deployed\n bool initialSetup = initialized == 0 && isTopLevelCall;\n bool construction = initialized == 1 && address(this).code.length == 0;\n\n if (!initialSetup && !construction) {\n revert InvalidInitialization();\n }\n $._initialized = 1;\n if (isTopLevelCall) {\n $._initializing = true;\n }\n _;\n if (isTopLevelCall) {\n $._initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n * are added through upgrades and that require initialization.\n *\n * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n * cannot be nested. If one is invoked in the context of another, execution will revert.\n *\n * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n * a contract, executing them in the right order is up to the developer or operator.\n *\n * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.\n *\n * Emits an {Initialized} event.\n */\n modifier reinitializer(uint64 version) {\n // solhint-disable-next-line var-name-mixedcase\n InitializableStorage storage $ = _getInitializableStorage();\n\n if ($._initializing || $._initialized >= version) {\n revert InvalidInitialization();\n }\n $._initialized = version;\n $._initializing = true;\n _;\n $._initializing = false;\n emit Initialized(version);\n }\n\n /**\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n * {initializer} and {reinitializer} modifiers, directly or indirectly.\n */\n modifier onlyInitializing() {\n _checkInitializing();\n _;\n }\n\n /**\n * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.\n */\n function _checkInitializing() internal view virtual {\n if (!_isInitializing()) {\n revert NotInitializing();\n }\n }\n\n /**\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n * through proxies.\n *\n * Emits an {Initialized} event the first time it is successfully executed.\n */\n function _disableInitializers() internal virtual {\n // solhint-disable-next-line var-name-mixedcase\n InitializableStorage storage $ = _getInitializableStorage();\n\n if ($._initializing) {\n revert InvalidInitialization();\n }\n if ($._initialized != type(uint64).max) {\n $._initialized = type(uint64).max;\n emit Initialized(type(uint64).max);\n }\n }\n\n /**\n * @dev Returns the highest version that has been initialized. See {reinitializer}.\n */\n function _getInitializedVersion() internal view returns (uint64) {\n return _getInitializableStorage()._initialized;\n }\n\n /**\n * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.\n */\n function _isInitializing() internal view returns (bool) {\n return _getInitializableStorage()._initializing;\n }\n\n /**\n * @dev Returns a pointer to the storage namespace.\n */\n // solhint-disable-next-line var-name-mixedcase\n function _getInitializableStorage() private pure returns (InitializableStorage storage $) {\n assembly {\n $.slot := INITIALIZABLE_STORAGE\n }\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.20;\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 value of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the value of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens as the allowance of `spender` over the\n * 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 value) external returns (bool);\n\n /**\n * @dev Moves a `value` amount of tokens from `from` to `to` using the\n * allowance mechanism. `value` 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(address from, address to, uint256 value) external returns (bool);\n}\n"},"src/collator/CollatorStakingHubStorage.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.20;\n\nimport \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\n\ncontract CollatorStakingHubStorage {\n // ---------------------- CollatorSetStorage ----------------------------\n // collator count;\n uint256 public count;\n // ordered collators.\n mapping(address => address) public collators;\n // collator => votes = staked_ring * (1 - commission)\n mapping(address => uint256) public votesOf;\n\n // ---------------------- CollatorStakingHubStorage ---------------------\n // Governance RING\n address public gRING;\n // Deposit NFT.\n address public DEPOSIT;\n // collator => nomination pool\n mapping(address => address) public poolOf;\n // collator => commission\n mapping(address => uint256) public commissionOf;\n // collator => user => stakingLockTime\n mapping(address => mapping(address => uint256)) public stakingLocks;\n // collator => commissonLockTime\n mapping(address => uint256) public commissionLocks;\n // user => collator => staked ring\n mapping(address => mapping(address => uint256)) public stakedRINGOf;\n // user => staked depositIds\n mapping(address => EnumerableSet.UintSet) internal _stakedDeposits;\n\n struct DepositInfo {\n address account;\n uint256 assets;\n address collator;\n }\n\n // depositId => depositInfo\n mapping(uint256 => DepositInfo) public depositInfos;\n}\n"}},"settings":{"remappings":["forge-std/=lib/forge-std/src/","@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/","@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/","openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/","solidity-stringutils/=lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/"],"optimizer":{"enabled":true,"runs":999999},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"":["ast"],"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata","storageLayout"]}},"evmVersion":"london","viaIR":false,"libraries":{}}} +{"language":"Solidity","sources":{"src/collator/CollatorStakingHub.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.20;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@openzeppelin/contracts/utils/Address.sol\";\nimport \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\nimport \"@openzeppelin/contracts/token/ERC721/IERC721.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol\";\nimport \"./interfaces/INominationPool.sol\";\nimport \"./interfaces/IGRING.sol\";\nimport \"../deposit/interfaces/IDeposit.sol\";\nimport \"./NominationPool.sol\";\nimport \"./CollatorSet.sol\";\n\ncontract CollatorStakingHub is ReentrancyGuardUpgradeable, CollatorSet {\n using Strings for uint256;\n using Address for address payable;\n using EnumerableSet for EnumerableSet.UintSet;\n\n // The lock-up period starts with the stake or inscrease stake.\n uint256 public constant STAKING_LOCK_PERIOD = 1 days;\n // The lock-up period starts with the collator commsission update;\n uint256 public constant COMMISSION_LOCK_PERIOD = 7 days;\n // System Account.\n address public constant SYSTEM_PALLET = 0x6D6f646c64612f74727372790000000000000000;\n // 0 ~ 100\n uint256 private constant COMMISSION_BASE = 100;\n\n event Staked(address indexed pool, address collator, address account, uint256 assets);\n event Unstaked(address indexed pool, address collator, address account, uint256 assets);\n event NominationPoolCreated(address indexed pool, address collator);\n event CommissionUpdated(address indexed collator, uint256 commission);\n event RewardDistributed(address indexed collator, uint256 reward);\n\n modifier onlySystem() {\n require(msg.sender == SYSTEM_PALLET, \"!system\");\n _;\n }\n\n function initialize(address gring, address dps) public initializer {\n gRING = gring;\n DEPOSIT = dps;\n __ReentrancyGuard_init();\n __CollatorSet_init();\n }\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor() {\n _disableInitializers();\n }\n\n /// 1. Create nomination pool\n /// 2. Join collator set\n /// 3. Set commsission\n function createAndCollate(address prev, uint256 commission) public returns (address pool) {\n address collator = msg.sender;\n pool = createNominationPool();\n _updateCommissionAndLock(collator, commission);\n _addCollator(collator, 0, prev);\n }\n\n /// 1. Join collator set\n /// 2. Set commission\n function collate(address prev, uint256 commission) public {\n address collator = msg.sender;\n require(poolOf[collator] != address(0), \"!pool\");\n _updateCommissionAndLock(collator, commission);\n _addCollator(collator, _assetsToVotes(commission, stakedOf(collator)), prev);\n }\n\n /// 1. Exit collator set\n /// 2. Clear commission\n function stopCollation(address prev) public {\n address collator = msg.sender;\n require(poolOf[collator] != address(0), \"!pool\");\n _setCommisson(collator, 0);\n _removeCollator(collator, prev);\n }\n\n function createNominationPool() public returns (address pool) {\n address collator = msg.sender;\n require(poolOf[collator] == address(0), \"created\");\n\n bytes memory bytecode = type(NominationPool).creationCode;\n bytes memory initCode = bytes.concat(bytecode, abi.encode(collator));\n assembly {\n pool := create2(0, add(initCode, 32), mload(initCode), 0)\n }\n require(pool != address(0), \"!create2\");\n poolOf[collator] = pool;\n emit NominationPoolCreated(pool, collator);\n }\n\n function updateCommission(uint256 commission, address oldPrev, address newPrev) public nonReentrant {\n address collator = msg.sender;\n require(poolOf[collator] != address(0), \"!pool\");\n require(commissionOf[collator] != commission, \"same\");\n _removeCollator(collator, oldPrev);\n _updateCommissionAndLock(collator, commission);\n _addCollator(collator, _assetsToVotes(commission, stakedOf(collator)), newPrev);\n }\n\n function _updateCommissionAndLock(address collator, uint256 commission) internal {\n require(commissionLocks[collator] < block.timestamp, \"!locked\");\n _setCommisson(collator, commission);\n commissionLocks[collator] = COMMISSION_LOCK_PERIOD + block.timestamp;\n }\n\n function _setCommisson(address collator, uint256 commission) internal {\n require(commission <= COMMISSION_BASE, \"!commission\");\n commissionOf[collator] = commission;\n emit CommissionUpdated(collator, commission);\n }\n\n function _updateCollatorVotes(address collator, address oldPrev, address newPrev) internal {\n uint256 assets = stakedOf(collator);\n uint256 newVotes = _assetsToVotes(commissionOf[collator], assets);\n _updateVotes(collator, newVotes, oldPrev, newPrev);\n }\n\n function _stake(address collator, address account, uint256 assets) internal {\n stakingLocks[collator][account] = STAKING_LOCK_PERIOD + block.timestamp;\n address pool = poolOf[collator];\n require(pool != address(0), \"!pool\");\n INominationPool(pool).stake(account, assets);\n IGRING(gRING).mint(account, assets);\n emit Staked(pool, collator, account, assets);\n }\n\n function _unstake(address collator, address account, uint256 assets) internal {\n require(stakingLocks[collator][account] < block.timestamp, \"!locked\");\n address pool = poolOf[collator];\n require(pool != address(0), \"!pool\");\n IGRING(gRING).burn(account, assets);\n INominationPool(pool).withdraw(account, assets);\n emit Unstaked(pool, collator, account, assets);\n }\n\n function claim(address collator) public nonReentrant {\n address pool = poolOf[collator];\n require(pool != address(0), \"!collator\");\n INominationPool(pool).getReward(msg.sender);\n }\n\n function stakeRING(address collator, address oldPrev, address newPrev) public payable nonReentrant {\n _stake(collator, msg.sender, msg.value);\n _updateCollatorVotes(collator, oldPrev, newPrev);\n stakedRINGOf[collator][msg.sender] += msg.value;\n }\n\n function unstakeRING(address collator, uint256 assets, address oldPrev, address newPrev) public nonReentrant {\n _unstake(collator, msg.sender, assets);\n _updateCollatorVotes(collator, oldPrev, newPrev);\n stakedRINGOf[collator][msg.sender] -= assets;\n payable(msg.sender).sendValue(assets);\n }\n\n function stakeDeposits(address collator, uint256[] calldata depositIds, address oldPrev, address newPrev)\n public\n nonReentrant\n {\n require(depositIds.length > 0, \"!len\");\n address account = msg.sender;\n uint256 totalAssets;\n for (uint256 i = 0; i < depositIds.length; i++) {\n uint256 depositId = depositIds[i];\n IDeposit(DEPOSIT).transferFrom(account, address(this), depositId);\n uint256 assets = IDeposit(DEPOSIT).assetsOf(depositId);\n depositInfos[depositId] = DepositInfo(account, assets, collator);\n require(_stakedDeposits[account].add(depositId), \"!add\");\n totalAssets += assets;\n }\n _stake(collator, account, totalAssets);\n _updateCollatorVotes(collator, oldPrev, newPrev);\n }\n\n function unstakeDeposits(address collator, uint256[] calldata depositIds, address oldPrev, address newPrev)\n public\n nonReentrant\n {\n require(depositIds.length > 0, \"!len\");\n address account = msg.sender;\n uint256 totalAssets;\n for (uint256 i = 0; i < depositIds.length; i++) {\n uint256 depositId = depositIds[i];\n DepositInfo memory info = depositInfos[depositId];\n require(info.account == account, \"!account\");\n require(info.collator == collator, \"!collator\");\n IDeposit(DEPOSIT).transferFrom(address(this), account, depositId);\n require(_stakedDeposits[account].remove(depositId), \"!remove\");\n delete depositInfos[depositId];\n totalAssets += info.assets;\n }\n _unstake(collator, account, totalAssets);\n _updateCollatorVotes(collator, oldPrev, newPrev);\n }\n\n /// @dev Distribute collator reward from Staking Pallet Account.\n /// The amount of the reward must be passed in via msg.value.\n /// @notice Only Staking Pallet Account could call this function.\n /// @param collator The collator address to distribute reward.\n function distributeReward(address collator) public payable onlySystem nonReentrant {\n address pool = poolOf[collator];\n require(pool != address(0), \"!pool\");\n uint256 rewards = msg.value;\n uint256 commission_ = rewards * commissionOf[collator] / COMMISSION_BASE;\n payable(collator).sendValue(commission_);\n INominationPool(pool).notifyRewardAmount{value: rewards - commission_}();\n emit RewardDistributed(collator, rewards);\n }\n\n function stakedOf(address collator) public view returns (uint256) {\n address pool = poolOf[collator];\n require(pool != address(0), \"!pool\");\n return INominationPool(pool).totalSupply();\n }\n\n function assetsToVotes(uint256 commission, uint256 assets) public pure returns (uint256) {\n return _assetsToVotes(commission, assets);\n }\n\n function _assetsToVotes(uint256 commission, uint256 assets) internal pure returns (uint256) {\n return assets * (COMMISSION_BASE - commission) / COMMISSION_BASE;\n }\n\n function stakedDepositsOf(address account) public view returns (uint256[] memory) {\n return _stakedDeposits[account].values();\n }\n\n function stakedDepositsLength(address account) public view returns (uint256) {\n return _stakedDeposits[account].length();\n }\n\n function stakedDepositsAt(address account, uint256 index) public view returns (uint256) {\n return _stakedDeposits[account].at(index);\n }\n\n function stakedDepositsContains(address account, uint256 depositId) public view returns (bool) {\n return _stakedDeposits[account].contains(depositId);\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Strings.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)\n\npragma solidity ^0.8.20;\n\nimport {Math} from \"./math/Math.sol\";\nimport {SignedMath} from \"./math/SignedMath.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant HEX_DIGITS = \"0123456789abcdef\";\n uint8 private constant ADDRESS_LENGTH = 20;\n\n /**\n * @dev The `value` string doesn't fit in the specified `length`.\n */\n error StringsInsufficientHexLength(uint256 value, uint256 length);\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n unchecked {\n uint256 length = Math.log10(value) + 1;\n string memory buffer = new string(length);\n uint256 ptr;\n /// @solidity memory-safe-assembly\n assembly {\n ptr := add(buffer, add(32, length))\n }\n while (true) {\n ptr--;\n /// @solidity memory-safe-assembly\n assembly {\n mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))\n }\n value /= 10;\n if (value == 0) break;\n }\n return buffer;\n }\n }\n\n /**\n * @dev Converts a `int256` to its ASCII `string` decimal representation.\n */\n function toStringSigned(int256 value) internal pure returns (string memory) {\n return string.concat(value < 0 ? \"-\" : \"\", toString(SignedMath.abs(value)));\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n unchecked {\n return toHexString(value, Math.log256(value) + 1);\n }\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n uint256 localValue = value;\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = HEX_DIGITS[localValue & 0xf];\n localValue >>= 4;\n }\n if (localValue != 0) {\n revert StringsInsufficientHexLength(value, length);\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal\n * representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);\n }\n\n /**\n * @dev Returns true if the two strings are equal.\n */\n function equal(string memory a, string memory b) internal pure returns (bool) {\n return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Address.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev The ETH balance of the account is not enough to perform the operation.\n */\n error AddressInsufficientBalance(address account);\n\n /**\n * @dev There's no code at `target` (it is not a contract).\n */\n error AddressEmptyCode(address target);\n\n /**\n * @dev A call to an address target failed. The target may have reverted.\n */\n error FailedInnerCall();\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://consensys.net/diligence/blog/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.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n if (address(this).balance < amount) {\n revert AddressInsufficientBalance(address(this));\n }\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n if (!success) {\n revert FailedInnerCall();\n }\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 or custom error, it is bubbled\n * up by this function (like regular Solidity function calls). However, if\n * the call reverted with no returned reason, this function reverts with a\n * {FailedInnerCall} error.\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 function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0);\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 function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n if (address(this).balance < value) {\n revert AddressInsufficientBalance(address(this));\n }\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an\n * unsuccessful call.\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata\n ) internal view returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n // only check if target is a contract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n if (returndata.length == 0 && target.code.length == 0) {\n revert AddressEmptyCode(target);\n }\n return returndata;\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n * revert reason or with a default {FailedInnerCall} error.\n */\n function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n return returndata;\n }\n }\n\n /**\n * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.\n */\n function _revert(bytes memory returndata) private pure {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert FailedInnerCall();\n }\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol)\n// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```solidity\n * contract Example {\n * // Add the library methods\n * using EnumerableSet for EnumerableSet.AddressSet;\n *\n * // Declare a set state variable\n * EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n *\n * [WARNING]\n * ====\n * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure\n * unusable.\n * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.\n *\n * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an\n * array of EnumerableSet.\n * ====\n */\nlibrary EnumerableSet {\n // To implement this library for multiple types with as little code\n // repetition as possible, we write it in terms of a generic Set type with\n // bytes32 values.\n // The Set implementation uses private functions, and user-facing\n // implementations (such as AddressSet) are just wrappers around the\n // underlying Set.\n // This means that we can only create new EnumerableSets for types that fit\n // in bytes32.\n\n struct Set {\n // Storage of set values\n bytes32[] _values;\n // Position is the index of the value in the `values` array plus 1.\n // Position 0 is used to mean a value is not in the set.\n mapping(bytes32 value => uint256) _positions;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function _add(Set storage set, bytes32 value) private returns (bool) {\n if (!_contains(set, value)) {\n set._values.push(value);\n // The value is stored at length-1, but we add 1 to all indexes\n // and use 0 as a sentinel value\n set._positions[value] = set._values.length;\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function _remove(Set storage set, bytes32 value) private returns (bool) {\n // We cache the value's position to prevent multiple reads from the same storage slot\n uint256 position = set._positions[value];\n\n if (position != 0) {\n // Equivalent to contains(set, value)\n // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n // the array, and then remove the last element (sometimes called as 'swap and pop').\n // This modifies the order of the array, as noted in {at}.\n\n uint256 valueIndex = position - 1;\n uint256 lastIndex = set._values.length - 1;\n\n if (valueIndex != lastIndex) {\n bytes32 lastValue = set._values[lastIndex];\n\n // Move the lastValue to the index where the value to delete is\n set._values[valueIndex] = lastValue;\n // Update the tracked position of the lastValue (that was just moved)\n set._positions[lastValue] = position;\n }\n\n // Delete the slot where the moved value was stored\n set._values.pop();\n\n // Delete the tracked position for the deleted slot\n delete set._positions[value];\n\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function _contains(Set storage set, bytes32 value) private view returns (bool) {\n return set._positions[value] != 0;\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function _length(Set storage set) private view returns (uint256) {\n return set._values.length;\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function _at(Set storage set, uint256 index) private view returns (bytes32) {\n return set._values[index];\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function _values(Set storage set) private view returns (bytes32[] memory) {\n return set._values;\n }\n\n // Bytes32Set\n\n struct Bytes32Set {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _add(set._inner, value);\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _remove(set._inner, value);\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n return _contains(set._inner, value);\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(Bytes32Set storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n return _at(set._inner, index);\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {\n bytes32[] memory store = _values(set._inner);\n bytes32[] memory result;\n\n /// @solidity memory-safe-assembly\n assembly {\n result := store\n }\n\n return result;\n }\n\n // AddressSet\n\n struct AddressSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(AddressSet storage set, address value) internal returns (bool) {\n return _add(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(AddressSet storage set, address value) internal returns (bool) {\n return _remove(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(AddressSet storage set, address value) internal view returns (bool) {\n return _contains(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(AddressSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(AddressSet storage set, uint256 index) internal view returns (address) {\n return address(uint160(uint256(_at(set._inner, index))));\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function values(AddressSet storage set) internal view returns (address[] memory) {\n bytes32[] memory store = _values(set._inner);\n address[] memory result;\n\n /// @solidity memory-safe-assembly\n assembly {\n result := store\n }\n\n return result;\n }\n\n // UintSet\n\n struct UintSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(UintSet storage set, uint256 value) internal returns (bool) {\n return _add(set._inner, bytes32(value));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(UintSet storage set, uint256 value) internal returns (bool) {\n return _remove(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n return _contains(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(UintSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n return uint256(_at(set._inner, index));\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function values(UintSet storage set) internal view returns (uint256[] memory) {\n bytes32[] memory store = _values(set._inner);\n uint256[] memory result;\n\n /// @solidity memory-safe-assembly\n assembly {\n result := store\n }\n\n return result;\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon\n * a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or\n * {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon\n * a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721\n * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must\n * understand this adds an external call which potentially creates a reentrancy vulnerability.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address from, address to, uint256 tokenId) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the address zero.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)\n\npragma solidity ^0.8.20;\nimport {Initializable} from \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuardUpgradeable is Initializable {\n // Booleans are more expensive than uint256 or any type that takes up a full\n // word because each write operation emits an extra SLOAD to first read the\n // slot's contents, replace the bits taken up by the boolean, and then write\n // back. This is the compiler's defense against contract upgrades and\n // pointer aliasing, and it cannot be disabled.\n\n // The values being non-zero value makes deployment a bit more expensive,\n // but in exchange the refund on every call to nonReentrant will be lower in\n // amount. Since refunds are capped to a percentage of the total\n // transaction's gas, it is best to keep them low in cases like this one, to\n // increase the likelihood of the full refund coming into effect.\n uint256 private constant NOT_ENTERED = 1;\n uint256 private constant ENTERED = 2;\n\n /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard\n struct ReentrancyGuardStorage {\n uint256 _status;\n }\n\n // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ReentrancyGuard\")) - 1)) & ~bytes32(uint256(0xff))\n bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;\n\n function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {\n assembly {\n $.slot := ReentrancyGuardStorageLocation\n }\n }\n\n /**\n * @dev Unauthorized reentrant call.\n */\n error ReentrancyGuardReentrantCall();\n\n function __ReentrancyGuard_init() internal onlyInitializing {\n __ReentrancyGuard_init_unchained();\n }\n\n function __ReentrancyGuard_init_unchained() internal onlyInitializing {\n ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n $._status = NOT_ENTERED;\n }\n\n /**\n * @dev Prevents a contract from calling itself, directly or indirectly.\n * Calling a `nonReentrant` function from another `nonReentrant`\n * function is not supported. It is possible to prevent this from happening\n * by making the `nonReentrant` function external, and making it call a\n * `private` function that does the actual work.\n */\n modifier nonReentrant() {\n _nonReentrantBefore();\n _;\n _nonReentrantAfter();\n }\n\n function _nonReentrantBefore() private {\n ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n // On the first call to nonReentrant, _status will be NOT_ENTERED\n if ($._status == ENTERED) {\n revert ReentrancyGuardReentrantCall();\n }\n\n // Any calls to nonReentrant after this point will fail\n $._status = ENTERED;\n }\n\n function _nonReentrantAfter() private {\n ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n // By storing the original value once again, a refund is triggered (see\n // https://eips.ethereum.org/EIPS/eip-2200)\n $._status = NOT_ENTERED;\n }\n\n /**\n * @dev Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n * `nonReentrant` function in the call stack.\n */\n function _reentrancyGuardEntered() internal view returns (bool) {\n ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n return $._status == ENTERED;\n }\n}\n"},"src/collator/interfaces/INominationPool.sol":{"content":"pragma solidity >=0.4.24;\n\ninterface INominationPool {\n // Views\n function lastTimeRewardApplicable() external view returns (uint256);\n\n function rewardPerToken() external view returns (uint256);\n\n function earned(address account) external view returns (uint256);\n\n function getRewardForDuration() external view returns (uint256);\n\n function totalSupply() external view returns (uint256);\n\n function balanceOf(address account) external view returns (uint256);\n\n // Mutative\n\n function stake(address account, uint256 assets) external;\n\n function withdraw(address account, uint256 assets) external;\n\n function getReward(address account) external;\n\n function notifyRewardAmount() external payable;\n}\n"},"src/collator/interfaces/IGRING.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity >=0.4.24;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\ninterface IGRING is IERC20 {\n function burn(address from, uint256 amount) external;\n function mint(address to, uint256 amount) external;\n}\n"},"src/deposit/interfaces/IDeposit.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity >=0.4.24;\n\nimport \"@openzeppelin/contracts/token/ERC721/IERC721.sol\";\n\ninterface IDeposit is IERC721 {\n function assetsOf(uint256 id) external view returns (uint256);\n}\n"},"src/collator/NominationPool.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.20;\n\nimport \"@openzeppelin/contracts/utils/Address.sol\";\nimport \"@openzeppelin/contracts/utils/math/Math.sol\";\n\ncontract NominationPool {\n using Address for address payable;\n\n /* ========== STATE VARIABLES ========== */\n\n address public hub;\n address public collator;\n uint256 public periodFinish = 0;\n uint256 public rewardRate = 0;\n uint256 public rewardsDuration = 7 days;\n uint256 public lastUpdateTime;\n uint256 public rewardPerTokenStored;\n\n mapping(address => uint256) public userRewardPerTokenPaid;\n mapping(address => uint256) public rewards;\n\n uint256 private _totalSupply;\n mapping(address => uint256) private _balances;\n\n modifier onlyHub() {\n require(msg.sender == hub);\n _;\n }\n\n /* ========== CONSTRUCTOR ========== */\n\n constructor(address collator_) {\n hub = msg.sender;\n collator = collator_;\n }\n\n /* ========== VIEWS ========== */\n\n function totalSupply() external view returns (uint256) {\n return _totalSupply;\n }\n\n function balanceOf(address account) external view returns (uint256) {\n return _balances[account];\n }\n\n function lastTimeRewardApplicable() public view returns (uint256) {\n return Math.min(block.timestamp, periodFinish);\n }\n\n function rewardPerToken() public view returns (uint256) {\n if (_totalSupply == 0) {\n return rewardPerTokenStored;\n }\n return rewardPerTokenStored + (lastTimeRewardApplicable() - lastUpdateTime) * rewardRate * 1e18 / _totalSupply;\n }\n\n function earned(address account) public view returns (uint256) {\n return _balances[account] * (rewardPerToken() - userRewardPerTokenPaid[account]) / 1e18 + rewards[account];\n }\n\n function getRewardForDuration() external view returns (uint256) {\n return rewardRate * rewardsDuration;\n }\n\n /* ========== MUTATIVE FUNCTIONS ========== */\n\n function stake(address account, uint256 amount) external onlyHub updateReward(account) {\n require(amount > 0, \"Cannot stake 0\");\n _totalSupply += amount;\n _balances[account] += amount;\n emit Staked(account, amount);\n }\n\n function withdraw(address account, uint256 amount) public onlyHub updateReward(account) {\n require(amount > 0, \"Cannot withdraw 0\");\n _totalSupply -= amount;\n _balances[account] -= amount;\n emit Withdrawn(account, amount);\n }\n\n function getReward(address account) public onlyHub updateReward(account) {\n uint256 reward = rewards[account];\n if (reward > 0) {\n rewards[account] = 0;\n payable(account).sendValue(reward);\n emit RewardPaid(account, reward);\n }\n }\n\n /* ========== RESTRICTED FUNCTIONS ========== */\n\n function notifyRewardAmount() external payable onlyHub updateReward(address(0)) {\n uint256 reward = msg.value;\n if (block.timestamp >= periodFinish) {\n rewardRate = reward / rewardsDuration;\n } else {\n uint256 remaining = periodFinish - block.timestamp;\n uint256 leftover = remaining * rewardRate;\n rewardRate = (reward + leftover) / rewardsDuration;\n }\n\n // Ensure the provided reward amount is not more than the balance in the contract.\n // This keeps the reward rate in the right range, preventing overflows due to\n // very high values of rewardRate in the earned and rewardsPerToken functions;\n // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.\n uint256 balance = address(this).balance;\n require(rewardRate <= balance / rewardsDuration, \"Provided reward too high\");\n\n lastUpdateTime = block.timestamp;\n periodFinish = block.timestamp + rewardsDuration;\n emit RewardAdded(reward);\n }\n\n /* ========== MODIFIERS ========== */\n\n modifier updateReward(address account) {\n rewardPerTokenStored = rewardPerToken();\n lastUpdateTime = lastTimeRewardApplicable();\n if (account != address(0)) {\n rewards[account] = earned(account);\n userRewardPerTokenPaid[account] = rewardPerTokenStored;\n }\n _;\n }\n\n /* ========== EVENTS ========== */\n\n event RewardAdded(uint256 reward);\n event Staked(address indexed user, uint256 amount);\n event Withdrawn(address indexed user, uint256 amount);\n event RewardPaid(address indexed user, uint256 reward);\n}\n"},"src/collator/CollatorSet.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.20;\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"./CollatorStakingHubStorage.sol\";\n\nabstract contract CollatorSet is Initializable, CollatorStakingHubStorage {\n address internal constant HEAD = address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF);\n address internal constant TAIL = address(0x1);\n\n event AddCollator(address indexed cur, uint256 votes, address prev);\n event RemoveCollator(address indexed cur, address prev);\n event UpdateCollator(address indexed cur, uint256 votes, address oldPrev, address newPrev);\n\n function __CollatorSet_init() internal onlyInitializing {\n collators[HEAD] = TAIL;\n votesOf[HEAD] = type(uint256).max;\n }\n\n /// @dev Fetch top k collators in ordered collator set.\n /// @param `k` Count of top collators.\n /// @return The `k` top collators.\n /// *Note* The result of top collators length is always be `k`.\n /// If the length of collator set `len` is less than `k`,\n /// the array result of first `len` is filled by nomal collators\n /// and the rest of `len - k` collators is filled by address(0)\n function getTopCollators(uint256 k) public view returns (address[] memory) {\n address[] memory topCollators = new address[](k);\n uint256 len = count;\n if (len > k) len = k;\n address cur = collators[HEAD];\n for (uint256 i = 0; i < len; i++) {\n topCollators[i] = cur;\n cur = collators[cur];\n }\n return topCollators;\n }\n\n function _isValid(address c) internal pure returns (bool) {\n return c != address(0) && c != HEAD && c != TAIL;\n }\n\n function _addCollator(address cur, uint256 votes, address prev) internal {\n require(_isValid(cur), \"!valid\");\n address next = collators[prev];\n // No duplicate collator allowed.\n require(collators[cur] == address(0), \"!cur\");\n // Next collator must in the list.\n require(next != address(0), \"!prev\");\n require(_verifyIndex(prev, votes, next, cur), \"!votes\");\n collators[cur] = next;\n collators[prev] = cur;\n votesOf[cur] = votes;\n count++;\n emit AddCollator(cur, votes, prev);\n }\n\n function _removeCollator(address cur, address prev) internal {\n require(_isValid(cur), \"!valid\");\n require(collators[cur] != address(0), \"!cur\");\n require(_isPrevCollator(cur, prev), \"!prev\");\n collators[prev] = collators[cur];\n collators[cur] = address(0);\n votesOf[cur] = 0;\n count--;\n emit RemoveCollator(cur, prev);\n }\n\n function _updateVotes(address cur, uint256 newVotes, address oldPrev, address newPrev) internal {\n require(_isValid(cur), \"!valid\");\n require(collators[cur] != address(0), \"!cur\");\n require(collators[oldPrev] != address(0), \"!oldPrev1\");\n require(collators[newPrev] != address(0), \"!newPrev\");\n if (oldPrev == newPrev) {\n require(_isPrevCollator(cur, oldPrev), \"!oldPrev2\");\n require(_verifyIndex(newPrev, newVotes, collators[cur], cur), \"!votes\");\n votesOf[cur] = newVotes;\n } else {\n _removeCollator(cur, oldPrev);\n _addCollator(cur, newVotes, newPrev);\n }\n emit UpdateCollator(cur, newVotes, oldPrev, newPrev);\n }\n\n // 1. votes(prev) >= votes(cur) >= votes(next)\n // 2. addr(prev) > addr(cur) > addr(next)\n function _verifyIndex(address prev, uint256 newValue, address next, address cur) internal view returns (bool) {\n return ((votesOf[prev] > newValue) || (votesOf[prev] == newValue && prev > cur))\n && ((newValue > votesOf[next]) || (newValue == votesOf[next] && cur > next));\n }\n\n function _isPrevCollator(address c, address prev) internal view returns (bool) {\n return collators[prev] == c;\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/Math.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n /**\n * @dev Muldiv operation overflow.\n */\n error MathOverflowedMulDiv();\n\n enum Rounding {\n Floor, // Toward negative infinity\n Ceil, // Toward positive infinity\n Trunc, // Toward zero\n Expand // Away from zero\n }\n\n /**\n * @dev Returns the addition of two unsigned integers, with an overflow flag.\n */\n function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n uint256 c = a + b;\n if (c < a) return (false, 0);\n return (true, c);\n }\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, with an overflow flag.\n */\n function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b > a) return (false, 0);\n return (true, a - b);\n }\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n */\n function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) return (true, 0);\n uint256 c = a * b;\n if (c / a != b) return (false, 0);\n return (true, c);\n }\n }\n\n /**\n * @dev Returns the division of two unsigned integers, with a division by zero flag.\n */\n function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b == 0) return (false, 0);\n return (true, a / b);\n }\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n */\n function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b == 0) return (false, 0);\n return (true, a % b);\n }\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds towards infinity instead\n * of rounding towards zero.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n if (b == 0) {\n // Guarantee the same behavior as in a regular Solidity division.\n return a / b;\n }\n\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or\n * denominator == 0.\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by\n * Uniswap Labs also under MIT license.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0 = x * y; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n // The surrounding unchecked block does not change this fact.\n // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n if (denominator <= prod1) {\n revert MathOverflowedMulDiv();\n }\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator.\n // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.\n\n uint256 twos = denominator & (0 - denominator);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also\n // works in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded\n * towards zero.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n //\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n //\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n //\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1 << (log2(a) >> 1);\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = sqrt(a);\n return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 2 of a positive value rounded towards zero.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 128;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 64;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 32;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 16;\n }\n if (value >> 8 > 0) {\n value >>= 8;\n result += 8;\n }\n if (value >> 4 > 0) {\n value >>= 4;\n result += 4;\n }\n if (value >> 2 > 0) {\n value >>= 2;\n result += 2;\n }\n if (value >> 1 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 10 of a positive value rounded towards zero.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10 ** 64) {\n value /= 10 ** 64;\n result += 64;\n }\n if (value >= 10 ** 32) {\n value /= 10 ** 32;\n result += 32;\n }\n if (value >= 10 ** 16) {\n value /= 10 ** 16;\n result += 16;\n }\n if (value >= 10 ** 8) {\n value /= 10 ** 8;\n result += 8;\n }\n if (value >= 10 ** 4) {\n value /= 10 ** 4;\n result += 4;\n }\n if (value >= 10 ** 2) {\n value /= 10 ** 2;\n result += 2;\n }\n if (value >= 10 ** 1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 256 of a positive value rounded towards zero.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 16;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 8;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 4;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 2;\n }\n if (value >> 8 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.\n */\n function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {\n return uint8(rounding) % 2 == 1;\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard signed math utilities missing in the Solidity language.\n */\nlibrary SignedMath {\n /**\n * @dev Returns the largest of two signed numbers.\n */\n function max(int256 a, int256 b) internal pure returns (int256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two signed numbers.\n */\n function min(int256 a, int256 b) internal pure returns (int256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two signed numbers without overflow.\n * The result is rounded towards zero.\n */\n function average(int256 a, int256 b) internal pure returns (int256) {\n // Formula from the book \"Hacker's Delight\"\n int256 x = (a & b) + ((a ^ b) >> 1);\n return x + (int256(uint256(x) >> 255) & (a ^ b));\n }\n\n /**\n * @dev Returns the absolute unsigned value of a signed value.\n */\n function abs(int256 n) internal pure returns (uint256) {\n unchecked {\n // must be unchecked in order to support `n = type(int256).min`\n return uint256(n >= 0 ? n : -n);\n }\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```solidity\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n *\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Storage of the initializable contract.\n *\n * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions\n * when using with upgradeable contracts.\n *\n * @custom:storage-location erc7201:openzeppelin.storage.Initializable\n */\n struct InitializableStorage {\n /**\n * @dev Indicates that the contract has been initialized.\n */\n uint64 _initialized;\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool _initializing;\n }\n\n // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.Initializable\")) - 1)) & ~bytes32(uint256(0xff))\n bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;\n\n /**\n * @dev The contract is already initialized.\n */\n error InvalidInitialization();\n\n /**\n * @dev The contract is not initializing.\n */\n error NotInitializing();\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint64 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts.\n *\n * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any\n * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in\n * production.\n *\n * Emits an {Initialized} event.\n */\n modifier initializer() {\n // solhint-disable-next-line var-name-mixedcase\n InitializableStorage storage $ = _getInitializableStorage();\n\n // Cache values to avoid duplicated sloads\n bool isTopLevelCall = !$._initializing;\n uint64 initialized = $._initialized;\n\n // Allowed calls:\n // - initialSetup: the contract is not in the initializing state and no previous version was\n // initialized\n // - construction: the contract is initialized at version 1 (no reininitialization) and the\n // current contract is just being deployed\n bool initialSetup = initialized == 0 && isTopLevelCall;\n bool construction = initialized == 1 && address(this).code.length == 0;\n\n if (!initialSetup && !construction) {\n revert InvalidInitialization();\n }\n $._initialized = 1;\n if (isTopLevelCall) {\n $._initializing = true;\n }\n _;\n if (isTopLevelCall) {\n $._initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n * are added through upgrades and that require initialization.\n *\n * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n * cannot be nested. If one is invoked in the context of another, execution will revert.\n *\n * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n * a contract, executing them in the right order is up to the developer or operator.\n *\n * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.\n *\n * Emits an {Initialized} event.\n */\n modifier reinitializer(uint64 version) {\n // solhint-disable-next-line var-name-mixedcase\n InitializableStorage storage $ = _getInitializableStorage();\n\n if ($._initializing || $._initialized >= version) {\n revert InvalidInitialization();\n }\n $._initialized = version;\n $._initializing = true;\n _;\n $._initializing = false;\n emit Initialized(version);\n }\n\n /**\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n * {initializer} and {reinitializer} modifiers, directly or indirectly.\n */\n modifier onlyInitializing() {\n _checkInitializing();\n _;\n }\n\n /**\n * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.\n */\n function _checkInitializing() internal view virtual {\n if (!_isInitializing()) {\n revert NotInitializing();\n }\n }\n\n /**\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n * through proxies.\n *\n * Emits an {Initialized} event the first time it is successfully executed.\n */\n function _disableInitializers() internal virtual {\n // solhint-disable-next-line var-name-mixedcase\n InitializableStorage storage $ = _getInitializableStorage();\n\n if ($._initializing) {\n revert InvalidInitialization();\n }\n if ($._initialized != type(uint64).max) {\n $._initialized = type(uint64).max;\n emit Initialized(type(uint64).max);\n }\n }\n\n /**\n * @dev Returns the highest version that has been initialized. See {reinitializer}.\n */\n function _getInitializedVersion() internal view returns (uint64) {\n return _getInitializableStorage()._initialized;\n }\n\n /**\n * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.\n */\n function _isInitializing() internal view returns (bool) {\n return _getInitializableStorage()._initializing;\n }\n\n /**\n * @dev Returns a pointer to the storage namespace.\n */\n // solhint-disable-next-line var-name-mixedcase\n function _getInitializableStorage() private pure returns (InitializableStorage storage $) {\n assembly {\n $.slot := INITIALIZABLE_STORAGE\n }\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.20;\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 value of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the value of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens as the allowance of `spender` over the\n * 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 value) external returns (bool);\n\n /**\n * @dev Moves a `value` amount of tokens from `from` to `to` using the\n * allowance mechanism. `value` 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(address from, address to, uint256 value) external returns (bool);\n}\n"},"src/collator/CollatorStakingHubStorage.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.20;\n\nimport \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\n\ncontract CollatorStakingHubStorage {\n // ---------------------- CollatorSetStorage ----------------------------\n // collator count\n uint256 public count;\n // ordered collators\n mapping(address => address) public collators;\n // collator => votes = staked_ring * (1 - commission)\n mapping(address => uint256) public votesOf;\n\n // ---------------------- CollatorStakingHubStorage ---------------------\n // Governance RING\n address public gRING;\n // Deposit NFT\n address public DEPOSIT;\n // collator => nomination pool\n mapping(address => address) public poolOf;\n // collator => commission\n mapping(address => uint256) public commissionOf;\n // collator => user => stakingLockTime\n mapping(address => mapping(address => uint256)) public stakingLocks;\n // collator => commissonLockTime\n mapping(address => uint256) public commissionLocks;\n // collator => user => staked ring\n mapping(address => mapping(address => uint256)) public stakedRINGOf;\n // user => staked depositIds\n mapping(address => EnumerableSet.UintSet) internal _stakedDeposits;\n\n struct DepositInfo {\n address account;\n uint256 assets;\n address collator;\n }\n\n // depositId => depositInfo\n mapping(uint256 => DepositInfo) public depositInfos;\n}\n"}},"settings":{"remappings":["forge-std/=lib/forge-std/src/","@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/","@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/","openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/","solidity-stringutils/=lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/"],"optimizer":{"enabled":true,"runs":999999},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"":["ast"],"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata","storageLayout"]}},"evmVersion":"london","viaIR":false,"libraries":{}}} diff --git a/verify/Deposit.json b/verify/Deposit.json index 3e6674e..5822ef1 100644 --- a/verify/Deposit.json +++ b/verify/Deposit.json @@ -1 +1 @@ -{"language":"Solidity","sources":{"src/deposit/Deposit.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.20;\n\nimport \"@openzeppelin/contracts/utils/Address.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"./interfaces/IKTON.sol\";\n\ncontract Deposit is\n Initializable,\n ERC721Upgradeable,\n ERC721EnumerableUpgradeable,\n ERC721URIStorageUpgradeable,\n ReentrancyGuardUpgradeable\n{\n using Address for address payable;\n\n // https://github.com/darwinia-network/darwinia/blob/main/core/inflation/src/test.rs#L86C1-L103C2\n // precision = 10_000\n uint256[37] public INTERESTS;\n uint256 private _nextTokenId;\n\n struct PalletInfo {\n uint128 value;\n uint64 startAt;\n uint64 expiredAt;\n }\n\n struct DepositInfo {\n uint64 months;\n uint64 startAt;\n uint128 value;\n }\n\n mapping(uint256 => DepositInfo) public depositOf;\n\n uint256 public constant MONTH = 30 days;\n // System Account.\n address public constant SYSTEM_PALLET = 0x6D6f646c64612f74727372790000000000000000;\n IKTON public constant KTON = IKTON(0x0000000000000000000000000000000000000402);\n\n event DepositCreated(\n uint256 indexed depositId, address indexed account, uint256 value, uint256 months, uint256 interest\n );\n event DepositMigrated(address account, uint256[] depositIds, PalletInfo[] deposits);\n event DepositClaimed(uint256 indexed depositId, address indexed account, uint256 value);\n event ClaimWithPenalty(uint256 indexed depositId, address indexed account, uint256 penalty);\n\n modifier onlySystem() {\n require(msg.sender == SYSTEM_PALLET);\n _;\n }\n\n function initialize(string memory name, string memory symbol) public initializer {\n __DepositInterest_init();\n __ERC721_init(name, symbol);\n __ERC721Enumerable_init();\n __ERC721URIStorage_init();\n __ReentrancyGuard_init();\n }\n\n function __DepositInterest_init() internal onlyInitializing {\n INTERESTS = [\n 0,\n 761,\n 1522,\n 2335,\n 3096,\n 3959,\n 4771,\n 5634,\n 6446,\n 7309,\n 8223,\n 9086,\n 10000,\n 10913,\n 11878,\n 12842,\n 13807,\n 14771,\n 15736,\n 16751,\n 17766,\n 18832,\n 19898,\n 20964,\n 22030,\n 23147,\n 24263,\n 25380,\n 26548,\n 27715,\n 28934,\n 30101,\n 31370,\n 32588,\n 33857,\n 35126,\n 36446\n ];\n }\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor() {\n _disableInitializers();\n }\n\n /// @dev Migrate user's deposits from Deposit Pallet to Deposit smart contract.\n /// The total amount of the deposit value must be passed in via msg.value.\n /// @notice Only System Pallet Account could call this function.\n /// @param account The user account address stored in Deposit Pallet.\n /// @param deposits The deposits to migrate.\n function migrate(address account, PalletInfo[] calldata deposits) external payable onlySystem nonReentrant {\n uint256 len = deposits.length;\n require(len > 0, \"!deposits\");\n uint256 totalValue;\n uint256[] memory ids = new uint256[](len);\n for (uint256 i = 0; i < len; i++) {\n PalletInfo memory info = deposits[i];\n require(info.value > 0, \"!value\");\n uint64 months = (info.expiredAt - info.startAt) / uint64(MONTH);\n require(months <= 36 && months >= 1, \"!months\");\n require(info.startAt <= block.timestamp, \"!startAt\");\n\n uint256 id = _nextTokenId++;\n depositOf[id] = DepositInfo({months: months, startAt: info.startAt, value: info.value});\n _safeMint(account, id);\n ids[i] = id;\n totalValue += info.value;\n }\n require(totalValue == msg.value, \"!totalValue\");\n emit DepositMigrated(account, ids, deposits);\n }\n\n function deposit(uint64 months) external payable nonReentrant returns (uint256) {\n return _deposit(msg.sender, msg.value, months);\n }\n\n function claim(uint256 depositId) external nonReentrant {\n DepositInfo memory info = depositOf[depositId];\n require(block.timestamp - info.startAt >= info.months * MONTH, \"penalty\");\n _claim(msg.sender, depositId, info.value);\n }\n\n function claimWithPenalty(uint256 depositId) public nonReentrant {\n uint256 penalty = computePenalty(depositId);\n require(KTON.transferFrom(msg.sender, address(this), penalty), \"!transfer\");\n require(KTON.burn(address(this), penalty), \"!burn\");\n\n DepositInfo memory info = depositOf[depositId];\n require(block.timestamp - info.startAt < info.months * MONTH, \"!penalty\");\n _claim(msg.sender, depositId, info.value);\n\n emit ClaimWithPenalty(depositId, msg.sender, penalty);\n }\n\n function assetsOf(uint256 id) public view returns (uint256) {\n _requireOwned(id);\n return depositOf[id].value;\n }\n\n function _deposit(address account, uint256 value, uint64 months) internal returns (uint256) {\n require(value > 0 && value < type(uint128).max);\n require(months <= 36 && months >= 1);\n\n uint256 id = _nextTokenId++;\n depositOf[id] = DepositInfo({months: months, startAt: uint64(block.timestamp), value: uint128(value)});\n\n uint256 interest = computeInterest(value, months);\n require(interest > 0, \"!interest\");\n require(KTON.mint(account, interest), \"!mint\");\n _safeMint(account, id);\n\n emit DepositCreated(id, account, value, months, interest);\n return id;\n }\n\n function computeInterest(uint256 value, uint256 months) public view returns (uint256) {\n uint256 interest = INTERESTS[months];\n return value * interest / 10_000 / 10_000;\n }\n\n function isClaimRequirePenalty(uint256 id) public view returns (bool) {\n _requireOwned(id);\n return block.timestamp - depositOf[id].startAt < depositOf[id].months * MONTH;\n }\n\n function computePenalty(uint256 id) public view returns (uint256) {\n DepositInfo memory info = depositOf[id];\n\n uint256 monthsDuration = (block.timestamp - info.startAt) / MONTH;\n\n return 3 * (computeInterest(info.value, info.months) - computeInterest(info.value, monthsDuration));\n }\n\n function _claim(address account, uint256 id, uint256 value) internal {\n require(_requireOwned(id) == account, \"!owned\");\n\n _burn(id);\n delete depositOf[id];\n payable(account).sendValue(value);\n\n emit DepositClaimed(id, account, value);\n }\n\n // The following functions are overrides required by Solidity.\n\n function _update(address to, uint256 tokenId, address auth)\n internal\n override(ERC721Upgradeable, ERC721EnumerableUpgradeable)\n returns (address)\n {\n return super._update(to, tokenId, auth);\n }\n\n function _increaseBalance(address account, uint128 value)\n internal\n override(ERC721Upgradeable, ERC721EnumerableUpgradeable)\n {\n super._increaseBalance(account, value);\n }\n\n function tokenURI(uint256)\n public\n pure\n override(ERC721Upgradeable, ERC721URIStorageUpgradeable)\n returns (string memory)\n {\n return \"ipfs://bafybeih57kauz6npkbafh2x3cv3hyljcakdccuckb4huwnwxxxrtqr5pqe\";\n }\n\n function supportsInterface(bytes4 interfaceId)\n public\n view\n override(ERC721Upgradeable, ERC721EnumerableUpgradeable, ERC721URIStorageUpgradeable)\n returns (bool)\n {\n return super.supportsInterface(interfaceId);\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Address.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev The ETH balance of the account is not enough to perform the operation.\n */\n error AddressInsufficientBalance(address account);\n\n /**\n * @dev There's no code at `target` (it is not a contract).\n */\n error AddressEmptyCode(address target);\n\n /**\n * @dev A call to an address target failed. The target may have reverted.\n */\n error FailedInnerCall();\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://consensys.net/diligence/blog/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.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n if (address(this).balance < amount) {\n revert AddressInsufficientBalance(address(this));\n }\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n if (!success) {\n revert FailedInnerCall();\n }\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 or custom error, it is bubbled\n * up by this function (like regular Solidity function calls). However, if\n * the call reverted with no returned reason, this function reverts with a\n * {FailedInnerCall} error.\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 function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0);\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 function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n if (address(this).balance < value) {\n revert AddressInsufficientBalance(address(this));\n }\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an\n * unsuccessful call.\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata\n ) internal view returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n // only check if target is a contract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n if (returndata.length == 0 && target.code.length == 0) {\n revert AddressEmptyCode(target);\n }\n return returndata;\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n * revert reason or with a default {FailedInnerCall} error.\n */\n function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n return returndata;\n }\n }\n\n /**\n * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.\n */\n function _revert(bytes memory returndata) private pure {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert FailedInnerCall();\n }\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/token/ERC721/ERC721Upgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC721} from \"@openzeppelin/contracts/token/ERC721/IERC721.sol\";\nimport {IERC721Receiver} from \"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol\";\nimport {IERC721Metadata} from \"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol\";\nimport {ContextUpgradeable} from \"../../utils/ContextUpgradeable.sol\";\nimport {Strings} from \"@openzeppelin/contracts/utils/Strings.sol\";\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport {ERC165Upgradeable} from \"../../utils/introspection/ERC165Upgradeable.sol\";\nimport {IERC721Errors} from \"@openzeppelin/contracts/interfaces/draft-IERC6093.sol\";\nimport {Initializable} from \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\nabstract contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721, IERC721Metadata, IERC721Errors {\n using Strings for uint256;\n\n /// @custom:storage-location erc7201:openzeppelin.storage.ERC721\n struct ERC721Storage {\n // Token name\n string _name;\n\n // Token symbol\n string _symbol;\n\n mapping(uint256 tokenId => address) _owners;\n\n mapping(address owner => uint256) _balances;\n\n mapping(uint256 tokenId => address) _tokenApprovals;\n\n mapping(address owner => mapping(address operator => bool)) _operatorApprovals;\n }\n\n // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ERC721\")) - 1)) & ~bytes32(uint256(0xff))\n bytes32 private constant ERC721StorageLocation = 0x80bb2b638cc20bc4d0a60d66940f3ab4a00c1d7b313497ca82fb0b4ab0079300;\n\n function _getERC721Storage() private pure returns (ERC721Storage storage $) {\n assembly {\n $.slot := ERC721StorageLocation\n }\n }\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {\n __ERC721_init_unchained(name_, symbol_);\n }\n\n function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\n ERC721Storage storage $ = _getERC721Storage();\n $._name = name_;\n $._symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual returns (uint256) {\n ERC721Storage storage $ = _getERC721Storage();\n if (owner == address(0)) {\n revert ERC721InvalidOwner(address(0));\n }\n return $._balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual returns (address) {\n return _requireOwned(tokenId);\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual returns (string memory) {\n ERC721Storage storage $ = _getERC721Storage();\n return $._name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual returns (string memory) {\n ERC721Storage storage $ = _getERC721Storage();\n return $._symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual returns (string memory) {\n _requireOwned(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string.concat(baseURI, tokenId.toString()) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual {\n _approve(to, tokenId, _msgSender());\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual returns (address) {\n _requireOwned(tokenId);\n\n return _getApproved(tokenId);\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {\n ERC721Storage storage $ = _getERC721Storage();\n return $._operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(address from, address to, uint256 tokenId) public virtual {\n if (to == address(0)) {\n revert ERC721InvalidReceiver(address(0));\n }\n // Setting an \"auth\" arguments enables the `_isAuthorized` check which verifies that the token exists\n // (from != 0). Therefore, it is not needed to verify that the return value is not 0 here.\n address previousOwner = _update(to, tokenId, _msgSender());\n if (previousOwner != from) {\n revert ERC721IncorrectOwner(from, tokenId, previousOwner);\n }\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId) public {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual {\n transferFrom(from, to, tokenId);\n _checkOnERC721Received(from, to, tokenId, data);\n }\n\n /**\n * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist\n *\n * IMPORTANT: Any overrides to this function that add ownership of tokens not tracked by the\n * core ERC721 logic MUST be matched with the use of {_increaseBalance} to keep balances\n * consistent with ownership. The invariant to preserve is that for any address `a` the value returned by\n * `balanceOf(a)` must be equal to the number of tokens such that `_ownerOf(tokenId)` is `a`.\n */\n function _ownerOf(uint256 tokenId) internal view virtual returns (address) {\n ERC721Storage storage $ = _getERC721Storage();\n return $._owners[tokenId];\n }\n\n /**\n * @dev Returns the approved address for `tokenId`. Returns 0 if `tokenId` is not minted.\n */\n function _getApproved(uint256 tokenId) internal view virtual returns (address) {\n ERC721Storage storage $ = _getERC721Storage();\n return $._tokenApprovals[tokenId];\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `owner`'s tokens, or `tokenId` in\n * particular (ignoring whether it is owned by `owner`).\n *\n * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this\n * assumption.\n */\n function _isAuthorized(address owner, address spender, uint256 tokenId) internal view virtual returns (bool) {\n return\n spender != address(0) &&\n (owner == spender || isApprovedForAll(owner, spender) || _getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Checks if `spender` can operate on `tokenId`, assuming the provided `owner` is the actual owner.\n * Reverts if `spender` does not have approval from the provided `owner` for the given token or for all its assets\n * the `spender` for the specific `tokenId`.\n *\n * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this\n * assumption.\n */\n function _checkAuthorized(address owner, address spender, uint256 tokenId) internal view virtual {\n if (!_isAuthorized(owner, spender, tokenId)) {\n if (owner == address(0)) {\n revert ERC721NonexistentToken(tokenId);\n } else {\n revert ERC721InsufficientApproval(spender, tokenId);\n }\n }\n }\n\n /**\n * @dev Unsafe write access to the balances, used by extensions that \"mint\" tokens using an {ownerOf} override.\n *\n * NOTE: the value is limited to type(uint128).max. This protect against _balance overflow. It is unrealistic that\n * a uint256 would ever overflow from increments when these increments are bounded to uint128 values.\n *\n * WARNING: Increasing an account's balance using this function tends to be paired with an override of the\n * {_ownerOf} function to resolve the ownership of the corresponding tokens so that balances and ownership\n * remain consistent with one another.\n */\n function _increaseBalance(address account, uint128 value) internal virtual {\n ERC721Storage storage $ = _getERC721Storage();\n unchecked {\n $._balances[account] += value;\n }\n }\n\n /**\n * @dev Transfers `tokenId` from its current owner to `to`, or alternatively mints (or burns) if the current owner\n * (or `to`) is the zero address. Returns the owner of the `tokenId` before the update.\n *\n * The `auth` argument is optional. If the value passed is non 0, then this function will check that\n * `auth` is either the owner of the token, or approved to operate on the token (by the owner).\n *\n * Emits a {Transfer} event.\n *\n * NOTE: If overriding this function in a way that tracks balances, see also {_increaseBalance}.\n */\n function _update(address to, uint256 tokenId, address auth) internal virtual returns (address) {\n ERC721Storage storage $ = _getERC721Storage();\n address from = _ownerOf(tokenId);\n\n // Perform (optional) operator check\n if (auth != address(0)) {\n _checkAuthorized(from, auth, tokenId);\n }\n\n // Execute the update\n if (from != address(0)) {\n // Clear approval. No need to re-authorize or emit the Approval event\n _approve(address(0), tokenId, address(0), false);\n\n unchecked {\n $._balances[from] -= 1;\n }\n }\n\n if (to != address(0)) {\n unchecked {\n $._balances[to] += 1;\n }\n }\n\n $._owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n return from;\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal {\n if (to == address(0)) {\n revert ERC721InvalidReceiver(address(0));\n }\n address previousOwner = _update(to, tokenId, address(0));\n if (previousOwner != address(0)) {\n revert ERC721InvalidSender(address(0));\n }\n }\n\n /**\n * @dev Mints `tokenId`, transfers it to `to` and checks for `to` acceptance.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {\n _mint(to, tokenId);\n _checkOnERC721Received(address(0), to, tokenId, data);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n * This is an internal function that does not check if the sender is authorized to operate on the token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal {\n address previousOwner = _update(address(0), tokenId, address(0));\n if (previousOwner == address(0)) {\n revert ERC721NonexistentToken(tokenId);\n }\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(address from, address to, uint256 tokenId) internal {\n if (to == address(0)) {\n revert ERC721InvalidReceiver(address(0));\n }\n address previousOwner = _update(to, tokenId, address(0));\n if (previousOwner == address(0)) {\n revert ERC721NonexistentToken(tokenId);\n } else if (previousOwner != from) {\n revert ERC721IncorrectOwner(from, tokenId, previousOwner);\n }\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking that contract recipients\n * are aware of the ERC721 standard to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is like {safeTransferFrom} in the sense that it invokes\n * {IERC721Receiver-onERC721Received} on the receiver, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `tokenId` token must exist and be owned by `from`.\n * - `to` cannot be the zero address.\n * - `from` cannot be the zero address.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(address from, address to, uint256 tokenId) internal {\n _safeTransfer(from, to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeTransfer-address-address-uint256-}[`_safeTransfer`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {\n _transfer(from, to, tokenId);\n _checkOnERC721Received(from, to, tokenId, data);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * The `auth` argument is optional. If the value passed is non 0, then this function will check that `auth` is\n * either the owner of the token, or approved to operate on all tokens held by this owner.\n *\n * Emits an {Approval} event.\n *\n * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.\n */\n function _approve(address to, uint256 tokenId, address auth) internal {\n _approve(to, tokenId, auth, true);\n }\n\n /**\n * @dev Variant of `_approve` with an optional flag to enable or disable the {Approval} event. The event is not\n * emitted in the context of transfers.\n */\n function _approve(address to, uint256 tokenId, address auth, bool emitEvent) internal virtual {\n ERC721Storage storage $ = _getERC721Storage();\n // Avoid reading the owner unless necessary\n if (emitEvent || auth != address(0)) {\n address owner = _requireOwned(tokenId);\n\n // We do not use _isAuthorized because single-token approvals should not be able to call approve\n if (auth != address(0) && owner != auth && !isApprovedForAll(owner, auth)) {\n revert ERC721InvalidApprover(auth);\n }\n\n if (emitEvent) {\n emit Approval(owner, to, tokenId);\n }\n }\n\n $._tokenApprovals[tokenId] = to;\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Requirements:\n * - operator can't be the address zero.\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {\n ERC721Storage storage $ = _getERC721Storage();\n if (operator == address(0)) {\n revert ERC721InvalidOperator(operator);\n }\n $._operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` doesn't have a current owner (it hasn't been minted, or it has been burned).\n * Returns the owner.\n *\n * Overrides to ownership logic should be done to {_ownerOf}.\n */\n function _requireOwned(uint256 tokenId) internal view returns (address) {\n address owner = _ownerOf(tokenId);\n if (owner == address(0)) {\n revert ERC721NonexistentToken(tokenId);\n }\n return owner;\n }\n\n /**\n * @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target address. This will revert if the\n * recipient doesn't accept the token transfer. The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n */\n function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory data) private {\n if (to.code.length > 0) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n if (retval != IERC721Receiver.onERC721Received.selector) {\n revert ERC721InvalidReceiver(to);\n }\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert ERC721InvalidReceiver(to);\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n }\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/ERC721Enumerable.sol)\n\npragma solidity ^0.8.20;\n\nimport {ERC721Upgradeable} from \"../ERC721Upgradeable.sol\";\nimport {IERC721Enumerable} from \"@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol\";\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport {Initializable} from \"../../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev This implements an optional extension of {ERC721} defined in the EIP that adds enumerability\n * of all the token ids in the contract as well as all token ids owned by each account.\n *\n * CAUTION: `ERC721` extensions that implement custom `balanceOf` logic, such as `ERC721Consecutive`,\n * interfere with enumerability and should not be used together with `ERC721Enumerable`.\n */\nabstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721Enumerable {\n /// @custom:storage-location erc7201:openzeppelin.storage.ERC721Enumerable\n struct ERC721EnumerableStorage {\n mapping(address owner => mapping(uint256 index => uint256)) _ownedTokens;\n mapping(uint256 tokenId => uint256) _ownedTokensIndex;\n\n uint256[] _allTokens;\n mapping(uint256 tokenId => uint256) _allTokensIndex;\n }\n\n // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ERC721Enumerable\")) - 1)) & ~bytes32(uint256(0xff))\n bytes32 private constant ERC721EnumerableStorageLocation = 0x645e039705490088daad89bae25049a34f4a9072d398537b1ab2425f24cbed00;\n\n function _getERC721EnumerableStorage() private pure returns (ERC721EnumerableStorage storage $) {\n assembly {\n $.slot := ERC721EnumerableStorageLocation\n }\n }\n\n /**\n * @dev An `owner`'s token query was out of bounds for `index`.\n *\n * NOTE: The owner being `address(0)` indicates a global out of bounds index.\n */\n error ERC721OutOfBoundsIndex(address owner, uint256 index);\n\n /**\n * @dev Batch mint is not allowed.\n */\n error ERC721EnumerableForbiddenBatchMint();\n\n function __ERC721Enumerable_init() internal onlyInitializing {\n }\n\n function __ERC721Enumerable_init_unchained() internal onlyInitializing {\n }\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721Upgradeable) returns (bool) {\n return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.\n */\n function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual returns (uint256) {\n ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();\n if (index >= balanceOf(owner)) {\n revert ERC721OutOfBoundsIndex(owner, index);\n }\n return $._ownedTokens[owner][index];\n }\n\n /**\n * @dev See {IERC721Enumerable-totalSupply}.\n */\n function totalSupply() public view virtual returns (uint256) {\n ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();\n return $._allTokens.length;\n }\n\n /**\n * @dev See {IERC721Enumerable-tokenByIndex}.\n */\n function tokenByIndex(uint256 index) public view virtual returns (uint256) {\n ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();\n if (index >= totalSupply()) {\n revert ERC721OutOfBoundsIndex(address(0), index);\n }\n return $._allTokens[index];\n }\n\n /**\n * @dev See {ERC721-_update}.\n */\n function _update(address to, uint256 tokenId, address auth) internal virtual override returns (address) {\n address previousOwner = super._update(to, tokenId, auth);\n\n if (previousOwner == address(0)) {\n _addTokenToAllTokensEnumeration(tokenId);\n } else if (previousOwner != to) {\n _removeTokenFromOwnerEnumeration(previousOwner, tokenId);\n }\n if (to == address(0)) {\n _removeTokenFromAllTokensEnumeration(tokenId);\n } else if (previousOwner != to) {\n _addTokenToOwnerEnumeration(to, tokenId);\n }\n\n return previousOwner;\n }\n\n /**\n * @dev Private function to add a token to this extension's ownership-tracking data structures.\n * @param to address representing the new owner of the given token ID\n * @param tokenId uint256 ID of the token to be added to the tokens list of the given address\n */\n function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {\n ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();\n uint256 length = balanceOf(to) - 1;\n $._ownedTokens[to][length] = tokenId;\n $._ownedTokensIndex[tokenId] = length;\n }\n\n /**\n * @dev Private function to add a token to this extension's token tracking data structures.\n * @param tokenId uint256 ID of the token to be added to the tokens list\n */\n function _addTokenToAllTokensEnumeration(uint256 tokenId) private {\n ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();\n $._allTokensIndex[tokenId] = $._allTokens.length;\n $._allTokens.push(tokenId);\n }\n\n /**\n * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that\n * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for\n * gas optimizations e.g. when performing a transfer operation (avoiding double writes).\n * This has O(1) time complexity, but alters the order of the _ownedTokens array.\n * @param from address representing the previous owner of the given token ID\n * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address\n */\n function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {\n ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();\n // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and\n // then delete the last slot (swap and pop).\n\n uint256 lastTokenIndex = balanceOf(from);\n uint256 tokenIndex = $._ownedTokensIndex[tokenId];\n\n // When the token to delete is the last token, the swap operation is unnecessary\n if (tokenIndex != lastTokenIndex) {\n uint256 lastTokenId = $._ownedTokens[from][lastTokenIndex];\n\n $._ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token\n $._ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index\n }\n\n // This also deletes the contents at the last position of the array\n delete $._ownedTokensIndex[tokenId];\n delete $._ownedTokens[from][lastTokenIndex];\n }\n\n /**\n * @dev Private function to remove a token from this extension's token tracking data structures.\n * This has O(1) time complexity, but alters the order of the _allTokens array.\n * @param tokenId uint256 ID of the token to be removed from the tokens list\n */\n function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {\n ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();\n // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and\n // then delete the last slot (swap and pop).\n\n uint256 lastTokenIndex = $._allTokens.length - 1;\n uint256 tokenIndex = $._allTokensIndex[tokenId];\n\n // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so\n // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding\n // an 'if' statement (like in _removeTokenFromOwnerEnumeration)\n uint256 lastTokenId = $._allTokens[lastTokenIndex];\n\n $._allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token\n $._allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index\n\n // This also deletes the contents at the last position of the array\n delete $._allTokensIndex[tokenId];\n $._allTokens.pop();\n }\n\n /**\n * See {ERC721-_increaseBalance}. We need that to account tokens that were minted in batch\n */\n function _increaseBalance(address account, uint128 amount) internal virtual override {\n if (amount > 0) {\n revert ERC721EnumerableForbiddenBatchMint();\n }\n super._increaseBalance(account, amount);\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/ERC721URIStorage.sol)\n\npragma solidity ^0.8.20;\n\nimport {ERC721Upgradeable} from \"../ERC721Upgradeable.sol\";\nimport {Strings} from \"@openzeppelin/contracts/utils/Strings.sol\";\nimport {IERC4906} from \"@openzeppelin/contracts/interfaces/IERC4906.sol\";\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport {Initializable} from \"../../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev ERC721 token with storage based token URI management.\n */\nabstract contract ERC721URIStorageUpgradeable is Initializable, IERC4906, ERC721Upgradeable {\n using Strings for uint256;\n\n // Interface ID as defined in ERC-4906. This does not correspond to a traditional interface ID as ERC-4906 only\n // defines events and does not include any external function.\n bytes4 private constant ERC4906_INTERFACE_ID = bytes4(0x49064906);\n\n /// @custom:storage-location erc7201:openzeppelin.storage.ERC721URIStorage\n struct ERC721URIStorageStorage {\n // Optional mapping for token URIs\n mapping(uint256 tokenId => string) _tokenURIs;\n }\n\n // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ERC721URIStorage\")) - 1)) & ~bytes32(uint256(0xff))\n bytes32 private constant ERC721URIStorageStorageLocation = 0x0542a41881ee128a365a727b282c86fa859579490b9bb45aab8503648c8e7900;\n\n function _getERC721URIStorageStorage() private pure returns (ERC721URIStorageStorage storage $) {\n assembly {\n $.slot := ERC721URIStorageStorageLocation\n }\n }\n\n function __ERC721URIStorage_init() internal onlyInitializing {\n }\n\n function __ERC721URIStorage_init_unchained() internal onlyInitializing {\n }\n /**\n * @dev See {IERC165-supportsInterface}\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Upgradeable, IERC165) returns (bool) {\n return interfaceId == ERC4906_INTERFACE_ID || super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n ERC721URIStorageStorage storage $ = _getERC721URIStorageStorage();\n _requireOwned(tokenId);\n\n string memory _tokenURI = $._tokenURIs[tokenId];\n string memory base = _baseURI();\n\n // If there is no base URI, return the token URI.\n if (bytes(base).length == 0) {\n return _tokenURI;\n }\n // If both are set, concatenate the baseURI and tokenURI (via string.concat).\n if (bytes(_tokenURI).length > 0) {\n return string.concat(base, _tokenURI);\n }\n\n return super.tokenURI(tokenId);\n }\n\n /**\n * @dev Sets `_tokenURI` as the tokenURI of `tokenId`.\n *\n * Emits {MetadataUpdate}.\n */\n function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {\n ERC721URIStorageStorage storage $ = _getERC721URIStorageStorage();\n $._tokenURIs[tokenId] = _tokenURI;\n emit MetadataUpdate(tokenId);\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)\n\npragma solidity ^0.8.20;\nimport {Initializable} from \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuardUpgradeable is Initializable {\n // Booleans are more expensive than uint256 or any type that takes up a full\n // word because each write operation emits an extra SLOAD to first read the\n // slot's contents, replace the bits taken up by the boolean, and then write\n // back. This is the compiler's defense against contract upgrades and\n // pointer aliasing, and it cannot be disabled.\n\n // The values being non-zero value makes deployment a bit more expensive,\n // but in exchange the refund on every call to nonReentrant will be lower in\n // amount. Since refunds are capped to a percentage of the total\n // transaction's gas, it is best to keep them low in cases like this one, to\n // increase the likelihood of the full refund coming into effect.\n uint256 private constant NOT_ENTERED = 1;\n uint256 private constant ENTERED = 2;\n\n /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard\n struct ReentrancyGuardStorage {\n uint256 _status;\n }\n\n // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ReentrancyGuard\")) - 1)) & ~bytes32(uint256(0xff))\n bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;\n\n function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {\n assembly {\n $.slot := ReentrancyGuardStorageLocation\n }\n }\n\n /**\n * @dev Unauthorized reentrant call.\n */\n error ReentrancyGuardReentrantCall();\n\n function __ReentrancyGuard_init() internal onlyInitializing {\n __ReentrancyGuard_init_unchained();\n }\n\n function __ReentrancyGuard_init_unchained() internal onlyInitializing {\n ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n $._status = NOT_ENTERED;\n }\n\n /**\n * @dev Prevents a contract from calling itself, directly or indirectly.\n * Calling a `nonReentrant` function from another `nonReentrant`\n * function is not supported. It is possible to prevent this from happening\n * by making the `nonReentrant` function external, and making it call a\n * `private` function that does the actual work.\n */\n modifier nonReentrant() {\n _nonReentrantBefore();\n _;\n _nonReentrantAfter();\n }\n\n function _nonReentrantBefore() private {\n ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n // On the first call to nonReentrant, _status will be NOT_ENTERED\n if ($._status == ENTERED) {\n revert ReentrancyGuardReentrantCall();\n }\n\n // Any calls to nonReentrant after this point will fail\n $._status = ENTERED;\n }\n\n function _nonReentrantAfter() private {\n ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n // By storing the original value once again, a refund is triggered (see\n // https://eips.ethereum.org/EIPS/eip-2200)\n $._status = NOT_ENTERED;\n }\n\n /**\n * @dev Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n * `nonReentrant` function in the call stack.\n */\n function _reentrancyGuardEntered() internal view returns (bool) {\n ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n return $._status == ENTERED;\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```solidity\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n *\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Storage of the initializable contract.\n *\n * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions\n * when using with upgradeable contracts.\n *\n * @custom:storage-location erc7201:openzeppelin.storage.Initializable\n */\n struct InitializableStorage {\n /**\n * @dev Indicates that the contract has been initialized.\n */\n uint64 _initialized;\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool _initializing;\n }\n\n // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.Initializable\")) - 1)) & ~bytes32(uint256(0xff))\n bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;\n\n /**\n * @dev The contract is already initialized.\n */\n error InvalidInitialization();\n\n /**\n * @dev The contract is not initializing.\n */\n error NotInitializing();\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint64 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts.\n *\n * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any\n * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in\n * production.\n *\n * Emits an {Initialized} event.\n */\n modifier initializer() {\n // solhint-disable-next-line var-name-mixedcase\n InitializableStorage storage $ = _getInitializableStorage();\n\n // Cache values to avoid duplicated sloads\n bool isTopLevelCall = !$._initializing;\n uint64 initialized = $._initialized;\n\n // Allowed calls:\n // - initialSetup: the contract is not in the initializing state and no previous version was\n // initialized\n // - construction: the contract is initialized at version 1 (no reininitialization) and the\n // current contract is just being deployed\n bool initialSetup = initialized == 0 && isTopLevelCall;\n bool construction = initialized == 1 && address(this).code.length == 0;\n\n if (!initialSetup && !construction) {\n revert InvalidInitialization();\n }\n $._initialized = 1;\n if (isTopLevelCall) {\n $._initializing = true;\n }\n _;\n if (isTopLevelCall) {\n $._initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n * are added through upgrades and that require initialization.\n *\n * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n * cannot be nested. If one is invoked in the context of another, execution will revert.\n *\n * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n * a contract, executing them in the right order is up to the developer or operator.\n *\n * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.\n *\n * Emits an {Initialized} event.\n */\n modifier reinitializer(uint64 version) {\n // solhint-disable-next-line var-name-mixedcase\n InitializableStorage storage $ = _getInitializableStorage();\n\n if ($._initializing || $._initialized >= version) {\n revert InvalidInitialization();\n }\n $._initialized = version;\n $._initializing = true;\n _;\n $._initializing = false;\n emit Initialized(version);\n }\n\n /**\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n * {initializer} and {reinitializer} modifiers, directly or indirectly.\n */\n modifier onlyInitializing() {\n _checkInitializing();\n _;\n }\n\n /**\n * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.\n */\n function _checkInitializing() internal view virtual {\n if (!_isInitializing()) {\n revert NotInitializing();\n }\n }\n\n /**\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n * through proxies.\n *\n * Emits an {Initialized} event the first time it is successfully executed.\n */\n function _disableInitializers() internal virtual {\n // solhint-disable-next-line var-name-mixedcase\n InitializableStorage storage $ = _getInitializableStorage();\n\n if ($._initializing) {\n revert InvalidInitialization();\n }\n if ($._initialized != type(uint64).max) {\n $._initialized = type(uint64).max;\n emit Initialized(type(uint64).max);\n }\n }\n\n /**\n * @dev Returns the highest version that has been initialized. See {reinitializer}.\n */\n function _getInitializedVersion() internal view returns (uint64) {\n return _getInitializableStorage()._initialized;\n }\n\n /**\n * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.\n */\n function _isInitializing() internal view returns (bool) {\n return _getInitializableStorage()._initializing;\n }\n\n /**\n * @dev Returns a pointer to the storage namespace.\n */\n // solhint-disable-next-line var-name-mixedcase\n function _getInitializableStorage() private pure returns (InitializableStorage storage $) {\n assembly {\n $.slot := INITIALIZABLE_STORAGE\n }\n }\n}\n"},"src/deposit/interfaces/IKTON.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity >=0.4.24;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\ninterface IKTON is IERC20 {\n function burn(address from, uint256 amount) external returns (bool);\n function mint(address to, uint256 amount) external returns (bool);\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon\n * a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or\n * {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon\n * a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721\n * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must\n * understand this adds an external call which potentially creates a reentrancy vulnerability.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address from, address to, uint256 tokenId) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the address zero.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be\n * reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/IERC721Metadata.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC721} from \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\n\npragma solidity ^0.8.20;\nimport {Initializable} from \"../proxy/utils/Initializable.sol\";\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 ContextUpgradeable is Initializable {\n function __Context_init() internal onlyInitializing {\n }\n\n function __Context_init_unchained() internal onlyInitializing {\n }\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 function _contextSuffixLength() internal view virtual returns (uint256) {\n return 0;\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Strings.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)\n\npragma solidity ^0.8.20;\n\nimport {Math} from \"./math/Math.sol\";\nimport {SignedMath} from \"./math/SignedMath.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant HEX_DIGITS = \"0123456789abcdef\";\n uint8 private constant ADDRESS_LENGTH = 20;\n\n /**\n * @dev The `value` string doesn't fit in the specified `length`.\n */\n error StringsInsufficientHexLength(uint256 value, uint256 length);\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n unchecked {\n uint256 length = Math.log10(value) + 1;\n string memory buffer = new string(length);\n uint256 ptr;\n /// @solidity memory-safe-assembly\n assembly {\n ptr := add(buffer, add(32, length))\n }\n while (true) {\n ptr--;\n /// @solidity memory-safe-assembly\n assembly {\n mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))\n }\n value /= 10;\n if (value == 0) break;\n }\n return buffer;\n }\n }\n\n /**\n * @dev Converts a `int256` to its ASCII `string` decimal representation.\n */\n function toStringSigned(int256 value) internal pure returns (string memory) {\n return string.concat(value < 0 ? \"-\" : \"\", toString(SignedMath.abs(value)));\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n unchecked {\n return toHexString(value, Math.log256(value) + 1);\n }\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n uint256 localValue = value;\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = HEX_DIGITS[localValue & 0xf];\n localValue >>= 4;\n }\n if (localValue != 0) {\n revert StringsInsufficientHexLength(value, length);\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal\n * representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);\n }\n\n /**\n * @dev Returns true if the two strings are equal.\n */\n function equal(string memory a, string memory b) internal pure returns (bool) {\n return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport {Initializable} from \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n */\nabstract contract ERC165Upgradeable is Initializable, IERC165 {\n function __ERC165_init() internal onlyInitializing {\n }\n\n function __ERC165_init_unchained() internal onlyInitializing {\n }\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard ERC20 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.\n */\ninterface IERC20Errors {\n /**\n * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n * @param balance Current balance for the interacting account.\n * @param needed Minimum amount required to perform a transfer.\n */\n error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);\n\n /**\n * @dev Indicates a failure with the token `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n */\n error ERC20InvalidSender(address sender);\n\n /**\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\n * @param receiver Address to which tokens are being transferred.\n */\n error ERC20InvalidReceiver(address receiver);\n\n /**\n * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.\n * @param spender Address that may be allowed to operate on tokens without being their owner.\n * @param allowance Amount of tokens a `spender` is allowed to operate with.\n * @param needed Minimum amount required to perform a transfer.\n */\n error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);\n\n /**\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n * @param approver Address initiating an approval operation.\n */\n error ERC20InvalidApprover(address approver);\n\n /**\n * @dev Indicates a failure with the `spender` to be approved. Used in approvals.\n * @param spender Address that may be allowed to operate on tokens without being their owner.\n */\n error ERC20InvalidSpender(address spender);\n}\n\n/**\n * @dev Standard ERC721 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.\n */\ninterface IERC721Errors {\n /**\n * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.\n * Used in balance queries.\n * @param owner Address of the current owner of a token.\n */\n error ERC721InvalidOwner(address owner);\n\n /**\n * @dev Indicates a `tokenId` whose `owner` is the zero address.\n * @param tokenId Identifier number of a token.\n */\n error ERC721NonexistentToken(uint256 tokenId);\n\n /**\n * @dev Indicates an error related to the ownership over a particular token. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n * @param tokenId Identifier number of a token.\n * @param owner Address of the current owner of a token.\n */\n error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);\n\n /**\n * @dev Indicates a failure with the token `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n */\n error ERC721InvalidSender(address sender);\n\n /**\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\n * @param receiver Address to which tokens are being transferred.\n */\n error ERC721InvalidReceiver(address receiver);\n\n /**\n * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n * @param operator Address that may be allowed to operate on tokens without being their owner.\n * @param tokenId Identifier number of a token.\n */\n error ERC721InsufficientApproval(address operator, uint256 tokenId);\n\n /**\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n * @param approver Address initiating an approval operation.\n */\n error ERC721InvalidApprover(address approver);\n\n /**\n * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n * @param operator Address that may be allowed to operate on tokens without being their owner.\n */\n error ERC721InvalidOperator(address operator);\n}\n\n/**\n * @dev Standard ERC1155 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.\n */\ninterface IERC1155Errors {\n /**\n * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n * @param balance Current balance for the interacting account.\n * @param needed Minimum amount required to perform a transfer.\n * @param tokenId Identifier number of a token.\n */\n error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);\n\n /**\n * @dev Indicates a failure with the token `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n */\n error ERC1155InvalidSender(address sender);\n\n /**\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\n * @param receiver Address to which tokens are being transferred.\n */\n error ERC1155InvalidReceiver(address receiver);\n\n /**\n * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n * @param operator Address that may be allowed to operate on tokens without being their owner.\n * @param owner Address of the current owner of a token.\n */\n error ERC1155MissingApprovalForAll(address operator, address owner);\n\n /**\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n * @param approver Address initiating an approval operation.\n */\n error ERC1155InvalidApprover(address approver);\n\n /**\n * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n * @param operator Address that may be allowed to operate on tokens without being their owner.\n */\n error ERC1155InvalidOperator(address operator);\n\n /**\n * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.\n * Used in batch transfers.\n * @param idsLength Length of the array of token identifiers\n * @param valuesLength Length of the array of token amounts\n */\n error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/IERC721Enumerable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Enumerable.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC721} from \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Enumerable is IERC721 {\n /**\n * @dev Returns the total amount of tokens stored by the contract.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns a token ID owned by `owner` at a given `index` of its token list.\n * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.\n */\n function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);\n\n /**\n * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.\n * Use along with {totalSupply} to enumerate all tokens.\n */\n function tokenByIndex(uint256 index) external view returns (uint256);\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC4906.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC4906.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"./IERC165.sol\";\nimport {IERC721} from \"./IERC721.sol\";\n\n/// @title EIP-721 Metadata Update Extension\ninterface IERC4906 is IERC165, IERC721 {\n /// @dev This event emits when the metadata of a token is changed.\n /// So that the third-party platforms such as NFT market could\n /// timely update the images and related attributes of the NFT.\n event MetadataUpdate(uint256 _tokenId);\n\n /// @dev This event emits when the metadata of a range of tokens is changed.\n /// So that the third-party platforms such as NFT market could\n /// timely update the images and related attributes of the NFTs.\n event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.20;\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 value of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the value of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens as the allowance of `spender` over the\n * 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 value) external returns (bool);\n\n /**\n * @dev Moves a `value` amount of tokens from `from` to `to` using the\n * allowance mechanism. `value` 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(address from, address to, uint256 value) external returns (bool);\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/Math.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n /**\n * @dev Muldiv operation overflow.\n */\n error MathOverflowedMulDiv();\n\n enum Rounding {\n Floor, // Toward negative infinity\n Ceil, // Toward positive infinity\n Trunc, // Toward zero\n Expand // Away from zero\n }\n\n /**\n * @dev Returns the addition of two unsigned integers, with an overflow flag.\n */\n function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n uint256 c = a + b;\n if (c < a) return (false, 0);\n return (true, c);\n }\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, with an overflow flag.\n */\n function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b > a) return (false, 0);\n return (true, a - b);\n }\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n */\n function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) return (true, 0);\n uint256 c = a * b;\n if (c / a != b) return (false, 0);\n return (true, c);\n }\n }\n\n /**\n * @dev Returns the division of two unsigned integers, with a division by zero flag.\n */\n function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b == 0) return (false, 0);\n return (true, a / b);\n }\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n */\n function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b == 0) return (false, 0);\n return (true, a % b);\n }\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds towards infinity instead\n * of rounding towards zero.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n if (b == 0) {\n // Guarantee the same behavior as in a regular Solidity division.\n return a / b;\n }\n\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or\n * denominator == 0.\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by\n * Uniswap Labs also under MIT license.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0 = x * y; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n // The surrounding unchecked block does not change this fact.\n // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n if (denominator <= prod1) {\n revert MathOverflowedMulDiv();\n }\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator.\n // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.\n\n uint256 twos = denominator & (0 - denominator);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also\n // works in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded\n * towards zero.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n //\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n //\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n //\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1 << (log2(a) >> 1);\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = sqrt(a);\n return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 2 of a positive value rounded towards zero.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 128;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 64;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 32;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 16;\n }\n if (value >> 8 > 0) {\n value >>= 8;\n result += 8;\n }\n if (value >> 4 > 0) {\n value >>= 4;\n result += 4;\n }\n if (value >> 2 > 0) {\n value >>= 2;\n result += 2;\n }\n if (value >> 1 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 10 of a positive value rounded towards zero.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10 ** 64) {\n value /= 10 ** 64;\n result += 64;\n }\n if (value >= 10 ** 32) {\n value /= 10 ** 32;\n result += 32;\n }\n if (value >= 10 ** 16) {\n value /= 10 ** 16;\n result += 16;\n }\n if (value >= 10 ** 8) {\n value /= 10 ** 8;\n result += 8;\n }\n if (value >= 10 ** 4) {\n value /= 10 ** 4;\n result += 4;\n }\n if (value >= 10 ** 2) {\n value /= 10 ** 2;\n result += 2;\n }\n if (value >= 10 ** 1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 256 of a positive value rounded towards zero.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 16;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 8;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 4;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 2;\n }\n if (value >> 8 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.\n */\n function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {\n return uint8(rounding) % 2 == 1;\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard signed math utilities missing in the Solidity language.\n */\nlibrary SignedMath {\n /**\n * @dev Returns the largest of two signed numbers.\n */\n function max(int256 a, int256 b) internal pure returns (int256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two signed numbers.\n */\n function min(int256 a, int256 b) internal pure returns (int256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two signed numbers without overflow.\n * The result is rounded towards zero.\n */\n function average(int256 a, int256 b) internal pure returns (int256) {\n // Formula from the book \"Hacker's Delight\"\n int256 x = (a & b) + ((a ^ b) >> 1);\n return x + (int256(uint256(x) >> 255) & (a ^ b));\n }\n\n /**\n * @dev Returns the absolute unsigned value of a signed value.\n */\n function abs(int256 n) internal pure returns (uint256) {\n unchecked {\n // must be unchecked in order to support `n = type(int256).min`\n return uint256(n >= 0 ? n : -n);\n }\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"../utils/introspection/IERC165.sol\";\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC721.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC721.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC721} from \"../token/ERC721/IERC721.sol\";\n"}},"settings":{"remappings":["forge-std/=lib/forge-std/src/","@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/","@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/","openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/","solidity-stringutils/=lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/"],"optimizer":{"enabled":true,"runs":999999},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"":["ast"],"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata","storageLayout"]}},"evmVersion":"london","viaIR":false,"libraries":{}}} +{"language":"Solidity","sources":{"src/deposit/Deposit.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.20;\n\nimport \"@openzeppelin/contracts/utils/Address.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"./interfaces/IKTON.sol\";\n\ncontract Deposit is\n Initializable,\n ERC721Upgradeable,\n ERC721EnumerableUpgradeable,\n ERC721URIStorageUpgradeable,\n ReentrancyGuardUpgradeable\n{\n using Address for address payable;\n\n // https://github.com/darwinia-network/darwinia/blob/main/core/inflation/src/test.rs#L86C1-L103C2\n // precision = 10_000\n uint256[37] public INTERESTS;\n uint256 private _nextTokenId;\n\n struct PalletInfo {\n uint128 value;\n uint64 startAt;\n uint64 expiredAt;\n }\n\n struct DepositInfo {\n uint64 months;\n uint64 startAt;\n uint128 value;\n }\n\n mapping(uint256 => DepositInfo) public depositOf;\n\n uint256 public constant MONTH = 30 days;\n // System Account.\n address public constant SYSTEM_PALLET = 0x6D6f646c64612f74727372790000000000000000;\n IKTON public constant KTON = IKTON(0x0000000000000000000000000000000000000402);\n\n event DepositCreated(\n uint256 indexed depositId, address indexed account, uint256 value, uint256 months, uint256 interest\n );\n event DepositMigrated(address account, uint256[] depositIds, PalletInfo[] deposits);\n event DepositClaimed(uint256 indexed depositId, address indexed account, uint256 value);\n event ClaimWithPenalty(uint256 indexed depositId, address indexed account, uint256 penalty);\n\n modifier onlySystem() {\n require(msg.sender == SYSTEM_PALLET);\n _;\n }\n\n function initialize(string memory name, string memory symbol) public initializer {\n __DepositInterest_init();\n __ERC721_init(name, symbol);\n __ERC721Enumerable_init();\n __ERC721URIStorage_init();\n __ReentrancyGuard_init();\n }\n\n function __DepositInterest_init() internal onlyInitializing {\n INTERESTS = [\n 0,\n 761,\n 1522,\n 2335,\n 3096,\n 3959,\n 4771,\n 5634,\n 6446,\n 7309,\n 8223,\n 9086,\n 10000,\n 10913,\n 11878,\n 12842,\n 13807,\n 14771,\n 15736,\n 16751,\n 17766,\n 18832,\n 19898,\n 20964,\n 22030,\n 23147,\n 24263,\n 25380,\n 26548,\n 27715,\n 28934,\n 30101,\n 31370,\n 32588,\n 33857,\n 35126,\n 36446\n ];\n }\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor() {\n _disableInitializers();\n }\n\n /// @dev Migrate user's deposits from Deposit Pallet to Deposit smart contract.\n /// The total amount of the deposit value must be passed in via msg.value.\n /// @notice Only System Pallet Account could call this function.\n /// @param account The user account address stored in Deposit Pallet.\n /// @param deposits The deposits to migrate.\n function migrate(address account, PalletInfo[] calldata deposits) external payable onlySystem nonReentrant {\n uint256 len = deposits.length;\n require(len > 0, \"!deposits\");\n uint256 totalValue;\n uint256[] memory ids = new uint256[](len);\n for (uint256 i = 0; i < len; i++) {\n PalletInfo memory info = deposits[i];\n require(info.value > 0, \"!value\");\n uint64 months = (info.expiredAt - info.startAt) / uint64(MONTH);\n require(months <= 36 && months >= 1, \"!months\");\n require(info.startAt <= block.timestamp, \"!startAt\");\n\n uint256 id = _nextTokenId++;\n depositOf[id] = DepositInfo({months: months, startAt: info.startAt, value: info.value});\n _safeMint(account, id);\n ids[i] = id;\n totalValue += info.value;\n }\n require(totalValue == msg.value, \"!totalValue\");\n emit DepositMigrated(account, ids, deposits);\n }\n\n function deposit(uint64 months) external payable nonReentrant returns (uint256) {\n return _deposit(msg.sender, msg.value, months);\n }\n\n function claim(uint256 depositId) external nonReentrant {\n DepositInfo memory info = depositOf[depositId];\n require(block.timestamp - info.startAt >= info.months * MONTH, \"penalty\");\n _claim(msg.sender, depositId, info.value);\n }\n\n function claimWithPenalty(uint256 depositId) public nonReentrant {\n uint256 penalty = computePenalty(depositId);\n require(KTON.transferFrom(msg.sender, address(this), penalty), \"!transfer\");\n require(KTON.burn(address(this), penalty), \"!burn\");\n\n DepositInfo memory info = depositOf[depositId];\n require(block.timestamp - info.startAt < info.months * MONTH, \"!penalty\");\n _claim(msg.sender, depositId, info.value);\n\n emit ClaimWithPenalty(depositId, msg.sender, penalty);\n }\n\n function assetsOf(uint256 id) public view returns (uint256) {\n _requireOwned(id);\n return depositOf[id].value;\n }\n\n function _deposit(address account, uint256 value, uint64 months) internal returns (uint256) {\n require(value > 0 && value < type(uint128).max);\n require(months <= 36 && months >= 1);\n\n uint256 id = _nextTokenId++;\n depositOf[id] = DepositInfo({months: months, startAt: uint64(block.timestamp), value: uint128(value)});\n\n uint256 interest = computeInterest(value, months);\n require(interest > 0, \"!interest\");\n require(KTON.mint(account, interest), \"!mint\");\n _safeMint(account, id);\n\n emit DepositCreated(id, account, value, months, interest);\n return id;\n }\n\n function computeInterest(uint256 value, uint256 months) public view returns (uint256) {\n uint256 interest = INTERESTS[months];\n return value * interest / 10_000 / 10_000;\n }\n\n function isClaimRequirePenalty(uint256 id) public view returns (bool) {\n _requireOwned(id);\n return block.timestamp - depositOf[id].startAt < depositOf[id].months * MONTH;\n }\n\n function computePenalty(uint256 id) public view returns (uint256) {\n DepositInfo memory info = depositOf[id];\n\n uint256 monthsDuration = (block.timestamp - info.startAt) / MONTH;\n\n return 3 * (computeInterest(info.value, info.months) - computeInterest(info.value, monthsDuration));\n }\n\n function _claim(address account, uint256 id, uint256 value) internal {\n require(_requireOwned(id) == account, \"!owned\");\n\n _burn(id);\n delete depositOf[id];\n payable(account).sendValue(value);\n\n emit DepositClaimed(id, account, value);\n }\n\n // The following functions are overrides required by Solidity.\n\n function _update(address to, uint256 tokenId, address auth)\n internal\n override(ERC721Upgradeable, ERC721EnumerableUpgradeable)\n returns (address)\n {\n return super._update(to, tokenId, auth);\n }\n\n function _increaseBalance(address account, uint128 value)\n internal\n override(ERC721Upgradeable, ERC721EnumerableUpgradeable)\n {\n super._increaseBalance(account, value);\n }\n\n function tokenURI(uint256)\n public\n pure\n override(ERC721Upgradeable, ERC721URIStorageUpgradeable)\n returns (string memory)\n {\n return \"ipfs://bafybeifyt273t4ns4f5c4u57uvtbbh5cuv5uxtpt6x3kn32mfecgltjeh4\";\n }\n\n function supportsInterface(bytes4 interfaceId)\n public\n view\n override(ERC721Upgradeable, ERC721EnumerableUpgradeable, ERC721URIStorageUpgradeable)\n returns (bool)\n {\n return super.supportsInterface(interfaceId);\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Address.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev The ETH balance of the account is not enough to perform the operation.\n */\n error AddressInsufficientBalance(address account);\n\n /**\n * @dev There's no code at `target` (it is not a contract).\n */\n error AddressEmptyCode(address target);\n\n /**\n * @dev A call to an address target failed. The target may have reverted.\n */\n error FailedInnerCall();\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://consensys.net/diligence/blog/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.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n if (address(this).balance < amount) {\n revert AddressInsufficientBalance(address(this));\n }\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n if (!success) {\n revert FailedInnerCall();\n }\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 or custom error, it is bubbled\n * up by this function (like regular Solidity function calls). However, if\n * the call reverted with no returned reason, this function reverts with a\n * {FailedInnerCall} error.\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 function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0);\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 function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n if (address(this).balance < value) {\n revert AddressInsufficientBalance(address(this));\n }\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an\n * unsuccessful call.\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata\n ) internal view returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n // only check if target is a contract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n if (returndata.length == 0 && target.code.length == 0) {\n revert AddressEmptyCode(target);\n }\n return returndata;\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n * revert reason or with a default {FailedInnerCall} error.\n */\n function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n return returndata;\n }\n }\n\n /**\n * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.\n */\n function _revert(bytes memory returndata) private pure {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert FailedInnerCall();\n }\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/token/ERC721/ERC721Upgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC721} from \"@openzeppelin/contracts/token/ERC721/IERC721.sol\";\nimport {IERC721Receiver} from \"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol\";\nimport {IERC721Metadata} from \"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol\";\nimport {ContextUpgradeable} from \"../../utils/ContextUpgradeable.sol\";\nimport {Strings} from \"@openzeppelin/contracts/utils/Strings.sol\";\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport {ERC165Upgradeable} from \"../../utils/introspection/ERC165Upgradeable.sol\";\nimport {IERC721Errors} from \"@openzeppelin/contracts/interfaces/draft-IERC6093.sol\";\nimport {Initializable} from \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\nabstract contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721, IERC721Metadata, IERC721Errors {\n using Strings for uint256;\n\n /// @custom:storage-location erc7201:openzeppelin.storage.ERC721\n struct ERC721Storage {\n // Token name\n string _name;\n\n // Token symbol\n string _symbol;\n\n mapping(uint256 tokenId => address) _owners;\n\n mapping(address owner => uint256) _balances;\n\n mapping(uint256 tokenId => address) _tokenApprovals;\n\n mapping(address owner => mapping(address operator => bool)) _operatorApprovals;\n }\n\n // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ERC721\")) - 1)) & ~bytes32(uint256(0xff))\n bytes32 private constant ERC721StorageLocation = 0x80bb2b638cc20bc4d0a60d66940f3ab4a00c1d7b313497ca82fb0b4ab0079300;\n\n function _getERC721Storage() private pure returns (ERC721Storage storage $) {\n assembly {\n $.slot := ERC721StorageLocation\n }\n }\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {\n __ERC721_init_unchained(name_, symbol_);\n }\n\n function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\n ERC721Storage storage $ = _getERC721Storage();\n $._name = name_;\n $._symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual returns (uint256) {\n ERC721Storage storage $ = _getERC721Storage();\n if (owner == address(0)) {\n revert ERC721InvalidOwner(address(0));\n }\n return $._balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual returns (address) {\n return _requireOwned(tokenId);\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual returns (string memory) {\n ERC721Storage storage $ = _getERC721Storage();\n return $._name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual returns (string memory) {\n ERC721Storage storage $ = _getERC721Storage();\n return $._symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual returns (string memory) {\n _requireOwned(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string.concat(baseURI, tokenId.toString()) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual {\n _approve(to, tokenId, _msgSender());\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual returns (address) {\n _requireOwned(tokenId);\n\n return _getApproved(tokenId);\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {\n ERC721Storage storage $ = _getERC721Storage();\n return $._operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(address from, address to, uint256 tokenId) public virtual {\n if (to == address(0)) {\n revert ERC721InvalidReceiver(address(0));\n }\n // Setting an \"auth\" arguments enables the `_isAuthorized` check which verifies that the token exists\n // (from != 0). Therefore, it is not needed to verify that the return value is not 0 here.\n address previousOwner = _update(to, tokenId, _msgSender());\n if (previousOwner != from) {\n revert ERC721IncorrectOwner(from, tokenId, previousOwner);\n }\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId) public {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual {\n transferFrom(from, to, tokenId);\n _checkOnERC721Received(from, to, tokenId, data);\n }\n\n /**\n * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist\n *\n * IMPORTANT: Any overrides to this function that add ownership of tokens not tracked by the\n * core ERC721 logic MUST be matched with the use of {_increaseBalance} to keep balances\n * consistent with ownership. The invariant to preserve is that for any address `a` the value returned by\n * `balanceOf(a)` must be equal to the number of tokens such that `_ownerOf(tokenId)` is `a`.\n */\n function _ownerOf(uint256 tokenId) internal view virtual returns (address) {\n ERC721Storage storage $ = _getERC721Storage();\n return $._owners[tokenId];\n }\n\n /**\n * @dev Returns the approved address for `tokenId`. Returns 0 if `tokenId` is not minted.\n */\n function _getApproved(uint256 tokenId) internal view virtual returns (address) {\n ERC721Storage storage $ = _getERC721Storage();\n return $._tokenApprovals[tokenId];\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `owner`'s tokens, or `tokenId` in\n * particular (ignoring whether it is owned by `owner`).\n *\n * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this\n * assumption.\n */\n function _isAuthorized(address owner, address spender, uint256 tokenId) internal view virtual returns (bool) {\n return\n spender != address(0) &&\n (owner == spender || isApprovedForAll(owner, spender) || _getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Checks if `spender` can operate on `tokenId`, assuming the provided `owner` is the actual owner.\n * Reverts if `spender` does not have approval from the provided `owner` for the given token or for all its assets\n * the `spender` for the specific `tokenId`.\n *\n * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this\n * assumption.\n */\n function _checkAuthorized(address owner, address spender, uint256 tokenId) internal view virtual {\n if (!_isAuthorized(owner, spender, tokenId)) {\n if (owner == address(0)) {\n revert ERC721NonexistentToken(tokenId);\n } else {\n revert ERC721InsufficientApproval(spender, tokenId);\n }\n }\n }\n\n /**\n * @dev Unsafe write access to the balances, used by extensions that \"mint\" tokens using an {ownerOf} override.\n *\n * NOTE: the value is limited to type(uint128).max. This protect against _balance overflow. It is unrealistic that\n * a uint256 would ever overflow from increments when these increments are bounded to uint128 values.\n *\n * WARNING: Increasing an account's balance using this function tends to be paired with an override of the\n * {_ownerOf} function to resolve the ownership of the corresponding tokens so that balances and ownership\n * remain consistent with one another.\n */\n function _increaseBalance(address account, uint128 value) internal virtual {\n ERC721Storage storage $ = _getERC721Storage();\n unchecked {\n $._balances[account] += value;\n }\n }\n\n /**\n * @dev Transfers `tokenId` from its current owner to `to`, or alternatively mints (or burns) if the current owner\n * (or `to`) is the zero address. Returns the owner of the `tokenId` before the update.\n *\n * The `auth` argument is optional. If the value passed is non 0, then this function will check that\n * `auth` is either the owner of the token, or approved to operate on the token (by the owner).\n *\n * Emits a {Transfer} event.\n *\n * NOTE: If overriding this function in a way that tracks balances, see also {_increaseBalance}.\n */\n function _update(address to, uint256 tokenId, address auth) internal virtual returns (address) {\n ERC721Storage storage $ = _getERC721Storage();\n address from = _ownerOf(tokenId);\n\n // Perform (optional) operator check\n if (auth != address(0)) {\n _checkAuthorized(from, auth, tokenId);\n }\n\n // Execute the update\n if (from != address(0)) {\n // Clear approval. No need to re-authorize or emit the Approval event\n _approve(address(0), tokenId, address(0), false);\n\n unchecked {\n $._balances[from] -= 1;\n }\n }\n\n if (to != address(0)) {\n unchecked {\n $._balances[to] += 1;\n }\n }\n\n $._owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n return from;\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal {\n if (to == address(0)) {\n revert ERC721InvalidReceiver(address(0));\n }\n address previousOwner = _update(to, tokenId, address(0));\n if (previousOwner != address(0)) {\n revert ERC721InvalidSender(address(0));\n }\n }\n\n /**\n * @dev Mints `tokenId`, transfers it to `to` and checks for `to` acceptance.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {\n _mint(to, tokenId);\n _checkOnERC721Received(address(0), to, tokenId, data);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n * This is an internal function that does not check if the sender is authorized to operate on the token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal {\n address previousOwner = _update(address(0), tokenId, address(0));\n if (previousOwner == address(0)) {\n revert ERC721NonexistentToken(tokenId);\n }\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(address from, address to, uint256 tokenId) internal {\n if (to == address(0)) {\n revert ERC721InvalidReceiver(address(0));\n }\n address previousOwner = _update(to, tokenId, address(0));\n if (previousOwner == address(0)) {\n revert ERC721NonexistentToken(tokenId);\n } else if (previousOwner != from) {\n revert ERC721IncorrectOwner(from, tokenId, previousOwner);\n }\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking that contract recipients\n * are aware of the ERC721 standard to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is like {safeTransferFrom} in the sense that it invokes\n * {IERC721Receiver-onERC721Received} on the receiver, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `tokenId` token must exist and be owned by `from`.\n * - `to` cannot be the zero address.\n * - `from` cannot be the zero address.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(address from, address to, uint256 tokenId) internal {\n _safeTransfer(from, to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeTransfer-address-address-uint256-}[`_safeTransfer`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {\n _transfer(from, to, tokenId);\n _checkOnERC721Received(from, to, tokenId, data);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * The `auth` argument is optional. If the value passed is non 0, then this function will check that `auth` is\n * either the owner of the token, or approved to operate on all tokens held by this owner.\n *\n * Emits an {Approval} event.\n *\n * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.\n */\n function _approve(address to, uint256 tokenId, address auth) internal {\n _approve(to, tokenId, auth, true);\n }\n\n /**\n * @dev Variant of `_approve` with an optional flag to enable or disable the {Approval} event. The event is not\n * emitted in the context of transfers.\n */\n function _approve(address to, uint256 tokenId, address auth, bool emitEvent) internal virtual {\n ERC721Storage storage $ = _getERC721Storage();\n // Avoid reading the owner unless necessary\n if (emitEvent || auth != address(0)) {\n address owner = _requireOwned(tokenId);\n\n // We do not use _isAuthorized because single-token approvals should not be able to call approve\n if (auth != address(0) && owner != auth && !isApprovedForAll(owner, auth)) {\n revert ERC721InvalidApprover(auth);\n }\n\n if (emitEvent) {\n emit Approval(owner, to, tokenId);\n }\n }\n\n $._tokenApprovals[tokenId] = to;\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Requirements:\n * - operator can't be the address zero.\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {\n ERC721Storage storage $ = _getERC721Storage();\n if (operator == address(0)) {\n revert ERC721InvalidOperator(operator);\n }\n $._operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` doesn't have a current owner (it hasn't been minted, or it has been burned).\n * Returns the owner.\n *\n * Overrides to ownership logic should be done to {_ownerOf}.\n */\n function _requireOwned(uint256 tokenId) internal view returns (address) {\n address owner = _ownerOf(tokenId);\n if (owner == address(0)) {\n revert ERC721NonexistentToken(tokenId);\n }\n return owner;\n }\n\n /**\n * @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target address. This will revert if the\n * recipient doesn't accept the token transfer. The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n */\n function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory data) private {\n if (to.code.length > 0) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n if (retval != IERC721Receiver.onERC721Received.selector) {\n revert ERC721InvalidReceiver(to);\n }\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert ERC721InvalidReceiver(to);\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n }\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/ERC721Enumerable.sol)\n\npragma solidity ^0.8.20;\n\nimport {ERC721Upgradeable} from \"../ERC721Upgradeable.sol\";\nimport {IERC721Enumerable} from \"@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol\";\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport {Initializable} from \"../../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev This implements an optional extension of {ERC721} defined in the EIP that adds enumerability\n * of all the token ids in the contract as well as all token ids owned by each account.\n *\n * CAUTION: `ERC721` extensions that implement custom `balanceOf` logic, such as `ERC721Consecutive`,\n * interfere with enumerability and should not be used together with `ERC721Enumerable`.\n */\nabstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721Enumerable {\n /// @custom:storage-location erc7201:openzeppelin.storage.ERC721Enumerable\n struct ERC721EnumerableStorage {\n mapping(address owner => mapping(uint256 index => uint256)) _ownedTokens;\n mapping(uint256 tokenId => uint256) _ownedTokensIndex;\n\n uint256[] _allTokens;\n mapping(uint256 tokenId => uint256) _allTokensIndex;\n }\n\n // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ERC721Enumerable\")) - 1)) & ~bytes32(uint256(0xff))\n bytes32 private constant ERC721EnumerableStorageLocation = 0x645e039705490088daad89bae25049a34f4a9072d398537b1ab2425f24cbed00;\n\n function _getERC721EnumerableStorage() private pure returns (ERC721EnumerableStorage storage $) {\n assembly {\n $.slot := ERC721EnumerableStorageLocation\n }\n }\n\n /**\n * @dev An `owner`'s token query was out of bounds for `index`.\n *\n * NOTE: The owner being `address(0)` indicates a global out of bounds index.\n */\n error ERC721OutOfBoundsIndex(address owner, uint256 index);\n\n /**\n * @dev Batch mint is not allowed.\n */\n error ERC721EnumerableForbiddenBatchMint();\n\n function __ERC721Enumerable_init() internal onlyInitializing {\n }\n\n function __ERC721Enumerable_init_unchained() internal onlyInitializing {\n }\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721Upgradeable) returns (bool) {\n return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.\n */\n function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual returns (uint256) {\n ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();\n if (index >= balanceOf(owner)) {\n revert ERC721OutOfBoundsIndex(owner, index);\n }\n return $._ownedTokens[owner][index];\n }\n\n /**\n * @dev See {IERC721Enumerable-totalSupply}.\n */\n function totalSupply() public view virtual returns (uint256) {\n ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();\n return $._allTokens.length;\n }\n\n /**\n * @dev See {IERC721Enumerable-tokenByIndex}.\n */\n function tokenByIndex(uint256 index) public view virtual returns (uint256) {\n ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();\n if (index >= totalSupply()) {\n revert ERC721OutOfBoundsIndex(address(0), index);\n }\n return $._allTokens[index];\n }\n\n /**\n * @dev See {ERC721-_update}.\n */\n function _update(address to, uint256 tokenId, address auth) internal virtual override returns (address) {\n address previousOwner = super._update(to, tokenId, auth);\n\n if (previousOwner == address(0)) {\n _addTokenToAllTokensEnumeration(tokenId);\n } else if (previousOwner != to) {\n _removeTokenFromOwnerEnumeration(previousOwner, tokenId);\n }\n if (to == address(0)) {\n _removeTokenFromAllTokensEnumeration(tokenId);\n } else if (previousOwner != to) {\n _addTokenToOwnerEnumeration(to, tokenId);\n }\n\n return previousOwner;\n }\n\n /**\n * @dev Private function to add a token to this extension's ownership-tracking data structures.\n * @param to address representing the new owner of the given token ID\n * @param tokenId uint256 ID of the token to be added to the tokens list of the given address\n */\n function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {\n ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();\n uint256 length = balanceOf(to) - 1;\n $._ownedTokens[to][length] = tokenId;\n $._ownedTokensIndex[tokenId] = length;\n }\n\n /**\n * @dev Private function to add a token to this extension's token tracking data structures.\n * @param tokenId uint256 ID of the token to be added to the tokens list\n */\n function _addTokenToAllTokensEnumeration(uint256 tokenId) private {\n ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();\n $._allTokensIndex[tokenId] = $._allTokens.length;\n $._allTokens.push(tokenId);\n }\n\n /**\n * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that\n * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for\n * gas optimizations e.g. when performing a transfer operation (avoiding double writes).\n * This has O(1) time complexity, but alters the order of the _ownedTokens array.\n * @param from address representing the previous owner of the given token ID\n * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address\n */\n function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {\n ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();\n // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and\n // then delete the last slot (swap and pop).\n\n uint256 lastTokenIndex = balanceOf(from);\n uint256 tokenIndex = $._ownedTokensIndex[tokenId];\n\n // When the token to delete is the last token, the swap operation is unnecessary\n if (tokenIndex != lastTokenIndex) {\n uint256 lastTokenId = $._ownedTokens[from][lastTokenIndex];\n\n $._ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token\n $._ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index\n }\n\n // This also deletes the contents at the last position of the array\n delete $._ownedTokensIndex[tokenId];\n delete $._ownedTokens[from][lastTokenIndex];\n }\n\n /**\n * @dev Private function to remove a token from this extension's token tracking data structures.\n * This has O(1) time complexity, but alters the order of the _allTokens array.\n * @param tokenId uint256 ID of the token to be removed from the tokens list\n */\n function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {\n ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();\n // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and\n // then delete the last slot (swap and pop).\n\n uint256 lastTokenIndex = $._allTokens.length - 1;\n uint256 tokenIndex = $._allTokensIndex[tokenId];\n\n // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so\n // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding\n // an 'if' statement (like in _removeTokenFromOwnerEnumeration)\n uint256 lastTokenId = $._allTokens[lastTokenIndex];\n\n $._allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token\n $._allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index\n\n // This also deletes the contents at the last position of the array\n delete $._allTokensIndex[tokenId];\n $._allTokens.pop();\n }\n\n /**\n * See {ERC721-_increaseBalance}. We need that to account tokens that were minted in batch\n */\n function _increaseBalance(address account, uint128 amount) internal virtual override {\n if (amount > 0) {\n revert ERC721EnumerableForbiddenBatchMint();\n }\n super._increaseBalance(account, amount);\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/ERC721URIStorage.sol)\n\npragma solidity ^0.8.20;\n\nimport {ERC721Upgradeable} from \"../ERC721Upgradeable.sol\";\nimport {Strings} from \"@openzeppelin/contracts/utils/Strings.sol\";\nimport {IERC4906} from \"@openzeppelin/contracts/interfaces/IERC4906.sol\";\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport {Initializable} from \"../../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev ERC721 token with storage based token URI management.\n */\nabstract contract ERC721URIStorageUpgradeable is Initializable, IERC4906, ERC721Upgradeable {\n using Strings for uint256;\n\n // Interface ID as defined in ERC-4906. This does not correspond to a traditional interface ID as ERC-4906 only\n // defines events and does not include any external function.\n bytes4 private constant ERC4906_INTERFACE_ID = bytes4(0x49064906);\n\n /// @custom:storage-location erc7201:openzeppelin.storage.ERC721URIStorage\n struct ERC721URIStorageStorage {\n // Optional mapping for token URIs\n mapping(uint256 tokenId => string) _tokenURIs;\n }\n\n // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ERC721URIStorage\")) - 1)) & ~bytes32(uint256(0xff))\n bytes32 private constant ERC721URIStorageStorageLocation = 0x0542a41881ee128a365a727b282c86fa859579490b9bb45aab8503648c8e7900;\n\n function _getERC721URIStorageStorage() private pure returns (ERC721URIStorageStorage storage $) {\n assembly {\n $.slot := ERC721URIStorageStorageLocation\n }\n }\n\n function __ERC721URIStorage_init() internal onlyInitializing {\n }\n\n function __ERC721URIStorage_init_unchained() internal onlyInitializing {\n }\n /**\n * @dev See {IERC165-supportsInterface}\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Upgradeable, IERC165) returns (bool) {\n return interfaceId == ERC4906_INTERFACE_ID || super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n ERC721URIStorageStorage storage $ = _getERC721URIStorageStorage();\n _requireOwned(tokenId);\n\n string memory _tokenURI = $._tokenURIs[tokenId];\n string memory base = _baseURI();\n\n // If there is no base URI, return the token URI.\n if (bytes(base).length == 0) {\n return _tokenURI;\n }\n // If both are set, concatenate the baseURI and tokenURI (via string.concat).\n if (bytes(_tokenURI).length > 0) {\n return string.concat(base, _tokenURI);\n }\n\n return super.tokenURI(tokenId);\n }\n\n /**\n * @dev Sets `_tokenURI` as the tokenURI of `tokenId`.\n *\n * Emits {MetadataUpdate}.\n */\n function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {\n ERC721URIStorageStorage storage $ = _getERC721URIStorageStorage();\n $._tokenURIs[tokenId] = _tokenURI;\n emit MetadataUpdate(tokenId);\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)\n\npragma solidity ^0.8.20;\nimport {Initializable} from \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuardUpgradeable is Initializable {\n // Booleans are more expensive than uint256 or any type that takes up a full\n // word because each write operation emits an extra SLOAD to first read the\n // slot's contents, replace the bits taken up by the boolean, and then write\n // back. This is the compiler's defense against contract upgrades and\n // pointer aliasing, and it cannot be disabled.\n\n // The values being non-zero value makes deployment a bit more expensive,\n // but in exchange the refund on every call to nonReentrant will be lower in\n // amount. Since refunds are capped to a percentage of the total\n // transaction's gas, it is best to keep them low in cases like this one, to\n // increase the likelihood of the full refund coming into effect.\n uint256 private constant NOT_ENTERED = 1;\n uint256 private constant ENTERED = 2;\n\n /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard\n struct ReentrancyGuardStorage {\n uint256 _status;\n }\n\n // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ReentrancyGuard\")) - 1)) & ~bytes32(uint256(0xff))\n bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;\n\n function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {\n assembly {\n $.slot := ReentrancyGuardStorageLocation\n }\n }\n\n /**\n * @dev Unauthorized reentrant call.\n */\n error ReentrancyGuardReentrantCall();\n\n function __ReentrancyGuard_init() internal onlyInitializing {\n __ReentrancyGuard_init_unchained();\n }\n\n function __ReentrancyGuard_init_unchained() internal onlyInitializing {\n ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n $._status = NOT_ENTERED;\n }\n\n /**\n * @dev Prevents a contract from calling itself, directly or indirectly.\n * Calling a `nonReentrant` function from another `nonReentrant`\n * function is not supported. It is possible to prevent this from happening\n * by making the `nonReentrant` function external, and making it call a\n * `private` function that does the actual work.\n */\n modifier nonReentrant() {\n _nonReentrantBefore();\n _;\n _nonReentrantAfter();\n }\n\n function _nonReentrantBefore() private {\n ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n // On the first call to nonReentrant, _status will be NOT_ENTERED\n if ($._status == ENTERED) {\n revert ReentrancyGuardReentrantCall();\n }\n\n // Any calls to nonReentrant after this point will fail\n $._status = ENTERED;\n }\n\n function _nonReentrantAfter() private {\n ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n // By storing the original value once again, a refund is triggered (see\n // https://eips.ethereum.org/EIPS/eip-2200)\n $._status = NOT_ENTERED;\n }\n\n /**\n * @dev Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n * `nonReentrant` function in the call stack.\n */\n function _reentrancyGuardEntered() internal view returns (bool) {\n ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n return $._status == ENTERED;\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```solidity\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n *\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Storage of the initializable contract.\n *\n * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions\n * when using with upgradeable contracts.\n *\n * @custom:storage-location erc7201:openzeppelin.storage.Initializable\n */\n struct InitializableStorage {\n /**\n * @dev Indicates that the contract has been initialized.\n */\n uint64 _initialized;\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool _initializing;\n }\n\n // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.Initializable\")) - 1)) & ~bytes32(uint256(0xff))\n bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;\n\n /**\n * @dev The contract is already initialized.\n */\n error InvalidInitialization();\n\n /**\n * @dev The contract is not initializing.\n */\n error NotInitializing();\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint64 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts.\n *\n * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any\n * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in\n * production.\n *\n * Emits an {Initialized} event.\n */\n modifier initializer() {\n // solhint-disable-next-line var-name-mixedcase\n InitializableStorage storage $ = _getInitializableStorage();\n\n // Cache values to avoid duplicated sloads\n bool isTopLevelCall = !$._initializing;\n uint64 initialized = $._initialized;\n\n // Allowed calls:\n // - initialSetup: the contract is not in the initializing state and no previous version was\n // initialized\n // - construction: the contract is initialized at version 1 (no reininitialization) and the\n // current contract is just being deployed\n bool initialSetup = initialized == 0 && isTopLevelCall;\n bool construction = initialized == 1 && address(this).code.length == 0;\n\n if (!initialSetup && !construction) {\n revert InvalidInitialization();\n }\n $._initialized = 1;\n if (isTopLevelCall) {\n $._initializing = true;\n }\n _;\n if (isTopLevelCall) {\n $._initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n * are added through upgrades and that require initialization.\n *\n * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n * cannot be nested. If one is invoked in the context of another, execution will revert.\n *\n * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n * a contract, executing them in the right order is up to the developer or operator.\n *\n * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.\n *\n * Emits an {Initialized} event.\n */\n modifier reinitializer(uint64 version) {\n // solhint-disable-next-line var-name-mixedcase\n InitializableStorage storage $ = _getInitializableStorage();\n\n if ($._initializing || $._initialized >= version) {\n revert InvalidInitialization();\n }\n $._initialized = version;\n $._initializing = true;\n _;\n $._initializing = false;\n emit Initialized(version);\n }\n\n /**\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n * {initializer} and {reinitializer} modifiers, directly or indirectly.\n */\n modifier onlyInitializing() {\n _checkInitializing();\n _;\n }\n\n /**\n * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.\n */\n function _checkInitializing() internal view virtual {\n if (!_isInitializing()) {\n revert NotInitializing();\n }\n }\n\n /**\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n * through proxies.\n *\n * Emits an {Initialized} event the first time it is successfully executed.\n */\n function _disableInitializers() internal virtual {\n // solhint-disable-next-line var-name-mixedcase\n InitializableStorage storage $ = _getInitializableStorage();\n\n if ($._initializing) {\n revert InvalidInitialization();\n }\n if ($._initialized != type(uint64).max) {\n $._initialized = type(uint64).max;\n emit Initialized(type(uint64).max);\n }\n }\n\n /**\n * @dev Returns the highest version that has been initialized. See {reinitializer}.\n */\n function _getInitializedVersion() internal view returns (uint64) {\n return _getInitializableStorage()._initialized;\n }\n\n /**\n * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.\n */\n function _isInitializing() internal view returns (bool) {\n return _getInitializableStorage()._initializing;\n }\n\n /**\n * @dev Returns a pointer to the storage namespace.\n */\n // solhint-disable-next-line var-name-mixedcase\n function _getInitializableStorage() private pure returns (InitializableStorage storage $) {\n assembly {\n $.slot := INITIALIZABLE_STORAGE\n }\n }\n}\n"},"src/deposit/interfaces/IKTON.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity >=0.4.24;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\ninterface IKTON is IERC20 {\n function burn(address from, uint256 amount) external returns (bool);\n function mint(address to, uint256 amount) external returns (bool);\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon\n * a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or\n * {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon\n * a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721\n * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must\n * understand this adds an external call which potentially creates a reentrancy vulnerability.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address from, address to, uint256 tokenId) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the address zero.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be\n * reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/IERC721Metadata.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC721} from \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\n\npragma solidity ^0.8.20;\nimport {Initializable} from \"../proxy/utils/Initializable.sol\";\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 ContextUpgradeable is Initializable {\n function __Context_init() internal onlyInitializing {\n }\n\n function __Context_init_unchained() internal onlyInitializing {\n }\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 function _contextSuffixLength() internal view virtual returns (uint256) {\n return 0;\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Strings.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)\n\npragma solidity ^0.8.20;\n\nimport {Math} from \"./math/Math.sol\";\nimport {SignedMath} from \"./math/SignedMath.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant HEX_DIGITS = \"0123456789abcdef\";\n uint8 private constant ADDRESS_LENGTH = 20;\n\n /**\n * @dev The `value` string doesn't fit in the specified `length`.\n */\n error StringsInsufficientHexLength(uint256 value, uint256 length);\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n unchecked {\n uint256 length = Math.log10(value) + 1;\n string memory buffer = new string(length);\n uint256 ptr;\n /// @solidity memory-safe-assembly\n assembly {\n ptr := add(buffer, add(32, length))\n }\n while (true) {\n ptr--;\n /// @solidity memory-safe-assembly\n assembly {\n mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))\n }\n value /= 10;\n if (value == 0) break;\n }\n return buffer;\n }\n }\n\n /**\n * @dev Converts a `int256` to its ASCII `string` decimal representation.\n */\n function toStringSigned(int256 value) internal pure returns (string memory) {\n return string.concat(value < 0 ? \"-\" : \"\", toString(SignedMath.abs(value)));\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n unchecked {\n return toHexString(value, Math.log256(value) + 1);\n }\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n uint256 localValue = value;\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = HEX_DIGITS[localValue & 0xf];\n localValue >>= 4;\n }\n if (localValue != 0) {\n revert StringsInsufficientHexLength(value, length);\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal\n * representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);\n }\n\n /**\n * @dev Returns true if the two strings are equal.\n */\n function equal(string memory a, string memory b) internal pure returns (bool) {\n return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport {Initializable} from \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n */\nabstract contract ERC165Upgradeable is Initializable, IERC165 {\n function __ERC165_init() internal onlyInitializing {\n }\n\n function __ERC165_init_unchained() internal onlyInitializing {\n }\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard ERC20 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.\n */\ninterface IERC20Errors {\n /**\n * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n * @param balance Current balance for the interacting account.\n * @param needed Minimum amount required to perform a transfer.\n */\n error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);\n\n /**\n * @dev Indicates a failure with the token `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n */\n error ERC20InvalidSender(address sender);\n\n /**\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\n * @param receiver Address to which tokens are being transferred.\n */\n error ERC20InvalidReceiver(address receiver);\n\n /**\n * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.\n * @param spender Address that may be allowed to operate on tokens without being their owner.\n * @param allowance Amount of tokens a `spender` is allowed to operate with.\n * @param needed Minimum amount required to perform a transfer.\n */\n error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);\n\n /**\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n * @param approver Address initiating an approval operation.\n */\n error ERC20InvalidApprover(address approver);\n\n /**\n * @dev Indicates a failure with the `spender` to be approved. Used in approvals.\n * @param spender Address that may be allowed to operate on tokens without being their owner.\n */\n error ERC20InvalidSpender(address spender);\n}\n\n/**\n * @dev Standard ERC721 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.\n */\ninterface IERC721Errors {\n /**\n * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.\n * Used in balance queries.\n * @param owner Address of the current owner of a token.\n */\n error ERC721InvalidOwner(address owner);\n\n /**\n * @dev Indicates a `tokenId` whose `owner` is the zero address.\n * @param tokenId Identifier number of a token.\n */\n error ERC721NonexistentToken(uint256 tokenId);\n\n /**\n * @dev Indicates an error related to the ownership over a particular token. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n * @param tokenId Identifier number of a token.\n * @param owner Address of the current owner of a token.\n */\n error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);\n\n /**\n * @dev Indicates a failure with the token `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n */\n error ERC721InvalidSender(address sender);\n\n /**\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\n * @param receiver Address to which tokens are being transferred.\n */\n error ERC721InvalidReceiver(address receiver);\n\n /**\n * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n * @param operator Address that may be allowed to operate on tokens without being their owner.\n * @param tokenId Identifier number of a token.\n */\n error ERC721InsufficientApproval(address operator, uint256 tokenId);\n\n /**\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n * @param approver Address initiating an approval operation.\n */\n error ERC721InvalidApprover(address approver);\n\n /**\n * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n * @param operator Address that may be allowed to operate on tokens without being their owner.\n */\n error ERC721InvalidOperator(address operator);\n}\n\n/**\n * @dev Standard ERC1155 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.\n */\ninterface IERC1155Errors {\n /**\n * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n * @param balance Current balance for the interacting account.\n * @param needed Minimum amount required to perform a transfer.\n * @param tokenId Identifier number of a token.\n */\n error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);\n\n /**\n * @dev Indicates a failure with the token `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n */\n error ERC1155InvalidSender(address sender);\n\n /**\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\n * @param receiver Address to which tokens are being transferred.\n */\n error ERC1155InvalidReceiver(address receiver);\n\n /**\n * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n * @param operator Address that may be allowed to operate on tokens without being their owner.\n * @param owner Address of the current owner of a token.\n */\n error ERC1155MissingApprovalForAll(address operator, address owner);\n\n /**\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n * @param approver Address initiating an approval operation.\n */\n error ERC1155InvalidApprover(address approver);\n\n /**\n * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n * @param operator Address that may be allowed to operate on tokens without being their owner.\n */\n error ERC1155InvalidOperator(address operator);\n\n /**\n * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.\n * Used in batch transfers.\n * @param idsLength Length of the array of token identifiers\n * @param valuesLength Length of the array of token amounts\n */\n error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC721/extensions/IERC721Enumerable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Enumerable.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC721} from \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Enumerable is IERC721 {\n /**\n * @dev Returns the total amount of tokens stored by the contract.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns a token ID owned by `owner` at a given `index` of its token list.\n * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.\n */\n function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);\n\n /**\n * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.\n * Use along with {totalSupply} to enumerate all tokens.\n */\n function tokenByIndex(uint256 index) external view returns (uint256);\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC4906.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC4906.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"./IERC165.sol\";\nimport {IERC721} from \"./IERC721.sol\";\n\n/// @title EIP-721 Metadata Update Extension\ninterface IERC4906 is IERC165, IERC721 {\n /// @dev This event emits when the metadata of a token is changed.\n /// So that the third-party platforms such as NFT market could\n /// timely update the images and related attributes of the NFT.\n event MetadataUpdate(uint256 _tokenId);\n\n /// @dev This event emits when the metadata of a range of tokens is changed.\n /// So that the third-party platforms such as NFT market could\n /// timely update the images and related attributes of the NFTs.\n event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.20;\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 value of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the value of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens as the allowance of `spender` over the\n * 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 value) external returns (bool);\n\n /**\n * @dev Moves a `value` amount of tokens from `from` to `to` using the\n * allowance mechanism. `value` 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(address from, address to, uint256 value) external returns (bool);\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/Math.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n /**\n * @dev Muldiv operation overflow.\n */\n error MathOverflowedMulDiv();\n\n enum Rounding {\n Floor, // Toward negative infinity\n Ceil, // Toward positive infinity\n Trunc, // Toward zero\n Expand // Away from zero\n }\n\n /**\n * @dev Returns the addition of two unsigned integers, with an overflow flag.\n */\n function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n uint256 c = a + b;\n if (c < a) return (false, 0);\n return (true, c);\n }\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, with an overflow flag.\n */\n function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b > a) return (false, 0);\n return (true, a - b);\n }\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n */\n function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) return (true, 0);\n uint256 c = a * b;\n if (c / a != b) return (false, 0);\n return (true, c);\n }\n }\n\n /**\n * @dev Returns the division of two unsigned integers, with a division by zero flag.\n */\n function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b == 0) return (false, 0);\n return (true, a / b);\n }\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n */\n function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b == 0) return (false, 0);\n return (true, a % b);\n }\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds towards infinity instead\n * of rounding towards zero.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n if (b == 0) {\n // Guarantee the same behavior as in a regular Solidity division.\n return a / b;\n }\n\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or\n * denominator == 0.\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by\n * Uniswap Labs also under MIT license.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0 = x * y; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n // The surrounding unchecked block does not change this fact.\n // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n if (denominator <= prod1) {\n revert MathOverflowedMulDiv();\n }\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator.\n // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.\n\n uint256 twos = denominator & (0 - denominator);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also\n // works in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded\n * towards zero.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n //\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n //\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n //\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1 << (log2(a) >> 1);\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = sqrt(a);\n return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 2 of a positive value rounded towards zero.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 128;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 64;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 32;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 16;\n }\n if (value >> 8 > 0) {\n value >>= 8;\n result += 8;\n }\n if (value >> 4 > 0) {\n value >>= 4;\n result += 4;\n }\n if (value >> 2 > 0) {\n value >>= 2;\n result += 2;\n }\n if (value >> 1 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 10 of a positive value rounded towards zero.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10 ** 64) {\n value /= 10 ** 64;\n result += 64;\n }\n if (value >= 10 ** 32) {\n value /= 10 ** 32;\n result += 32;\n }\n if (value >= 10 ** 16) {\n value /= 10 ** 16;\n result += 16;\n }\n if (value >= 10 ** 8) {\n value /= 10 ** 8;\n result += 8;\n }\n if (value >= 10 ** 4) {\n value /= 10 ** 4;\n result += 4;\n }\n if (value >= 10 ** 2) {\n value /= 10 ** 2;\n result += 2;\n }\n if (value >= 10 ** 1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 256 of a positive value rounded towards zero.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 16;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 8;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 4;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 2;\n }\n if (value >> 8 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.\n */\n function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {\n return uint8(rounding) % 2 == 1;\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard signed math utilities missing in the Solidity language.\n */\nlibrary SignedMath {\n /**\n * @dev Returns the largest of two signed numbers.\n */\n function max(int256 a, int256 b) internal pure returns (int256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two signed numbers.\n */\n function min(int256 a, int256 b) internal pure returns (int256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two signed numbers without overflow.\n * The result is rounded towards zero.\n */\n function average(int256 a, int256 b) internal pure returns (int256) {\n // Formula from the book \"Hacker's Delight\"\n int256 x = (a & b) + ((a ^ b) >> 1);\n return x + (int256(uint256(x) >> 255) & (a ^ b));\n }\n\n /**\n * @dev Returns the absolute unsigned value of a signed value.\n */\n function abs(int256 n) internal pure returns (uint256) {\n unchecked {\n // must be unchecked in order to support `n = type(int256).min`\n return uint256(n >= 0 ? n : -n);\n }\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"../utils/introspection/IERC165.sol\";\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC721.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC721.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC721} from \"../token/ERC721/IERC721.sol\";\n"}},"settings":{"remappings":["forge-std/=lib/forge-std/src/","@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/","@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/","openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/","solidity-stringutils/=lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/"],"optimizer":{"enabled":true,"runs":999999},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"":["ast"],"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata","storageLayout"]}},"evmVersion":"london","viaIR":false,"libraries":{}}} diff --git a/verify/NominationPool.json b/verify/NominationPool.json new file mode 100644 index 0000000..fc5c4af --- /dev/null +++ b/verify/NominationPool.json @@ -0,0 +1 @@ +{"language":"Solidity","sources":{"src/collator/NominationPool.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.20;\n\nimport \"@openzeppelin/contracts/utils/Address.sol\";\nimport \"@openzeppelin/contracts/utils/math/Math.sol\";\n\ncontract NominationPool {\n using Address for address payable;\n\n /* ========== STATE VARIABLES ========== */\n\n address public hub;\n address public collator;\n uint256 public periodFinish = 0;\n uint256 public rewardRate = 0;\n uint256 public rewardsDuration = 7 days;\n uint256 public lastUpdateTime;\n uint256 public rewardPerTokenStored;\n\n mapping(address => uint256) public userRewardPerTokenPaid;\n mapping(address => uint256) public rewards;\n\n uint256 private _totalSupply;\n mapping(address => uint256) private _balances;\n\n modifier onlyHub() {\n require(msg.sender == hub);\n _;\n }\n\n /* ========== CONSTRUCTOR ========== */\n\n constructor(address collator_) {\n hub = msg.sender;\n collator = collator_;\n }\n\n /* ========== VIEWS ========== */\n\n function totalSupply() external view returns (uint256) {\n return _totalSupply;\n }\n\n function balanceOf(address account) external view returns (uint256) {\n return _balances[account];\n }\n\n function lastTimeRewardApplicable() public view returns (uint256) {\n return Math.min(block.timestamp, periodFinish);\n }\n\n function rewardPerToken() public view returns (uint256) {\n if (_totalSupply == 0) {\n return rewardPerTokenStored;\n }\n return rewardPerTokenStored + (lastTimeRewardApplicable() - lastUpdateTime) * rewardRate * 1e18 / _totalSupply;\n }\n\n function earned(address account) public view returns (uint256) {\n return _balances[account] * (rewardPerToken() - userRewardPerTokenPaid[account]) / 1e18 + rewards[account];\n }\n\n function getRewardForDuration() external view returns (uint256) {\n return rewardRate * rewardsDuration;\n }\n\n /* ========== MUTATIVE FUNCTIONS ========== */\n\n function stake(address account, uint256 amount) external onlyHub updateReward(account) {\n require(amount > 0, \"Cannot stake 0\");\n _totalSupply += amount;\n _balances[account] += amount;\n emit Staked(account, amount);\n }\n\n function withdraw(address account, uint256 amount) public onlyHub updateReward(account) {\n require(amount > 0, \"Cannot withdraw 0\");\n _totalSupply -= amount;\n _balances[account] -= amount;\n emit Withdrawn(account, amount);\n }\n\n function getReward(address account) public onlyHub updateReward(account) {\n uint256 reward = rewards[account];\n if (reward > 0) {\n rewards[account] = 0;\n payable(account).sendValue(reward);\n emit RewardPaid(account, reward);\n }\n }\n\n /* ========== RESTRICTED FUNCTIONS ========== */\n\n function notifyRewardAmount() external payable onlyHub updateReward(address(0)) {\n uint256 reward = msg.value;\n if (block.timestamp >= periodFinish) {\n rewardRate = reward / rewardsDuration;\n } else {\n uint256 remaining = periodFinish - block.timestamp;\n uint256 leftover = remaining * rewardRate;\n rewardRate = (reward + leftover) / rewardsDuration;\n }\n\n // Ensure the provided reward amount is not more than the balance in the contract.\n // This keeps the reward rate in the right range, preventing overflows due to\n // very high values of rewardRate in the earned and rewardsPerToken functions;\n // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.\n uint256 balance = address(this).balance;\n require(rewardRate <= balance / rewardsDuration, \"Provided reward too high\");\n\n lastUpdateTime = block.timestamp;\n periodFinish = block.timestamp + rewardsDuration;\n emit RewardAdded(reward);\n }\n\n /* ========== MODIFIERS ========== */\n\n modifier updateReward(address account) {\n rewardPerTokenStored = rewardPerToken();\n lastUpdateTime = lastTimeRewardApplicable();\n if (account != address(0)) {\n rewards[account] = earned(account);\n userRewardPerTokenPaid[account] = rewardPerTokenStored;\n }\n _;\n }\n\n /* ========== EVENTS ========== */\n\n event RewardAdded(uint256 reward);\n event Staked(address indexed user, uint256 amount);\n event Withdrawn(address indexed user, uint256 amount);\n event RewardPaid(address indexed user, uint256 reward);\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Address.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev The ETH balance of the account is not enough to perform the operation.\n */\n error AddressInsufficientBalance(address account);\n\n /**\n * @dev There's no code at `target` (it is not a contract).\n */\n error AddressEmptyCode(address target);\n\n /**\n * @dev A call to an address target failed. The target may have reverted.\n */\n error FailedInnerCall();\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://consensys.net/diligence/blog/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.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n if (address(this).balance < amount) {\n revert AddressInsufficientBalance(address(this));\n }\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n if (!success) {\n revert FailedInnerCall();\n }\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 or custom error, it is bubbled\n * up by this function (like regular Solidity function calls). However, if\n * the call reverted with no returned reason, this function reverts with a\n * {FailedInnerCall} error.\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 function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0);\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 function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n if (address(this).balance < value) {\n revert AddressInsufficientBalance(address(this));\n }\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an\n * unsuccessful call.\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata\n ) internal view returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n // only check if target is a contract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n if (returndata.length == 0 && target.code.length == 0) {\n revert AddressEmptyCode(target);\n }\n return returndata;\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n * revert reason or with a default {FailedInnerCall} error.\n */\n function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n return returndata;\n }\n }\n\n /**\n * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.\n */\n function _revert(bytes memory returndata) private pure {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert FailedInnerCall();\n }\n }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/Math.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n /**\n * @dev Muldiv operation overflow.\n */\n error MathOverflowedMulDiv();\n\n enum Rounding {\n Floor, // Toward negative infinity\n Ceil, // Toward positive infinity\n Trunc, // Toward zero\n Expand // Away from zero\n }\n\n /**\n * @dev Returns the addition of two unsigned integers, with an overflow flag.\n */\n function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n uint256 c = a + b;\n if (c < a) return (false, 0);\n return (true, c);\n }\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, with an overflow flag.\n */\n function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b > a) return (false, 0);\n return (true, a - b);\n }\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n */\n function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) return (true, 0);\n uint256 c = a * b;\n if (c / a != b) return (false, 0);\n return (true, c);\n }\n }\n\n /**\n * @dev Returns the division of two unsigned integers, with a division by zero flag.\n */\n function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b == 0) return (false, 0);\n return (true, a / b);\n }\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n */\n function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b == 0) return (false, 0);\n return (true, a % b);\n }\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds towards infinity instead\n * of rounding towards zero.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n if (b == 0) {\n // Guarantee the same behavior as in a regular Solidity division.\n return a / b;\n }\n\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or\n * denominator == 0.\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by\n * Uniswap Labs also under MIT license.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0 = x * y; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n // The surrounding unchecked block does not change this fact.\n // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n if (denominator <= prod1) {\n revert MathOverflowedMulDiv();\n }\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator.\n // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.\n\n uint256 twos = denominator & (0 - denominator);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also\n // works in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded\n * towards zero.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n //\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n //\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n //\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1 << (log2(a) >> 1);\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = sqrt(a);\n return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 2 of a positive value rounded towards zero.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 128;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 64;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 32;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 16;\n }\n if (value >> 8 > 0) {\n value >>= 8;\n result += 8;\n }\n if (value >> 4 > 0) {\n value >>= 4;\n result += 4;\n }\n if (value >> 2 > 0) {\n value >>= 2;\n result += 2;\n }\n if (value >> 1 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 10 of a positive value rounded towards zero.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10 ** 64) {\n value /= 10 ** 64;\n result += 64;\n }\n if (value >= 10 ** 32) {\n value /= 10 ** 32;\n result += 32;\n }\n if (value >= 10 ** 16) {\n value /= 10 ** 16;\n result += 16;\n }\n if (value >= 10 ** 8) {\n value /= 10 ** 8;\n result += 8;\n }\n if (value >= 10 ** 4) {\n value /= 10 ** 4;\n result += 4;\n }\n if (value >= 10 ** 2) {\n value /= 10 ** 2;\n result += 2;\n }\n if (value >= 10 ** 1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 256 of a positive value rounded towards zero.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 16;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 8;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 4;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 2;\n }\n if (value >> 8 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.\n */\n function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {\n return uint8(rounding) % 2 == 1;\n }\n}\n"}},"settings":{"remappings":["forge-std/=lib/forge-std/src/","@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/","@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/","openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/","solidity-stringutils/=lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/"],"optimizer":{"enabled":true,"runs":999999},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"":["ast"],"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata","storageLayout"]}},"evmVersion":"london","viaIR":false,"libraries":{}}}